hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
45af9f5e5dd5a4a0f511280f5660c0154fe8ddcc | 1,003 | cpp | C++ | CPP STL/word-search-in-graph.cpp | Pravi16/open-source-contribution | 3742ac253324f9e210935fd4f43b4045093ba5b5 | [
"MIT"
] | 2 | 2022-03-10T17:37:24.000Z | 2022-03-10T17:40:05.000Z | CPP STL/word-search-in-graph.cpp | Pravi16/open-source-contribution | 3742ac253324f9e210935fd4f43b4045093ba5b5 | [
"MIT"
] | null | null | null | CPP STL/word-search-in-graph.cpp | Pravi16/open-source-contribution | 3742ac253324f9e210935fd4f43b4045093ba5b5 | [
"MIT"
] | 1 | 2021-12-29T16:13:52.000Z | 2021-12-29T16:13:52.000Z | //PROBLEM : https://leetcode.com/problems/word-search/
// Asked in Intuit Interview
class Solution {
public:
bool dfs(vector<vector<char>>& board,int count, int i, int j, int m, int n, string& word)
{
if(word.size()==count) return true;
if(i<0 || i>=m || j<0 || j>=n || board[i][j]!=word[count]) return false;
char c = board[i][j];
board[i][j] = ' ';
bool res = dfs(board, count+1, i+1,j,m,n,word) || dfs(board,count+1,i-1,j,m,n,word) || dfs(board, count+1,i,j+1,m,n,word) || dfs(board, count+1,i,j-1,m,n,word);
board[i][j] = c;
return res;
}
bool exist(vector<vector<char>>& board, string word) {
if(board.empty()) return false;
int m = board.size();
int n = board[0].size();
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(dfs(board,0, i, j, m, n,word)) return true;
}
}
return false;
}
};
| 29.5 | 168 | 0.491525 | [
"vector"
] |
45b7829ff90ab028c80cdcf1b09a4cac89004d76 | 148,809 | cpp | C++ | groups/bal/balst/balst_stacktraceresolverimpl_elf.cpp | hughesr/bde | d593e3213918b9292c25e08cfc5b6651bacdea0d | [
"Apache-2.0"
] | 1 | 2019-01-22T19:44:05.000Z | 2019-01-22T19:44:05.000Z | groups/bal/balst/balst_stacktraceresolverimpl_elf.cpp | anuranrc/bde | d593e3213918b9292c25e08cfc5b6651bacdea0d | [
"Apache-2.0"
] | null | null | null | groups/bal/balst/balst_stacktraceresolverimpl_elf.cpp | anuranrc/bde | d593e3213918b9292c25e08cfc5b6651bacdea0d | [
"Apache-2.0"
] | null | null | null | // balst_stacktraceresolverimpl_elf.cpp -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#include <balst_stacktraceresolverimpl_elf.h>
#include <bsls_ident.h>
BSLS_IDENT_RCSID(balst_stacktraceresolverimpl_elf_cpp,"$Id$ $CSID$")
#include <balst_objectfileformat.h>
#ifdef BALST_OBJECTFILEFORMAT_RESOLVER_ELF
#include <balst_stacktraceresolver_dwarfreader.h>
#include <balst_stacktraceresolver_filehelper.h>
#include <bdlb_string.h>
#include <bdls_filesystemutil.h>
#include <bslma_usesbslmaallocator.h>
#include <bslmf_nestedtraitdeclaration.h>
#include <bsls_assert.h>
#include <bsls_platform.h>
#include <bsl_algorithm.h>
#include <bsl_cstddef.h>
#include <bsl_cstdlib.h>
#include <bsl_cerrno.h>
#include <bsl_cstring.h>
#include <bsl_climits.h>
#include <bsl_cstdarg.h>
#include <bsl_deque.h>
#include <bsl_vector.h>
#include <elf.h>
#include <sys/types.h> // lstat
#include <sys/stat.h> // lstat
#include <unistd.h>
#undef u_DWARF
#if defined(BALST_OBJECTFILEFORMAT_RESOLVER_DWARF)
# define u_DWARF 1
# include <dwarf.h>
#endif
#if defined(BSLS_PLATFORM_OS_HPUX)
# include <dl.h>
# include <aCC/acxx_demangle.h>
#elif defined(BSLS_PLATFORM_OS_LINUX)
# include <cxxabi.h>
# include <dlfcn.h>
# include <execinfo.h>
# include <link.h>
#elif defined(BSLS_PLATFORM_OS_SOLARIS)
# include <link.h>
# if defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG)
# include <cxxabi.h>
# else
# include <demangle.h>
# endif
#else
# error unrecognized ELF platform
#endif
#if defined(BSLS_PLATFORM_CMP_SUN) && BSLS_PLATFORM_CMP_VERSION == 0x5130
# define BALST_COMPILER_DEFECT_NO_TYPEDEF_DESTRUCTORS 1
// The Sun CC 12.4 compiler has a problem when the spelling of the name of the
// destructor does not exactly match the class name. One of the implementation
// techniques in this file involves using a typedef name quite widely, which
// includes a case of defining a destructor.
#endif
// 'u_' PREFIX:
// We have many types, static functions and macros defined in this file. Prior
// to when we were using package namespaces, all global types and functions
// began with the package prefix, so the reader saw a type, macro, or function
// without the package prefix they knew it was probably local to the file. Now
// that we have package prefixes, this is no longer the case, leading to
// confusion. Hence, local definitions at file scope begin with 'u_', lending
// considerable clarity.
//
// Rohan's:
// IMPLEMENTATION NOTES:
//
// All of the following 'struct' definitions are specific to Sun Solaris and
// are derived from '/usr/include/sys/elf.h'. Note that we use 32-bit
// 'struct's for explanation.
//
// Each ELF object file or executable starts with an ELF header that specifies
// how many segments are provided in the file. The ELF header looks as
// follows:
//..
// typedef struct {
// unsigned char e_ident[EI_NIDENT]; // ident bytes
// Elf32_Half e_type; // file type
// Elf32_Half e_machine; // target machine
// Elf32_Word e_version; // file version
// Elf32_Addr e_entry; // start address
// Elf32_Off e_phoff; // program header file offset
// Elf32_Off e_shoff; // section header file offset
// Elf32_Word e_flags; // file flags
// Elf32_Half e_ehsize; // sizeof ehdr
// Elf32_Half e_phentsize; // sizeof phdr
// Elf32_Half e_phnum; // number of program headers
// Elf32_Half e_shentsize; // sizeof section header
// Elf32_Half e_shnum; // number of section headers
// Elf32_Half e_shstrndx; // shdr string index
// } u_Elf32_Ehdr;
//..
// Each segment is described by a program header that is an array of
// structures, each describing a segment or other information the system needs
// to prepare the program for execution, and typically looks as follows:
//..
// typedef struct {
// Elf32_Word p_type; // entry type
// Elf32_Off p_offset; // file offset
// Elf32_Addr p_vaddr; // virtual address
// Elf32_Addr p_paddr; // physical address
// Elf32_Word p_filesz; // file size
// Elf32_Word p_memsz; // memory size
// Elf32_Word p_flags; // entry flags
// Elf32_Word p_align; // memory/file alignment
// } u_Elf32_Phdr;
//..
// An object file segment contains one or more sections. The string table
// provides the names of the various sections corresponding to the integral
// 'sh_name'. An elf file will typically contain sections such as '.text',
// '.data', '.bss' etc.
//..
// typedef struct {
// Elf32_Word sh_name; // section name
// Elf32_Word sh_type; // SHT_...
// Elf32_Word sh_flags; // SHF_...
// Elf32_Addr sh_addr; // virtual address
// Elf32_Off sh_offset; // file offset
// Elf32_Word sh_size; // section size
// Elf32_Word sh_link; // misc info
// Elf32_Word sh_info; // misc info
// Elf32_Word sh_addralign; // memory alignment
// Elf32_Word sh_entsize; // entry size if table
// } u_Elf32_Shdr;
//
// typedef struct
// {
// Elf32_Word st_name; // Symbol name (string tbl index)
// Elf32_Addr st_value; // Symbol value
// Elf32_Word st_size; // Symbol size
// unsigned char st_info; // Symbol type and binding
// unsigned char st_other; // Symbol visibility
// Elf32_Section st_shndx; // Section index - 16-bit
// } u_Elf32_Sym;
//..
// Below we explain the strategies to resolve symbols on the various platforms
// that we support.
//
// Solaris:
// ----------------------------------------------------------------------------
//
// The _DYNAMIC symbol references a _dynamic structure that refers to the
// linked symbols:
//..
// typedef struct {
// Elf32_Sword d_tag; // how to interpret value
// union {
// Elf32_Word d_val;
// Elf32_Addr d_ptr;
// Elf32_Off d_off;
// } d_un;
// } u_Elf32_Dyn;
//..
// Tag values
//..
// #define DT_NULL 0 // last entry in list
// #define DT_DEBUG 21 // pointer to r_debug structure
//
// struct r_debug {
// int r_version; // debugging info version no.
// Link_map *r_map; // address of link_map
// unsigned long r_brk; // address of update routine
// r_state_e r_state;
// unsigned long r_ldbase; // base addr of ld.so
// Link_map *r_ldsomap; // address of ld.so.1's link map
// rd_event_e r_rdevent; // debug event
// rd_flags_e r_flags; // misc flags.
// };
//..
// The link_map is a chain of loaded object.
//..
// struct link_map {
//
// unsigned long l_addr; // address at which object is
// // mapped
// char *l_name; // full name of loaded object
// #ifdef _LP64
// Elf64_Dyn *l_ld; // dynamic structure of object
// #else
// Elf32_Dyn *l_ld; // dynamic structure of object
// #endif
// Link_map *l_next; // next link object
// Link_map *l_prev; // previous link object
// char *l_refname; // filters reference name
// };
//..
// Linux:
// ----------------------------------------------------------------------------
//..
// int dl_iterate_phdr(int (*callback) (struct dl_phdr_info *info,
// size_t size,
// void *data),
// void *data);
// // Walk through the list of an application's shared objects and invoke
// // the specified 'callback' (taking the specified 'info' object of
// // the specified 'size' and specifying the user supplied 'data') using
// // the specified 'data' to be passed to 'callback'.
//
// struct dl_phdr_info
// {
// ElfW(Addr) dlpi_addr;
// const char *dlpi_name;
// const ElfW(Phdr) *dlpi_phdr;
// ElfW(Half) dlpi_phnum;
//
// // Note: the next two members were introduced after the first
// // version of this structure was available. Check the SIZE
// // argument passed to the dl_iterate_phdr() callback to determine
// // whether or not they are provided.
//
// // Incremented when a new object may have been added.
// unsigned long long int dlpi_adds;
//
// // Incremented when an object may have been removed.
// unsigned long long int dlpi_subs;
// };
//..
// HPUX:
// ----------------------------------------------------------------------------
//..
// struct shl_descriptor {
// unsigned long tstart; // start address of the shared
// // library text segment
//
// unsigned long tend; // end address of the shared
// // library text segment
//
// unsigned long dstart;
// unsigned long dend;
// void *ltptr;
// shl_t handle;
// char filename[MAXPATHLEN + 1];
// void *initializer;
// unsigned long ref_count;
// unsigned long reserved3;
// unsigned long reserved2;
// unsigned long reserved1;
// unsigned long reserved0;
// };
//
// int shl_get_r(int index, struct shl_descriptor *desc);
// // Load into the specified 'desc' information about the loaded library
// // at the specified 'index'. For libraries loaded implicitly (at
// // startup time), 'index' is the ordinal number of the library as it
// // appeared on the command line. Return 0 on success and a non-zero
// // value otherwise. Note that an 'index' value of 0 refers to the main
// // program itself and -1 refers to the dynamic loader.
//..
// ----------------------------------------------------------------------------
// Bill's:
//
// Note that ELF and DWARF are separate formats. ELF has a certain amount of
// information, including library file names, symbol names, and basenames of
// source file names for static symbols. Dwarf contains full path source file
// names for all symbols and line number information.
//
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ELF IMPLEMENTATION NOTES:
//
// The following 'struct' definitions describing the Elf format are modified
// from those found in the .h files (mostly 'elf.h'). The following
// transformations have been done on the definitions found in the .h file --
// typedefs to fundamental types have been resolved (some that are equivalent
// to 'bsls::Types::UintPtr' have been translated to 'UintPtr') and the names
// given for the structs are the names of typedefs to them in the unnamed
// namespace within this file. Significantly, data members not used in this
// source file are ommitted.
//
// Each ELF object file or executable starts with an ELF header that specifies
// how many segments are provided in the file. The ELF header looks as
// follows:
//..
// typedef struct {
// unsigned char e_ident[EI_NIDENT]; // ident bytes
// UintPtr e_phoff; // program header file offset
// UintPtr e_shoff; // section header file offset
// short e_shentsize; // sizeof section header
// short e_shnum; // number of section headers
// short e_shstrndx; // shdr string index
// } u_ElfHeader;
//..
// Each segment is described by a program header that is an array of
// structures, each describing a segment or other information the system needs
// to prepare the program for execution, and typically looks as follows:
//..
// typedef struct {
// unsigned int p_type; // entry type
// UintPtr p_offset; // file offset
// unsigned int p_vaddr; // virtual address
// unsigned int p_memsz; // memory size
// } u_ElfProgramHeader;
//..
// An object file segment contains one or more sections. The string table
// provides the names of the various sections corresponding to the integral
// 'sh_name'. An elf file will typically contain sections such as '.text',
// '.data', '.bss' etc.
//..
// typedef struct {
// unsigned int sh_name; // section name
// unsigned int sh_type; // SHT_...
// UintPtr sh_offset; // file offset
// unsigned int sh_size; // section size
// } u_ElfSectionHeader;
//
// typedef struct
// {
// unsigned int st_name; // Symbol name (string tbl index)
// UintPtr st_value; // Symbol value
// unsigned int st_size; // Symbol size
// unsigned char st_info; // Symbol type and binding
// } u_ElfSymbol;
//..
// ----------------------------------------------------------------------------
// The above definitions describe the data within one file. However, if the
// executable is dynamically linked, that usually being the case, multiple
// files must be traversed. Unfortunately, no one strategy for traversing the
// files works for more than one platform -- so for the 3 platform currently
// supported, Solaris, Linux, and HPUX, we have a 3 custom strategies.
//
// Solaris:
// ----------------------------------------------------------------------------
//
// The link_map is a node in a chain, each representing a loaded object.
//..
// struct link_map {
// unsigned long l_addr; // address at which object is
// // mapped
// char *l_name; // full name of loaded object
// u_ElfDynamic *l_ld; // dynamic structure of object
// Link_map *l_next; // next link object
// };
//
// struct r_debug {
// link_map *r_map; // address of link_map
// };
//
// typedef struct {
// int d_tag; // how to interpret value
// union {
// // Note other interpretations of this union are no used, so they
// // are omitted here.
//
// UintPtr d_ptr; // really a pointer of type 'r_debug *'
// } d_un;
// } u_ElfDynamic;
//
// Tag values
//
// #define DT_NULL 0 // last entry in list
// #define DT_DEBUG 21 // pointer to 'r_debug' structure
//..
// The '_DYNAMIC' symbol is the address of the beginning of an array of objects
// of type 'u_ElfDynamic', one of which contains a pointer to the
// 'r_debug' object, which contains a pointer to the linked list of 'link_map'
// objects, one of which exists for each executable or shared library.
//
// Linux:
// ----------------------------------------------------------------------------
//..
// int dl_iterate_phdr(int (*callback) (struct dl_phdr_info *info,
// size_t size,
// void *data),
// // Walk through the list of an application's shared objects and invoke
// // the specified 'callback' (taking the specified 'info' object of
// // the specified 'size' and specifying the user supplied 'data') using
// // the specified 'data' to be passed to 'callback'.
//
// struct dl_phdr_info
// {
// UintPtr dlpi_addr; // base address
// const char *dlpi_name; // lib name
// const u_ElfProgramHeader *dlpi_phdr; // array of program
// // headers
// short dlpi_phnum; // base address
// };
//..
// HPUX:
// ----------------------------------------------------------------------------
//..
// struct shl_descriptor {
// unsigned long tstart; // start address of the shared
// // library text segment
//
// unsigned long tend; // end address of the shared
// // library text segment
//
// char filename[MAXPATHLEN + 1];
// };
//
// int shl_get_r(int index, struct shl_descriptor *desc);
// // Load into the specified 'desc' information about the loaded library
// // at the specified 'index'. For libraries loaded implicitly (at
// // startup time), 'index' is the ordinal number of the library as it
// // appeared on the command line. Return 0 on success and a non-zero
// // value otherwise. Note that an 'index' value of 0 refers to the main
// // program itself and -1 refers to the dynamic loader.
//..
// ============================================================================
//
// // -----
// // DWARF
// // -----
//
// The information in ELF format only tells us:
//: o function names
//: o source file names, but only in the case of file-scope static functions,
//: and only the base names of those few source files.
//
// Line number information and full source file information, if available at
// all, is present in other formats. On Linux, that information is in the
// DWARF format.
//
// The DWARF document is at: http://www.dwarfstd.org/Download.php and various
// enums are provided in the file '/usr/include/dwarf.h'. Note that on the
// platform this was developed on, the include file was version 3, but the
// executables this was developed with was were DWARF version 4. Thus some
// symbols had to be added in the enum type
// 'StackTraceResolver_DwarfReader::Dwarf4Enums'.
//
// In general, the spec is 255 pages long and not very well organized. It
// sometimes only vaguely implies necessary assumptions, in other cases it
// utterly fails to mention things (see 'mysteryZero' below) or mentions things
// that do not actually occur in the binaries (see 'isStmt' below). In
// addition, it sometimes describes multiple ways to encode information, only
// one of which was encountered in the test cases, so we have had to code for
// multiple possibilities yet are only able to test one of them. Given this,
// we face a lot of uncertainty when decoding DWARF information. We are only
// reading DWARF information to get line numbers and source file names. ELF
// gives source file names, but only in the instance of static identifiers, and
// then gives only the base name, while DWARF gives the full path of all source
// file names.
//
// So the DWARF code was written on the assumption that we already have a
// pretty good stack trace based on ELF information, and if, while decoding
// DWARF information, we encounter something unexpected or strange, we should
// just abandon decoding the DWARF inforation (or decoding a subset of the
// DWARF information) and continue delivering the rest of the information we
// have. A core dump would be highly inappropriate. We use 'u_ASSERT_BAIL' to
// check things, which just returns a failure code if the check fails, and
// depending on 'u_TRACES', may print out a message and possibly exit.
// 'u_TRACES' will always be 0 in production, in which case 'u_ASSERT_BAIL'
// will just return -1 without printing any error messages or exiting.
//
// '/usr/include/dwarf.h' defines only 'enum' constant values, no 'class'es,
// 'struct's or 'union's. The organization of the data is described only by
// prose in the spec.
//..
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// The DWARF information is in 6 sections:
//
// .debug_abbrev: Contains sequences of enum's dictating how the
// information in the .debug_info section is to be
// interpreted
// .debug_aranges: Specifies addresses ranges, and for each range, the
// offset of the compilation unit for addresss within those
// ranges in the .debug_info section.
// .debug_info: Various information about the compilation unit,
// including the source file directory and name and the
// offset in the .debug_line section of the line number
// information. Also contains information about the
// address range to which the compilation unit applies.
// .debug_line: Line number and source file information.
// .debug_ranges: When one compilation unit (described in the .debug_info
// and .debug_abbrev sections) applies to multiple address
// ranges, they refer to a sequence of ranges in the
// .debug_ranges section. This section is not traversed
// unless 'u_DWARF_CHECK_ADDRESSES' is set.
// .debug_str Section where null-terminated strings are stored,
// referred to by offsets that reside in the .debug_info
// section that are the offset of the beginning of a
// string from the beginning of the .debug_str section.
//..
//
// // .debug_aranges
//
// We start with the .debug_aranges section, which contains address ranges to
// be compared with stack pointers. If a stack pointer matches a range, the
// range indicates an offset in the .debug_info section where the compilation
// unit's information is contained.
//
// // .debug_info
//
// The graphic "Figure 48" from the DWARF doc, page 188, in Appendix D.1, was
// particularly enlightening about how to read the description of a compilation
// unit in the .debug_info and .debug_abbrev sections. Things were illustrated
// there that had not been spelled out formally in this doc.
//
// The compilation unit section of the .debug_info starts out with a header
// that indicates the offset of the information in the .debug_abbrev section
// corresponding to the compilation unit.
//
// The .debug_abbrev section contains pairs of enums that indicate how the
// information in the .debug_info that follows the compilation unit header is
// to be interpreted. The .debug_abbrev information for the compile unit will
// start with a 'tag' which should be 'DW_TAG_compilation_unit' or
// 'DW_TAG_partial_unit', followed by a boolean byte to indicate whether the
// tag has any children. We are not interested in the children byte.
//
// Following the '(tag, hasChildren)' pair is a null-terminated sequence of
// '(attr, form)' pairs where the 'attr' is an enum of type 'DW_AT_*' and the
// form is an enum of the type 'DW_FORM_*'. There are many 'DW_AT_*'s defined,
// but only a few of them will appear in the compile unit section. The 'attr'
// specifies the attribute, which is the kind of information being stored, and
// the 'form' specifies the way in which the information is stored. For
// example, an 'attr' or 'DW_AT_name' indicates that the information is a
// string indicating the base name of the source file. In that case, the form
// can be of two types -- a 'DW_FORM_string', in which case the name is a null
// terminated string stored in the .debug_info section, or a 'DW_FORM_strp',
// which indicates the .debug_info section contains a section offset into
// the .debug_str section where the null terminated string resides.
//
// One piece of information we are interested in is the offset
// in .debug_line where our line number information and most of the file name
// information is located. This will be found where 'DW_AT_stmt_list == attr',
// and we use 'form' to interpret how to read that offset.
//
// // .debug_line
//
// The layout of the line number information is in changer 6.2 of the DWARF
// doc. In the .debug_line section at the specified offset is the information
// for the given compile unit. It begins with the header, which includes,
// among other things:
//: o A table of all directories that source files (including include files)
//: are in, though not including the directory where the compilation was
//: run (which was in the .debug_info section).
//: o A table of all source files, and what directories they're in, (but not
//: including the .cpp file that was compiled, which was in the .debug_info
//: section).
//: o Initialization of some variables, including, among others:
//: 1 'lineBase'
//: 2 'lineRange'
//: 3 'opcodeBase'
//
// The line number information header is followed by unsigned byte opcodes in a
// program described in section 6.2.5 of the DWARF doc. The opcodes describe a
// state machine, that always has
//: o A current line number, which may increase or decrease.
//: o A current address, which always increases.
//: o A current source file name.
// If '1 <= opcode < opcodeBase', 'opcode' is one of the 'DW_LNS_*' identifiers
// described in 'dwarf.h', and it's meaning and what arguments it has is
// described in the DWARF doc. If 'opcode >= opcodeBase', then it will modify
// the value of the current line number and the current address in a complex
// formula described in the doc (and in the code).
//
// If '0 == opcode', it is followed by an extended opcode of the form
// 'DW_LNE_*' defined in dwarf.h and in the DWARF doc. Often the 0 is followed
// by a 5 or a 9 which has no meaning and is to be skipped (and which is not
// described in the spec).
//
// Once the address is greater than the address from the stack trace, then the
// current line number is the line number to be reported for the stack frame,
// and the current file name is the source file name to be reported.
//
// // Subset of DWARF Doc to Read to Parse DWARF for g++
//
// The DWARF 4 doc is 311 pages wrong. A key part of tackling this task was
// determining the subset of it necessary to deliver line number and source
// file name information.
//
// To understand how to find the compilation unit based on the stack address
// from the .debug_aranges section, read chapter 6.1.2, which is not very long.
// The .debug_aranges section will tell us the offset of the compile unit
// information in the .debug_info section.
//
// To understand how to read the compilation unit, one must gather information
// from several parts of the doc. The compilation unit will tell us 3 things:
//: o The directory in which the compilation was run.
//: o The source file that was compiled. Note that if the address was in a
//: function in an include file (an inline called out-of-line, or a template
//: function), then this will not be the right source file name.
//: o The offset into the .debug_line section where the line number information
//: for the compile unit resides.
// The compilation unit information will begin with the compile unit header,
// which is described in chapter 7.5.1.1, which is not very long. This header
// will tell us the offset of the information in the .debug_abbrev section that
// we will want to read together with the .debug_info section. Figure 48
// explains how the .debug_info and .debug_abbrev sections are read together to
// describe a compilation unit. This figure mentions a few things not
// mentioned in the prose in other parts of the doc. Chapter 3.1.1 explains
// some of how to parse the .debug_info information, explaining which 'DW_AT_*'
// identifiers will be encountered while parsing a compile unit. Note that
// since we don't want to parse information about types or variables, the
// number of 'DW_AT_*' id's we will have to understand is a very small subset
// of the total number described in 'dwarf.h'.
//
// Once we get to the line number information in .debug_line, we simply follow
// the directions in chapter 6.2, which must be read in its entirety, but it's
// only about 15 pages. The .debug_line entry begins with a header
// described in 6.2.4.
//
// // Clang Support For DWARF
//
// Doing line number information with DWARF on Linux using the clang compiler
// is problematic. There are two ways the DWARF information can tell you
// which compile unit an address is in -- either in the .debug_aranges section,
// or in address information in the compile unit itself. The clang compiler
// produces no .debug_aranges, and does not put the address information into
// the compile unit information. gdb is able to function anyway, examination of
// the gdb code determined that they were building huge datastructure in RAM
// based on the voluminous .debug_line information, which we don't want to do
// because in a large 32-bit executable we would exhaust the address space. We
// also decided that, for the time being, clang is not a very important
// platform for us. It might be possible to support clang by traversing all
// in the .debug_line information and resolving all addresses at once, but this
// might be very slow.
//
// // Proposed Clang Support
//
// A proposed way to provide clang support without having to use large amounts
// of memory, which has not been coded, would be to traverse all the compile
// units in the .debug_info section, and for each one go to its corresponding
// section in the .debug_line inforation, then parse the .debug line
// information in such a way to determine which ranges of addresses are
// described, and for each range, use the STL 'lower_bound' function to
// determine which of the stack addresses, if any, apply to that range. If
// any do apply, assign the compile unit offset of the compile unit to those
// frame records. Then go back in a later pass and use the existing Linux
// code to traverse those compile units and line number information.
// ============================================================================
// Debugging trace macros: 'eprintf' and 'zprintf'
// ============================================================================
#undef u_TRACES
#define u_TRACES 0 // 0 == debugging traces off, eprintf and zprint do nothing
// 1 == debugging traces on, eprintf is like zprintf
// 2 == debugging traces on, eprintf exits
// If the .debug_aranges section is present, the code guarded by
// '#ifdef u_DWARF_CHECK_ADDRESSES' is not necessary. But plan to eventually
// port to a Solaris platform that uses DWARF, and we don't know if the
// .debug_aranges section will be present there, so keep this already tested
// and debugged code around as it may become useful.
#undef u_DWARF_CHECK_ADDRESSES
#define u_DWARF_CHECK_ADDRESSES 0
// zprintf: For non-error debug traces. 0 == u_TRACES: 0: null function
// 0 < u_TRACES: : like printf
// eprintf: Called when errors occur in data.
// 0 == u_TRACES: null function
// 1 == u_TRACES: like printf
// 2 == u_TRACES: printf, then exit 1
// u_ASSERT_BAIL(expr) gentle assert.
// 0 == TRACES: if !(expr) return -1;
// 0 < TRACES: if !(expr) message & return -1
// // 'u_ASSERT_BAIL' is needed because we need asserts for the DWARF code,
// // but it's totally inappropriate to core dump if the DWARF data is
// // corrupt, because we can give a prety good stack trace without the
// // DWARF information, so if 'expr' fails, just quit the DWARF analysis
// // and continue showing the rest of the stack trace to the user.
//
// u_P(expr):
// 0 == u_TRACES: evaluates to 'false'.
// 0 < u_TRACES: output << #expr << ':' << (expr) then evaluate to false
// // P(expr) is to be used in u_ASSERT_BAIL, i.e.
// // 'u_ASSERT_BAIL(5 == x || P(x))' will, if (5 != x), print out the value
// // of x then print the assert message and return -1.
//
// u_PH(expr): like P(expr), except prints the value in hex.
#undef u_eprintf
#undef u_zprintf
#undef u_ASSERT_BAIL
#undef u_P
#undef u_PH
#if u_TRACES > 0
# include <stdio.h>
#define u_zprintf printf
static const char u_assertBailString[] = {
"Warning: assertion (%s) failed at line %d in function %s\n" };
#define u_ASSERT_BAIL(expr) do { \
if (!(expr)) { \
u_eprintf(u_assertBailString, #expr, __LINE__, rn); \
return -1; \
} \
} while (false)
// If the specified 'expr' evaluates to 'false', print a message and return
// -1. Note that if 'TRACES > 1' the 'eprintf' will exit 1.
#if 0 // comment until used, avoid "never called" warnings.
static bool u_warnPrint(const char *name, const void *value)
// Print out the specified 'value' and the specified 'name', which is the
// name of the expression have value 'value'. This function is intended
// only to be called by the macro 'PH'. Return 'false'.
{
u_zprintf("%s = %p\n", name, value);
return false;
}
#endif
#if defined(u_DWARF)
// 'P()' and 'PH()' are only used in u_ASSERT_BAIL in DWARF code, only define
// these functions in DWARF compiles, otherwise get unused messages.
static bool u_warnPrint(const char *name,
BloombergLP::bsls::Types::Uint64 value)
// Print out the specified 'value' and the specified 'name', which is the
// name of the expression have value 'value'. This function is intended
// only to be called by the macro 'P'. Return 'false'.
{
u_zprintf("%s = %llu\n", name, value);
return false;
}
static bool u_warnPrintHex(const char *expr,
BloombergLP::bsls::Types::Uint64 value)
// Print out the specified 'value' and the specified 'name', which is the
// name of the expression have value 'value'. This function is intended
// only to be called by the macro 'PH'. Return 'false'.
{
u_zprintf("%s = 0x%llx\n", expr, value);
return false;
}
#define u_P(expr) u_warnPrint( #expr, (expr))
// Print '<source code for 'expr'> = <value of expr' with the value in
// decimal and return 'false'.
#define u_PH(expr) u_warnPrintHex(#expr, (expr))
// Print '<source code for 'expr'> = <value of expr' with the value in
// hex and return 'false'.
#endif
#if 1 == u_TRACES
# define u_eprintf printf
#else
static
int u_eprintf(const char *format, ...)
// Do with the arguments, including the specified 'format', exactly what
// 'printf' would do, then exit.
{
va_list ap;
va_start(ap, format);
vprintf(format, ap);
va_end(ap);
exit(1); // If traces are enabled, there are so many traces that the
// only way to draw attention to an error is to exit. Core
// files would just waste disk space -- we can always put a
// breakpoint here and repeat.
return 0;
}
#endif
#else
static inline
int u_eprintf(const char *, ...)
// do nothing
{
return 0;
}
static inline
int u_zprintf(const char *, ...)
// do nothing
{
return 0;
}
#define u_ASSERT_BAIL(expr) do { \
if (!(expr)) { \
return -1; \
} \
} while (false)
// If the specified 'expr' evaluates to 'false', return -1, otherwise do
// nothing.
#if defined(u_DWARF)
#define u_P(expr) (false)
// Ignore 'expr' and return 'false'.
#define u_PH(expr) (false)
// Ignore 'expr' and return 'false'.
#endif
#endif
#ifdef BSLS_ASSERT_SAFE_IS_ACTIVE
# define u_ASSERT_BAIL_SAFE(expr) u_ASSERT_BAIL(expr)
// Do u_ASSERT_BAIL
#else
# define u_ASSERT_BAIL_SAFE(expr)
// Do nothing.
#endif
namespace BloombergLP {
namespace {
namespace u {
static inline
long long ll(long long value)
// Coerce the specied 'value' to a long long.
{
return value;
}
static inline
long l(long value)
// Coerce the specified 'value' to a long.
{
return value;
}
template <class TYPE>
static TYPE approxAbs(TYPE x)
// Return approximately the absolute value of the specified 'x'.
{
BSLMF_ASSERT(static_cast<TYPE>(-1) < 0);
x = x < 0 ? -x : x;
x = x < 0 ? ~x : x; // in the case of, i.e., INT_MIN, ~x is close
// enough
BSLS_ASSERT_SAFE(0 <= x);
return x;
}
typedef bsls::Types::UintPtr UintPtr;
typedef bsls::Types::Uint64 Uint64;
typedef bdls::FilesystemUtil::Offset Offset;
#ifdef u_DWARF
typedef balst::StackTraceResolver_DwarfReader Reader;
typedef u::Reader::Section Section;
#endif
static const u::Offset maxOffset = LLONG_MAX;
static const u::UintPtr minusOne = ~static_cast<u::UintPtr>(0);
BSLMF_ASSERT(sizeof(u::Uint64) == sizeof(u::Offset));
BSLMF_ASSERT(sizeof(u::UintPtr) == sizeof(void *));
BSLMF_ASSERT(static_cast<u::Offset>(-1) < 0);
BSLMF_ASSERT(u::maxOffset > 0);
BSLMF_ASSERT(u::maxOffset > INT_MAX);
BSLMF_ASSERT(static_cast<u::Offset>(static_cast<u::Uint64>(u::maxOffset) + 1) <
0);
typedef balst::StackTraceResolverImpl<balst::ObjectFileFormat::Elf>
StackTraceResolver;
// --------------------------
// Run-Time Platform Switches
// --------------------------
#if defined(BSLS_PLATFORM_OS_LINUX)
enum { e_IS_LINUX = 1 };
#else
enum { e_IS_LINUX = 0 };
#endif
#if defined(BSLS_PLATFORM_IS_BIG_ENDIAN)
enum { e_IS_BIG_ENDIAN = 1,
e_IS_LITTLE_ENDIAN = 0 };
#elif defined(BSLS_PLATFORM_IS_LITTLE_ENDIAN)
enum { e_IS_BIG_ENDIAN = 0,
e_IS_LITTLE_ENDIAN = 1 };
#else
# error endianness is undefined
#endif
#ifdef u_DWARF
enum Dwarf4Enums {
// DWARF 4 flags not necessarily defined in our dwarf.h.
e_DW_TAG_type_unit = u::Reader::e_DW_TAG_type_unit,
e_DW_TAG_rvalue_reference_type = u::Reader::e_DW_TAG_rvalue_reference_type,
e_DW_TAG_template_alias = u::Reader::e_DW_TAG_template_alias,
e_DW_AT_signature = u::Reader::e_DW_AT_signature,
e_DW_AT_main_subprogram = u::Reader::e_DW_AT_main_subprogram,
e_DW_AT_data_bit_offset = u::Reader::e_DW_AT_data_bit_offset,
e_DW_AT_const_expr = u::Reader::e_DW_AT_const_expr,
e_DW_AT_enum_class = u::Reader::e_DW_AT_enum_class,
e_DW_AT_linkage_name = u::Reader::e_DW_AT_linkage_name,
e_DW_FORM_sec_offset = u::Reader::e_DW_FORM_sec_offset,
e_DW_FORM_exprloc = u::Reader::e_DW_FORM_exprloc,
e_DW_FORM_flag_present = u::Reader::e_DW_FORM_flag_present,
e_DW_FORM_ref_sig8 = u::Reader::e_DW_FORM_ref_sig8,
e_DW_LNE_set_discriminator = u::Reader::e_DW_LNE_set_discriminator
};
#endif
// ---------
// Constants
// ---------
enum { k_SCRATCH_BUF_LEN = 32 * 1024 - 64 };
// length in bytes of d_buffer_p, 32K minus a little so we don't waste a
// page
#ifdef u_DWARF
BSLMF_ASSERT(static_cast<int>(u::k_SCRATCH_BUF_LEN) ==
static_cast<int>(u::Reader::k_SCRATCH_BUF_LEN));
// u::Reader really needs the buffers passed to it to be at least
// 'u::Reader::k_SCRATCH_BUF_LEN' long.
#endif
// ---------------
// local Elf Types
// ---------------
#undef u_SPLICE
#ifdef BSLS_PLATFORM_CPU_64_BIT
# define u_SPLICE(suffix) Elf64_ ## suffix
#else
# define u_SPLICE(suffix) Elf32_ ## suffix
#endif
// The following types are part of the ELF standard, and describe structs that
// occur in the executable file / shared libraries.
typedef u_SPLICE(Dyn) ElfDynamic; // The expression '&_DYNAMIC' is a
// 'void *' pointer to a an array of
// 'struct's of this type, used to
// find the link map on Solaris.
typedef u_SPLICE(Ehdr) ElfHeader; // The elf header is a standard
// header at the start of any ELF
// file
typedef u_SPLICE(Phdr) ElfProgramHeader; // Program headers are obtained from
// the link map. We use them to
// find code segments.
typedef u_SPLICE(Shdr) ElfSectionHeader; // Section headers are located from
// the U::ElfHeader, they tell us
// where the sections containing
// symbols and strings are
typedef u_SPLICE(Sym) ElfSymbol; // Describes one symbol in the
// symbol table.
#undef u_SPLICE
// --------
// FrameRec
// --------
class FrameRec {
// A struct consisting of the things we want stored associated with a given
// frame that will not be stored in the 'StackTraceFrame' itself. We put
// these into a vector and sort them by address so that later we can do
// O(log n) lookup of frames by address. (The code was previously always
// doing an exhaustive search of all the addresses).
// DATA
const void *d_address; // == 'd_frame_p->address()'
balst::StackTraceFrame *d_frame_p; // held, not owned
#ifdef u_DWARF
u::Offset d_compileUnitOffset;
u::Offset d_lineNumberOffset;
bsl::string d_compileUnitDir;
bsl::string d_compileUnitFileName;
#endif
int d_index;
bool d_isSymbolResolved;
public:
BSLMF_NESTED_TRAIT_DECLARATION(u::FrameRec, bslma::UsesBslmaAllocator);
// CREATORS
FrameRec(const void *address,
balst::StackTraceFrame *stackTraceFrame,
int index,
bslma::Allocator *allocator);
// Create a 'u::FrameRec' referring to the specified 'address' and the
// specified 'framePtr'.
FrameRec(const u::FrameRec& original,
bslma::Allocator *allocator);
// Create a 'u::FrameRec' that uses the specified 'allocator' and is a
// copy of the specified 'original'.
// ~u::FrameRec() = default;
// MANIPULATORS
// inline operator=(const u::FrameRec&) = default;
void setAddress(const void *value);
// Set tthe 'address' field to the specified 'value'.
void setAddress(u::UintPtr value);
// Set tthe 'address' field to the specified 'value'.
#ifdef u_DWARF
void setCompileUnitDir(const bsl::string& value);
// Set the compile unit directory to the specified 'value'.
void setCompileUnitFileName(const bsl::string& value);
// Set the compile unit file name to the specified 'value'.
void setCompileUnitOffset(const u::Offset value);
// Set tthe compilation unit offset field to the specified 'value'.
void setLineNumberOffset(u::Offset value);
// Set tthe line number offset field to the specified 'value'.
#endif
void setSymbolResolved();
// Set this frame as being done.
// ACCESSORS
bool operator<(const u::FrameRec& rhs) const;
// Return 'true' if the address field of this object is less than the
// address field of 'rhs'.
const void *address() const;
// Return the 'address' field from this object.
#ifdef u_DWARF
const bsl::string& compileUnitDir() const;
// Return the compile unit directory name.
const bsl::string& compileUnitFileName() const;
// Return the compile unit file name.
u::Offset compileUnitOffset() const;
// Return the compile unit offset field.
u::Offset lineNumberOffset() const;
// Return the line number offset field.
#endif
balst::StackTraceFrame& frame() const;
// Return a reference to the modifiable 'frame' referenced by this
// object. Note that though this is a 'const' method, modifiable
// access to the frame is provided.
int index() const;
// Return the index of the frame in the stack trace.
bool isSymbolResolved() const;
// Return 'true' if this frame is done and 'false' otherwise.
};
// --------------
// class FrameRec
// --------------
// CREATORS
FrameRec::FrameRec(const void *address,
balst::StackTraceFrame *stackTraceFrame,
int index,
bslma::Allocator *allocator)
: d_address(address)
, d_frame_p(stackTraceFrame)
#ifdef u_DWARF
, d_compileUnitOffset(u::maxOffset)
, d_lineNumberOffset( u::maxOffset)
, d_compileUnitDir(allocator)
, d_compileUnitFileName(allocator)
#endif
, d_index(index)
, d_isSymbolResolved(false)
{
(void) allocator; // in case not DWARF
}
FrameRec::FrameRec(const FrameRec& original,
bslma::Allocator *allocator)
: d_address( original.d_address)
, d_frame_p( original.d_frame_p)
#ifdef u_DWARF
, d_compileUnitOffset( original.d_compileUnitOffset)
, d_lineNumberOffset( original.d_lineNumberOffset)
, d_compileUnitDir( original.d_compileUnitDir, allocator)
, d_compileUnitFileName(original.d_compileUnitFileName, allocator)
#endif
, d_index( original.d_index)
, d_isSymbolResolved( original.d_isSymbolResolved)
{
(void) allocator; // in case not DWARF
}
// MANIPULATORS
inline
void FrameRec::setAddress(const void *value)
{
d_address = value;
}
inline
void FrameRec::setAddress(u::UintPtr value)
{
d_address = reinterpret_cast<const void *>(value);
}
#ifdef u_DWARF
inline
void FrameRec::setCompileUnitDir(const bsl::string& value)
{
d_compileUnitDir = value;
}
inline
void FrameRec::setCompileUnitFileName(const bsl::string& value)
{
d_compileUnitFileName = value;
}
inline
void FrameRec::setCompileUnitOffset(const u::Offset value)
{
d_compileUnitOffset = value;
}
inline
void FrameRec::setLineNumberOffset(u::Offset value)
{
d_lineNumberOffset = value;
}
#endif
inline
void FrameRec::setSymbolResolved()
{
d_isSymbolResolved = true;
}
// ACCESSORS
inline
bool FrameRec::operator<(const FrameRec& rhs) const
{
return d_address < rhs.d_address;
}
inline
const void *FrameRec::address() const
{
return d_address;
}
#if u_DWARF
inline
const bsl::string& FrameRec::compileUnitDir() const
{
return d_compileUnitDir;
}
inline
const bsl::string& FrameRec::compileUnitFileName() const
{
return d_compileUnitFileName;
}
inline
u::Offset FrameRec::compileUnitOffset() const
{
return d_compileUnitOffset;
}
inline
u::Offset FrameRec::lineNumberOffset() const
{
return d_lineNumberOffset;
}
#endif
inline
balst::StackTraceFrame& FrameRec::frame() const
{
return *d_frame_p;
}
inline
int FrameRec::index() const
{
return d_index;
}
inline
bool FrameRec::isSymbolResolved() const
{
return d_isSymbolResolved;
}
typedef bsl::vector<u::FrameRec> FrameRecVec; // Vector of 'u::FrameRec's.
typedef u::FrameRecVec::iterator FrameRecVecIt; // Iterator of
// 'u::FrameRecVec'.
// ============
// AddressRange
// ============
struct AddressRange {
// This 'struct' specifies a range of addresses over
// '[ d_address, d_address + d_size )'.
u::UintPtr d_address;
u::UintPtr d_size;
// ACCESSORS
bool contains(const void *address) const;
// Return 'true' if this address range contains the specified 'address'
// and 'false' otherwise.
bool contains(u::UintPtr address) const;
// Return 'true' if this address range contains the specified 'address'
// and 'false' otherwise.
bool overlaps(const AddressRange& other) const;
// Return 'true' if this address range overlaps the specified
// u_AddressRange 'other' and 'false' otherwise. Note that if the
// boundaries of the addresses ranges merely 'touch', that does not
// count as an overlap.
};
// ------------
// AddressRange
// ------------
// ACCESSORS
bool u::AddressRange::contains(const void *address) const
{
u::UintPtr a = reinterpret_cast<u::UintPtr>(address);
return d_address <= a && a < d_address + d_size;
}
bool u::AddressRange::contains(u::UintPtr address) const
{
return d_address <= address && address < d_address + d_size;
}
bool u::AddressRange::overlaps(const AddressRange& other) const
{
return d_address <= other.d_address
? d_address + d_size > other.d_address
: other.d_address + other.d_size > d_address;
}
class FreeGuard {
// This 'class' will manage a buffer, which was allocated by 'malloc' and
// is returned by '__cxa_demangle'.
// DATA
char *d_buffer;
public:
// CREATORS
explicit
FreeGuard(char *buffer)
: d_buffer(buffer)
// Create a 'FreeGuard' object that manages the specified 'buffer'.
{}
~FreeGuard()
// If 'd_buffer' is non-null, free it.
{
if (d_buffer) {
::free(d_buffer);
}
}
};
// ---------------------------------------
// free functions in the unnamed namespace
// ---------------------------------------
static int cleanupString(bsl::string *str, bslma::Allocator *alloc)
// Eliminate all instances of "/./" from the specified '*str', and also as
// many instances of "/../" as possible. Do not resolve symlinks. Use the
// specified 'alloc' for memory allocation of temporaries. Return 0 unless
// "*str" does not represent an acceptable full path for a source file, and
// a non-zero value otherwise.
{
static const char rn[] = { "u::cleanupString:" };
const bsl::size_t npos = bsl::string::npos;
if (str->empty() || '/' != (*str)[0] ||
!bdls::FilesystemUtil::exists(*str)) {
return -1; // RETURN
}
// First eliminate all "/./" sequences.
bsl::size_t pos;
while (npos != (pos = str->find("/./"))) {
str->erase(pos, 2);
}
bsl::string preDir(alloc);
// Next, eliminate as many instances of "/../" as possible.
while (npos != (pos = str->find("/../"))) {
// u_zprintf("%s found '/../' in %s\n", rn, str->c_str());
u_ASSERT_BAIL(pos >= 1);
// Abandon cleanup unless the path prior to '/../' is not a symlink and
// is a directory. Note that if the path is "/a/b/c/../d.cpp" and "c"
// is a symlink to "/e/f", the correct cleanup would be "/e/d.cpp" and
// "/a/b/d.cpp" would be completely wrong. By default, stack traces
// only display the leaf name of the path, so it's not worth the effort
// to dereference symlinks, just clean up in the obvious case when
// we're sure we're not introducing inaccuracies.
preDir.assign(str->begin(), str->begin() + pos);
struct stat s;
int rc = ::lstat(preDir.c_str(), &s);
if (0 != rc || (s.st_mode & S_IFLNK) || !S_ISDIR(s.st_mode)) {
// It's possible the file is not there or is not a directory, which
// could mean that we are not running on the machine the code was
// compiled on, which will frequently happen and is not worth
// returning an error code over.
u_TRACES && u_zprintf(
"%s difficulty cleaning up, but not an error\n", rn);
return 0; // RETURN
}
bsl::size_t rpos = str->rfind('/', pos - 1);
u_ASSERT_BAIL(npos != rpos && ".. below root directory");
u_ASSERT_BAIL(rpos < pos - 1 && '/' == (*str)[rpos]);
str->erase(rpos, pos + 3 - rpos);
// u_zprintf("%s optimized to %s\n", rn, str->c_str());
}
return 0;
}
#ifdef u_DWARF
static int dumpBinary(u::Reader *reader, int numRows)
// Dump out the specified 'numRows' of 16 byte rows of the binary about to
// be read by the specified 'reader'. Note that this function is called
// for debugging when we encounter unexpected things in the binary.
{
static const char rn[] = { "u::dumpBinary:" }; (void) rn;
if (0 == u_TRACES) {
return -1; // RETURN
}
int rc;
u::Offset o = reader->offset();
for (int ii = 0; ii < numRows; ++ii) {
for (int jj = 0; jj < 16; ++jj) {
unsigned char uc;
rc = reader->readValue(&uc);
if (0 != rc) {
// We probably just bumped into the end of the section.
// Recover reasonably well.
rc = reader->skipTo(o);
u_ASSERT_BAIL(0 == rc);
return -1; // RETURN
}
u_zprintf("%s%x", (jj ? " " : ""), uc);
}
u_zprintf("\n");
}
rc = reader->skipTo(o);
u_ASSERT_BAIL(0 == rc);
return 0;
}
#endif
static
int checkElfHeader(u::ElfHeader *elfHeader)
// Return 0 if the magic numbers in the specified 'elfHeader' are correct
// and a non-zero value otherwise.
{
if (ELFMAG0 != elfHeader->e_ident[EI_MAG0]
|| ELFMAG1 != elfHeader->e_ident[EI_MAG1]
|| ELFMAG2 != elfHeader->e_ident[EI_MAG2]
|| ELFMAG3 != elfHeader->e_ident[EI_MAG3]) {
return -1; // RETURN
}
// this code can only read native-endian ELF files
if ((u::e_IS_BIG_ENDIAN ? ELFDATA2MSB : ELFDATA2LSB) !=
elfHeader->e_ident[EI_DATA]) {
return -1; // RETURN
}
// this code can only read native-sized ELF files
if ((sizeof(void *) == 4 ? ELFCLASS32 : ELFCLASS64) !=
elfHeader->e_ident[EI_CLASS]) {
return -1; // RETURN
}
return 0;
}
} // close namespace u
} // close unnamed namespace
// --------------------------------
// u::StackTraceResolver::HiddenRec
// --------------------------------
struct u::StackTraceResolver::HiddenRec {
// This 'struct' contains information for the stack trace resolver that is
// hidden from the .h file. Thus, we avoid having to expose
// balst_stacktraceresolver_dwarfreader.h' in the .h, and we can use types
// that are locally defined in this imp file.
// DATA
StackTraceResolver_FileHelper
*d_helper_p; // file helper associated with current
// segment
StackTrace *d_stackTrace_p; // the stack trace we are resolving
u::AddressRange d_addressRange; // address range of the current segment
u::FrameRecVec d_frameRecs; // Vector of address frame pairs for
// fast lookup of addresses. Not local
// to current segment -- initialized
// once per resolve, and sorted by
// address.
u::FrameRecVecIt // This begin, end pair indicates the
d_frameRecsBegin; // range of frame records that pertain
u::FrameRecVecIt // to the current segment at a given
d_frameRecsEnd; // time.
u::UintPtr d_adjustment; // adjustment between addresses
// expressed in object file and actual
// addresses in memory for current
// segment
u::Offset d_symTableOffset; // symbol table section (symbol table
u::Offset d_symTableSize; // does not contain symbol names, just
// offsets into string table) from the
// beginning of the executable or
// library file
u::Offset d_stringTableOffset;// string table offset from the
u::Offset d_stringTableSize; // beginning of the file
#ifdef u_DWARF
u::Section d_abbrevSec; // .debug_abbrev section
u::Reader d_abbrevReader; // reader for that section
u::Section d_arangesSec; // .debug_aranges section
u::Reader d_arangesReader; // reader for that section
u::Section d_infoSec; // .debug_info section
u::Reader d_infoReader; // reader for that section
u::Section d_lineSec; // .debug_line section
u::Reader d_lineReader; // reader for that section
u::Section d_rangesSec; // .debug_ranges section
u::Reader d_rangesReader; // reader for that section
u::Section d_strSec; // .debug_str section
u::Reader d_strReader; // reader for that section
#endif
u::Offset d_libraryFileSize; // size of the current library or
// executable file
char *d_scratchBufA_p; // crratch buffer A (from resolver)
char *d_scratchBufB_p; // scratch buffer B (from resolver)
#ifdef u_DWARF
char *d_scratchBufC_p; // scratch buffer C (from resolver)
char *d_scratchBufD_p; // scratch buffer D (from resolver)
#endif
int d_numTotalUnmatched; // Total number of unmatched frames
// remaining in this resolve.
bool d_isMainExecutable; // 'true' if in main executable
// segment, as opposed to a shared
// library
bslma::Allocator
*d_allocator_p; // The resolver's heap bypass
// allocator.
private:
// NOT IMPLEMENTED
HiddenRec(const HiddenRec&);
HiddenRec& operator=(const HiddenRec&);
public:
// CREATORS
explicit
HiddenRec(u::StackTraceResolver *resolver);
// Create this 'Seg' object, initialize 'd_numFrames' to 'numFrames',
// and initialize all other fields to 0.
// MANIPULATORS
#ifdef u_DWARF
# if u_DWARF_CHECK_ADDRESSES
int dwarfCheckRanges(bool *isMatch,
u::UintPtr addressToMatch,
u::UintPtr baseAddress,
u::Offset offset);
// Read a ranges section and determine if an address matches.
# endif
int dwarfReadAll();
// Read the DWARF information.
int dwarfReadAranges();
// Read the .debug_aranges section. Return the number of frames
// matched.
int dwarfReadCompileOrPartialUnit(u::FrameRec *frameRec,
bool *addressMatched);
// Read a compile or partial unit for the given 'frameRec', assuming
// that 'd_infoReader' is positioned right after the tag & children
// info, and 'd_abbrevReader' is positioned right after the tag index,
// and at the first attribute. Set the specified '*addressMatched', to
// 'true' if the section matched the frame record and 'false'
// otherwise, except if 'u_CHECK_ADDRESSES' is 'false', in which case
// '*addressMatched' is always to be set to 'true'.
int dwarfReadDebugInfo();
// Read the .debug_info and .debug_abbrev sections.
int dwarfReadDebugInfoFrameRec(u::FrameRec *frameRec);
// Read the dwarf info for a single compilation unit for a single
// frame. Return
//..
//: o rc < 0: failure
//: o rc == 0: successfully parsed, but no match
//: o rc == 1: successfully parsed, matched address & line number info
//..
int dwarfReadDebugLine();
// Read the .debug_line section.
int dwarfReadDebugLineFrameRec(u::FrameRec *frameRec);
// Read the .debug_line section pertaining to the specified
// '*frameRec', and populate the source file name and line number
// information.
#endif
void reset();
// Zero numerous fields.
};
// CREATORS
u::StackTraceResolver::HiddenRec::HiddenRec(u::StackTraceResolver *resolver)
: d_helper_p(0)
, d_stackTrace_p(resolver->d_stackTrace_p)
, d_frameRecs(&resolver->d_hbpAlloc)
, d_frameRecsBegin()
, d_frameRecsEnd()
, d_adjustment(0)
, d_symTableOffset(0)
, d_symTableSize(0)
, d_stringTableOffset(0)
, d_stringTableSize(0)
#ifdef u_DWARF
, d_abbrevSec()
, d_arangesSec()
, d_infoSec()
, d_lineSec()
, d_rangesSec()
#endif
, d_scratchBufA_p(resolver->d_scratchBufA_p)
, d_scratchBufB_p(resolver->d_scratchBufB_p)
#ifdef u_DWARF
, d_scratchBufC_p(resolver->d_scratchBufC_p)
, d_scratchBufD_p(resolver->d_scratchBufD_p)
#endif
, d_numTotalUnmatched(resolver->d_stackTrace_p->length())
, d_isMainExecutable(0)
, d_allocator_p(&resolver->d_hbpAlloc)
{
d_frameRecs.reserve(d_numTotalUnmatched);
for (int ii = 0; ii < d_numTotalUnmatched; ++ii) {
balst::StackTraceFrame& frame = (*resolver->d_stackTrace_p)[ii];
d_frameRecs.push_back(u::FrameRec(frame.address(),
&frame,
ii,
&resolver->d_hbpAlloc));
}
bsl::sort(d_frameRecs.begin(), d_frameRecs.end());
}
// MANIPULATORS
#ifdef u_DWARF
#if u_DWARF_CHECK_ADDRESSES
// This code has been tested and works. This is unnecessary if the
// .debug_aranges section pointed us at the right part of the .debug_info,
// but the clang compiler generates no .debug_aranges section, so we'll have
// to scan all the compile units and use this code to find which one
// matches on that platform.
int u::StackTraceResolver::HiddenRec::dwarfCheckRanges(
bool *isMatch,
u::UintPtr addressToMatch,
u::UintPtr baseAddress,
u::Offset offset)
{
static const char rn[] = { "HiddenRec::dwarfCheckRanges:" };
int rc;
*isMatch = false;
rc = d_rangesReader.skipTo(d_rangesSec.d_offset + offset);
u_ASSERT_BAIL(0 == rc);
bool firstTime = true;
while (true) {
u::UintPtr loAddress, hiAddress;
rc = d_rangesReader.readAddress(&loAddress);
u_ASSERT_BAIL(0 == rc && "read loAddress failed");
rc = d_rangesReader.readAddress(&hiAddress);
u_ASSERT_BAIL(0 == rc && "read hiAddress failed");
if (0 == loAddress && 0 == hiAddress) {
u_TRACES && u_zprintf("%s done - no match found\n", rn);
return 0; // RETURN
}
if (firstTime) {
firstTime = false;
const u::UintPtr baseIndicator =
static_cast<int>(sizeof(u::UintPtr)) ==
d_rangesReader.addressSize()
? u::minusOne
: 0xffffffffUL;
if (baseIndicator == loAddress) {
baseAddress = hiAddress;
}
else {
if (u::minusOne == baseAddress) {
baseAddress = d_adjustment;
}
u_TRACES && u_zprintf("%s base address not in .debug_ranges,"
" loAddress: %llx, baseAddress: 0x%llx\n",
rn, u::ll(loAddress), u::ll(baseAddress));
}
if (addressToMatch < baseAddress) {
u_TRACES && u_zprintf("%s address to match 0x%llx below base"
" address 0x%llx -- not a bug\n",
rn, u::ll(addressToMatch), u::ll(baseAddress));
return 0; // RETURN
}
addressToMatch -= baseAddress;
if (baseIndicator == loAddress) {
continue;
}
}
u_ASSERT_BAIL_SAFE(loAddress <= hiAddress);
if (loAddress <= addressToMatch && addressToMatch < hiAddress) {
u_TRACES && u_zprintf("%s .debug_ranges matched address 0x%llx in"
" [0x%llx, 0x%llx)\n",
rn, u::ll(addressToMatch + baseAddress),
u::ll(loAddress + baseAddress),
u::ll(hiAddress + baseAddress));
*isMatch = true;
return 0; // RETURN
}
}
}
#endif
int u::StackTraceResolver::HiddenRec::dwarfReadAll()
{
static const char rn[] = { "HiddenRec::dwarfReadAll:" }; (void) rn;
u_TRACES && u_zprintf("%s starting\n", rn);
if (0 == d_infoSec.d_size || 0 == d_lineSec.d_size) {
u_TRACES && u_zprintf("%s Not enough information to find file names"
" or line numbers.\n", rn);
return -1; // RETURN
}
int rc;
if (d_arangesSec.d_size) {
rc = dwarfReadAranges(); // Get the locations of the compile unit info
if (rc < 0) {
u_TRACES && u_zprintf(".debug_aranges failed");
}
else if (0 == rc) {
u_TRACES && u_zprintf(".debug_aranges did not match anything");
}
}
rc = dwarfReadDebugInfo(); // Get the location of the line number info,
// from .debug_info.
u_ASSERT_BAIL(0 == rc && "dwarfReadDebugInfo failed");
rc = dwarfReadDebugLine(); // Get the line numbers, from .debug_line.
if (rc) {
u_TRACES && u_zprintf("%s .debug_line failed\n", rn);
return -1; // RETURN
}
return 0;
}
int u::StackTraceResolver::HiddenRec::dwarfReadAranges()
{
static const char rn[] = { "HiddenRec::dwarfReadAranges:" }; (void) rn;
// Buffer use: this function usee only scratch buf A.
int rc;
const u::FrameRecVecIt end = d_frameRecsEnd;
const int toMatch = static_cast<int>(end - d_frameRecsBegin);
BSLS_ASSERT(toMatch > 0); // otherwise we should not have been called
int matched = 0;
u_TRACES && u_zprintf("%s starting, toMatch=%d\n", rn, toMatch);
rc = d_arangesReader.init(d_helper_p, d_scratchBufA_p, d_arangesSec,
d_libraryFileSize);
u_ASSERT_BAIL(0 == rc);
u::AddressRange addressRange, prevRange = { 0, 0 }; (void) prevRange;
u::FrameRec dummyFrameRec(0, 0, 0, d_allocator_p);
while (!d_arangesReader.atEndOfSection()) {
u::Offset rangeLength;
int rc = d_arangesReader.readInitialLength(&rangeLength);
u_ASSERT_BAIL(0 == rc && "read initial length failed");
u::Offset endOffset = d_arangesReader.offset() + rangeLength;
// 'endOffset has already been checked to fit within the section.
unsigned short version;
rc = d_arangesReader.readValue(&version);
u_ASSERT_BAIL(0 == rc && "read version failed");
u_ASSERT_BAIL(2 == version || u_P(version));
u::Offset debugInfoOffset;
rc = d_arangesReader.readSectionOffset(&debugInfoOffset);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(0 <= debugInfoOffset || u_PH(debugInfoOffset));
u_ASSERT_BAIL( debugInfoOffset < d_infoSec.d_size ||
u_PH(debugInfoOffset));
rc = d_arangesReader.readAddressSize();
u_ASSERT_BAIL(0 == rc);
const bool isAddressSizeSizeofUintPtr =
sizeof(u::UintPtr) == d_arangesReader.addressSize();
// The meaning of the word 'segment' here is different from its meaning
// elsewhere in this file. Here the 'segment size' is the size of a
// segment on a segmented architecture processor. The 8086 and 80286
// were segmented architectures, and 'segmentSize' might have had some
// relevance there, but since the 80386 (ca 1992) x86 architectures
// have been able to access memory in a non-segmented manner.
// We don't expect this code to be used on any segmented architectures,
// in which case 'segmentSizeSize' will be 0 and the 'tuple's of
// '(segmentSize, address, and size)' will instead be 'pair's of
// '(address, size)' where 'sizeof(size) == sizeof(address)'.
unsigned char segmentSizeSize;
rc = d_arangesReader.readValue(&segmentSizeSize);
u_ASSERT_BAIL(0 == rc && "read segment size size failed");
u_ASSERT_BAIL(0 == segmentSizeSize);
// According to section 2.70 of the spec, the header is padded here
// to the point where 'd_addressReader.offset()' will be a multiple
// of the size of a tuple. Since '0 == segmentSize', the size of
// a tuple is '2 * d_arangesReader.addressSize()'.
// On Linux at least, this turns out to be wrong. It turns out that
// regardless of how 'd_arangesReader.offset()' is aligned, we are to
// skip 4 bytes here.
rc = d_arangesReader.skipTo(d_arangesReader.offset() + 4);
u_ASSERT_BAIL(0 == rc && "skip padding failed");
// u_TRACES && u_zprintf("%s Starting section %g pairs long.\n", rn,
// (double) (endOffset - d_arangesReader.offset()) /
// (2 * d_arangesReader.addressSize()));
bool foundZeroes = false;
while (d_arangesReader.offset() < endOffset) {
if (isAddressSizeSizeofUintPtr) {
rc = d_arangesReader.readValue(&addressRange);
}
else {
rc = d_arangesReader.readAddress(&addressRange.d_address);
rc |= d_arangesReader.readAddress(&addressRange.d_size);
}
u_ASSERT_BAIL(0 == rc);
if (0 == addressRange.d_address && 0 == addressRange.d_size) {
if (d_arangesReader.offset() != endOffset) {
u_eprintf("%s terminating 0's %s range end\n", rn,
d_arangesReader.offset() < endOffset ? "reached before"
: "overlap");
rc = d_arangesReader.skipTo(endOffset);
u_ASSERT_BAIL(0 == rc);
}
foundZeroes = true;
break;
}
addressRange.d_address += d_adjustment; // This was not
// mentioned in the
// spec.
if (!d_addressRange.contains(addressRange.d_address)
|| 0 == addressRange.d_size
|| !d_addressRange.contains(
addressRange.d_address + addressRange.d_size - 1)) {
// Sometimes the address ranges are just garbage.
u_TRACES && u_zprintf("Garbage address range (0x%lx, 0x%lx)\n",
u::l(addressRange.d_address), u::l(addressRange.d_size));
continue;
}
if (u_TRACES && prevRange.overlaps(addressRange)) {
u_eprintf("%s overlapping ranges (0x%lx, 0x%lx)"
" (0x%lx, 0x%lx)\n", rn,
u::l(prevRange.d_address), u::l(prevRange.d_size),
u::l(addressRange.d_address), u::l(addressRange.d_size));
}
prevRange = addressRange;
// u_TRACES && u_zprintf("%s range:[0x%lx, 0x%lx)\n",
// rn, u::l(addressRange.d_address),
// u::l(addressRange.d_size));
dummyFrameRec.setAddress(addressRange.d_address);
u::FrameRecVecIt begin =
bsl::lower_bound(d_frameRecsBegin, end, dummyFrameRec);
for (u::FrameRecVecIt it = begin; it < end &&
addressRange.contains(it->address()); ++it) {
const bool isRedundant =
u::maxOffset != it->compileUnitOffset();
u_TRACES && u_zprintf("%s%s range (0x%lx, 0x%lx) matches"
" frame %d, address: %p, offset 0x%llx\n",
rn, isRedundant ? " redundant" : "",
u::l(addressRange.d_address), u::l(addressRange.d_size),
it->index(),
it->address(), u::ll(debugInfoOffset));
if (isRedundant) {
continue;
}
it->setCompileUnitOffset(debugInfoOffset);
if (toMatch == ++matched) {
u_TRACES && u_zprintf(
"%s last frame in segment matched\n", rn);
d_arangesReader.disable();
return matched; // RETURN
}
}
}
u_ASSERT_BAIL(foundZeroes);
}
u_zprintf("%s failed to complete -- %d frames unmatched.\n",
rn, toMatch - matched);
d_arangesReader.disable();
return matched;
}
int u::StackTraceResolver::HiddenRec::dwarfReadCompileOrPartialUnit(
u::FrameRec *frameRec,
bool *addressMatched)
{
static const char rn[] = { "HiddenRec::dwarfReadCompileOrPartialUnit:" };
int rc;
enum ObtainedFlags {
k_OBTAINED_ADDRESS_MATCH = 0x1,
k_OBTAINED_DIR_NAME = 0x2,
k_OBTAINED_BASE_NAME = 0x4,
k_OBTAINED_LINE_OFFSET = 0x8,
k_OBTAINED_SOURCE_NAME = k_OBTAINED_DIR_NAME | k_OBTAINED_BASE_NAME,
k_OBTAINED_ALL = 0xf };
int obtained = u_DWARF_CHECK_ADDRESSES ? 0
: k_OBTAINED_ADDRESS_MATCH;
*addressMatched = false;
#if u_DWARF_CHECK_ADDRESSES
const u::UintPtr addressToMatch =
reinterpret_cast<u::UintPtr>(frameRec->address());
u::UintPtr loPtr = u::minusOne, hiPtr = 0;
#endif
const int index = frameRec->index(); (void) index;
bsl::string baseName(d_allocator_p), dirName(d_allocator_p);
dirName.reserve(200);
u::Offset lineNumberInfoOffset;
do {
unsigned int attr;
rc = d_abbrevReader.readULEB128(&attr);
u_ASSERT_BAIL(0 == rc);
unsigned int form;
rc = d_abbrevReader.readULEB128(&form);
u_ASSERT_BAIL(0 == rc);
if (0 == attr) {
u_ASSERT_BAIL(0 == form);
u_TRACES && u_zprintf("%s 0 0 encountered, section done\n", rn);
break;
}
u_TRACES && u_zprintf("%s %s %s\n", rn, u::Reader::stringForAt(attr),
u::Reader::stringForForm(form));
switch (attr) {
#if u_DWARF_CHECK_ADDRESSES
case DW_AT_low_pc: { // DWARF doc 3.1.1.1
u_ASSERT_BAIL(u::minusOne == loPtr);
rc = d_infoReader.readAddress(&loPtr, form);
u_ASSERT_BAIL(0 == rc);
if (DW_FORM_addr != form) {
// this was not in the doc
loPtr += d_adjustment;
}
u_TRACES && u_zprintf("%s loPtr: 0x%llx\n", rn, u::ll(loPtr));
if (0 != hiPtr) {
if (loPtr <= addressToMatch && addressToMatch < hiPtr) {
u_TRACES && u_zprintf("%s loHiMatch on lo\n", rn);
obtained |= k_OBTAINED_ADDRESS_MATCH;
}
else {
u_TRACES && u_zprintf("%s loHi failed to match on lo\n",
rn);
}
}
} break;
case DW_AT_high_pc: { // DWARF doc 3.1.1.1
u_ASSERT_BAIL(0 == hiPtr);
rc = d_infoReader.readAddress(&hiPtr, form);
u_ASSERT_BAIL(0 == rc);
if (DW_FORM_addr != form) {
// this was not in the doc, just guessing
hiPtr += u::minusOne != loPtr ? loPtr : d_adjustment;
}
u_TRACES && u_zprintf("%s hiPtr: 0x%llx\n", rn, u::ll(hiPtr));
if (u::minusOne != loPtr) {
if (loPtr <= addressToMatch && addressToMatch < hiPtr) {
u_TRACES && u_zprintf("%s loHiMatch on hi\n", rn);
obtained |= k_OBTAINED_ADDRESS_MATCH;
}
else {
u_TRACES && u_zprintf("%s loHi failed to match on hi\n",
rn);
}
}
} break;
case DW_AT_ranges: { // DWARF doc 3.1.1.1
u::Offset rangesOffset;
rc = d_infoReader.readOffsetFromForm(&rangesOffset, form);
u_ASSERT_BAIL(0 == rc && "trouble reading ranges offset");
u_ASSERT_BAIL(rangesOffset < d_rangesSec.d_size);
bool isMatch;
rc = dwarfCheckRanges(
&isMatch,
reinterpret_cast<u::UintPtr>(frameRec->address()),
loPtr,
rangesOffset);
u_ASSERT_BAIL(0 == rc && "dwarfCheckRanges failed");
if (isMatch) {
u_TRACES && u_zprintf("%s ranges match\n", rn);
obtained |= k_OBTAINED_ADDRESS_MATCH;
}
} break;
#endif
case DW_AT_name: { // DWARF doc 3.1.1.2
u_ASSERT_BAIL(0 == (obtained & k_OBTAINED_BASE_NAME));
u_ASSERT_BAIL(baseName.empty());
rc = d_infoReader.readStringFromForm(
&baseName, &d_strReader, form);
u_ASSERT_BAIL(0 == rc);
if (!baseName.empty()) {
u_TRACES && u_zprintf("%s baseName \"%s\" found\n",
rn, baseName.c_str());
obtained |= k_OBTAINED_BASE_NAME |
('/' == baseName.c_str()[0] ? k_OBTAINED_DIR_NAME
: 0);
}
} break;
case DW_AT_stmt_list: { // DWARF doc 3.1.1.4
u_ASSERT_BAIL(0 == (obtained & k_OBTAINED_LINE_OFFSET));
rc = d_infoReader.readOffsetFromForm(&lineNumberInfoOffset, form);
u_ASSERT_BAIL(0 == rc && "trouble reading line offset");
u_TRACES && u_zprintf("%s found line offset %lld\n",
rn, u::ll(lineNumberInfoOffset));
obtained |= k_OBTAINED_LINE_OFFSET;
} break;
case DW_AT_comp_dir: { // DWARF doc 3.1.1.6
rc = d_infoReader.readStringFromForm(&dirName, &d_strReader, form);
u_ASSERT_BAIL(0 == rc);
if (!dirName.empty()) {
if ('/' != dirName[dirName.length() - 1]) {
dirName += '/';
}
u_TRACES && u_zprintf("%s dirName \"%s\" found\n",
rn, dirName.c_str());
obtained |= k_OBTAINED_DIR_NAME;
}
} break;
#if 0 == u_DWARF_CHECK_ADDRESSES
case DW_AT_low_pc: // DWARF doc 3.1.1.1
case DW_AT_high_pc: // DWARF doc 3.1.1.1
case DW_AT_ranges: // DWARF doc 3.1.1.1
#endif
case DW_AT_language: // DWARF doc 3.1.1.3
case DW_AT_macro_info: // DWARF doc 3.1.1.5
case DW_AT_producer: // DWARF doc 3.1.1.7
case DW_AT_identifier_case: // DWARF doc 3.1.1.8
case DW_AT_base_types: // DWARF doc 3.1.1.9
case DW_AT_use_UTF8: // DWARF doc 3.1.1.10
case u::e_DW_AT_main_subprogram: // DWARF doc 3.1.1.11
case DW_AT_entry_pc: // not in doc, but
// crops up
case DW_AT_description:
case DW_AT_segment: {
rc = d_infoReader.skipForm(form);
u_ASSERT_BAIL((0 == rc && "problem skipping") || u_PH(attr) ||
u_PH(form));
} break;
default: {
u_ASSERT_BAIL((0 && "compile unit: unrecognized attribute")
|| u_PH(attr));
}
}
// If 'u_TRACES' is set, continue until we hit the terminating '0's to
// verify that our code is handling everything in compile units. If
// 'u_TRACES' is not set, quit once we have the info we want.
} while (u_TRACES || k_OBTAINED_ALL != obtained);
if (u_TRACES) {
u_zprintf("%s (attr, form) loop terminated, all%s obtained\n", rn,
(k_OBTAINED_ALL == obtained) ? "" : " not");
u_zprintf("%s base name %s, dir name %s, line # offset %s\n", rn,
!baseName.empty() ? "found" : "not found",
!dirName .empty() ? "found" : "not found",
(obtained | k_OBTAINED_LINE_OFFSET) ? "found" : "not found");
}
*addressMatched = !!(obtained & k_OBTAINED_ADDRESS_MATCH);
if (!*addressMatched) {
return 0; // RETURN
}
u_ASSERT_BAIL((k_OBTAINED_LINE_OFFSET & obtained) || u_P(index));
u_ASSERT_BAIL(!baseName.empty());
u_ASSERT_BAIL(!dirName.empty());
(void) u::cleanupString(&dirName, d_allocator_p);
frameRec->setCompileUnitDir( dirName);
frameRec->setCompileUnitFileName(baseName);
frameRec->setLineNumberOffset(lineNumberInfoOffset);
return 0;
}
int u::StackTraceResolver::HiddenRec::dwarfReadDebugInfo()
{
static const char rn[] = { "HiddenRec::dwarfDebugInfo:" }; (void) rn;
const u::FrameRecVecIt end = d_frameRecsEnd;
for (u::FrameRecVecIt it = d_frameRecsBegin, prev = end; it < end;
prev = it, ++it) {
// Because the 'u::FrameRec's are sorted by address, those referring to
// the same compilation unit are going to be adjacent.
if (end != prev && d_arangesSec.d_size &&
u::maxOffset != it->compileUnitOffset() &&
prev->compileUnitOffset() == it->compileUnitOffset()) {
u_TRACES && u_zprintf("%s frames %d and %d are from the same"
" compilation unit\n", rn,
prev->index(), it->index());
if (!it->frame().isSourceFileNameKnown()) {
// This is the name of the file that was compiled, which might
// not be the right file. If reading line number information
// is successful, it will be overwritten by the right file.
it->frame().setSourceFileName(prev->frame().sourceFileName());
}
it->setCompileUnitDir( prev->compileUnitDir());
it->setCompileUnitFileName( prev->compileUnitFileName());
it->setLineNumberOffset( prev->lineNumberOffset());
continue;
}
int rc = dwarfReadDebugInfoFrameRec(&*it);
if (0 != rc) {
// The fact that we failed on one doesn't mean we'll fail on the
// others -- keep going.
u_TRACES && u_zprintf("%s dwarfReadDebugInfoFrameRec failed on"
" frame %d\n", rn, it->index());
}
}
return 0;
}
int u::StackTraceResolver::HiddenRec::dwarfReadDebugInfoFrameRec(
u::FrameRec *frameRec)
{
static const char rn[] = { "HiddenRec::dwarfDebugInfoFrameRec:" };
(void) rn;
int rc;
const int index = frameRec->index(); (void) index;
u_ASSERT_BAIL(0 < d_infoSec .d_size);
u_ASSERT_BAIL(0 < d_abbrevSec.d_size);
u_ASSERT_BAIL(0 < d_rangesSec.d_size);
u_ASSERT_BAIL(0 < d_strSec .d_size);
u_TRACES && u_zprintf("%s reading frame %d, symbol: %s\n", rn,
index, frameRec->frame().symbolName().c_str());
rc = d_infoReader.init( d_helper_p, d_scratchBufA_p, d_infoSec,
d_libraryFileSize);
u_ASSERT_BAIL(0 == rc);
rc = d_abbrevReader.init(d_helper_p, d_scratchBufB_p, d_abbrevSec,
d_libraryFileSize);
u_ASSERT_BAIL(0 == rc);
rc = d_rangesReader.init(d_helper_p, d_scratchBufC_p, d_rangesSec,
d_libraryFileSize);
u_ASSERT_BAIL(0 == rc);
rc = d_strReader.init( d_helper_p, d_scratchBufD_p, d_strSec,
d_libraryFileSize);
u_ASSERT_BAIL(0 == rc);
bool addressMatched;
u::Offset nextCompileUnitOffset = d_infoSec.d_offset;
if (d_arangesSec.d_size && u::maxOffset != frameRec->compileUnitOffset()) {
nextCompileUnitOffset += frameRec->compileUnitOffset();
}
do {
rc = d_infoReader.skipTo(nextCompileUnitOffset);
u_ASSERT_BAIL(0 == rc && "skipTo failed");
{
u::Offset compileUnitLength;
rc = d_infoReader.readInitialLength(&compileUnitLength);
u_ASSERT_BAIL(0 == rc);
nextCompileUnitOffset = d_infoReader.offset() + compileUnitLength;
}
{
unsigned short version;
rc = d_infoReader.readValue(&version);
u_ASSERT_BAIL(0 == rc && "read version failed");
u_ASSERT_BAIL((2 <= version && version <= 4) || u_P(version));
}
// This is the compilation unit headers as outlined in 7.5.1.1
{
u::Offset abbrevOffset;
rc = d_infoReader.readSectionOffset(&abbrevOffset);
u_ASSERT_BAIL(0 == rc && "read abbrev offset failed");
rc = d_abbrevReader.skipTo(d_abbrevSec.d_offset + abbrevOffset);
u_ASSERT_BAIL(0 == rc);
}
rc = d_infoReader.readAddressSize();
u_ASSERT_BAIL(0 == rc && "read address size failed");
d_rangesReader.setAddressSize(d_infoReader.addressSize());
{
u::Offset readTagIdx;
// These tag indexes were barely, vaguely mentioned by the doc,
// with some implication that they'd be '1' before the first tag we
// encounter. If they turn out not to be '1' in production it's
// certainly not worth abandoning DWARF decoding over.
rc = d_infoReader.readULEB128(&readTagIdx);
u_ASSERT_BAIL(0 == rc);
(1 != readTagIdx && u_TRACES) && u_eprintf( // we don't care much
"%s strange .debug_info tag idx %llx\n",
rn, u::ll(readTagIdx));
rc = d_abbrevReader.readULEB128(&readTagIdx);
u_ASSERT_BAIL(0 == rc);
(1 != readTagIdx && u_TRACES) && u_eprintf( // we don't care much
"%s strange .debug_abbrev tag idx %llx\n",
rn, u::ll(readTagIdx));
}
unsigned int tag;
rc = d_abbrevReader.readULEB128(&tag);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(DW_TAG_compile_unit == tag ||
DW_TAG_partial_unit == tag || u_PH(tag));
BSLMF_ASSERT(0 == DW_CHILDREN_no && 1 == DW_CHILDREN_yes);
unsigned int hasChildren;
rc = d_abbrevReader.readULEB128(&hasChildren);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(hasChildren <= 1); // other than that, we don't care
rc = dwarfReadCompileOrPartialUnit(frameRec, &addressMatched);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(!d_arangesSec.d_size || addressMatched);
} while (!d_arangesSec.d_size && !addressMatched &&
nextCompileUnitOffset < d_infoSec.d_offset + d_infoSec.d_size);
if (u_TRACES && !addressMatched) {
// Sometimes there's a frame, like the routine that calls 'main', for
// which no debug info is available. This will also happen if a file
// was compiled with the debug switch on. A disappointment, but not an
// error.
u_zprintf("%s failed to match address for symbol \"%s\"\n", rn,
frameRec->frame().symbolName().c_str());
}
d_infoReader. disable();
d_abbrevReader.disable();
d_rangesReader.disable();
d_strReader. disable();
return 0;
}
int u::StackTraceResolver::HiddenRec::dwarfReadDebugLine()
{
static const char rn[] = { "HiddenRec::dwarfDebugLine:" }; (void) rn;
const u::FrameRecVecIt end = d_frameRecsEnd;
for (u::FrameRecVecIt it = d_frameRecsBegin, prev = end; it < end;
prev = it, ++it) {
// Because the 'u::FrameRec's are sorted by address, those referring to
// the same address are going to be adjacent.
if (end != prev && prev->frame().address() == it->frame().address()) {
u_TRACES && u_zprintf("%s recursion: frames %d and %d are from"
" the same compilation unit\n", rn,
prev->index(), it->index());
// Recursion on the stack -- file name, line # info will be
// identical.
it->frame().setSourceFileName(prev->frame().sourceFileName());
it->frame().setLineNumber( prev->frame().lineNumber());
continue;
}
int rc = dwarfReadDebugLineFrameRec(&*it);
if (0 != rc) {
// The fact that we failed on one doesn't mean we'll fail on the
// others -- keep going.
u_TRACES && u_zprintf("%s dwarfReadDebugLineFrameRec failed on"
" frame %d\n", rn, it->index());
d_lineReader.disable();
}
}
return 0;
}
int u::StackTraceResolver::HiddenRec::dwarfReadDebugLineFrameRec(
u::FrameRec *frameRec)
{
static const char rn[] = { "HiddenRec:dwarfDebugLineFrameRec:" };
(void) rn;
int rc;
rc = d_lineReader.init(d_helper_p, d_scratchBufA_p, d_lineSec,
d_libraryFileSize);
u_ASSERT_BAIL(0 == rc);
u_TRACES && u_zprintf(
"%s Symbol: %s, frame %d, lineNumberOffset: 0x%llx\n",
rn, frameRec->frame().symbolName().c_str(),
frameRec->index(),
u::ll(frameRec->lineNumberOffset()));
if (u::maxOffset == frameRec->lineNumberOffset()) {
u_TRACES && u_zprintf("%s no line number information for frame %d,"
" cannot proceed\n", rn, frameRec->index());
return -1; // RETURN
}
rc = d_lineReader.skipTo(d_lineSec.d_offset +
frameRec->lineNumberOffset());
u_ASSERT_BAIL(0 == rc);
u::Offset debugLineLength;
rc = d_lineReader.readInitialLength(&debugLineLength);
u_ASSERT_BAIL(0 == rc);
rc = d_lineReader.setEndOffset(d_lineReader.offset() + debugLineLength);
u_ASSERT_BAIL(0 == rc);
u::Offset endOfHeader;
{
unsigned short version;
d_lineReader.readValue(&version);
u_ASSERT_BAIL(version >= 2 || u_P(version));
rc = d_lineReader.readSectionOffset(&endOfHeader);
u_ASSERT_BAIL(0 == rc);
u_TRACES && u_zprintf("%s version: %u, header len: %llu\n",
rn, version, u::ll(endOfHeader));
endOfHeader += d_lineReader.offset();
}
unsigned char minInstructionLength;
rc = d_lineReader.readValue(&minInstructionLength);
u_ASSERT_BAIL(0 == rc);
unsigned char maxOperationsPerInsruction;
rc = d_lineReader.readValue(&maxOperationsPerInsruction);
u_ASSERT_BAIL(0 == rc);
u_TRACES && u_zprintf("%s debugLineLength: %lld minInst: %u maxOp: %u\n",
rn, u::ll(debugLineLength),
minInstructionLength, maxOperationsPerInsruction);
0 && u::dumpBinary(&d_lineReader, 8);
#if 0
// In section 6.2.4.5, the DWARF docs (versions 2, 3 and 4) say this field
// should be there, but it's not in the binary.
{
unsigned char isStmt;
rc = d_lineReader.readValue(&isStmt);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(isStmt <= 1 || u_P(isStmt));
}
#endif
int lineBase;
{
signed char sc;
rc = d_lineReader.readValue(&sc);
u_ASSERT_BAIL(0 == rc);
lineBase = sc;
u_ASSERT_BAIL(lineBase <= 1);
}
int lineRange;
{
unsigned char uc;
rc = d_lineReader.readValue(&uc);
u_ASSERT_BAIL(0 == rc);
lineRange = uc;
u_ASSERT_BAIL(0 < lineRange);
}
unsigned char opcodeBase;
rc = d_lineReader.readValue(&opcodeBase);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(opcodeBase < 64); // Should be 10 or 13, maybe plus a few.
// 64 would be absurd.
bsl::vector<unsigned char> opcodeLengths(d_allocator_p); // # of ULEB128
// args for std
// opcodes
opcodeLengths.resize(opcodeBase, 0);
for (unsigned int ii = 1; ii < opcodeBase; ++ii) {
rc = d_lineReader.readValue(&opcodeLengths[ii]);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(opcodeLengths[ii] <= 10 || u_P(opcodeLengths[ii]));
}
{
int ii = 0; (void) ii;
#undef CHECK_ARG_COUNT
#define CHECK_ARG_COUNT(argCount, id) \
BSLS_ASSERT_SAFE(ii++ == id); \
u_ASSERT_BAIL(id >= opcodeBase || argCount == opcodeLengths[id]);
CHECK_ARG_COUNT(0, 0);
CHECK_ARG_COUNT(0, DW_LNS_copy);
CHECK_ARG_COUNT(1, DW_LNS_advance_pc);
CHECK_ARG_COUNT(1, DW_LNS_advance_line);
CHECK_ARG_COUNT(1, DW_LNS_set_file);
CHECK_ARG_COUNT(1, DW_LNS_set_column);
CHECK_ARG_COUNT(0, DW_LNS_negate_stmt);
CHECK_ARG_COUNT(0, DW_LNS_set_basic_block);
CHECK_ARG_COUNT(0, DW_LNS_const_add_pc);
CHECK_ARG_COUNT(1, DW_LNS_fixed_advance_pc);
CHECK_ARG_COUNT(0, DW_LNS_set_prologue_end);
CHECK_ARG_COUNT(0, DW_LNS_set_epilogue_begin);
CHECK_ARG_COUNT(1, DW_LNS_set_isa);
#undef CHECK_ARG_COUNT
}
const bsl::string nullString(d_allocator_p);
bsl::deque<bsl::string> dirPaths(d_allocator_p);
dirPaths.push_back(frameRec->compileUnitDir());
{
bsl::string dir(d_allocator_p);
for (;;) {
rc = d_lineReader.readString(&dir);
u_ASSERT_BAIL(0 == rc);
if (dir.empty()) {
break;
}
if ('/' != dir[dir.length() - 1]) {
dir += '/';
}
dirPaths.push_back(dir);
}
if (0 && u_TRACES) {
for (unsigned int ii = 0; ii < dirPaths.size(); ++ii) {
u_zprintf("%s dirPaths[%u]: %s\n",
rn, ii, dirPaths[ii].c_str());
}
}
}
bsl::deque<bsl::string> fileNames(d_allocator_p);
fileNames.push_back(frameRec->compileUnitFileName());
bsl::deque<unsigned int> dirIndexes(d_allocator_p);
dirIndexes.push_back(0);
for (unsigned int ii = 1;; ++ii) {
fileNames.push_back(nullString);
BSLS_ASSERT_SAFE(ii + 1 == fileNames.size());
rc = d_lineReader.readString(&fileNames[ii]);
u_ASSERT_BAIL(0 == rc);
if (fileNames[ii].empty()) {
break;
}
dirIndexes.push_back(-1);
BSLS_ASSERT_SAFE(dirIndexes.size() == fileNames.size());
rc = d_lineReader.readULEB128(&dirIndexes[ii]);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(dirIndexes[ii] < dirPaths.size());
if (0 && u_TRACES) {
u_zprintf("%s fileNames[%u]: %s dirIdx %lld:\n", rn, ii,
fileNames[ii].c_str(), u::ll(dirIndexes[ii]));
}
rc = d_lineReader.skipULEB128(); // mod time, ignored
u_ASSERT_BAIL(0 == rc);
rc = d_lineReader.skipULEB128(); // file length, ignored
u_ASSERT_BAIL(0 == rc);
}
u_ASSERT_BAIL(2 <= fileNames.size());
fileNames.resize(fileNames.size() - 1); // chomp empty entry
BSLS_ASSERT_SAFE(dirIndexes.size() == fileNames.size());
bsl::string definedFile(d_allocator_p); // in case a file is defined
unsigned int definedDirIndex; // by the DW_LNE_define_file
// cmd, in which case
// 'fileIdx' will be -1.
u::UintPtr addressToMatch =
reinterpret_cast<u::UintPtr>(frameRec->frame().address());
u::UintPtr address = 0, prevAddress = 0;
unsigned int opIndex = 0;
int fileIdx = 0;
int line = 1, prevLine = 1; // The spec says to begin line
// numbers at 0, but they come
// out right this way.
{
u::Offset toSkip = endOfHeader - d_lineReader.offset();
u_TRACES && u_zprintf("%s Symbol %s, %ld dirs, %ld files, skip: %lld,"
" addrToMatch: 0x%lx, minLength: %u, maxOps: %u"
" lineBase: %d, lineRange: %d, initLen: %lld,"
" opBase: %u\n",
rn, frameRec->frame().symbolName().c_str(), u::l(dirPaths.size()),
u::l(fileNames.size()), u::ll(toSkip), u::l(addressToMatch),
minInstructionLength, maxOperationsPerInsruction,
lineBase, lineRange, u::ll(debugLineLength),
opcodeBase);
u_ASSERT_BAIL(0 <= toSkip);
d_lineReader.skipBytes(toSkip);
}
0 && u::dumpBinary(&d_lineReader, 24);
bool nullPrevStatement = true;
bool endOfSequence = false;
int statementsSinceSetFile = 100;
for (; !d_lineReader.atEndOfSection(); ++statementsSinceSetFile) {
unsigned char opcode;
rc = d_lineReader.readValue(&opcode);
u_ASSERT_BAIL(0 == rc);
bool statement = false;
if (opcodeBase <= opcode) {
// special opcode // DWARF doc 6.2.5.1
const int opAdjust = opcode - opcodeBase;
const unsigned int opAdvance = opAdjust / lineRange;
const u::UintPtr addressAdvance = minInstructionLength *
((opIndex + opAdvance) / maxOperationsPerInsruction);
const int lineAdvance = lineBase + opAdjust % lineRange;
u_TRACES && u_zprintf("%s special opcode %u, opAdj: %u, opAdv: %u,"
" addrAdv: %lu, lineAdv: %d\n", rn,
opcode, opAdjust, opAdvance,
u::l(addressAdvance), lineAdvance);
statement = true;
address += addressAdvance;
opIndex = (opIndex + opAdvance) % maxOperationsPerInsruction;
line += lineAdvance;
u_ASSERT_BAIL(line >= 0);
}
else if (0 < opcode) {
// standard opcode // DWARF doc 6.2.5.2
if (opcode <= DW_LNS_set_isa) {
u_zprintf("%s standard opcode %s\n", rn,
u::Reader::stringForLNS(opcode));
}
else {
u_zprintf("%s unrecognized standard opcode %u\n", rn, opcode);
}
switch (opcode) {
case DW_LNS_copy: { // 1
statement = true;
} break;
case DW_LNS_advance_pc: { // 2
u::UintPtr opAdvance;
rc = d_lineReader.readULEB128(&opAdvance);
u_ASSERT_BAIL(0 == rc);
u::UintPtr advanceBy = minInstructionLength *
((opIndex + opAdvance) / maxOperationsPerInsruction);
u_TRACES && u_zprintf("%s advance@By: %lu\n",
rn, u::l(advanceBy));
statement = true;
address += advanceBy;
opIndex = static_cast<unsigned int>(
(opIndex + opAdvance) % maxOperationsPerInsruction);
} break;
case DW_LNS_advance_line: { // 3
int lineAdvance;
rc = d_lineReader.readLEB128(&lineAdvance);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(u::approxAbs(lineAdvance) < 10 * 1000 * 1000);
u_TRACES && u_zprintf("%s advanceLnBy: %d\n", rn, lineAdvance);
line += lineAdvance;
u_ASSERT_BAIL(line >= 0);
} break;
case DW_LNS_set_file: { // 4
rc = d_lineReader.readULEB128(&fileIdx);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(0 <= fileIdx);
u_ASSERT_BAIL( fileIdx <
static_cast<int>(fileNames.size()));
nullPrevStatement = true;
statementsSinceSetFile = 0;
u_TRACES && u_zprintf("%s set file to %u %s%s\n", rn, fileIdx,
dirPaths[dirIndexes[fileIdx]].c_str(),
fileNames[fileIdx].c_str());
} break;
case DW_LNS_set_column: { // 5
rc = d_lineReader.skipULEB128(); // ignored
u_ASSERT_BAIL(0 == rc);
} break;
case DW_LNS_negate_stmt: { // 6
; // no args, ignored
} break;
case DW_LNS_set_basic_block: { // 7
; // no args, ignored
} break;
case DW_LNS_const_add_pc: { // 8
unsigned int opAdvance = (255 - opcodeBase) / lineRange;
address += minInstructionLength *
((opIndex + opAdvance) / maxOperationsPerInsruction);
opIndex = (opIndex + opAdvance) % maxOperationsPerInsruction;
} break;
case DW_LNS_fixed_advance_pc: { // 9
unsigned short advance;
rc = d_lineReader.readValue(&advance);
u_ASSERT_BAIL(0 == rc);
address += advance;
opIndex = 0;
} break;
case DW_LNS_set_prologue_end: { // 10
statement = true;
} break;
case DW_LNS_set_epilogue_begin: { // 11
statement = true;
} break;
case DW_LNS_set_isa: { // 12
rc = d_lineReader.skipULEB128(); // ignored
u_ASSERT_BAIL(0 == rc);
} break;
default: {
u_ASSERT_BAIL(DW_LNS_set_isa < opcode);
u_ASSERT_BAIL( opcode < opcodeLengths.size());
// use 'opcodeLengths' to skip and ignore any arguments
for (unsigned int ii = 0; ii < opcodeLengths[opcode]; ++ii) {
rc = d_lineReader.skipULEB128();
u_ASSERT_BAIL(0 == rc);
}
} break;
}
}
else {
BSLS_ASSERT_SAFE(0 == opcode);
// expect extended opcode // DWARF doc 6.2.5.3
rc = d_lineReader.readValue(&opcode);
u_ASSERT_BAIL(0 == rc);
// Sometimes it's just a 0 followed by the extended opcode,
// sometimes there's a 9 or a 5 between the 0 and the extended
// opcode.
#if defined(BSLS_PLATFORM_CPU_64_BIT)
if (9 == opcode) { // Not in spec
#else
if (5 == opcode) { // Not in spec
#endif
rc = d_lineReader.readValue(&opcode);
u_ASSERT_BAIL(0 == rc);
}
u_zprintf("%s extended opcode %s\n",
rn, u::Reader::stringForLNE(opcode));
switch (opcode) {
case DW_LNE_end_sequence: { // 1
0 && u::dumpBinary(&d_lineReader, 8);
// There was an extra byte there in the example, but it's not
// described in the spec, so its function is unknown.
unsigned char uc;
rc = d_lineReader.readValue(&uc);
u_ASSERT_BAIL(!u_TRACES || 0 == rc);
u_ASSERT_BAIL(!u_TRACES || 1 == uc); // it always seems to be 1
// only complain if it's
// not if traces are on
endOfSequence = true;
statement = true;
} break;
case DW_LNE_set_address: { // 2
rc = d_lineReader.readValue(&address);
u_ASSERT_BAIL(0 == rc);
address += d_adjustment;
opIndex = 0;
if (statementsSinceSetFile <= 1) {
// Apparently, if this statement immediately follows a
// 'set file', we are to reset the line #, otherwise leave
// it alone.
line = prevLine = 1;
}
nullPrevStatement = true;
} break;
case DW_LNE_define_file: { // 3
rc = d_lineReader.readString(&definedFile);
u_ASSERT_BAIL(0 == rc);
rc = d_lineReader.readULEB128(&definedDirIndex);
u_ASSERT_BAIL(0 == rc);
u_ASSERT_BAIL(definedDirIndex < dirIndexes.size());
rc = d_lineReader.skipULEB128(); // mod time, ignored
u_ASSERT_BAIL(0 == rc);
rc = d_lineReader.skipULEB128(); // file length, ignored
u_ASSERT_BAIL(0 == rc);
fileIdx = -1;
line = prevLine = 1;
} break;
case u::e_DW_LNE_set_discriminator: {
rc = d_lineReader.skipULEB128(); // ignored
u_ASSERT_BAIL(0 == rc);
} break;
default: {
u_zprintf("%s unrecognized extended opcode %u\n", rn, opcode);
(void) u::dumpBinary(&d_lineReader, 8);
u_ASSERT_BAIL(u_P(opcode) && "unrecognized extended opcode");
}
}
}
if (statement) {
u_TRACES && u_zprintf("%s stmt: addr: 0x%lx, line: %u\n",
rn, u::l(address), line);
if (!nullPrevStatement &&
addressToMatch <= address && prevAddress < addressToMatch) {
u_TRACES && u_zprintf(
"%s stmt match: @'s(0x%lx, 0x%lx, 0x%lx),"
" line(%d, %d)\n",
rn, u::l(prevAddress), u::l(addressToMatch),
u::l(address), prevLine, line);
frameRec->frame().setLineNumber(line);
if (-1 == fileIdx) {
if ('/' != definedFile.c_str()[0]) {
definedFile.insert(0, dirPaths[definedDirIndex]);
}
(void) u::cleanupString(&definedFile, d_allocator_p);
frameRec->frame().setSourceFileName(definedFile);
}
else {
bsl::string& sfn = fileNames[fileIdx];
if ('/' != sfn.c_str()[0]) {
bsl::string& dir = dirPaths[dirIndexes[fileIdx]];
if (0 != dirIndexes[fileIdx] &&
'/' != dir.c_str()[0]) {
dir.insert(0, dirPaths[0]);
}
sfn.insert(0, dir);
}
(void) u::cleanupString(&sfn, d_allocator_p);
frameRec->frame().setSourceFileName(sfn);
}
u_TRACES && u_zprintf("%s stmt MATCH %s %s:%d\n", rn,
frameRec->frame().symbolName().c_str(),
frameRec->frame().sourceFileName().c_str(),
frameRec->frame().lineNumber());
d_lineReader.disable();
return 0; // RETURN
}
if (endOfSequence) {
endOfSequence = false;
u_TRACES && u_zprintf("%s ----------------------------\n", rn);
address = 0, prevAddress = 0;
opIndex = 0;
fileIdx = 0;
line = 1, prevLine = 1;
nullPrevStatement = true;
}
else {
prevLine = line;
prevAddress = address;
nullPrevStatement = false;
}
}
}
d_lineReader.disable();
return -1; // 'addressToMatch' not matched
}
#endif // u_DWARF
void u::StackTraceResolver::HiddenRec::reset()
{
// Note that 'd_frameRecs' and 'd_numTotalUnmatched' are not to be cleared
// or reinitialized, they have a lifetime of the length of the resolve.
d_helper_p = 0;
d_frameRecsBegin = u::FrameRecVecIt();
d_frameRecsEnd = u::FrameRecVecIt();
d_adjustment = 0;
d_symTableOffset = 0;
d_symTableSize = 0;
d_stringTableOffset = 0;
d_stringTableSize = 0;
#ifdef u_DWARF
d_abbrevSec. reset();
d_arangesSec.reset();
d_infoSec. reset();
d_lineSec. reset();
d_rangesSec. reset();
d_strSec. reset();
d_abbrevReader. disable();
d_arangesReader.disable();
d_infoReader. disable();
d_lineReader. disable();
d_rangesReader. disable();
d_strReader. disable();
#endif
}
// -----------------------------------------------------------------
// class balst::u::StackTraceResolverImpl<balst::ObjectFileFormat::Elf>
// == class U::u::StackTraceResolver
// -----------------------------------------------------------------
// PRIVATE CREATORS
u::StackTraceResolver::StackTraceResolverImpl(
balst::StackTrace *stackTrace,
bool demanglingPreferredFlag)
: d_hbpAlloc()
, d_stackTrace_p(stackTrace)
, d_scratchBufA_p(static_cast<char *>(
d_hbpAlloc.allocate(u::k_SCRATCH_BUF_LEN)))
, d_scratchBufB_p(static_cast<char *>(
d_hbpAlloc.allocate(u::k_SCRATCH_BUF_LEN)))
#ifdef u_DWARF
, d_scratchBufC_p(static_cast<char *>(
d_hbpAlloc.allocate(u::k_SCRATCH_BUF_LEN)))
, d_scratchBufD_p(static_cast<char *>(
d_hbpAlloc.allocate(u::k_SCRATCH_BUF_LEN)))
#endif
, d_hidden(*(new (d_hbpAlloc) HiddenRec(this))) // must be after scratch
// buffers
, d_demangle(demanglingPreferredFlag)
{
}
#if defined(BALST_COMPILER_DEFECT_NO_TYPEDEF_DESTRUCTORS)
balst::StackTraceResolverImpl<balst::ObjectFileFormat::Elf>::
~StackTraceResolverImpl()
#else
u::StackTraceResolver::~StackTraceResolverImpl()
#endif
{
// Don't free anything, the heap bypass allocator will free it all when
// it's destroyed.
}
// PRIVATE MANIPULATORS
int u::StackTraceResolver::loadSymbols(int matched)
{
char *symbolBuf = d_scratchBufA_p;
char *stringBuf = d_scratchBufB_p;
const int symSize = static_cast<int>(sizeof(u::ElfSymbol));
const u::Offset maxSymbolsPerPass = u::k_SCRATCH_BUF_LEN / symSize;
const u::Offset numSyms = d_hidden.d_symTableSize / symSize;
u::Offset sourceFileNameOffset = u::maxOffset;
u::UintPtr numSymsThisTime;
for (u::Offset symIndex = 0; symIndex < numSyms;
symIndex += numSymsThisTime) {
numSymsThisTime = static_cast<u::UintPtr>(
bsl::min(numSyms - symIndex, maxSymbolsPerPass));
const u::Offset offsetToRead = d_hidden.d_symTableOffset +
symIndex * symSize;
int rc = d_hidden.d_helper_p->readExact(
symbolBuf,
numSymsThisTime * symSize,
offsetToRead);
if (rc) {
u_eprintf(
"failed to read %lu symbols from offset %llu, errno %d\n",
u::l(numSymsThisTime),
u::ll(offsetToRead),
errno);
return -1; // RETURN
}
const u::ElfSymbol *symBufStart = static_cast<u::ElfSymbol *>(
static_cast<void *>(symbolBuf));
const u::ElfSymbol *symBufEnd = symBufStart + numSymsThisTime;
for (const u::ElfSymbol *sym = symBufStart; sym < symBufEnd; ++sym) {
switch (ELF32_ST_TYPE(sym->st_info)) {
case STT_FILE: {
sourceFileNameOffset = sym->st_name;
} break;
case STT_FUNC: {
if (SHN_UNDEF != sym->st_shndx) {
const void *symbolAddress = reinterpret_cast<const void *>(
sym->st_value + d_hidden.d_adjustment);
const void *endSymbolAddress =
static_cast<const char *>(symbolAddress) +
sym->st_size;
const u::FrameRecVecIt begin =
bsl::lower_bound(d_hidden.d_frameRecsBegin,
d_hidden.d_frameRecsEnd,
u::FrameRec(symbolAddress,
0,
0,
&d_hbpAlloc));
const u::FrameRecVecIt end =
bsl::lower_bound(d_hidden.d_frameRecsBegin,
d_hidden.d_frameRecsEnd,
u::FrameRec(endSymbolAddress,
0,
0,
&d_hbpAlloc));
for (u::FrameRecVecIt it = begin; it < end; ++it) {
if (it->isSymbolResolved()) {
continue;
}
balst::StackTraceFrame& frame = it->frame();
frame.setOffsetFromSymbol(
static_cast<const char *>(it->address())
- static_cast<const char *>(symbolAddress));
// in ELF, filename information is only accurate
// for statics in the main executable
if (d_hidden.d_isMainExecutable
&& STB_LOCAL == ELF32_ST_BIND(sym->st_info)
&& u::maxOffset != sourceFileNameOffset) {
frame.setSourceFileName(
d_hidden.d_helper_p->loadString(
d_hidden.d_stringTableOffset +
sourceFileNameOffset,
stringBuf,
u::k_SCRATCH_BUF_LEN,
&d_hbpAlloc));
}
frame.setMangledSymbolName(
d_hidden.d_helper_p->loadString(
d_hidden.d_stringTableOffset +
sym->st_name,
stringBuf,
u::k_SCRATCH_BUF_LEN,
&d_hbpAlloc));
if (frame.isMangledSymbolNameKnown()) {
setFrameSymbolName(&frame,
stringBuf,
u::k_SCRATCH_BUF_LEN);
it->setSymbolResolved();
u_TRACES && u_zprintf(
"Resolved symbol %s, frame %d, [%p, %p)\n",
frame.symbolName().c_str(),
it->index(),
symbolAddress,
endSymbolAddress);
if (0 == --matched) {
u_TRACES && u_zprintf(
"Last symbol in segment loaded\n");
return 0; // RETURN
}
}
else {
u_TRACES && u_zprintf("Null symbol found for %p\n",
it->address());
}
}
}
} break;
}
}
}
return 0;
}
int u::StackTraceResolver::processLoadedImage(const char *fileName,
const void *programHeaders,
int numProgramHeaders,
void *textSegPtr,
void *baseAddress)
// Note this must be public so 'linkMapCallBack' can call it on Solaris.
// Also note that it assumes that both scratch buffers are available for
// writing.
{
static const char rn[] = { "Resolver::processLoadedImage" }; (void) rn;
BSLS_ASSERT(!textSegPtr || !baseAddress);
// Scratch buffers: some platforms use A to read the link, then
// 'resolveSegment' will trash both A and B.
d_hidden.reset();
#if defined(BSLS_PLATFORM_OS_HPUX)
const char *name = fileName;
#else
const char *name = 0;
if (fileName && fileName[0]) {
if (u::e_IS_LINUX) {
d_hidden.d_isMainExecutable = false;
}
name = fileName;
}
else {
if (u::e_IS_LINUX) {
d_hidden.d_isMainExecutable = true;
}
else {
u_ASSERT_BAIL(d_hidden.d_isMainExecutable);
}
// On Solaris and Linux, 'fileName' is sometimes null for the main
// executable file, but those platforms have a standard virtual symlink
// that points to the executable file name.
const int numChars = static_cast<int>(
readlink("/proc/self/exe",
d_scratchBufA_p,
u::k_SCRATCH_BUF_LEN));
if (numChars > 0) {
u_ASSERT_BAIL(numChars < u::k_SCRATCH_BUF_LEN);
d_scratchBufA_p[numChars] = 0;
name = d_scratchBufA_p;
}
else {
u_TRACES && u_zprintf("readlink of /proc/self/exe failed\n");
return -1; // RETURN
}
}
#endif
name = bdlb::String::copy(name, &d_hbpAlloc); // so we can trash the
// scratch buffers later
u_TRACES && u_zprintf("processing loaded image: fn:\"%s\", name:\"%s\""
" main:%d numHdrs:%d unmatched:%ld\n",
fileName ? fileName : "(null)", name ? name : "(null)",
static_cast<int>(d_hidden.d_isMainExecutable),
numProgramHeaders, u::l(d_hidden.d_frameRecs.size()));
balst::StackTraceResolver_FileHelper helper(name);
d_hidden.d_helper_p = &helper;
for (int i = 0; i < numProgramHeaders; ++i) {
const u::ElfProgramHeader *ph =
static_cast<const u::ElfProgramHeader *>(programHeaders) + i;
// if (ph->p_type == PT_LOAD && ph->p_offset == 0) {
if (PT_LOAD == ph->p_type) {
// on Linux, textSegPtr will be 0, on Solaris && HPUX, baseAddress
// will be 0. We will always have 1 of the two, and since they
// differ by ph->p_vaddr, we can always calculate the one we don't
// have.
if (textSegPtr) {
BSLS_ASSERT(0 == baseAddress);
// calculating baseAddress from textSegPtr
baseAddress = static_cast<char *>(textSegPtr) - ph->p_vaddr;
}
else {
// or the other way around
textSegPtr = static_cast<char *>(baseAddress) + ph->p_vaddr;
}
// 'resolveSegment' trashes scratch buffers A and B
int rc = resolveSegment(baseAddress, // base address
textSegPtr, // seg ptr
ph->p_memsz, // seg size
name); // file name
if (rc) {
return -1; // RETURN
}
return 0; // RETURN
}
}
return -1;
}
int u::StackTraceResolver::resolveSegment(void *segmentBaseAddress,
void *segmentPtr,
u::UintPtr segmentSize,
const char *libraryFileName)
{
int rc;
// Scratch Buffers: beginning: 'sec' is A
// Then 'loadSymbols' trashes both A and B
// Then 'readDwarfAll' trasnes both A and B
d_hidden.d_addressRange.d_address =
reinterpret_cast<u::UintPtr>(segmentPtr);
d_hidden.d_addressRange.d_size = segmentSize;
const char *sp = static_cast<char *>(segmentPtr);
const char *se = sp + segmentSize;
d_hidden.d_frameRecsBegin = bsl::lower_bound(d_hidden.d_frameRecs.begin(),
d_hidden.d_frameRecs.end(),
u::FrameRec(sp,
0,
0,
&d_hbpAlloc));
d_hidden.d_frameRecsEnd = bsl::lower_bound(d_hidden.d_frameRecs.begin(),
d_hidden.d_frameRecs.end(),
u::FrameRec(se,
0,
0,
&d_hbpAlloc));
int matched = static_cast<int>(
d_hidden.d_frameRecsEnd - d_hidden.d_frameRecsBegin);
BSLS_ASSERT(0 <= matched);
BSLS_ASSERT(matched <= d_stackTrace_p->length());
u_TRACES && u_zprintf(
"ResolveSegment lfn=%s\nba=%p sp=%p se=%p matched=%d\n",
libraryFileName, segmentBaseAddress, sp, se, matched);
if (0 == matched) {
u_TRACES && u_zprintf(
"0 addresses match in library %s\n", libraryFileName);
return 0; // RETURN
}
d_hidden.d_libraryFileSize = bdls::FilesystemUtil::getFileSize(
libraryFileName);
bsl::string libName(libraryFileName, &d_hbpAlloc);
int cleanupRc = u::cleanupString(&libName, &d_hbpAlloc);
u::FrameRecVecIt it, end = d_hidden.d_frameRecsEnd;
for (it = d_hidden.d_frameRecsBegin; it < end; ++it) {
u_TRACES && u_zprintf("address %p MATCH\n", it->address());
it->frame().setLibraryFileName(0 == cleanupRc ? libName.c_str()
: libraryFileName);
}
// read the elf header
u::ElfHeader elfHeader;
rc = d_hidden.d_helper_p->readExact(&elfHeader,
sizeof(u::ElfHeader),
0);
if (0 != rc) {
return -1; // RETURN
}
if (0 != u::checkElfHeader(&elfHeader)) {
return -1; // RETURN
}
d_hidden.d_adjustment = reinterpret_cast<u::UintPtr>(segmentBaseAddress);
// find the section headers we're interested in, that is, .symtab and
// .strtab, or, if the file was stripped, .dynsym and .dynstr
u::ElfSectionHeader symTabHdr, strTabHdr, dynSymHdr, dynStrHdr;
bsl::memset(&symTabHdr, 0, sizeof(u::ElfSectionHeader));
bsl::memset(&strTabHdr, 0, sizeof(u::ElfSectionHeader));
bsl::memset(&dynSymHdr, 0, sizeof(u::ElfSectionHeader));
bsl::memset(&dynStrHdr, 0, sizeof(u::ElfSectionHeader));
// Possible speedup: read all the section headers at once instead of one at
// a time.
int numSections = elfHeader.e_shnum;
u::UintPtr sectionHeaderSize = elfHeader.e_shentsize;
u::UintPtr sectionHeaderOffset = elfHeader.e_shoff;
if (u::k_SCRATCH_BUF_LEN < sectionHeaderSize) {
return -1; // RETURN
}
u::ElfSectionHeader *sec = static_cast<u::ElfSectionHeader *>(
static_cast<void *>(d_scratchBufA_p));
// read the string table that is used for section names
int stringSectionIndex = elfHeader.e_shstrndx;
u::UintPtr stringSectionHeaderOffset =
sectionHeaderOffset + stringSectionIndex * sectionHeaderSize;
if (0 != d_hidden.d_helper_p->readExact(sec,
sectionHeaderSize,
stringSectionHeaderOffset)) {
return -1; // RETURN
}
u::UintPtr headerStringsOffset = sec->sh_offset;
for (int i = 0; i < numSections; ++i) {
if (0 != d_hidden.d_helper_p->readExact(sec,
sectionHeaderSize,
sectionHeaderOffset +
i * sectionHeaderSize)) {
return -1; // RETURN
}
char sectionName[16];
if (0 != d_hidden.d_helper_p->readExact(sectionName,
sizeof(sectionName),
headerStringsOffset +
sec->sh_name)) {
return -1; // RETURN
}
u_zprintf("Section: type:%d name:%s\n", sec->sh_type, sectionName);
switch (sec->sh_type) {
case SHT_STRTAB: {
if (!bsl::strcmp(sectionName, ".strtab")) {
strTabHdr = *sec;
}
else if (!bsl::strcmp(sectionName, ".dynstr")) {
dynStrHdr = *sec;
}
} break;
case SHT_SYMTAB: {
if (!bsl::strcmp(sectionName, ".symtab")) {
symTabHdr = *sec;
}
} break;
case SHT_DYNSYM: {
if (!bsl::strcmp(sectionName, ".dynsym")) {
dynSymHdr = *sec;
}
} break;
#ifdef u_DWARF
case SHT_PROGBITS: {
if ('d' != sectionName[1]) {
; // do nothing
}
else if (!bsl::strcmp(sectionName, ".debug_abbrev")) {
d_hidden.d_abbrevSec. reset(sec->sh_offset, sec->sh_size);
}
else if (!bsl::strcmp(sectionName, ".debug_aranges")) {
d_hidden.d_arangesSec.reset(sec->sh_offset, sec->sh_size);
}
else if (!bsl::strcmp(sectionName, ".debug_info")) {
d_hidden.d_infoSec. reset(sec->sh_offset, sec->sh_size);
}
else if (!bsl::strcmp(sectionName, ".debug_line")) {
d_hidden.d_lineSec. reset(sec->sh_offset, sec->sh_size);
}
else if (!bsl::strcmp(sectionName, ".debug_ranges")) {
d_hidden.d_rangesSec. reset(sec->sh_offset, sec->sh_size);
}
else if (!bsl::strcmp(sectionName, ".debug_str")) {
d_hidden.d_strSec. reset(sec->sh_offset, sec->sh_size);
}
} break;
#endif
}
}
u_TRACES && u_zprintf("symtab:(0x%llx, 0x%llx), strtab:(0x%llx, 0x%llx)\n",
u::ll(symTabHdr.sh_offset), u::ll(symTabHdr.sh_size),
u::ll(strTabHdr.sh_offset), u::ll(strTabHdr.sh_size));
u_TRACES && u_zprintf("dynsym:(0x%llx, %llu), dynstr:(0x%llx, %llu)\n",
u::ll(dynSymHdr.sh_offset), u::ll(dynSymHdr.sh_size),
u::ll(dynStrHdr.sh_offset), u::ll(dynStrHdr.sh_size));
if (0 != strTabHdr.sh_size && 0 != symTabHdr.sh_size) {
// use the full symbol table if it is available
d_hidden.d_symTableOffset = symTabHdr.sh_offset;
d_hidden.d_symTableSize = symTabHdr.sh_size;
d_hidden.d_stringTableOffset = strTabHdr.sh_offset;
d_hidden.d_stringTableSize = strTabHdr.sh_size;
}
else if (0 != dynSymHdr.sh_size && 0 != dynStrHdr.sh_size) {
// otherwise use the dynamic symbol table
d_hidden.d_symTableOffset = dynSymHdr.sh_offset;
d_hidden.d_symTableSize = dynSymHdr.sh_size;
d_hidden.d_stringTableOffset = dynStrHdr.sh_offset;
d_hidden.d_stringTableSize = dynStrHdr.sh_size;
}
else {
// otherwise fail
return -1; // RETURN
}
u_TRACES && u_zprintf(
"Sym table:(0x%llx, 0x%llx) string table:(0x%llx 0x%llx)\n",
u::ll(d_hidden.d_symTableOffset),
u::ll(d_hidden.d_symTableSize),
u::ll(d_hidden.d_stringTableOffset),
u::ll(d_hidden.d_stringTableSize));
#ifdef u_DWARF
u_TRACES && u_zprintf("abbrev:(0x%llx, 0x%llx) aranges:(0x%llx, 0x%llx)"
" info:(0x%llx 0x%llx) line::(0x%llx 0x%llx)"
" ranges:(0x%llx, 0x%llx) str:(0x%llx, 0x%llx)\n",
u::ll(d_hidden.d_abbrevSec.d_offset),
u::ll(d_hidden.d_abbrevSec.d_size),
u::ll(d_hidden.d_arangesSec.d_offset),
u::ll(d_hidden.d_arangesSec.d_size),
u::ll(d_hidden.d_infoSec.d_offset),
u::ll(d_hidden.d_infoSec.d_size),
u::ll(d_hidden.d_lineSec.d_offset),
u::ll(d_hidden.d_lineSec.d_size),
u::ll(d_hidden.d_rangesSec.d_offset),
u::ll(d_hidden.d_rangesSec.d_size),
u::ll(d_hidden.d_strSec.d_offset),
u::ll(d_hidden.d_strSec.d_size));
#endif
// Note that 'loadSymbols' trashes scratchBufA and scratchBufB.
rc = loadSymbols(matched);
if (rc) {
u_eprintf("loadSymbols failed\n");
return -1; // RETURN
}
// we return 'rc' at the end.
#ifdef u_DWARF
// Note that 'readDwarfAll' trashes scratchBufs A, B, C, and D
rc = d_hidden.dwarfReadAll();
if (rc) {
u_TRACES && u_zprintf("readDwarf failed\n");
}
#endif
if (u_TRACES && 0 == (d_hidden.d_numTotalUnmatched -= matched)) {
u_zprintf("Last address in stack trace matched\n");
}
return 0;
}
// PRIVATE ACCESSORS
void u::StackTraceResolver::setFrameSymbolName(
balst::StackTraceFrame *frame,
char *buffer,
bsl::size_t bufferLen) const
{
#if !defined(BSLS_PLATFORM_OS_SOLARIS) \
|| defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG)
// Linux or Sun g++ or HPUX
(void) buffer; // silence 'unused' warning
(void) bufferLen; // silence 'unused' warning
int status = -1;
if (d_demangle) {
// note the demangler uses 'malloc' to allocate its result
#if defined(BSLS_PLATFORM_OS_HPUX)
char *demangled = __cxa_demangle(frame->mangledSymbolName().c_str(),
0,
0,
&status);
#else
char *demangled = abi::__cxa_demangle(
frame->mangledSymbolName().c_str(),
0,
0,
&status);
#endif
u::FreeGuard guard(demangled);
frame->setSymbolName(demangled ? demangled : "");
}
if (0 != status || frame->symbolName().empty()) {
u_TRACES && u_zprintf("Did not demangle: status: %d\n", status);
frame->setSymbolName(frame->mangledSymbolName());
}
#endif
#if defined(BSLS_PLATFORM_OS_SOLARIS) \
&& !(defined(BSLS_PLATFORM_CMP_GNU) || defined(BSLS_PLATFORM_CMP_CLANG))
// Sun CC
int rc = -1;
if (d_demangle) {
#if 0
// Calling the demangler with the Solaris CC compiler requires linking
// with '-ldemangle', which results in unresolved symbols in Robo.
// someday this should be redone loading the appropriate library via
// 'dlopen', until then, just use the mangled symbol.
rc = ::cplus_demangle(frame->mangledSymbolName().c_str(),
buffer,
bufferLen);
u_TRACES && 0 != rc && u_zprintf("Demangling failed, rc:%d\n", rc);
#endif
}
frame->setSymbolName(0 == rc ? buffer
: frame->mangledSymbolName().c_str());
#endif
}
#if defined(BSLS_PLATFORM_OS_LINUX)
// Linux could use the same method as Solaris, but we would need a special case
// for statically linked apps. Instead of that we're going to use the
// 'dl_iterate_phdr' function, which works for static and dynamic apps (you get
// called back once if the app is static).
extern "C" {
static
int linkmapCallback(struct dl_phdr_info *info,
bsl::size_t size,
void *data)
// This routine is called once for the executable file, and once for every
// shared library that is loaded. The specified 'info' contains a pointer
// to the relevant information in the link map. The specified 'size' is
// unused, the specified 'data' is a pointer to the elf resolver. Return 0
// on success and a non-zero value otherwise.
{
(void) size;
u::StackTraceResolver *resolver =
reinterpret_cast<u::StackTraceResolver *>(data);
// If we have completed resolving, there is no way to signal the caller to
// stop iterating through the shared libs, but we aren't allowed to throw
// and the caller ignores and propagates the return value we pass to it.
// So just return without doing any work once resolving is done.
if (0 == resolver->numUnmatchedFrames()) {
return 0; // RETURN
}
// here the base address is known and text segment loading address is
// unknown
int rc = resolver->processLoadedImage(
info->dlpi_name,
info->dlpi_phdr,
info->dlpi_phnum,
0,
reinterpret_cast<void *>(info->dlpi_addr));
if (rc) {
return -1; // RETURN
}
return 0;
}
} // extern "C"
#endif
#if defined(BSLS_PLATFORM_OS_SOLARIS)
// modern Solaris applications are NEVER statically linked, so we always
// have a link_map.
extern "C" void *_DYNAMIC; // global pointer that leads to the link map
#endif
// CLASS METHODS
int u::StackTraceResolver::resolve(
balst::StackTrace *stackTrace,
bool demanglingPreferredFlag)
{
static const char rn[] = { "Resolver::resolve" }; (void) rn;
#if defined(BSLS_PLATFORM_OS_HPUX)
int rc;
u::StackTraceResolver resolver(stackTrace,
demanglingPreferredFlag);
// The HPUX compiler, 'aCC', doesn't accept the -Bstatic option, suggesting
// we are never statically linked on HPUX, so 'shl_get_r' should always
// work.
shl_descriptor desc;
bsl::memset(&desc, 0, sizeof(shl_descriptor));
// 'programHeaders' will point to a segment of memory we will allocate and
// reallocated to the needed size indicated by the 'ElfHeader's we
// encounter. The max is the number of program headers that will fit in
// the allcoated segment.
u::ElfProgramHeader *programHeaders = 0;
int maxNumProgramHeaders = 0;
u::ElfHeader elfHeader;
for (int i = -1;
0 < resolver.numUnmatchedFrames() && -1 != shl_get_r(i, &desc);
++i) {
int numProgramHeaders = 0;
{
// this block limits the lifetime of 'helper' below
u_TRACES && u_zprintf("(%d) %s 0x%lx-0x%lx\n",
i,
desc.filename && desc.fileName[0] ? desc.fileName :"(null)"
desc.tstart,
desc.tend);
// index 0 is for the main executable
resolver.d_hidden.d_isMainExecutable = (0 == i);
// note this will be opened twice, here and in 'processLoadedImage'
balst::StackTraceResolver_FileHelper helper(desc.filename);
rc = helper.readExact(&elfHeader, sizeof(elfHeader), 0);
u_ASSERT_BAIL(0 == rc);
numProgramHeaders = elfHeader.e_phnum;
if (numProgramHeaders > maxNumProgramHeaders) {
programHeaders = static_cast<u::ElfProgramHeader *>(
resolver.d_hbpAlloc.allocate(
numProgramHeaders * sizeof(u::ElfProgramHeader)));
maxNumProgramHeaders = numProgramHeaders;
}
rc = helper.readExact(
programHeaders,
numProgramHeaders * sizeof(u::ElfProgramHeader),
elfHeader.e_phoff);
u_ASSERT_BAIL(0 == rc);
}
rc = resolver.processLoadedImage(
desc.filename,
programHeaders,
numProgramHeaders,
static_cast<void *>(desc.tstart),
0);
u_ASSERT_BAIL(0 == rc);
}
#elif defined(BSLS_PLATFORM_OS_LINUX)
u::StackTraceResolver resolver(stackTrace,
demanglingPreferredFlag);
// 'dl_iterate_phdr' will iterate over all loaded files, the executable and
// all the .so's. It doesn't exist on Solaris.
dl_iterate_phdr(&linkmapCallback,
&resolver);
#elif defined(BSLS_PLATFORM_OS_SOLARIS)
u::StackTraceResolver resolver(stackTrace,
demanglingPreferredFlag);
struct link_map *linkMap = 0;
#if 0
// This method of getting the linkMap was deemed less desirable because it
// calls 'malloc'.
dlinfo(RTLD_SELF, RTLD_DI_LINKMAP, &linkMap);
if (0 == linkMap) {
return -1; // RETURN
}
#else
// This method was adopted as superior to the above (commented out) method.
u::ElfDynamic *dynamic = reinterpret_cast<u::ElfDynamic *>(&_DYNAMIC);
u_ASSERT_BAIL(dynamic);
for (; true; ++dynamic) {
// DT_NULL means we reached then end of list without finding the link
// map
u_ASSERT_BAIL(DT_NULL != dynamic->d_tag);
if (DT_DEBUG == dynamic->d_tag) {
r_debug *rdb = reinterpret_cast<r_debug *>(dynamic->d_un.d_ptr);
u_ASSERT_BAIL(0 != rdb);
linkMap = rdb->r_map;
break;
}
}
#endif
for (int i = 0; 0 < resolver.numUnmatchedFrames() && linkMap;
++i, linkMap = linkMap->l_next) {
u::ElfHeader *elfHeader = reinterpret_cast<u::ElfHeader *>(
linkMap->l_addr);
if (0 != u::checkElfHeader(elfHeader)) {
return -1;
}
u::ElfProgramHeader *programHeaders =
reinterpret_cast<u::ElfProgramHeader *>(
linkMap->l_addr + elfHeader->e_phoff);
int numProgramHeaders = elfHeader->e_phnum;
resolver.d_hidden.d_isMainExecutable = (0 == i);
// Here the text segment address is known, not base address. On this
// platform, but not necessarily on other platforms, the text segment
// begins with the Elf Header.
int rc = resolver.processLoadedImage(linkMap->l_name,
programHeaders,
numProgramHeaders,
static_cast<void *>(elfHeader),
0);
if (rc) {
return -1; // RETURN
}
}
#else
# error unrecognized platform
#endif
return 0;
}
// PUBLIC ACCESSOR
int u::StackTraceResolver::numUnmatchedFrames() const
{
return static_cast<int>(d_hidden.d_numTotalUnmatched);
}
} // close enterprise namespace
#endif
// ----------------------------------------------------------------------------
// Copyright 2015 Bloomberg Finance L.P.
//
// 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.
// ----------------------------- END-OF-FILE ----------------------------------
| 39.492834 | 79 | 0.531211 | [
"object",
"vector"
] |
45c05e951745297ce3f00e065427c31d9213248a | 3,960 | cpp | C++ | tools/spfx_munge/src/munge_spfx.cpp | SleepKiller/shaderpatch | 4bda848df0273993c96f1d20a2cf79161088a77d | [
"MIT"
] | 13 | 2019-03-25T09:40:12.000Z | 2022-03-13T16:12:39.000Z | tools/spfx_munge/src/munge_spfx.cpp | SleepKiller/shaderpatch | 4bda848df0273993c96f1d20a2cf79161088a77d | [
"MIT"
] | 110 | 2018-10-16T09:05:43.000Z | 2022-03-16T23:32:28.000Z | tools/spfx_munge/src/munge_spfx.cpp | SleepKiller/swbfii-shaderpatch | b49ce3349d4dd09b19237ff4766652166ba1ffd4 | [
"MIT"
] | 1 | 2020-02-06T20:32:50.000Z | 2020-02-06T20:32:50.000Z |
#include "munge_spfx.hpp"
#include "compose_exception.hpp"
#include "envfx_edits.hpp"
#include "munge_colorgrading_regions.hpp"
#include "req_file_helpers.hpp"
#include "string_utilities.hpp"
#include "synced_io.hpp"
#include "volume_resource.hpp"
#include <filesystem>
#include <fstream>
#include <string_view>
#include <gsl/gsl>
#pragma warning(push)
#pragma warning(disable : 4996)
#pragma warning(disable : 4127)
#include <yaml-cpp/yaml.h>
#pragma warning(pop)
#include <glm/gtc/quaternion.hpp>
namespace sp {
namespace fs = std::filesystem;
using namespace std::literals;
namespace {
auto regions_file_path(const fs::path& spfx_path) -> fs::path
{
const auto filename = spfx_path.stem() += L"_colorgrading.rgn"sv;
auto rgn_path = spfx_path;
rgn_path.replace_filename(filename);
return rgn_path;
}
bool regions_file_exists(const fs::path& rgn_path) noexcept
{
try {
return fs::exists(rgn_path) && fs::is_regular_file(rgn_path);
}
catch (std::exception&) {
return false;
}
}
auto read_spfx_yaml_raw(const fs::path& spfx_path) -> std::vector<std::byte>
{
// Test that the file is valid YAML.
YAML::LoadFile(spfx_path.string());
std::ifstream file{spfx_path, std::ios::ate};
std::vector<std::byte> data;
data.resize(static_cast<std::size_t>(file.tellg()));
file.seekg(0);
file.read(reinterpret_cast<char*>(data.data()), data.size());
return data;
}
void generate_spfx_req_file(YAML::Node spfx, const fs::path& save_path,
const fs::path& region_file_path, const bool has_regions)
{
auto req_path = save_path;
req_path.replace_extension(".envfx.req"sv);
std::vector<std::pair<std::string, std::vector<std::string>>> key_sections{
{"game_envfx"s, {save_path.stem().string()}}};
if (has_regions) {
key_sections.emplace_back("color_regions"s,
std::vector{region_file_path.stem().string()});
}
std::vector<std::string> textures;
for (auto section : spfx) {
if (!section.second.IsMap()) continue;
for (auto key : section.second) {
if (!key.second.IsScalar()) continue;
if (make_ci_string(key.first.as<std::string>()).find("texture") !=
Ci_string::npos) {
auto texture = key.second.as<std::string>();
if (texture.empty()) continue;
textures.emplace_back(std::move(texture));
}
}
}
key_sections.emplace_back("sptex"s, std::move(textures));
emit_req_file(req_path, key_sections);
}
}
void munge_spfx(const fs::path& spfx_path, const fs::path& output_dir)
{
Expects(fs::exists(spfx_path) && fs::is_regular_file(spfx_path));
auto envfx_path = spfx_path;
envfx_path.replace_extension(".fx"sv);
if (!fs::exists(envfx_path) || !fs::is_regular_file(envfx_path)) {
throw compose_exception<std::runtime_error>("Freestanding .spfx file "sv,
spfx_path, " found."sv);
}
edit_envfx(envfx_path, output_dir);
synced_print("Munging "sv, spfx_path.filename().string(), "..."sv);
YAML::Node spfx_node;
try {
spfx_node = YAML::LoadFile(spfx_path.string());
}
catch (std::exception& e) {
synced_error_print("Error parsing "sv, spfx_path, " message was: "sv, e.what());
return;
}
const auto data = read_spfx_yaml_raw(spfx_path);
const auto save_path =
output_dir / spfx_path.filename().replace_extension(".envfx");
const auto regions_path = regions_file_path(spfx_path);
const bool has_regions = regions_file_exists(regions_path);
if (has_regions) {
munge_colorgrading_regions(regions_path, regions_path.parent_path(), output_dir);
}
save_volume_resource(save_path.string(), spfx_path.stem().string(),
Volume_resource_type::fx_config, data);
generate_spfx_req_file(spfx_node, save_path, regions_path, has_regions);
}
}
| 25.714286 | 87 | 0.663636 | [
"vector"
] |
45c0a76abee8b3008e3b83c2ec8e85e07e288ae8 | 4,029 | cpp | C++ | nfa.cpp | TooSchoolForCool/NFA-Converter | 5076b52f96dbff6c5595a68fac5eee5fa1b0d2ba | [
"MIT"
] | null | null | null | nfa.cpp | TooSchoolForCool/NFA-Converter | 5076b52f96dbff6c5595a68fac5eee5fa1b0d2ba | [
"MIT"
] | null | null | null | nfa.cpp | TooSchoolForCool/NFA-Converter | 5076b52f96dbff6c5595a68fac5eee5fa1b0d2ba | [
"MIT"
] | null | null | null | /*********************************************************************
* MODULE: nfa.cpp
* PURPOSE: Implement NFA class here
* AUTHER: Zeyu Zhang
* DATE STARTED: 2017-05-11
*********************************************************************/
#include "nfa.h"
using namespace std;
NFA::NFA()
{
// ...
}
NFA::~NFA()
{
// ...
}
void NFA::convert2DFA(DFA &dfa)
{
queue<string> state_queue;
map<string, bool> checked_states;
map<PSC, string> new_transitions;
state_queue.push( _epsilonClosure(startState_) );
checked_states[_epsilonClosure(startState_)] = true;
while( !state_queue.empty() )
{
string cur_state = state_queue.front();
state_queue.pop();
// cout << "pop: " << cur_state << endl;
for(int i = 0; i < alphabets_.size(); i++)
{
// cerr << "current: " << cur_state;
string next_state = _gotoNextStates(cur_state, alphabets_[i]);
// cerr << " read: " << alphabets_[i];
next_state = _epsilonClosure(next_state);
if(checked_states.find(next_state) == checked_states.end())
{
state_queue.push(next_state);
checked_states[next_state] = true;
// cerr << " push: " << next_state << endl;
}
new_transitions[PSC(cur_state, alphabets_[i])] = next_state;
}
}
_generateDFA(dfa, checked_states, new_transitions);
}
string NFA::_epsilonClosure(string state)
{
vector<string> split_states;
map<string, bool> closure;
_splitState(state, split_states);
for(int i = 0; i < split_states.size(); i++)
{
closure[split_states[i]] = true;
}
for(int i = 0; i < split_states.size(); i++)
{
// epsilone transition exists
if( _isTransitionExist(split_states[i], '*') )
{
string new_state = transitions_[ PSC(split_states[i], '*') ];
// check if new state already exists in the closure
if(closure.find(new_state) == closure.end())
{
split_states.push_back( new_state );
closure[new_state] = true;
}
}
}
return _mergeState(split_states);
}
void NFA::_splitState(const string &src_state, vector<string> &dst_states)
{
string str = "";
dst_states.clear();
for(int i = 0; i < src_state.size(); i++)
{
if(src_state[i] != '-')
str += src_state[i];
else
{
dst_states.push_back(str);
str = "";
}
}
dst_states.push_back(str);
sort(dst_states.begin(), dst_states.end());
}
string NFA::_mergeState(vector<string> &src_states)
{
string dst_state = "";
if(src_states.size() == 0)
return "";
sort(src_states.begin(), src_states.end());
for(int i = 0; i < src_states.size() - 1; i++)
{
dst_state += src_states[i] + '-';
}
dst_state += src_states.back();
return dst_state;
}
string NFA::_gotoNextStates(string state, char ch)
{
vector<string> split_states;
_splitState(state, split_states);
for(vector<string>::iterator iter = split_states.begin(); iter != split_states.end(); iter++)
{
if( _isTransitionExist(*iter, ch) )
*iter = transitions_[ PSC(*iter, ch) ];
else
{
iter = split_states.erase(iter);
iter--;
}
}
return _mergeState(split_states);
}
void NFA::_generateDFA(DFA &dfa, map<string, bool> new_states, map<PSC, string> new_transitions)
{
map<string, string> renaming_table;
int state_cnt = 0;
for(map<string, bool>::iterator iter = new_states.begin(); iter != new_states.end(); iter++)
{
renaming_table[iter->first] = int2string(state_cnt);
// set new states
dfa.addNewState(int2string(state_cnt++));
// set final states
vector<string> split_states;
_splitState(iter->first, split_states);
for(int i = 0; i < split_states.size(); i++)
{
if( _isAccepted(split_states[i]) )
{
dfa.setAcceptedState( int2string(state_cnt - 1) );
break;
}
}
}
// set start states
dfa.setStartState( renaming_table[_epsilonClosure(startState_)] );
// set alphabets
dfa.setAlphabets(alphabets_);
// add transitions
for(map<PSC, string>::iterator iter = new_transitions.begin(); iter != new_transitions.end(); iter++)
dfa.addTransition(renaming_table[iter->first.first], renaming_table[iter->second], iter->first.second);
} | 21.545455 | 105 | 0.639365 | [
"vector"
] |
45c4c25d364c0037d60acc9a26b87ea9c095911b | 1,943 | cpp | C++ | src/state_machine/BeagleBone_black/src/demo_vector.cpp | Hyp-ed/testing-proto-2018 | d283de2e6e1257de6fa7718ee67240e2179c73b6 | [
"Apache-2.0"
] | null | null | null | src/state_machine/BeagleBone_black/src/demo_vector.cpp | Hyp-ed/testing-proto-2018 | d283de2e6e1257de6fa7718ee67240e2179c73b6 | [
"Apache-2.0"
] | 1 | 2018-11-12T17:59:29.000Z | 2018-11-12T18:37:08.000Z | src/state_machine/BeagleBone_black/src/demo_vector.cpp | Hyp-ed/testing-proto-2018 | d283de2e6e1257de6fa7718ee67240e2179c73b6 | [
"Apache-2.0"
] | null | null | null |
/*
* Author: Uday Patel
* Organisation: HYPED
* Date: 24 February 2018
* Description:
*
* Copyright 2018 HYPED
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <iostream>
#include "utils/math/vector.hpp"
using hyped::utils::math::Vector;
template <typename T, int N>
void print(Vector<T, N> &v)
{
for (int i = 0; i < N; i++)
std::cout << v[i] << '\t';
std::cout << '\n';
}
int main()
{
Vector<int, 10> vector1;
Vector<int, 10> vector2;
Vector<int, 10> vector3;
Vector<double, 10> vector4;
Vector<double, 2> vector5({3, 4});
Vector<int, 2> vector6(1);
Vector<double, 2> vector7(1.0/sqrt(2));
print(vector1);
print(vector2);
print(vector3);
for (int i = 0; i < 10; i++)
vector1[i] = i+1,
vector4[i] = 1.1;
print(vector4);
vector2 += 1;
vector3 = vector1 + vector2;
vector2 = vector2 - 2;
vector3 = vector1 - vector2;
vector3 = vector1 * 5.0;
vector3 = vector1 / 5.0;
vector4 = vector4 + vector1;
vector4 = vector4 - vector1;
(vector1 == vector3) ? std::cout << "False\n" : std::cout << "True\n";
(vector5.norm() == 5) ? std::cout << "True\n" : std::cout << "False\n";
(vector6.norm() == sqrt(2)) ? std::cout << "True\n" : std::cout << "False\n";
(vector6.toUnitVector() == vector7) ? std::cout << "True\n" : std::cout << "False\n";
print(vector1);
print(vector2);
print(vector3);
print(vector4);
}
| 24.2875 | 87 | 0.623778 | [
"vector"
] |
45c5190a389d8eb0279a8970eb8cb3eff868d888 | 1,778 | hpp | C++ | lab_control_center/src/TimeSeries.hpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 9 | 2020-06-24T11:22:15.000Z | 2022-01-13T14:14:13.000Z | lab_control_center/src/TimeSeries.hpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 1 | 2021-05-10T13:48:04.000Z | 2021-05-10T13:48:04.000Z | lab_control_center/src/TimeSeries.hpp | Durrrr95/cpm_lab | e2e6f4ace4ebc01e8ddd87e2f4acf13e6ffdcc67 | [
"MIT"
] | 2 | 2021-11-08T11:59:29.000Z | 2022-03-15T13:50:54.000Z | #pragma once
#include "defaults.hpp"
#include "VehicleCommandTrajectory.hpp"
#include "cpm/get_time_ns.hpp"
/**
* \brief Data class for storing values & (receive) times to get latest / newest data etc
* \ingroup lcc
*/
template<typename T>
class _TimeSeries
{
//! TODO
vector<function<void(_TimeSeries&, uint64_t time, T value)>> new_sample_callbacks;
//! TODO
vector<uint64_t> times;
//! TODO
vector<T> values;
//! TODO
const string name;
//! TODO
const string format;
//! TODO
const string unit;
//! TODO
mutable std::mutex m_mutex;
public:
/**
* \brief TODO Constructor
* \param _name TODO
* \param _format TODO
* \param _unit TODO
*/
_TimeSeries(string _name, string _format, string _unit);
/**
* \brief TODO
* \param time TODO
* \param value TODO
*/
void push_sample(uint64_t time, T value);
/**
* \brief TODO
* \param value TODO
*/
string format_value(double value);
/**
* \brief TODO
*/
T get_latest_value() const;
/**
* \brief TODO
*/
uint64_t get_latest_time() const;
/**
* \brief TODO
* \param dt TODO
*/
bool has_new_data(double dt) const;
/**
* \brief TODO
*/
bool has_data() const;
/**
* \brief TODO
*/
string get_name() const {return name;}
/**
* \brief TODO
*/
string get_unit() const {return unit;}
/**
* \brief TODO
* \param n TODO
*/
vector<T> get_last_n_values(size_t n) const;
};
/**
* \brief TODO
* \ingroup lcc
*/
using TimeSeries = _TimeSeries<double>;
/**
* \brief TODO
* \ingroup lcc
*/
using TimeSeries_TrajectoryPoint = _TimeSeries<TrajectoryPoint>; | 17.431373 | 89 | 0.57874 | [
"vector"
] |
45c79ddbd90bafaee39aed50724fdb47913db677 | 1,758 | hpp | C++ | Assign2/DisplayModule/Frustum.hpp | thekana/MTRN3500-Assign2 | 07083eb3aab3f3b061c42159d83cbe50b5f55c68 | [
"OLDAP-2.5"
] | null | null | null | Assign2/DisplayModule/Frustum.hpp | thekana/MTRN3500-Assign2 | 07083eb3aab3f3b061c42159d83cbe50b5f55c68 | [
"OLDAP-2.5"
] | null | null | null | Assign2/DisplayModule/Frustum.hpp | thekana/MTRN3500-Assign2 | 07083eb3aab3f3b061c42159d83cbe50b5f55c68 | [
"OLDAP-2.5"
] | null | null | null |
#ifndef SCOS_FRUSTUM_H
#define SCOS_FRUSTUM_H
#include <iostream>
#include <cmath>
#include <cstdlib>
#include "VectorMaths.hpp"
namespace scos {
class Frustum {
private:
static const int X = 0;
static const int Y = 1;
static const int Z = 2;
float hfov; // horizontal field of view (in radians)
float vfov; // vertical field of view in radians
float aspect; // aspect ratio (horiz/vert)
// windows.h makes it annoying if you want to use the words 'near' or 'far'... and I do
#ifdef near
#undef near
#endif
#ifdef far
#undef far
#endif
float near; // distance to near clip plane
float far; // distance to far clip plane
float m_pos[3]; // a copy of the position of the focal point of the frustum
float m_dir[3]; // a copy of the direction of the axis of symmetry of the frustum
float m_up[3]; // a copy of the up vector
float far_tan_half_vfov;
float near_tan_half_vfov;
float far_tan_half_hfov;
float near_tan_half_hfov;
float * r_abc, r_d; // right plane
float * u_abc, u_d; // up plane
float * l_abc, l_d; // left plane
float * d_abc, d_d; // down plane
float * n_abc, n_d; // near plane
float * f_abc, f_d; // far plane
public:
Frustum(float vfov_, float aspect_, float near_, float far_);
~Frustum();
void update(float * pos, float * dir, float * up);
void renderFrustumPlanes(); // used for debugging (renders based on frustum vertices)
void renderFrustumPlanes_v2(); // used for debugging (renders based on stored values for a,b,c,d for each plane)
int pointInFrustum(float * p);
int sphereInFrustum(float * c, float rad); // c -> center, rad -> radius
};
};
#endif // for SCOS_FRUSTUM_H
| 25.852941 | 116 | 0.660978 | [
"vector"
] |
68fa177e7e1255e5b88cfa131d41b564cae0bffa | 874 | cpp | C++ | graph/bfs/bfs_topological.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | graph/bfs/bfs_topological.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | graph/bfs/bfs_topological.cpp | Takumi1122/data-structure-algorithm | 6b9f26e4dbba981f034518a972ecfc698b86d837 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int, int>;
using Graph = vector<vector<int>>;
// トポロジカルソート
// DAG : サイクルのない有向グラフ
// 出次数 deg[v]: 頂点vを始点とする辺の個数
// シンク: 出次数が0であるような頂点
int main() {
int n, m;
cin >> n >> m;
Graph G(n);
vector<int> deg(n, 0);
rep(i, m) {
int a, b;
cin >> a >> b;
a--;
b--;
// 逆向きに辺を張る
G[b].push_back(a);
deg[a]++;
}
// シンクたちをキューに挿入する
queue<int> que;
rep(i, n) if (deg[i] == 0) que.push(i);
vector<int> order;
while (!que.empty()) {
int v = que.front();
que.pop();
order.push_back(v);
for (auto nv : G[v]) {
// 辺 (nv, v) を削除する
--deg[nv];
if (deg[nv] == 0) que.push(nv);
}
}
reverse(order.begin(), order.end());
for (auto v : order) cout << v << endl;
return 0;
} | 17.836735 | 47 | 0.516018 | [
"vector"
] |
ec073fbce5438fd02291e62c40d9ce8916bbde1e | 4,724 | cpp | C++ | client/src/ui/content/item/search.cpp | zDestinate/InventoryManagement | b2f568cbeca3e9fa7e2c1fc213f3b527a6755216 | [
"MIT"
] | null | null | null | client/src/ui/content/item/search.cpp | zDestinate/InventoryManagement | b2f568cbeca3e9fa7e2c1fc213f3b527a6755216 | [
"MIT"
] | null | null | null | client/src/ui/content/item/search.cpp | zDestinate/InventoryManagement | b2f568cbeca3e9fa7e2c1fc213f3b527a6755216 | [
"MIT"
] | null | null | null | #include <iostream>
#include <codecvt>
#include "ui/content/item/search.h"
#pragma comment(lib, "comctl32.lib")
content_item_search::content_item_search(HWND hwndParent, int lpParam, int x, int y, int width, int height)
{
hwnd = CreateWindow("EDIT", "", WS_CHILD | WS_VISIBLE | WS_TABSTOP, x, y, width, height, hwndParent, (HMENU)lpParam, NULL, NULL);
SetWindowSubclass(hwnd, UnderLineTxtBoxProc, lpParam, (DWORD_PTR)this);
this->hwndParent= hwndParent;
hFont = CreateFont(17, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_MODERN, TEXT("Arial"));
SetFont(hFont);
wstrIcon = L"\uf002";
nIconX = 30;
bSolidIcon = false;
}
LRESULT CALLBACK content_item_search::UnderLineTxtBoxProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam, UINT_PTR uIdSubclass, DWORD_PTR dwRefData)
{
//Using the dwRefData we passed from and create this pointer
content_item_search* pThis = (content_item_search*) dwRefData;
switch (message)
{
case WM_PAINT:
{
//Get the current HWND Rect
RECT rc;
GetClientRect(hwnd, &rc);
//Clear all the painting and update the hwnd
//InvalidateRect(hwnd, &rc, TRUE);
//UpdateWindow(hwnd);
//RedrawWindow(hwnd, 0, 0, RDW_ERASE | RDW_UPDATENOW);
PAINTSTRUCT ps;
HDC hdc;
HPEN hPen;
//Start painting the line base on the focus status
hdc = BeginPaint(hwnd, &ps);
if(pThis->bFocus)
{
//Blue
hPen = CreatePen(PS_SOLID, 3, RGB(36, 164, 255));
}
else
{
//Black
hPen = CreatePen(PS_SOLID, 3, RGB(0, 0, 0));
}
SelectObject(hdc, hPen);
//Starting location
MoveToEx(hdc, rc.left - pThis->nIconX, rc.bottom + 1, 0);
//Ending location
LineTo(hdc, rc.right - rc.left, rc.bottom + 1);
//Delete the HPEN and finish painting
DeleteObject(hPen);
//Grab current font
HFONT hFont = (HFONT)GetStockObject(DEFAULT_GUI_FONT);
if(pThis->bFocus)
{
SetTextColor(hdc, RGB(36, 164, 255));
}
else
{
SetTextColor(hdc, RGB(0, 0, 0));
}
//Icon
HFONT hFontIcon;
if(pThis->bSolidIcon)
{
hFontIcon = CreateFont(22, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_MODERN, TEXT("Font Awesome 6 Pro Solid"));
}
else
{
hFontIcon = CreateFont(22, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, DEFAULT_CHARSET,
OUT_TT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH | FF_MODERN, TEXT("Font Awesome 6 Pro Regular"));
}
SelectObject(hdc, hFontIcon);
RECT rectIcon;
GetClientRect(hwnd, &rectIcon);
rectIcon.left -= pThis->nIconX;
rectIcon.top -= 7;
DrawTextW(hdc, (LPCWSTR)pThis->wstrIcon.c_str(), pThis->wstrIcon.length(), &rectIcon, DT_VCENTER | DT_SINGLELINE);
//Reset color
SetTextColor(hdc, RGB(0, 0, 0));
//Font for placeholder
SelectObject(hdc, hFont);
EndPaint(hwnd, &ps);
pThis->SetPlaceHolder(pThis->PlaceHolder);
}
break;
case WM_SETFOCUS:
{
pThis->bFocus = true;
}
break;
case WM_KILLFOCUS:
{
pThis->bFocus = false;
}
break;
case WM_COMMAND:
{
switch(HIWORD(wParam))
{
case EN_CHANGE:
{
SendMessage(pThis->hwndParent, WM_COMMAND, wParam, NULL);
}
break;
}
}
break;
}
return DefSubclassProc(hwnd, message, wParam, lParam);
}
void content_item_search::SetFont(HFONT hFont)
{
if(IsWindow(hwnd))
{
SendMessage(hwnd, WM_SETFONT, (WPARAM)hFont, TRUE);
}
}
void content_item_search::SetPlaceHolder(string strPlaceHolder)
{
if(IsWindow(hwnd))
{
wstring wstrPlaceHolder = wstring_convert<codecvt_utf8<wchar_t>>().from_bytes(strPlaceHolder);
SendMessage(hwnd, EM_SETCUEBANNER, FALSE, (LPARAM)wstrPlaceHolder.c_str());
}
} | 29.898734 | 155 | 0.550381 | [
"solid"
] |
ec2eac7d3453e53f2620d45b8aeea7ce23522925 | 1,187 | cpp | C++ | UVa Online Judge/11396 - Claw Decomposition.cpp | SamanKhamesian/ACM-ICPC-Problems | c68c04bee4de9ba9f30e665cd108484e0fcae4d7 | [
"Apache-2.0"
] | 2 | 2019-03-19T23:59:48.000Z | 2019-03-21T20:13:12.000Z | UVa Online Judge/11396 - Claw Decomposition.cpp | SamanKhamesian/ACM-ICPC-Problems | c68c04bee4de9ba9f30e665cd108484e0fcae4d7 | [
"Apache-2.0"
] | null | null | null | UVa Online Judge/11396 - Claw Decomposition.cpp | SamanKhamesian/ACM-ICPC-Problems | c68c04bee4de9ba9f30e665cd108484e0fcae4d7 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <algorithm>
#include <queue>
#include <vector>
using namespace std;
int n;
vector <short> color;
vector < vector <int> > graph;
bool bfs(int start)
{
int b = 0, w = 0;
queue <int> q;
q.push(start);
color[start] = 1;
while (!q.empty())
{
int top = q.front();
q.pop();
color[top] ? b++ : w++;
for (int i = 0; i < graph[top].size(); i++)
{
int child = graph[top][i];
if (color[child] == -1)
{
color[child] = !color[top];
q.push(child);
}
else if (color[child] == color[top])
{
return false;
}
}
}
return (abs(b - w)) ? false : true;
}
int main()
{
while (cin >> n, n != 0)
{
bool ans = true;
graph.clear();
graph.resize(n);
color.clear();
color.resize(n, -1);
int x, y;
while (cin >> x >> y, x != 0 || y != 0)
{
x--;
y--;
graph[x].push_back(y);
graph[y].push_back(x);
}
if (n % 2 == 1) cout << "NO" << endl;
else
{
for (int i = 0; i < n; i++)
{
if (color[i] == -1)
{
ans &= bfs(i);
}
}
printf("%s\n", ans ? "YES" : "NO");
}
}
} | 13.337079 | 46 | 0.443134 | [
"vector"
] |
ec305f52e45ac1542d7c51f4c233b1d2b201a8cc | 577 | hpp | C++ | include/ioh/problem/bbob/gallagher21.hpp | FurongYe/IOHexperimenter | ebc54792cf5b2a3ce23b59c56a6264339ea64072 | [
"BSD-3-Clause"
] | 27 | 2019-03-29T18:06:37.000Z | 2022-02-01T17:15:00.000Z | include/ioh/problem/bbob/gallagher21.hpp | FurongYe/IOHexperimenter | ebc54792cf5b2a3ce23b59c56a6264339ea64072 | [
"BSD-3-Clause"
] | 58 | 2019-08-30T11:16:22.000Z | 2022-03-31T16:57:23.000Z | include/ioh/problem/bbob/gallagher21.hpp | FurongYe/IOHexperimenter | ebc54792cf5b2a3ce23b59c56a6264339ea64072 | [
"BSD-3-Clause"
] | 16 | 2019-07-15T15:09:46.000Z | 2022-02-28T01:26:07.000Z | #pragma once
#include "bbob_problem.hpp"
namespace ioh::problem::bbob
{
//! Gallagher 21 problem id 22
class Gallagher21 final : public Gallagher<Gallagher21>
{
public:
/**
* @brief Construct a new Gallagher 2 1 object
*
* @param instance instance id
* @param n_variables the dimension of the problem
*/
Gallagher21(const int instance, const int n_variables) :
Gallagher(22, instance, n_variables, "Gallagher21", 21, 9.8, 4.9, 1000.)
{
}
};
}
| 25.086957 | 85 | 0.563258 | [
"object"
] |
ec35b4f249069ce3d3d3324097db02e2426b3598 | 11,921 | cpp | C++ | export/windows/obj/src/openfl/_internal/stage3D/GLCompressedTextureFormats.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | export/windows/obj/src/openfl/_internal/stage3D/GLCompressedTextureFormats.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | export/windows/obj/src/openfl/_internal/stage3D/GLCompressedTextureFormats.cpp | seanbashaw/frozenlight | 47c540d30d63e946ea2dc787b4bb602cc9347d21 | [
"MIT"
] | null | null | null | // Generated by Haxe 3.4.7
#include <hxcpp.h>
#ifndef INCLUDED_haxe_IMap
#include <haxe/IMap.h>
#endif
#ifndef INCLUDED_haxe_ds_IntMap
#include <haxe/ds/IntMap.h>
#endif
#ifndef INCLUDED_lime__internal_backend_native_NativeOpenGLRenderContext
#include <lime/_internal/backend/native/NativeOpenGLRenderContext.h>
#endif
#ifndef INCLUDED_lime_graphics_RenderContext
#include <lime/graphics/RenderContext.h>
#endif
#ifndef INCLUDED_openfl__internal_stage3D_GLCompressedTextureFormats
#include <openfl/_internal/stage3D/GLCompressedTextureFormats.h>
#endif
HX_DEFINE_STACK_FRAME(_hx_pos_0594741cd2107140_20_new,"openfl._internal.stage3D.GLCompressedTextureFormats","new",0xe896a2a8,"openfl._internal.stage3D.GLCompressedTextureFormats.new","openfl/_internal/stage3D/GLCompressedTextureFormats.hx",20,0x2202e8a5)
HX_LOCAL_STACK_FRAME(_hx_pos_0594741cd2107140_36_checkDXT,"openfl._internal.stage3D.GLCompressedTextureFormats","checkDXT",0x50d4e330,"openfl._internal.stage3D.GLCompressedTextureFormats.checkDXT","openfl/_internal/stage3D/GLCompressedTextureFormats.hx",36,0x2202e8a5)
HX_LOCAL_STACK_FRAME(_hx_pos_0594741cd2107140_60_checkETC1,"openfl._internal.stage3D.GLCompressedTextureFormats","checkETC1",0x6a1805cd,"openfl._internal.stage3D.GLCompressedTextureFormats.checkETC1","openfl/_internal/stage3D/GLCompressedTextureFormats.hx",60,0x2202e8a5)
HX_LOCAL_STACK_FRAME(_hx_pos_0594741cd2107140_93_checkPVRTC,"openfl._internal.stage3D.GLCompressedTextureFormats","checkPVRTC",0xc1b35ceb,"openfl._internal.stage3D.GLCompressedTextureFormats.checkPVRTC","openfl/_internal/stage3D/GLCompressedTextureFormats.hx",93,0x2202e8a5)
HX_LOCAL_STACK_FRAME(_hx_pos_0594741cd2107140_120_toTextureFormat,"openfl._internal.stage3D.GLCompressedTextureFormats","toTextureFormat",0x8c1b5a3f,"openfl._internal.stage3D.GLCompressedTextureFormats.toTextureFormat","openfl/_internal/stage3D/GLCompressedTextureFormats.hx",120,0x2202e8a5)
namespace openfl{
namespace _internal{
namespace stage3D{
void GLCompressedTextureFormats_obj::__construct( ::lime::graphics::RenderContext context){
HX_GC_STACKFRAME(&_hx_pos_0594741cd2107140_20_new)
HXLINE( 24) this->_hx___formatMapAlpha = ::haxe::ds::IntMap_obj::__alloc( HX_CTX );
HXLINE( 23) this->_hx___formatMap = ::haxe::ds::IntMap_obj::__alloc( HX_CTX );
HXLINE( 29) this->checkDXT(context);
HXLINE( 30) this->checkETC1(context);
HXLINE( 31) this->checkPVRTC(context);
}
Dynamic GLCompressedTextureFormats_obj::__CreateEmpty() { return new GLCompressedTextureFormats_obj; }
void *GLCompressedTextureFormats_obj::_hx_vtable = 0;
Dynamic GLCompressedTextureFormats_obj::__Create(hx::DynamicArray inArgs)
{
hx::ObjectPtr< GLCompressedTextureFormats_obj > _hx_result = new GLCompressedTextureFormats_obj();
_hx_result->__construct(inArgs[0]);
return _hx_result;
}
bool GLCompressedTextureFormats_obj::_hx_isInstanceOf(int inClassId) {
return inClassId==(int)0x00000001 || inClassId==(int)0x276d7fd2;
}
void GLCompressedTextureFormats_obj::checkDXT( ::lime::graphics::RenderContext context){
HX_STACKFRAME(&_hx_pos_0594741cd2107140_36_checkDXT)
HXLINE( 39) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = context->webgl;
HXLINE( 47) ::Dynamic compressedExtension = gl->getExtension(HX_("EXT_texture_compression_s3tc",6a,86,aa,80));
HXLINE( 50) if (hx::IsNotNull( compressedExtension )) {
HXLINE( 52) {
HXLINE( 52) int v = ( (int)(compressedExtension->__Field(HX_("COMPRESSED_RGBA_S3TC_DXT1_EXT",b6,6f,45,f9),hx::paccDynamic)) );
HXDLIN( 52) this->_hx___formatMap->set((int)0,v);
}
HXLINE( 53) {
HXLINE( 53) int v1 = ( (int)(compressedExtension->__Field(HX_("COMPRESSED_RGBA_S3TC_DXT5_EXT",ba,c1,df,46),hx::paccDynamic)) );
HXDLIN( 53) this->_hx___formatMapAlpha->set((int)0,v1);
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(GLCompressedTextureFormats_obj,checkDXT,(void))
void GLCompressedTextureFormats_obj::checkETC1( ::lime::graphics::RenderContext context){
HX_STACKFRAME(&_hx_pos_0594741cd2107140_60_checkETC1)
HXLINE( 63) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = context->webgl;
HXLINE( 80) ::Dynamic compressedExtension = gl->getExtension(HX_("OES_compressed_ETC1_RGB8_texture",cd,f1,a0,b8));
HXLINE( 81) if (hx::IsNotNull( compressedExtension )) {
HXLINE( 83) {
HXLINE( 83) int v = ( (int)(compressedExtension->__Field(HX_("ETC1_RGB8_OES",ab,04,61,eb),hx::paccDynamic)) );
HXDLIN( 83) this->_hx___formatMap->set((int)2,v);
}
HXLINE( 84) {
HXLINE( 84) int v1 = ( (int)(compressedExtension->__Field(HX_("ETC1_RGB8_OES",ab,04,61,eb),hx::paccDynamic)) );
HXDLIN( 84) this->_hx___formatMapAlpha->set((int)2,v1);
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(GLCompressedTextureFormats_obj,checkETC1,(void))
void GLCompressedTextureFormats_obj::checkPVRTC( ::lime::graphics::RenderContext context){
HX_STACKFRAME(&_hx_pos_0594741cd2107140_93_checkPVRTC)
HXLINE( 96) ::lime::_internal::backend::native::NativeOpenGLRenderContext gl = context->webgl;
HXLINE( 105) ::Dynamic compressedExtension = gl->getExtension(HX_("IMG_texture_compression_pvrtc",02,61,85,d1));
HXLINE( 108) if (hx::IsNotNull( compressedExtension )) {
HXLINE( 110) {
HXLINE( 110) int v = ( (int)(compressedExtension->__Field(HX_("COMPRESSED_RGB_PVRTC_4BPPV1_IMG",a1,18,41,ce),hx::paccDynamic)) );
HXDLIN( 110) this->_hx___formatMap->set((int)1,v);
}
HXLINE( 111) {
HXLINE( 111) int v1 = ( (int)(compressedExtension->__Field(HX_("COMPRESSED_RGBA_PVRTC_4BPPV1_IMG",be,45,75,bf),hx::paccDynamic)) );
HXDLIN( 111) this->_hx___formatMapAlpha->set((int)1,v1);
}
}
}
HX_DEFINE_DYNAMIC_FUNC1(GLCompressedTextureFormats_obj,checkPVRTC,(void))
int GLCompressedTextureFormats_obj::toTextureFormat(bool alpha,int gpuFormat){
HX_STACKFRAME(&_hx_pos_0594741cd2107140_120_toTextureFormat)
HXDLIN( 120) if (alpha) {
HXLINE( 122) return ( (int)(this->_hx___formatMapAlpha->get(gpuFormat)) );
}
else {
HXLINE( 126) return ( (int)(this->_hx___formatMap->get(gpuFormat)) );
}
HXLINE( 120) return (int)0;
}
HX_DEFINE_DYNAMIC_FUNC2(GLCompressedTextureFormats_obj,toTextureFormat,return )
hx::ObjectPtr< GLCompressedTextureFormats_obj > GLCompressedTextureFormats_obj::__new( ::lime::graphics::RenderContext context) {
hx::ObjectPtr< GLCompressedTextureFormats_obj > __this = new GLCompressedTextureFormats_obj();
__this->__construct(context);
return __this;
}
hx::ObjectPtr< GLCompressedTextureFormats_obj > GLCompressedTextureFormats_obj::__alloc(hx::Ctx *_hx_ctx, ::lime::graphics::RenderContext context) {
GLCompressedTextureFormats_obj *__this = (GLCompressedTextureFormats_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(GLCompressedTextureFormats_obj), true, "openfl._internal.stage3D.GLCompressedTextureFormats"));
*(void **)__this = GLCompressedTextureFormats_obj::_hx_vtable;
__this->__construct(context);
return __this;
}
GLCompressedTextureFormats_obj::GLCompressedTextureFormats_obj()
{
}
void GLCompressedTextureFormats_obj::__Mark(HX_MARK_PARAMS)
{
HX_MARK_BEGIN_CLASS(GLCompressedTextureFormats);
HX_MARK_MEMBER_NAME(_hx___formatMap,"__formatMap");
HX_MARK_MEMBER_NAME(_hx___formatMapAlpha,"__formatMapAlpha");
HX_MARK_END_CLASS();
}
void GLCompressedTextureFormats_obj::__Visit(HX_VISIT_PARAMS)
{
HX_VISIT_MEMBER_NAME(_hx___formatMap,"__formatMap");
HX_VISIT_MEMBER_NAME(_hx___formatMapAlpha,"__formatMapAlpha");
}
hx::Val GLCompressedTextureFormats_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 8:
if (HX_FIELD_EQ(inName,"checkDXT") ) { return hx::Val( checkDXT_dyn() ); }
break;
case 9:
if (HX_FIELD_EQ(inName,"checkETC1") ) { return hx::Val( checkETC1_dyn() ); }
break;
case 10:
if (HX_FIELD_EQ(inName,"checkPVRTC") ) { return hx::Val( checkPVRTC_dyn() ); }
break;
case 11:
if (HX_FIELD_EQ(inName,"__formatMap") ) { return hx::Val( _hx___formatMap ); }
break;
case 15:
if (HX_FIELD_EQ(inName,"toTextureFormat") ) { return hx::Val( toTextureFormat_dyn() ); }
break;
case 16:
if (HX_FIELD_EQ(inName,"__formatMapAlpha") ) { return hx::Val( _hx___formatMapAlpha ); }
}
return super::__Field(inName,inCallProp);
}
hx::Val GLCompressedTextureFormats_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp)
{
switch(inName.length) {
case 11:
if (HX_FIELD_EQ(inName,"__formatMap") ) { _hx___formatMap=inValue.Cast< ::haxe::ds::IntMap >(); return inValue; }
break;
case 16:
if (HX_FIELD_EQ(inName,"__formatMapAlpha") ) { _hx___formatMapAlpha=inValue.Cast< ::haxe::ds::IntMap >(); return inValue; }
}
return super::__SetField(inName,inValue,inCallProp);
}
void GLCompressedTextureFormats_obj::__GetFields(Array< ::String> &outFields)
{
outFields->push(HX_HCSTRING("__formatMap","\x85","\x98","\x76","\x47"));
outFields->push(HX_HCSTRING("__formatMapAlpha","\x99","\x7c","\xdd","\x0d"));
super::__GetFields(outFields);
};
#if HXCPP_SCRIPTABLE
static hx::StorageInfo GLCompressedTextureFormats_obj_sMemberStorageInfo[] = {
{hx::fsObject /*::haxe::ds::IntMap*/ ,(int)offsetof(GLCompressedTextureFormats_obj,_hx___formatMap),HX_HCSTRING("__formatMap","\x85","\x98","\x76","\x47")},
{hx::fsObject /*::haxe::ds::IntMap*/ ,(int)offsetof(GLCompressedTextureFormats_obj,_hx___formatMapAlpha),HX_HCSTRING("__formatMapAlpha","\x99","\x7c","\xdd","\x0d")},
{ hx::fsUnknown, 0, null()}
};
static hx::StaticInfo *GLCompressedTextureFormats_obj_sStaticStorageInfo = 0;
#endif
static ::String GLCompressedTextureFormats_obj_sMemberFields[] = {
HX_HCSTRING("__formatMap","\x85","\x98","\x76","\x47"),
HX_HCSTRING("__formatMapAlpha","\x99","\x7c","\xdd","\x0d"),
HX_HCSTRING("checkDXT","\x78","\xfa","\xde","\xac"),
HX_HCSTRING("checkETC1","\x85","\x4d","\xe2","\x96"),
HX_HCSTRING("checkPVRTC","\x33","\xd6","\xe7","\xc5"),
HX_HCSTRING("toTextureFormat","\xf7","\x3b","\xc2","\xc3"),
::String(null()) };
static void GLCompressedTextureFormats_obj_sMarkStatics(HX_MARK_PARAMS) {
HX_MARK_MEMBER_NAME(GLCompressedTextureFormats_obj::__mClass,"__mClass");
};
#ifdef HXCPP_VISIT_ALLOCS
static void GLCompressedTextureFormats_obj_sVisitStatics(HX_VISIT_PARAMS) {
HX_VISIT_MEMBER_NAME(GLCompressedTextureFormats_obj::__mClass,"__mClass");
};
#endif
hx::Class GLCompressedTextureFormats_obj::__mClass;
void GLCompressedTextureFormats_obj::__register()
{
hx::Object *dummy = new GLCompressedTextureFormats_obj;
GLCompressedTextureFormats_obj::_hx_vtable = *(void **)dummy;
hx::Static(__mClass) = new hx::Class_obj();
__mClass->mName = HX_HCSTRING("openfl._internal.stage3D.GLCompressedTextureFormats","\xb6","\x6e","\x1e","\x84");
__mClass->mSuper = &super::__SGetClass();
__mClass->mConstructEmpty = &__CreateEmpty;
__mClass->mConstructArgs = &__Create;
__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
__mClass->mMarkFunc = GLCompressedTextureFormats_obj_sMarkStatics;
__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
__mClass->mMembers = hx::Class_obj::dupFunctions(GLCompressedTextureFormats_obj_sMemberFields);
__mClass->mCanCast = hx::TCanCast< GLCompressedTextureFormats_obj >;
#ifdef HXCPP_VISIT_ALLOCS
__mClass->mVisitFunc = GLCompressedTextureFormats_obj_sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mMemberStorageInfo = GLCompressedTextureFormats_obj_sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
__mClass->mStaticStorageInfo = GLCompressedTextureFormats_obj_sStaticStorageInfo;
#endif
hx::_hx_RegisterClass(__mClass->mName, __mClass);
}
} // end namespace openfl
} // end namespace _internal
} // end namespace stage3D
| 45.85 | 291 | 0.761597 | [
"object"
] |
ec41a25ed4fb535d45e1e145fa69a2fe7e833fe4 | 7,486 | cpp | C++ | Dark Basic Public Shared/Official Plugins/3D Cloth & Particles/Code/DBProPhysicsMaster/Vehicle/Physics_RigidBody.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 231 | 2018-01-28T00:06:56.000Z | 2022-03-31T21:39:56.000Z | Dark Basic Public Shared/Official Plugins/3D Cloth & Particles/Code/DBProPhysicsMaster/Vehicle/Physics_RigidBody.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 9 | 2016-02-10T10:46:16.000Z | 2017-12-06T17:27:51.000Z | Dark Basic Public Shared/Official Plugins/3D Cloth & Particles/Code/DBProPhysicsMaster/Vehicle/Physics_RigidBody.cpp | domydev/Dark-Basic-Pro | 237fd8d859782cb27b9d5994f3c34bc5372b6c04 | [
"MIT"
] | 66 | 2018-01-28T21:54:52.000Z | 2022-02-16T22:50:57.000Z | #include "stdafx.h"
RigidBody::RigidBody()
{
mass=1.0f;
invMass=1.0f;
CofG.Init();
MofI.Init();
invMofI.Init();
Reset(true);
}
RigidBody::~RigidBody()
{
}
void RigidBody::Reset(bool resetTransforms)
{
//Resets the dynamics system (and optionally the position and rotation)
if(resetTransforms)
{
world.Init();
invworld.Init();
local.Init();
invlocal.Init();
invMofIT=invMofI;
}
vel.Init();
qLocal.Init();
qLocalVel.Init();
angVel.Init();
angMom.Init();
totForce.Init();
totTorq.Init();
totImpulse.Init();
totRotImpulse.Init();
angThresh.x=0.0f;
angThresh.y=0.0f;
angThresh.z=0.0f;
pCofGValid=false;
updatedParentMatrix=true;
matValid_World=false;
matValid_invWorld=false;
matValid_invLocal=false;
quatValid_Local=false;
matValid_Local=true;
}
//A Note On The Methods Used
//~~~~~~~~~~~~~~~~~~~~~~~~~~
//Forces and points of application must always be converted to parent space.
//(Parent space will be identical to world space if the object has no parent.)
//This is because all the dynamics properties (momentum, angular momentum, etc.) are
//defined in parent space. Parenting an object to another like this isn't physically
//correct, but it is extremely convenient to do this.
//For example: This method allows a space ship to accelerate without its crew
//feeling the the effects of the acceleration. It effectively isolates its child
//objects from it's motion.
//If a child object is required to respond to the parent's motion, then the appropriate
//forces can easily be calculated for the correct response. This can make for extremely
//effective constraint systems.
void RigidBody::addForce(const Vector3 * force, eRefFrame fref, const Vector3 * point,eRefFrame pref)
{
static Vector3 pnt,frc;
//Allow NULL to be passed if they wish when using pref==COFG
if(point) pnt = *point;
frc = *force;
if(fref==LOCAL)
{
Local_RO().rotateV3(&frc); //Transform local force direction into parent space
}
else if(fref==COFG)
{
assert(false); //This should never be used for forces, as it makes no physical sense
}
if(pref==LOCAL)
{
Local_RO().rotateAndTransV3(&pnt); //Transform local point into parent space
}
if(pref!=COFG)
{
pnt-=getPCofG();
totTorq+=pnt*frc;
}
totForce+=frc;
}
void RigidBody::addTorq(const Vector3 * torq, eRefFrame tref)
{
static Vector3 trq;
trq = *torq;
if(tref==LOCAL)
{
Local_RO().rotateV3(&trq); //Transform local torq direction into parent space
}
else if(tref==COFG)
{
assert(false); //This should never be used for this, as it makes no physical sense
}
totTorq+=trq;
}
void RigidBody::addImpulse(const Vector3 * impulse, eRefFrame iref, const Vector3 * point,eRefFrame pref)
{
static Vector3 pnt,imp;
//Allow NULL to be passed if they wish when using pref==COFG
if(point) pnt = *point;
imp = *impulse;
if(iref==LOCAL)
{
Local_RO().rotateV3(&imp); //Transform local force direction into parent space
}
else if(iref==COFG)
{
assert(false); //This should never be used for forces, as it makes no physical sense
}
if(iref==LOCAL)
{
Local_RO().rotateAndTransV3(&pnt); //Transform local point into parent space
}
if(pref!=COFG)
{
pnt-=getPCofG();
totRotImpulse+=pnt*imp;
}
totImpulse+=imp;
}
void RigidBody::addRotImpulse(const Vector3 * impulse, eRefFrame iref, const Vector3 * point,eRefFrame pref)
{
static Vector3 pnt,imp;
pnt = *point;
imp = *impulse;
if(iref==LOCAL)
{
Local_RO().rotateV3(&imp); //Transform local force direction into parent space
}
else if(iref==COFG)
{
assert(false); //This should never be used for forces, as it makes no physical sense
}
if(iref==LOCAL)
{
Local_RO().rotateAndTransV3(&pnt); //Transform local point into parent space
}
if(pref!=COFG)
{
pnt-=getPCofG();
totRotImpulse+=pnt*imp;
}
//totImpulse+=imp;
}
void RigidBody::addRotImpulse(const Vector3 * rotImp, eRefFrame iref)
{
static Vector3 trq;
trq = *rotImp;
if(iref==LOCAL)
{
Local_RO().rotateV3(&trq); //Transform local rotImpulse direction into parent space
}
else if(iref==COFG)
{
assert(false); //This should never be used for this, as it makes no physical sense
}
totRotImpulse+=trq;
}
void RigidBody::addImpulseAndUpdate(const Vector3 * impulse, eRefFrame iref, const Vector3 * point,eRefFrame pref)
{
Vector3 imp(totImpulse);
Vector3 rotimp(totRotImpulse);
addImpulse(impulse,iref,point,pref);
imp = totImpulse-imp;
rotimp = totRotImpulse-rotimp;
totImpulse-=imp;
totRotImpulse-=rotimp;
//Add in impulses
vel+=imp*invMass;
angMom+= rotimp;
if(angMom.x<angThresh.x && angMom.x>-angThresh.x) angMom.x=0.0f;
if(angMom.y<angThresh.y && angMom.y>-angThresh.y) angMom.y=0.0f;
if(angMom.z<angThresh.z && angMom.z>-angThresh.z) angMom.z=0.0f;
//Calculate angular velocity
invMofIT.rotateV3(angMom,&angVel);
//Calculate rate of change of rotation quaternion
qLocalVel = 0.5f*Quat(angVel)*quatLocal_RO();
}
const Matrix& RigidBody::World()
{
if(!matValid_World)
{
//No parent exists, so world==local
world=Local_RO();
}
matValid_World=true;
return world;
}
const Matrix& RigidBody::invWorld()
{
if(!matValid_invWorld)
{
//Assumes orthogonal matrices
invworld=World();
invworld.TransposeThis();
matValid_invWorld=true;
}
return invworld;
}
const Matrix& RigidBody::Local_RO()
{
//Use for read only access
if(!matValid_Local)
{
assert(quatValid_Local); //local quaternion must be valid for this to happen
local.set3x3ToQuat(qLocal);
matValid_Local=true;
}
return local;
}
Matrix& RigidBody::Local_RW()
{
//This will be more expensive as it marks the other matrices to be recalculated
if(!matValid_Local)
{
assert(quatValid_Local); //local quaternion must be valid for this to happen
local.set3x3ToQuat(qLocal);
matValid_Local=true;
}
matValid_World=false;
matValid_invWorld=false;
matValid_invLocal=false;
quatValid_Local=false;
return local;
}
const Quat& RigidBody::quatLocal_RO()
{
//Use for read only access
if(!quatValid_Local)
{
assert(matValid_Local);//local matrix must be valid for this to happen
qLocal.Set(local);
quatValid_Local=true;
}
return qLocal;
}
Quat& RigidBody::quatLocal_RW()
{
//This will be more expensive as it marks the other matrices to be recalculated
if(!quatValid_Local)
{
assert(matValid_Local); //local matrix must be valid for this to happen
qLocal.Set(local);
quatValid_Local=true;
}
matValid_World=false;
matValid_invWorld=false;
matValid_invLocal=false;
matValid_Local=false;
return qLocal;
}
const Matrix& RigidBody::invLocal()
{
if(!matValid_invLocal)
{
//Assumes orthogonal matrices
invlocal=Local_RO();
invlocal.TransposeThis();
matValid_invLocal=true;
}
return invlocal;
}
void RigidBody::getPointWorldVel(const Vector3& localP, Vector3 * velOut)
{
//p is in local space for the rigid body
static Vector3 pnt,tmpVel;
pnt=localP;
pnt-=CofG;
Local_RO().rotateV3(&pnt);
*velOut=vel+angVel*pnt;
}
const Vector3& RigidBody::getPCofG()
{
//Transfer local space centre of gravity into parent space
if(!pCofGValid)
{
Local_RO().rotateAndTransV3(CofG,&pCofG);
}
return pCofG;
}
| 19.444156 | 114 | 0.686214 | [
"object",
"transform"
] |
ec488b0f06c5c2b93d5a4ead201458b59a1b7b50 | 1,376 | cpp | C++ | SlidingWindow/SlidingWindowMaximum.cpp | Ayush-projects/Leetcode_Sol | 123331fb6b5ec2d5993bb57b5a14a9d0ebe96f82 | [
"MIT"
] | 6 | 2021-10-08T13:22:59.000Z | 2022-03-04T19:44:04.000Z | SlidingWindow/SlidingWindowMaximum.cpp | Ayush-projects/Leetcode_Sol | 123331fb6b5ec2d5993bb57b5a14a9d0ebe96f82 | [
"MIT"
] | 3 | 2021-10-09T07:34:57.000Z | 2021-10-15T13:03:28.000Z | SlidingWindow/SlidingWindowMaximum.cpp | Ayush-projects/Leetcode_Sol | 123331fb6b5ec2d5993bb57b5a14a9d0ebe96f82 | [
"MIT"
] | 8 | 2021-10-08T17:02:24.000Z | 2022-01-08T20:17:12.000Z | //link of the question
//https://leetcode.com/problems/sliding-window-maximum/submissions/
//1)brute_force solution
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int>ans;
int n=nums.size();
int mx;
for (int i = 0; i <= n - k; i++)
{
mx = nums[i];
for (int j = 1; j < k; j++)
{
if (nums[i + j] > mx)
mx = nums[i + j];
}
ans.push_back(mx);
}
return ans;
}
};
//2) sliding window solution
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int>ans;
//suppose if k is greater than nums.size()
if (k>nums.size()) {
ans.push_back(*max_element(nums.begin(),nums.end()));
return ans;
}
int i=0,j=0;
list<int>ls;
while(j<nums.size()){
while(ls.size()>0 && ls.back()<nums[j]){
ls.pop_back();
}
ls.push_back(nums[j]);
if(j-i+1<k){
j++;
}else if(j-i+1==k){
ans.push_back(ls.front());
if(ls.front()==nums[i]){
ls.pop_front();
}
i++;
j++;
}
}
return ans;
}
};
| 22.933333 | 67 | 0.428052 | [
"vector"
] |
ec584b2cd1d21221cb5b41e69dd21485d638f5a1 | 4,844 | hpp | C++ | libs/rucksack/include/sge/rucksack/widget/box.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/rucksack/include/sge/rucksack/widget/box.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/rucksack/include/sge/rucksack/widget/box.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_RUCKSACK_WIDGET_BOX_HPP_INCLUDED
#define SGE_RUCKSACK_WIDGET_BOX_HPP_INCLUDED
#include <sge/core/detail/class_symbol.hpp>
#include <sge/rucksack/alignment.hpp>
#include <sge/rucksack/axis.hpp>
#include <sge/rucksack/axis_policy2_fwd.hpp>
#include <sge/rucksack/dim.hpp>
#include <sge/rucksack/padding.hpp>
#include <sge/rucksack/vector.hpp>
#include <sge/rucksack/detail/symbol.hpp>
#include <sge/rucksack/widget/base.hpp>
#include <sge/rucksack/widget/reference.hpp>
#include <sge/rucksack/widget/reference_alignment_container.hpp>
#include <fcppt/nonmovable.hpp>
#include <fcppt/config/external_begin.hpp>
#include <list>
#include <utility>
#include <fcppt/config/external_end.hpp>
namespace sge::rucksack::widget
{
/**
\brief Align child widgets next to each other in a box.
\details
The box class behaves just like the Qt box layout. It aligns its children
either vertically or horizontally (determined by the "axis" parameter which
specifies the "major axis" of alignment; hozirontal alignment has axis::x,
vertical has axis::y).
*/
class SGE_CORE_DETAIL_CLASS_SYMBOL box : public sge::rucksack::widget::base
{
FCPPT_NONMOVABLE(box);
using child_pair = std::pair<sge::rucksack::widget::reference, sge::rucksack::alignment>;
using child_list = std::list<child_pair>;
public:
SGE_RUCKSACK_DETAIL_SYMBOL
box(sge::rucksack::axis, sge::rucksack::padding);
SGE_RUCKSACK_DETAIL_SYMBOL
box(sge::rucksack::axis,
sge::rucksack::padding,
sge::rucksack::widget::reference_alignment_container const &);
// Nothing fancy, just set the stored size (this should NOT cause a relayout
// immediately)
SGE_RUCKSACK_DETAIL_SYMBOL
void size(sge::rucksack::dim const &) override;
using sge::rucksack::widget::base::size;
// Nothing fancy, just set the stored position (this should NOT cause a
// relayout immediately)
SGE_RUCKSACK_DETAIL_SYMBOL
void position(sge::rucksack::vector const &) override;
using sge::rucksack::widget::base::position;
[[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::dim size() const override;
[[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::vector position() const override;
// We have to calculate/set:
//
// 1. The minimum size (for each axis)
// 2. The preferred size (for each axis)
// 3. If the widget is expandable (for each axis)
// 4. Aspect
//
// The minimum size for the _major_ axis is easy: We just accumulate the
// minimum sizes of all the children.
//
// The minimum size of the _minor_ axis is equally simple: Take the maximum
// of all the children's sizes.
//
// For the preferred size, we forward to the minimum size if the preferred
// size is not given. If it _is_ given, we do the same as in the minimum
// case, just with "preferred" instead of "minimum".
//
// Finally, the widget is expandable on each axis if there's at least one
// widget that's expandable.
//
// Also note that currently, box widgets always have a preferred size (which
// might be equal to the minimum size).
[[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL sge::rucksack::axis_policy2 axis_policy() const override;
// This does a lot of stuff, see the code itself.
SGE_RUCKSACK_DETAIL_SYMBOL
void relayout() override;
SGE_RUCKSACK_DETAIL_SYMBOL
void push_back_child(sge::rucksack::widget::reference, sge::rucksack::alignment);
SGE_RUCKSACK_DETAIL_SYMBOL
void push_front_child(sge::rucksack::widget::reference, sge::rucksack::alignment);
SGE_RUCKSACK_DETAIL_SYMBOL
void pop_back_child();
SGE_RUCKSACK_DETAIL_SYMBOL
void pop_front_child();
SGE_RUCKSACK_DETAIL_SYMBOL
void clear();
using iterator = child_list::iterator;
using size_type = child_list::size_type;
[[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL iterator child_position(size_type);
[[nodiscard]] SGE_RUCKSACK_DETAIL_SYMBOL size_type children_size() const;
SGE_RUCKSACK_DETAIL_SYMBOL
void replace_children(iterator, sge::rucksack::widget::reference, sge::rucksack::alignment);
SGE_RUCKSACK_DETAIL_SYMBOL
~box() override;
private:
void insert_child(iterator, sge::rucksack::widget::reference, sge::rucksack::alignment);
iterator erase_child(iterator);
child_list children_;
sge::rucksack::axis const axis_;
sge::rucksack::padding const padding_;
sge::rucksack::vector position_;
sge::rucksack::dim size_;
[[nodiscard]] sge::rucksack::axis major_axis() const;
[[nodiscard]] sge::rucksack::axis minor_axis() const;
void child_destroyed(sge::rucksack::widget::base & // NOLINT(google-runtime-references)
) override;
};
}
#endif
| 31.251613 | 100 | 0.743394 | [
"vector"
] |
ec590b1c58ea30dc43c9d8813298f5916928b810 | 7,103 | cpp | C++ | OutputMethods/S3DShutter/Output_dx9.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 27 | 2020-11-12T19:24:54.000Z | 2022-03-27T23:10:45.000Z | OutputMethods/S3DShutter/Output_dx9.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 2 | 2020-11-02T06:30:39.000Z | 2022-02-23T18:39:55.000Z | OutputMethods/S3DShutter/Output_dx9.cpp | bo3b/iZ3D | ced8b3a4b0a152d0177f2e94008918efc76935d5 | [
"MIT"
] | 3 | 2021-08-16T00:21:08.000Z | 2022-02-23T19:19:36.000Z | /* IZ3D_FILE: $Id$
*
* Project : iZ3D Stereo Driver
* Copyright (C) iZ3D Inc. 2002 - 2010
*
* $Author$
* $Revision$
* $Date$
* $LastChangedBy$
* $URL$
*/
// Output.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "Output_dx9.h"
#include "S3DWrapper9\BaseSwapChain.h"
#include <tinyxml.h>
#include "ProductNames.h"
#include "..\CommonUtils\StringUtils.h"
#include "..\CommonUtils\CommonResourceFolders.h"
using namespace DX9Output;
using namespace std;
#ifdef _MANAGED
#pragma managed(push, off)
#endif
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#ifdef _MANAGED
#pragma managed(pop)
#endif
OUTPUT_API void* CALLBACK CreateOutputDX9(DWORD mode, DWORD spanMode)
{
return new S3DShutterOutput(mode, spanMode);
}
OUTPUT_API DWORD CALLBACK GetOutputCaps()
{
return odShutterModeSimpleOnly;
}
OUTPUT_API void CALLBACK GetOutputName(char* name, DWORD size)
{
strcpy_s(name, size, "Shutter mode");
}
OUTPUT_API BOOL CALLBACK EnumOutputModes(DWORD num, char* name, DWORD size)
{
switch(num)
{
case 0:
strcpy_s(name, size, "Marked shutter");
return TRUE;
default:
return FALSE;
}
}
S3DShutterOutput::S3DShutterOutput(DWORD mode, DWORD spanMode)
: OutputMethod(mode, spanMode)
{
}
S3DShutterOutput::~S3DShutterOutput(void)
{
}
HRESULT S3DShutterOutput::Initialize( IDirect3DDevice9* dev, bool MultiPass /*= false*/ )
{
HRESULT hResult = OutputMethod::Initialize(dev, MultiPass);
if(SUCCEEDED(hResult))
{
const char* specVersion;
const char* format = "";
m_MarkerIndex = 0;
m_MarkerSurfaceWidth = 0;
m_NumberOfMarkedLines = 0;
m_NumberOfMarks = 0;
m_InverseAxisYDirection = 0;
m_ScaleToFrame = 0;
m_ScaleFactor = .75;
vector< vector<DWORD> > LeftMark, RightMark;
TCHAR XMLFileName[MAX_PATH];
hResult = E_FAIL;
if(iz3d::resources::GetAllUsersDirectory( XMLFileName ))
{
PathAppend(XMLFileName, _T("MarkingSpec.xml") );
TiXmlDocument MarkFile( common::utils::to_multibyte( XMLFileName ).c_str() );
if(MarkFile.LoadFile())
{
TiXmlHandle docHandle( &MarkFile );
TiXmlHandle frameHandle = docHandle.FirstChild("FrameMarkingSpec");
TiXmlElement* element = frameHandle.Element();
if(element)
{
specVersion = element->Attribute("version");
if(strcmp(specVersion,"0.2") == 0)
{
ParseVersion_0_2(frameHandle, format, LeftMark, RightMark);
hResult = S_OK;
}
if(strcmp(specVersion,"0.3") == 0)
{
ParseVersion_0_2(frameHandle, format, LeftMark, RightMark);
ParseVersion_0_3(frameHandle);
hResult = S_OK;
}
}
}
}
//--- if some bug found while reading XML file - draw red line on top screen line ---
if(FAILED(hResult))
{
m_NumberOfMarkedLines = 16;
m_NumberOfMarks = 1;
m_InverseAxisYDirection = 0;
m_ScaleToFrame = 1;
m_ScaleFactor = 1;
LeftMark.clear(); LeftMark.push_back(vector<DWORD>(1, 0xFF0000));
RightMark.clear(); RightMark.push_back(vector<DWORD>(1, 0xFF0000));
m_MarkerSurfaceWidth = (UINT)LeftMark[0].size();
}
if(SUCCEEDED(dev->CreateOffscreenPlainSurface(m_MarkerSurfaceWidth, m_NumberOfMarks * 2, D3DFMT_X8R8G8B8, D3DPOOL_DEFAULT, &m_pMarkerSurface, NULL)))
{
D3DLOCKED_RECT rect;
m_pMarkerSurface->LockRect(&rect, NULL, D3DLOCK_DISCARD);
char* p1 = (char*)rect.pBits;
char* p2 = p1 + rect.Pitch * m_NumberOfMarks;
for(UINT i=0; i< m_NumberOfMarks; i++)
{
memcpy(p1, &LeftMark[i][0], m_MarkerSurfaceWidth * sizeof(DWORD));
memcpy(p2, &RightMark[i][0], m_MarkerSurfaceWidth * sizeof(DWORD));
p1 += rect.Pitch;
p2 += rect.Pitch;
}
m_pMarkerSurface->UnlockRect();
}
}
return hResult;
}
void S3DShutterOutput::ParseMarkLine( TiXmlElement* element, vector<vector<DWORD> >& MarkArray)
{
for(int index = 0; element; index++, element = element->NextSiblingElement())
{
MarkArray.push_back(vector<DWORD>());
if(const char* s = element->GetText())
{
const char* t = s;
UINT length = (UINT)strlen(s);
while(t < s + length)
{
DWORD color;
sscanf(t, "%x", &color); t+= 7;
MarkArray[index].push_back(color);
}
}
}
}
void S3DShutterOutput::ParseVersion_0_2(TiXmlHandle& frameHandle, const char* &format, vector< vector<DWORD> > &LeftMark, vector< vector<DWORD> > &RightMark)
{
TiXmlElement* element = frameHandle.Element();
element->QueryIntAttribute("NumberOfMarkedLines", (int*)&m_NumberOfMarkedLines);
TiXmlHandle lineHandle = frameHandle.FirstChild();
element = lineHandle.Element();
if(element)
{
format = element->Attribute("ColorFormat");
element->QueryIntAttribute("NumberOfMarks", (int*)&m_NumberOfMarks);
}
if(strcmpi(format, "r8g8b8_hex") == 0)
{
element = lineHandle.Child("LeftFrameMarks", 0).FirstChild().Element();
ParseMarkLine(element, LeftMark);
element = lineHandle.Child("RightFrameMarks", 0).FirstChild().Element();
ParseMarkLine(element, RightMark);
m_MarkerSurfaceWidth = (UINT)LeftMark[0].size();
}
}
void S3DShutterOutput::ParseVersion_0_3(TiXmlHandle& frameHandle)
{
TiXmlHandle lineHandle = frameHandle.FirstChild();
TiXmlElement* element = lineHandle.Element();
if(element)
{
element->QueryIntAttribute("InverseAxisYDirection", (int*)&m_InverseAxisYDirection);
element->QueryIntAttribute("ScaleToFrame", (int*)&m_ScaleToFrame);
element->QueryFloatAttribute("ScaleFactor", (float*)&m_ScaleFactor);
}
}
void S3DShutterOutput::Clear()
{
OutputMethod::Clear();
m_pMarkerSurface.Release();
}
HRESULT S3DShutterOutput::Output(bool bLeft, CBaseSwapChain* pSwapChain, RECT* pDestRect)
{
HRESULT hResult = S_OK;
IDirect3DSurface9* view = pSwapChain->GetViewRT(bLeft);
RECT* pViewRect = pSwapChain->GetViewRect(bLeft);
IDirect3DSurface9* primary = pSwapChain->GetPresenterBackBuffer();
IDirect3DSurface9* secondary = pSwapChain->m_pSecondaryBackBuffer;
SIZE bbSize = pSwapChain->m_BackBufferSize;
RECT MarkRectSrc, MarkRectDst;
int width = min(bbSize.cx, (int)m_MarkerSurfaceWidth);
if (bLeft)
SetRect(&MarkRectSrc, 0, m_MarkerIndex, width, m_MarkerIndex + 1);
else
SetRect(&MarkRectSrc, 0, m_MarkerIndex + m_NumberOfMarks, width, m_MarkerIndex + m_NumberOfMarks + 1);
int destSizeX = width, destStartY = 0;
if(m_InverseAxisYDirection)
destStartY = bbSize.cy - m_NumberOfMarkedLines;
if(m_ScaleToFrame)
destSizeX = (int)(m_ScaleFactor * bbSize.cx);
SetRect(&MarkRectDst, 0, destStartY, destSizeX, destStartY + m_NumberOfMarkedLines);
if (pDestRect)
{
MarkRectDst.left += pDestRect->left;
MarkRectDst.top += pDestRect->top;
MarkRectDst.right += pDestRect->left;
MarkRectDst.bottom += pDestRect->top;
}
m_MarkerIndex = (++m_MarkerIndex) % m_NumberOfMarks;
NSCALL(m_pd3dDevice->StretchRect(view, pViewRect, primary, pDestRect, D3DTEXF_NONE));
NSCALL(m_pd3dDevice->StretchRect(m_pMarkerSurface, &MarkRectSrc, primary, &MarkRectDst, D3DTEXF_POINT));
return hResult;
} | 27.638132 | 157 | 0.718992 | [
"vector"
] |
ec6d911cb15aa0370b0d7fdc1eca3fc0e1b87a15 | 7,992 | cpp | C++ | ace/tao/examples/Quoter/Factory_Finder.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 46 | 2015-12-04T17:12:58.000Z | 2022-03-11T04:30:49.000Z | ace/tao/examples/Quoter/Factory_Finder.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | null | null | null | ace/tao/examples/Quoter/Factory_Finder.cpp | tharindusathis/sourcecodes-of-CodeReadingTheOpenSourcePerspective | 1b0172cdb78757fd17898503aaf6ce03d940ef28 | [
"Apache-1.1"
] | 23 | 2016-10-24T09:18:14.000Z | 2022-02-25T02:11:35.000Z | // Factory_Finder.cpp,v 1.8 2001/03/06 22:05:52 brunsch Exp
// ============================================================================
//
// = FILENAME
// FactoryFinder.cpp
//
// = DESCRIPTION
// A Factory Finder for the Quoter example. This example conforms
// to the CosLifeCycle Factory Finder notion.
//
// = AUTHOR
// Michael Kircher (mk1@cs.wustl.edu)
//
// ============================================================================
#include "tao/corba.h"
#include "Factory_Finder.h"
ACE_RCSID(Quoter, Factory_Finder, "Factory_Finder.cpp,v 1.8 2001/03/06 22:05:52 brunsch Exp")
Quoter_Factory_Finder_Server::Quoter_Factory_Finder_Server (void)
: debug_level_ (1)
{
// Nothing
}
Quoter_Factory_Finder_Server::~Quoter_Factory_Finder_Server (void)
{
ACE_TRY_NEW_ENV
{
// Unbind the Quoter Factory Finder.
CosNaming::Name factory_Finder_Name (2);
factory_Finder_Name.length (2);
factory_Finder_Name[0].id = CORBA::string_dup ("IDL_Quoter");
factory_Finder_Name[1].id = CORBA::string_dup ("Quoter_Factory_Finder");
if (this->quoterNamingContext_var_.ptr () != 0)
this->quoterNamingContext_var_->unbind (factory_Finder_Name, ACE_TRY_ENV);
ACE_TRY_CHECK;
}
ACE_CATCHANY
{
ACE_ERROR ((LM_ERROR, "Could not unbind the Factor Finder from the Name Service\n"));
ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "~Quoter_Factor_Finder_Server");
}
ACE_ENDTRY;
}
int
Quoter_Factory_Finder_Server::init (int argc,
char *argv[],
CORBA::Environment &ACE_TRY_ENV)
{
const char *exception_message = "Null Message";
ACE_TRY
{
exception_message = "While ORB_Manager::init";
if (this->orb_manager_.init (argc,
argv,
ACE_TRY_ENV) == -1)
ACE_ERROR_RETURN ((LM_ERROR,
"%p\n",
"init"),
-1);
ACE_TRY_CHECK;
// Activate the POA manager
exception_message = "While activating the POA manager";
int result = this->orb_manager_.activate_poa_manager (ACE_TRY_ENV);
ACE_TRY_CHECK;
if (result == -1)
ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "activate_poa_manager"), -1);
// Copy them, because parse_args expects them there.
this->argc_ = argc;
this->argv_ = argv;
this->parse_args ();
ACE_NEW_RETURN (this->quoter_Factory_Finder_i_ptr_,
Quoter_Factory_Finder_i(this->debug_level_),
-1);
// Activate the object.
exception_message = "Failure while activating the Quoter Factory Finder Impl";
CORBA::String_var str =
this->orb_manager_.activate (this->quoter_Factory_Finder_i_ptr_,
ACE_TRY_ENV);
ACE_TRY_CHECK;
// Print the IOR.
if (this->debug_level_ >= 2)
ACE_DEBUG ((LM_DEBUG, "Factory Finder: IOR is: <%s>\n", str.in ()));
// Register the Quoter Factory Finder with the Naming Service
if (this->debug_level_ >= 2)
ACE_DEBUG ((LM_DEBUG,"Factory Finder: Trying to get a reference to the Naming Service.\n"));
// Get the Naming Service object reference.
exception_message = "While resolving the Name Service";
CORBA::Object_var namingObj_var =
orb_manager_.orb()->resolve_initial_references ("NameService", ACE_TRY_ENV);
ACE_TRY_CHECK;
if (CORBA::is_nil (namingObj_var.in ()))
ACE_ERROR ((LM_ERROR,
" (%P|%t) Unable get the Naming Service.\n"));
// Narrow the object reference to a Naming Context.
exception_message = "While narrowing the Naming Context";
CosNaming::NamingContext_var namingContext_var =
CosNaming::NamingContext::_narrow (namingObj_var.in (),
ACE_TRY_ENV);
ACE_TRY_CHECK;
// Get the IDL_Quoter naming context.
CosNaming::Name quoterContextName (1); // max = 1
quoterContextName.length (1);
quoterContextName[0].id = CORBA::string_dup ("IDL_Quoter");
exception_message = "While resolving the Quoter Naming Context";
CORBA::Object_var quoterNamingObj_var =
namingContext_var->resolve (quoterContextName, ACE_TRY_ENV);
ACE_TRY_CHECK;
exception_message = "While narrowing the Quoter Naming Context";
quoterNamingContext_var_ =
CosNaming::NamingContext::_narrow (quoterNamingObj_var.in (),
ACE_TRY_ENV);
ACE_TRY_CHECK;
if (this->debug_level_ >= 2)
ACE_DEBUG ((LM_DEBUG,
"Factory Finder: Have a proper reference to the Quoter Naming Context.\n"));
// Bind the QuoterFactory Finder to the IDL_Quoter naming
// context.
CosNaming::Name quoter_Factory_Finder_Name_ (1);
quoter_Factory_Finder_Name_.length (1);
quoter_Factory_Finder_Name_[0].id = CORBA::string_dup ("Quoter_Factory_Finder");
exception_message = "Factory_Factory::_this";
CORBA::Object_var ff_obj = this->quoter_Factory_Finder_i_ptr_->_this(ACE_TRY_ENV);
ACE_TRY_CHECK;
exception_message = "While binding the Factory Finder";
quoterNamingContext_var_->bind (quoter_Factory_Finder_Name_,
ff_obj.in (),
ACE_TRY_ENV);
ACE_TRY_CHECK;
if (this->debug_level_ >= 2)
ACE_DEBUG ((LM_DEBUG,
"Factory_Finder: Bound the Quoter Factory Finder to the Quoter Naming Context.\n"));
}
ACE_CATCHANY
{
ACE_ERROR ((LM_ERROR, "Quoter_Factor_Finder_Server::init - %s\n", exception_message));
ACE_PRINT_EXCEPTION (ACE_ANY_EXCEPTION, "SYS_EX");
return -1;
}
ACE_ENDTRY;
return 0;
}
int
Quoter_Factory_Finder_Server::run (CORBA::Environment &ACE_TRY_ENV)
{
if (this->debug_level_ >= 1)
ACE_DEBUG ((LM_DEBUG,
"\nQuoter Example: Quoter_Factory_Finder_Server is running\n"));
orb_manager_.orb()->run (ACE_TRY_ENV);
ACE_CHECK_RETURN (-1);
return 0;
}
// Function get_options.
u_int
Quoter_Factory_Finder_Server::parse_args (void)
{
ACE_Get_Opt get_opt (this->argc_, this->argv_, "?d:");
int opt;
int exit_code = 0;
while ((opt = get_opt ()) != EOF)
switch (opt)
{
case 'd': // debug flag.
this->debug_level_ = ACE_OS::atoi (get_opt.optarg);
break;
default:
exit_code = 1;
ACE_ERROR ((LM_ERROR,
"%s: unknown arg, -%c\n",
this->argv_[0], char(opt)));
case '?':
ACE_DEBUG ((LM_DEBUG,
"usage: %s"
" [-d] <debug level> - Set the debug level\n"
" [-?] - Prints this message\n"
"\n",
this->argv_[0]));
ACE_OS::exit (exit_code);
break;
}
return 0;
}
// function main
int
main (int argc, char *argv [])
{
Quoter_Factory_Finder_Server quoter_Factory_Finder_Server;
ACE_TRY_NEW_ENV
{
int result = quoter_Factory_Finder_Server.init (argc, argv, ACE_TRY_ENV);
ACE_TRY_CHECK;
if (result == -1)
return 1;
else
{
quoter_Factory_Finder_Server.run (ACE_TRY_ENV);
ACE_TRY_CHECK;
}
}
ACE_CATCH (CORBA::SystemException, sysex)
{
ACE_PRINT_EXCEPTION (sysex, "System Exception");
return -1;
}
ACE_CATCH (CORBA::UserException, userex)
{
ACE_PRINT_EXCEPTION (userex, "User Exception");
return -1;
}
ACE_ENDTRY;
return 0;
}
| 31.968 | 105 | 0.576201 | [
"object"
] |
ec73390c3f8ed4aef1847e5125f56e77a4c0e1de | 2,084 | cpp | C++ | algorithm/permuteUnique.cpp | jmaoito/happyCoding | 59bb1b1b6d390b5f3cbfdd8d78d2383cd00565e4 | [
"Apache-2.0"
] | null | null | null | algorithm/permuteUnique.cpp | jmaoito/happyCoding | 59bb1b1b6d390b5f3cbfdd8d78d2383cd00565e4 | [
"Apache-2.0"
] | null | null | null | algorithm/permuteUnique.cpp | jmaoito/happyCoding | 59bb1b1b6d390b5f3cbfdd8d78d2383cd00565e4 | [
"Apache-2.0"
] | null | null | null | /*******************************
LeetCode Permutations II
Given a collection of numbers that might contain duplicates, return all
possible unique permutations.
For example,
[1,1,2] have the following unique permutations:
[1,1,2], [1,2,1], and [2,1,1].
Tags: Backtracking
Discussion: calling nextPermutation(), see permutations I
implement a recursive function. the length of intermediate result p can be
used to judge the convergence.
time complexity O(n!), space complexity O(n);
***********************/
class Solution {
public:
vector<vector<int> > permuteUnique(vector<int> &num) {
sort(num.begin(), num.end());
unordered_map<int, int> count_map; // 记录每个元素的出现次数
for_each(num.begin(), num.end(), [&count_map](int e) {
if (count_map.find(e) != count_map.end())
count_map[e]++;
else
count_map[e] = 1;
});
// 将 map 里的 pair 拷贝到一个 vector 里
vector<pair<int, int> > elems;
for_each(count_map.begin(), count_map.end(),
[&elems](const pair<int, int> &e) {
elems.push_back(e);
});
vector<vector<int>> result; // 最终结果
vector<int> p; // 中间结果
n = num.size();
permute(elems.begin(), elems.end(), p, result);
return result;
}
private:
size_t n;
typedef vector<pair<int, int> >::const_iterator Iter;
void permute(Iter first, Iter last, vector<int> &p,
vector<vector<int> > &result) {
if (n == p.size()) { // 收敛条件
result.push_back(p);
}
// 扩展状态
for (auto i = first; i != last; i++) {
int count = 0; // 统计 *i 在 p 中出现过多少次
for (auto j = p.begin(); j != p.end(); j++) {
if (i->first == *j) {
count ++;
}
}
if (count < i->second) {
p.push_back(i->first);
permute(first, last, p, result);
p.pop_back(); // 撤销动作,返回上一层
}
}
}
};
| 30.647059 | 77 | 0.503839 | [
"vector"
] |
3f40a5d4dc79fd25927b7f40631a37d2bc1bb2f6 | 27,735 | cpp | C++ | connectors/dds4ccm/tests/filters/filter_attrib/listeners/state/receiver/fa_sl_receiver_exec.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 7 | 2016-04-12T15:09:33.000Z | 2022-01-26T02:28:28.000Z | connectors/dds4ccm/tests/filters/filter_attrib/listeners/state/receiver/fa_sl_receiver_exec.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 10 | 2019-11-26T15:24:01.000Z | 2022-03-28T11:45:14.000Z | connectors/dds4ccm/tests/filters/filter_attrib/listeners/state/receiver/fa_sl_receiver_exec.cpp | jwillemsen/ciaox11 | 483dd0f189a92615068366f566ea8354a1baf7a3 | [
"MIT"
] | 5 | 2016-04-12T18:40:44.000Z | 2019-12-18T14:27:52.000Z | // -*- C++ -*-
/**
* @file fa_sl_receiver_exec.cpp
* @author Marcel Smit
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
//@@{__RIDL_REGEN_MARKER__} - HEADER_END : fa_sl_receiver_impl.cpp[Header]
#include "fa_sl_receiver_exec.h"
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl[user_includes]
#include "dds4ccm/tests/filters/common/listeners/state/receiver/filters_common_sl_receiver_checks.h"
#include "dds4ccm/tests/common/dds4ccm_test_utils.h"
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl[user_includes]
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl[user_global_impl]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl[user_global_impl]
namespace FA_State_Listen_Test_Receiver_Impl
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl[user_namespace_impl]
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl[user_namespace_impl]
/**
* Facet Executor Implementation Class : listen_port_1_data_listener_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i[ctor]
listen_port_1_data_listener_exec_i::listen_port_1_data_listener_exec_i (
IDL::traits<FA_State_Listen_Test::CCM_Receiver_Context>::ref_type context,
std::atomic_ullong &created,
std::atomic_ullong &updated,
std::atomic_ullong &deleted)
: context_ (std::move (context))
, created_ (created)
, updated_ (updated)
, deleted_ (deleted)
{
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i[ctor]
listen_port_1_data_listener_exec_i::~listen_port_1_data_listener_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i[user_private_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i[user_private_ops]
/** Operations and attributes from listen_port_1_data_listener */
void
listen_port_1_data_listener_exec_i::on_creation (
const ::CommonTestMessage& datum,
const ::CCM_DDS::ReadInfo& info)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i::on_creation[_datum_info]
X11_UNUSED_ARG(info);
++this->created_;
check_on_creation_obo (datum);
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i::on_creation[_datum_info]
}
void
listen_port_1_data_listener_exec_i::on_one_update (
const ::CommonTestMessage& datum,
const ::CCM_DDS::ReadInfo& info)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i::on_one_update[_datum_info]
X11_UNUSED_ARG(info);
++this->updated_;
check_on_one_update (
"listen_port_1_data_listener_exec_i::on_one_update",
datum);
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i::on_one_update[_datum_info]
}
void
listen_port_1_data_listener_exec_i::on_many_updates (
const ::CommonTestMessageSeq& data,
const ::CCM_DDS::ReadInfoSeq& infos)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i::on_many_updates[_data_infos]
X11_UNUSED_ARG (data);
X11_UNUSED_ARG (infos);
DDS4CCM_TEST_ERROR << "ERROR: listen_port_1_data_listener_exec_i::on_many_updates - "
<< "Unexpected invocation." << std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i::on_many_updates[_data_infos]
}
void
listen_port_1_data_listener_exec_i::on_deletion (
const ::CommonTestMessage& datum,
const ::CCM_DDS::ReadInfo& info)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i::on_deletion[_datum_info]
X11_UNUSED_ARG(datum);
X11_UNUSED_ARG(info);
++this->deleted_;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_data_listener_exec_i::on_deletion[_datum_info]
}
/**
* Facet Executor Implementation Class : listen_port_1_status_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i[ctor]
listen_port_1_status_exec_i::listen_port_1_status_exec_i (
IDL::traits<FA_State_Listen_Test::CCM_Receiver_Context>::ref_type context)
: context_ (std::move (context))
{
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i[ctor]
listen_port_1_status_exec_i::~listen_port_1_status_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i[user_private_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i[user_private_ops]
/** Operations and attributes from listen_port_1_status */
void
listen_port_1_status_exec_i::on_requested_deadline_missed (
IDL::traits< ::DDS::DataReader>::ref_type the_reader,
const ::DDS::RequestedDeadlineMissedStatus& status)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i::on_requested_deadline_missed[_the_reader_status]
X11_UNUSED_ARG(the_reader);
DDS4CCM_TEST_ERROR << "on_requested_deadline_missed - " << DDS::dds_write (status) << std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i::on_requested_deadline_missed[_the_reader_status]
}
void
listen_port_1_status_exec_i::on_sample_lost (
IDL::traits< ::DDS::DataReader>::ref_type the_reader,
const ::DDS::SampleLostStatus& status)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i::on_sample_lost[_the_reader_status]
X11_UNUSED_ARG(the_reader);
DDS4CCM_TEST_ERROR << "on_sample_lost 1 - " << DDS::dds_write (status) << std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_1_status_exec_i::on_sample_lost[_the_reader_status]
}
/**
* Facet Executor Implementation Class : listen_port_2_data_listener_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i[ctor]
listen_port_2_data_listener_exec_i::listen_port_2_data_listener_exec_i (
IDL::traits<FA_State_Listen_Test::CCM_Receiver_Context>::ref_type context,
std::atomic_ullong &created,
std::atomic_ullong &updated,
std::atomic_ullong &deleted)
: context_ (std::move (context))
, created_ (created)
, updated_ (updated)
, deleted_ (deleted)
{
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i[ctor]
listen_port_2_data_listener_exec_i::~listen_port_2_data_listener_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i[user_private_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i[user_private_ops]
/** Operations and attributes from listen_port_2_data_listener */
void
listen_port_2_data_listener_exec_i::on_creation (
const ::CommonTestMessage& datum,
const ::CCM_DDS::ReadInfo& info)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i::on_creation[_datum_info]
X11_UNUSED_ARG(info);
++this->created_;
// The first sample is the one that's created in DDS and filtered in in this
// listener
check_on_creation_mbm (datum);
if (this->created_ == keys ())
{
// sender may continue.
IDL::traits< WriterStarter>::ref_type starter =
this->context_->get_connection_writer_start ();
starter->start_write ();
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i::on_creation[_datum_info]
}
void
listen_port_2_data_listener_exec_i::on_one_update (
const ::CommonTestMessage& datum,
const ::CCM_DDS::ReadInfo& info)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i::on_one_update[_datum_info]
X11_UNUSED_ARG (datum);
X11_UNUSED_ARG (info);
DDS4CCM_TEST_ERROR << "ERROR: listen_port_2_data_listener_exec_i::on_one_updates - "
<< "Unexpected invocation." << std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i::on_one_update[_datum_info]
}
void
listen_port_2_data_listener_exec_i::on_many_updates (
const ::CommonTestMessageSeq& data,
const ::CCM_DDS::ReadInfoSeq& infos)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i::on_many_updates[_data_infos]
X11_UNUSED_ARG(infos);
this->updated_ += data.size ();
check_on_many_updates (
"listen_port_2_data_listener_exec_i::on_many_updates",
data);
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i::on_many_updates[_data_infos]
}
void
listen_port_2_data_listener_exec_i::on_deletion (
const ::CommonTestMessage& datum,
const ::CCM_DDS::ReadInfo& info)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i::on_deletion[_datum_info]
X11_UNUSED_ARG(datum);
X11_UNUSED_ARG(info);
++this->deleted_;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_data_listener_exec_i::on_deletion[_datum_info]
}
/**
* Facet Executor Implementation Class : listen_port_2_status_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i[ctor]
listen_port_2_status_exec_i::listen_port_2_status_exec_i (
IDL::traits<FA_State_Listen_Test::CCM_Receiver_Context>::ref_type context)
: context_ (std::move (context))
{
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i[ctor]
listen_port_2_status_exec_i::~listen_port_2_status_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i[user_private_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i[user_private_ops]
/** Operations and attributes from listen_port_2_status */
void
listen_port_2_status_exec_i::on_requested_deadline_missed (
IDL::traits< ::DDS::DataReader>::ref_type the_reader,
const ::DDS::RequestedDeadlineMissedStatus& status)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i::on_requested_deadline_missed[_the_reader_status]
X11_UNUSED_ARG(the_reader);
DDS4CCM_TEST_ERROR << "on_requested_deadline_missed 2 - " << DDS::dds_write (status) << std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i::on_requested_deadline_missed[_the_reader_status]
}
void
listen_port_2_status_exec_i::on_sample_lost (
IDL::traits< ::DDS::DataReader>::ref_type the_reader,
const ::DDS::SampleLostStatus& status)
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i::on_sample_lost[_the_reader_status]
X11_UNUSED_ARG(the_reader);
DDS4CCM_TEST_ERROR << "on_sample_lost 2 - " << DDS::dds_write (status) << std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::listen_port_2_status_exec_i::on_sample_lost[_the_reader_status]
}
/**
* Component Executor Implementation Class : Receiver_exec_i
*/
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[ctor]
Receiver_exec_i::Receiver_exec_i ()
{
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[ctor]
Receiver_exec_i::~Receiver_exec_i ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[dtor]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[dtor]
}
/** User defined public operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[user_public_ops]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[user_public_ops]
/** User defined private operations. */
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[user_private_ops]
void
Receiver_exec_i::test_non_changeable (
uint16_t listener_port,
std::string const ¤t_query,
std::string const &new_query,
IDL::traits< CCM_DDS::DataListenerControl>::ref_type ldc)
{
std::string const test ("Receiver_exec_i::test_non_changeable (" +
std::to_string (listener_port) + ")");
try
{
IDL::traits< ::CORBA::Object>::ref_type cmp = ldc->_get_component ();
if (!cmp)
{
DDS4CCM_TEST_ERROR << "ERROR: " << test << " - "
<< "ERROR: Unable to get component interface." << std::endl;
return;
}
IDL::traits< ::CommonTestConnector::CCM_DDS_State>::ref_type conn =
IDL::traits< ::CommonTestConnector::CCM_DDS_State >::narrow (cmp);
if (!conn)
{
DDS4CCM_TEST_ERROR << "ERROR: " << test << " - "
<< "Unable to narrow connector interface." << std::endl;
return;
}
// First check the current filter.
CCM_DDS::QueryFilter filter =
conn->push_state_observer_filter ();
if (filter.expression () != current_query)
{
DDS4CCM_TEST_ERROR << "ERROR: " << test << " - "
<< "Retrieved an unexpected query: expected <" << current_query
<< "> - retrieved <" << filter.expression () << ">"
<< std::endl;
}
// Now be sure that the NonChangeable exception is thrown.
filter.expression (new_query);
conn->push_state_observer_filter (filter);
DDS4CCM_TEST_ERROR << "ERROR: " << test << " - "
<< "No NonChangeable exception caught while changing the filter expression."
<< std::endl;
}
catch (CCM_DDS::NonChangeable const &)
{
DDS4CCM_TEST_DEBUG << "OK: " << test << " - "
<< "caught a NonChangeable exception when trying the change the query."
<< std::endl;
}
catch_dds4ccm_test_ex (ex, test)
}
void
Receiver_exec_i::test_non_changeables ()
{
this->test_non_changeable (1, QUERY_LISTENER_I, QUERY_LISTENER_II,
this->context_->get_connection_listen_port_1_data_control ());
this->test_non_changeable (2, QUERY_LISTENER_II, QUERY_LISTENER_I,
this->context_->get_connection_listen_port_2_data_control ());
}
void
Receiver_exec_i::test_internal_error (
uint16_t listener_port,
IDL::traits< CCM_DDS::ContentFilterSetting>::ref_type cft)
{
std::string const test ("Receiver_exec_i::test_internal_error (" +
std::to_string (listener_port) + ")");
// Applying less parameters than listed in the query should result in an
// InternalError exception.
// Seems that NDDS excepts more parameters than listed in the query; it just
// uses up to the number of parameters needed in the query.
DDS::StringSeq params(1);
params[0] = "3";
try
{
cft->set_filter_parameters (params);
DDS4CCM_TEST_ERROR << "ERROR: " << test << " - "
<< "Did not caught a InternalError exception when trying to "
<< "set a wrong number of parameters." << std::endl;
}
catch (CCM_DDS::InternalError const &)
{
DDS4CCM_TEST_DEBUG << "OK: " << test << " - "
<< "caught a InternalErr exception when trying to set a wrong number "
<< "of parameters." << std::endl;
}
catch_dds4ccm_test_ex (ex, test)
}
void
Receiver_exec_i::test_internal_errors ()
{
this->test_internal_error (1,
this->context_->get_connection_listen_port_1_filter_config ());
this->test_internal_error (2,
this->context_->get_connection_listen_port_2_filter_config ());
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[user_private_ops]
/** Session component operations */
void Receiver_exec_i::configuration_complete ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[configuration_complete]
DDS4CCM_TEST_DEBUG << "Receiver_exec_i::configuration_complete" << std::endl;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[configuration_complete]
}
void Receiver_exec_i::ccm_activate ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[ccm_activate]
this->test_non_changeables ();
this->test_internal_errors ();
// Start the listeners
IDL::traits< ::CCM_DDS::DataListenerControl>::ref_type lc_1 =
this->context_->get_connection_listen_port_1_data_control ();
if (!lc_1)
{
DDS4CCM_TEST_ERROR << "Error: Listener (1) control receptacle is null!"
<< std::endl;
throw ::CORBA::INTERNAL ();
}
lc_1->mode (::CCM_DDS::ListenerMode::ONE_BY_ONE);
IDL::traits< ::CCM_DDS::DataListenerControl>::ref_type lc_2 =
this->context_->get_connection_listen_port_2_data_control ();
if (!lc_2)
{
DDS4CCM_TEST_ERROR << "Error: Listener (2) control receptacle is null!"
<< std::endl;
throw ::CORBA::INTERNAL ();
}
lc_2->mode (::CCM_DDS::ListenerMode::MANY_BY_MANY);
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[ccm_activate]
}
void Receiver_exec_i::ccm_passivate ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[ccm_passivate]
bool error = false;
if (this->created_on_listener_1_ != keys ())
{
DDS4CCM_TEST_ERROR << "ERROR: Receiver_exec_i::ccm_passivate - "
<< "Unexpected number of keys created on listener I: expected <"
<< keys () << "> - created <" << this->created_on_listener_1_ << ">."
<< std::endl;
error = true;
}
if (this->created_on_listener_2_ != keys ())
{
DDS4CCM_TEST_ERROR << "ERROR: Receiver_exec_i::ccm_passivate - "
<< "Unexpected number of keys created on listener II: expected <"
<< keys () << "> - created <" << this->created_on_listener_2_ << ">."
<< std::endl;
error = true;
}
if (this->updated_on_listener_1_ != expected_number_of_samples_on_listener_1 ())
{
DDS4CCM_TEST_ERROR << "ERROR: Receiver_exec_i::ccm_passivate - "
<< "Unexpected number of keys updated on listener I: expected <"
<< expected_number_of_samples_on_listener_1 () << "> - updated <"
<< this->updated_on_listener_1_ << ">." << std::endl;
error = true;
}
if (this->updated_on_listener_2_ != expected_number_of_samples_on_listener_2 ())
{
DDS4CCM_TEST_ERROR << "ERROR: Receiver_exec_i::ccm_passivate - "
<< "Unexpected number of keys updated on listener II: expected <"
<< expected_number_of_samples_on_listener_2 () << "> - updated <"
<< this->updated_on_listener_2_ << ">." << std::endl;
error = true;
}
#if (DDSX11_NDDS == 1)
// This test is filtering on non-key fields. Because we are using a non-key
// filter OpenDDS can't determine whether we want to have the dispose or not
// so it doesn't propagate these to our listeners.
if (this->deleted_on_listener_1_ != keys ())
{
DDS4CCM_TEST_ERROR << "ERROR: Receiver_exec_i::ccm_passivate - "
<< "Unexpected number of keys deleted on listener I: expected <"
<< keys () << "> - deleted <" << this->deleted_on_listener_1_ << ">."
<< std::endl;
error = true;
}
if (this->deleted_on_listener_2_ != keys ())
{
DDS4CCM_TEST_ERROR << "ERROR: Receiver_exec_i::ccm_passivate - "
<< "Unexpected number of keys deleted on listener II: expected <"
<< keys () << "> - deleted <" << this->deleted_on_listener_2_ << ">."
<< std::endl;
error = true;
}
#endif /* DDSX11_NDDS == 1 */
if (!error)
{
DDS4CCM_TEST_DEBUG << "OK: Receiver_exec_i::ccm_passivate - "
<< "Expected number of samples received." << std::endl;
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[ccm_passivate]
}
void Receiver_exec_i::ccm_remove ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[ccm_remove]
// Your code here
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[ccm_remove]
}
IDL::traits< ::CommonTestConnector::CCM_StateListener>::ref_type
Receiver_exec_i::get_listen_port_1_data_listener ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[get_listen_port_1_data_listener]
if (!this->listen_port_1_data_listener_)
{
this->listen_port_1_data_listener_ =
CORBA::make_reference <listen_port_1_data_listener_exec_i> (
this->context_,
this->created_on_listener_1_,
this->updated_on_listener_1_,
this->deleted_on_listener_1_);
}
return this->listen_port_1_data_listener_;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[get_listen_port_1_data_listener]
}
IDL::traits< ::CCM_DDS::CCM_PortStatusListener>::ref_type
Receiver_exec_i::get_listen_port_1_status ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[get_listen_port_1_status]
if (!this->listen_port_1_status_)
{
this->listen_port_1_status_ = CORBA::make_reference <listen_port_1_status_exec_i> (this->context_);
}
return this->listen_port_1_status_;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[get_listen_port_1_status]
}
IDL::traits< ::CommonTestConnector::CCM_StateListener>::ref_type
Receiver_exec_i::get_listen_port_2_data_listener ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[get_listen_port_2_data_listener]
if (!this->listen_port_2_data_listener_)
{
this->listen_port_2_data_listener_ =
CORBA::make_reference <listen_port_2_data_listener_exec_i> (
this->context_,
this->created_on_listener_2_,
this->updated_on_listener_2_,
this->deleted_on_listener_2_);
}
return this->listen_port_2_data_listener_;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[get_listen_port_2_data_listener]
}
IDL::traits< ::CCM_DDS::CCM_PortStatusListener>::ref_type
Receiver_exec_i::get_listen_port_2_status ()
{
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[get_listen_port_2_status]
if (!this->listen_port_2_status_)
{
this->listen_port_2_status_ = CORBA::make_reference <listen_port_2_status_exec_i> (this->context_);
}
return this->listen_port_2_status_;
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[get_listen_port_2_status]
}
/// Operations from Components::SessionComponent
void
Receiver_exec_i::set_session_context (
IDL::traits<Components::SessionContext>::ref_type ctx)
{
// Setting the context of this component.
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[set_session_context]
this->context_ = IDL::traits<FA_State_Listen_Test::CCM_Receiver_Context>::narrow (std::move(ctx));
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i[set_session_context]
}
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl[user_namespace_end_impl]
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl[user_namespace_end_impl]
} // namespace FA_State_Listen_Test_Receiver_Impl
//@@{__RIDL_REGEN_MARKER__} - BEGIN : FA_State_Listen_Test_Receiver_Impl[factory]
extern "C" void
create_FA_State_Listen_Test_Receiver_Impl (
IDL::traits<Components::EnterpriseComponent>::ref_type& component)
{
component = CORBA::make_reference <FA_State_Listen_Test_Receiver_Impl::Receiver_exec_i> ();
}
//@@{__RIDL_REGEN_MARKER__} - END : FA_State_Listen_Test_Receiver_Impl[factory]
//@@{__RIDL_REGEN_MARKER__} - BEGIN : fa_sl_receiver_impl.cpp[Footer]
// Your footer (code) here
// -*- END -*-
| 42.408257 | 155 | 0.734848 | [
"object"
] |
3f449f7ab6f0d90042edaa881ae99cb68ccd5f7e | 7,263 | cpp | C++ | dtls-client.cpp | eelcohn/DTLS | 3429ed7a43cf2c9f82553039c9b20f2e28c2bbcc | [
"MIT"
] | 2 | 2021-02-07T23:14:09.000Z | 2022-01-16T23:45:16.000Z | dtls-client.cpp | eelcohn/DTLS | 3429ed7a43cf2c9f82553039c9b20f2e28c2bbcc | [
"MIT"
] | null | null | null | dtls-client.cpp | eelcohn/DTLS | 3429ed7a43cf2c9f82553039c9b20f2e28c2bbcc | [
"MIT"
] | 1 | 2018-12-12T16:09:20.000Z | 2018-12-12T16:09:20.000Z | /* server-dtls.cpp - Simple DTLS (Datagram TLS) server
written by Eelco Huininga - 2018 */
#include <stdbool.h>
#include <stdio.h>
#include <cstring> /* strerror() */
#include <arpa/inet.h> /* inet_ntop() */
#include <openssl/ssl.h> /* SSL*, SSL_new(), SSL_get_error(), SSL_set_fd(), SSL_accept(), SSL_get_cipher_version(), SSL_get_cipher_name(), SSL_get_cipher_bits(), SSL_get_verify_result(), SSL_get_peer_certificate(), SSL_read(), SSL_write(), SSL_ERROR_WANT_READ, SSL_ERROR_SYSCALL, SSL_shutdown() */
#include <openssl/engine.h> /* ERR_get_error() */
#include "dtls.h"
#define PORT 33859
#define MAXLEN 4096
static bool done; /* To handle shutdown */
struct sockaddr_in serveraddr; /* Client's address */
void hexdump(const char *string, int size);
const char *SSL_CIPHERS = "ALL:kECDHE:!COMPLEMENTOFDEFAULT:!EXPORT:!LOW:!aNULL:!eNULL:!SSLv2:!SSLv3:!TLSv1:!kRSA:!SHA1";
const char *SSL_SIGALGS = "ECDSA+SHA512:RSA+SHA512";
const char *DHFILE = "./dh4096.pem";
const char *CA = NULL;
const char *CERT = "./client-cert.pem";
const char *PRIVKEY = "./client-key.pem";
const char message[] = "Apollo 11, this is Houston calling. Radio check, please.\n";
int main(__attribute__((__unused__))int argc, __attribute__((__unused__))char** argv) {
DTLSParams server; /* All variables and objects for this DTLS connection */
X509 *servercert; /* Placeholder for peer (client) certificate */
STACK_OF(X509) *servercertchain; /* Placeholder for peer (client) certificate chain */
socklen_t server_len;
ssize_t connfd = 0;
char buff[MAXLEN]; /* SSL_read buffer */
char ipAddress[INET6_ADDRSTRLEN];
const char serveraddr[] = "192.168.111.145";
int result = 0; /* Result from SSL_read() and SSL_write(); length of message */
int ssl_errno; /* SSL error number */
bool blocking;
/* Needed for recvfrom */
server_len = sizeof(serveraddr);
/* Initialize SSL Engine and context */
client.type = DTLS_CLIENT; // Initialize an OpenSSL server context
if (libdtls::ssl_initialize(&server) != 0) {
fprintf(stderr, "libdtls::ssl_initialize failed\n");
return -1;
}
/* Loop while polling for UDP data */
done = false;
while (done != true) {
/* Create a new socket */
client.socket = libdtls::create_socket(AF_INET, true, NULL, PORT);
/* Create a BIO and link it to the socket */
client.bio = BIO_new_dgram(client.socket, BIO_NOCLOSE);
if (client.bio == NULL) {
fprintf(stderr, "error creating bio\n");
return EXIT_FAILURE;
}
/* Create the OpenSSL object */
if ((client.ssl = SSL_new(client.ctx)) == NULL) {
libdtls::ssl_print_error("SSL_new", SSL_get_error(client.ssl, 0));
libdtls::ssl_cleanup(&client);
exit(1);
}
/* Link the BIO to the SSL object */
SSL_set_bio(client.ssl, client.bio, client.bio);
/* Connect the BIO to the server's address */
BIO_set_conn_hostname(params->bio, address);
/* Set the SSL object to work in server mode */
SSL_set_connect_state(client.ssl);
/* ... */
SSL_set_mode(params->ssl, SSL_MODE_AUTO_RETRY);
do {
connfd = recvfrom(client.socket, (char *)&buff, sizeof(buff), MSG_PEEK, (struct sockaddr*) &serveraddr, &server_len);
if (connfd < 0) {
if (errno != EWOULDBLOCK) {
fprintf(stderr, "recvfrom() failed: %s\n", strerror(errno));
libdtls::ssl_cleanup(&client);
exit(1);
}
}
if (connfd == 0) {
fprintf(stderr, "Peer has performed an orderly shutdown.\n");
libdtls::ssl_cleanup(&client);
exit(1);
}
} while (connfd < 0);
if (connect(client.socket, (const struct sockaddr *)&serveraddr, sizeof(serveraddr)) != 0) {
fprintf(stderr, "connect(): UDP connect failed.\n");
libdtls::ssl_cleanup(&server);
exit(1);
} else {
printf("Connected to %s:%d\n", inet_ntop(AF_INET, &(serveraddr.sin_addr), ipAddress, INET_ADDRSTRLEN), serveraddr.sin_port);
/* Set the session ssl to client connection port */
SSL_set_fd(server.ssl, server.socket);
/* Accept the connection */
if (SSL_accept(client.ssl) != 1) {
libdtls::ssl_print_error("SSL_accept", SSL_get_error(client.ssl, 0));
libdtls::ssl_cleanup(&client);
exit(1);
}
printf("%s handshake completed; secure connection established, using cipher %s (%d bits)\n", SSL_get_cipher_version(client.ssl), SSL_get_cipher_name(client.ssl), SSL_get_cipher_bits(client.ssl, NULL));
/* Verify the client certificate */
if ((servercert = SSL_get_peer_certificate(client.ssl)) != NULL) {
X509_print_ex_fp(stdout, servercert, XN_FLAG_COMPAT, X509_FLAG_COMPAT);
if (SSL_get_verify_result(client.ssl) == X509_V_OK) {
printf("Client certificate is valid\n");
servercertchain = SSL_get_peer_cert_chain(client.ssl);
printf("Client certificate's subject: %s", X509_NAME_oneline(X509_get_subject_name(servercert), NULL, 0));
printf("Client certificate's issuer: %s", X509_NAME_oneline(X509_get_issuer_name(servercert), NULL, 0));
printf("Client certificate's signature algorithm: %i", X509_get0_tbs_sigalg(servercert));
sk_X509_free(servercertchain);
} else {
printf("Client certificate is valid\n");
}
} else {
printf("No client certificate received\n");
}
X509_free(servercert);
blocking = false;
do {
if ((result = SSL_read(client.ssl, buff, sizeof(buff))) > 0) {
buff[result] = 0;
ssl_errno = SSL_get_error(client.ssl, 0);
printf("result:%i - sslerrno:%i - ERR_get_error:%lu - errno:%i %s - SSLpending:%i\n", result, ssl_errno, ERR_get_error(), errno, strerror(errno), SSL_pending(client.ssl));
printf("Received 0x%04x bytes:\n", result);
hexdump(buff, result);
if ((result = SSL_write(client.ssl, reply, sizeof(reply))) < 0) {
libdtls::ssl_print_error("SSL_write", SSL_get_error(client.ssl, result));
libdtls::ssl_cleanup(&client);
exit(1);
} else {
printf("Transmitted 0x%04x bytes:\n", (int)sizeof(reply));
hexdump(reply, sizeof(reply));
blocking = false;
}
} else {
ssl_errno = SSL_get_error(client.ssl, result);
printf("result:%i - sslerrno:%i - ERR_get_error:%lu - errno:%i %s - SSLpending:%i\n", result, ssl_errno, ERR_get_error(), errno, strerror(errno), SSL_pending(client.ssl));
if((ssl_errno != SSL_ERROR_WANT_READ) && ((ssl_errno == SSL_ERROR_SYSCALL) && (errno != EWOULDBLOCK))){
libdtls::ssl_print_error("SSL_read", ssl_errno);
libdtls::ssl_cleanup(&client);
exit(1);
} else
blocking = true;
}
} while (blocking == true);
printf("Closing connection\n");
if ((ssl_errno = SSL_shutdown(client.ssl)) < 0) {
libdtls::ssl_print_error("SSL_shutdown", ssl_errno);
}
done=true;
}
}
libdtls::ssl_cleanup(&client);
return 0;
}
void hexdump(const char *string, size_t size) {
size_t i, offset;
offset = 0;
while ((size - offset) > 0) {
printf("%04X ", offset);
for (i = 0; i < 16; i++) {
if ((offset + i) < size)
printf("%02X ", string[offset + i]);
else
printf(" ");
}
printf(" ");
for (i = 0; i < 16; i++) {
if ((offset + i) < size) {
if ((string[offset + i] > 31) && (string[offset + i] < 127))
printf("%c", string[offset + i]);
else
printf(".");
}
}
printf("\n");
offset += 16;
}
}
| 35.257282 | 297 | 0.661985 | [
"object"
] |
3f5026aaa07d8ba10f45070ea72c2d4da6bbe86a | 224 | hpp | C++ | src/opengl/arraybuffer.hpp | ruslashev/spacie | f4ecd81b5f4c466805d181056a3367623f2832c9 | [
"MIT"
] | null | null | null | src/opengl/arraybuffer.hpp | ruslashev/spacie | f4ecd81b5f4c466805d181056a3367623f2832c9 | [
"MIT"
] | null | null | null | src/opengl/arraybuffer.hpp | ruslashev/spacie | f4ecd81b5f4c466805d181056a3367623f2832c9 | [
"MIT"
] | null | null | null | #ifndef ARRAYBUFFER_HPP
#define ARRAYBUFFER_HPP
#include "opengl_buffer.hpp"
#include <vector>
#include <GL/glew.h>
class ArrayBuffer : public OpenGL_Buffer
{
public:
void Upload(std::vector<GLfloat> &data);
};
#endif
| 13.176471 | 41 | 0.75 | [
"vector"
] |
3f5579dfe425e3252116104dabb1129edd19a6ac | 1,041 | cpp | C++ | chap06/clamp.cpp | PacktPublishing/CPP-20-STL-Cookbook | 9310a24a6158bbb38d67b3a3c2ebc243dc1ee1e8 | [
"MIT"
] | 9 | 2021-11-05T10:54:46.000Z | 2022-03-18T23:58:06.000Z | chap06/clamp.cpp | PacktPublishing/CPP-20-STL-Cookbook | 9310a24a6158bbb38d67b3a3c2ebc243dc1ee1e8 | [
"MIT"
] | null | null | null | chap06/clamp.cpp | PacktPublishing/CPP-20-STL-Cookbook | 9310a24a6158bbb38d67b3a3c2ebc243dc1ee1e8 | [
"MIT"
] | 5 | 2021-12-19T07:23:08.000Z | 2022-02-04T23:24:43.000Z | // clamp.cpp
// as of 2021-12-27 bw [bw.org]
#include <format>
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <iterator>
using std::format;
using std::cout;
using std::string;
using std::string_view;
using std::vector;
using std::list;
using std::transform;
using std::clamp;
void printc(auto& c, string_view s = "") {
if(s.size()) cout << format("{}: ", s);
for(auto e : c) cout << format("{:>5} ", e);
cout << '\n';
}
int main() {
const auto il = { 0, -12, 2001, 4, 5, -14, 100, 200, 30000 };
constexpr int ilow{0};
constexpr int ihigh{500};
vector<int> voi{ il };
cout << "vector voi before:\n";
printc(voi);
cout << "vector voi after:\n";
for(auto& e : voi) e = clamp(e, ilow, ihigh);
printc(voi);
list<int> loi{ il };
cout << "list loi before:\n";
printc(loi);
transform(loi.begin(), loi.end(), loi.begin(), [=](auto e){ return clamp(e, ilow, ihigh); });
cout << "list loi after:\n";
printc(loi);
}
| 21.6875 | 97 | 0.582133 | [
"vector",
"transform"
] |
3f576002d856f585ccb7da6f012798d58042f52e | 899 | cpp | C++ | 류호석배 알고리즘 코딩 테스트/제3회/4번-공정 컨설턴트 호석/solution.cpp | rhs0266/FastCampus | 88b5f4c18ebfb9ebf141ace644e40d2975ff665a | [
"MIT"
] | 407 | 2020-11-14T02:25:56.000Z | 2022-03-31T04:12:17.000Z | 류호석배 알고리즘 코딩 테스트/제3회/4번-공정 컨설턴트 호석/solution.cpp | rhs0266/FastCampus | 88b5f4c18ebfb9ebf141ace644e40d2975ff665a | [
"MIT"
] | 48 | 2020-11-16T15:29:10.000Z | 2022-03-14T06:32:16.000Z | 류호석배 알고리즘 코딩 테스트/제3회/4번-공정 컨설턴트 호석/solution.cpp | rhs0266/FastCampus | 88b5f4c18ebfb9ebf141ace644e40d2975ff665a | [
"MIT"
] | 78 | 2020-11-28T08:29:39.000Z | 2022-03-29T06:54:48.000Z | #include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long int ll;
typedef pair<int, int> pii;
#define NM 100005
#define INF 0x7fffffff
int n, X, a[NM];
void input() {
cin >> n >> X;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
}
bool check(int num) {
vector<int> vec(num, 0);
priority_queue<int, vector<int>, greater<int>> Q(vec.begin(), vec.end());
for (int i = 1; i <= n; i++) {
int pick = Q.top();
Q.pop();
if (pick + a[i] > X) return false;
Q.push(pick + a[i]);
}
return true;
}
void pro() {
int L = 1, R = n, ans = n;
while (L <= R) {
int mid = (L + R) / 2;
if (check(mid)) {
ans = mid;
R = mid - 1;
} else {
L = mid + 1;
}
}
cout << ans;
}
int main() {
input();
pro();
return 0;
} | 18.346939 | 77 | 0.459399 | [
"vector"
] |
3f5b9925e2bf7cc0b6f0503fd4a30f90192575ea | 1,722 | cpp | C++ | producer/event_monitor_producer/src/win_event.cpp | SergeyYakubov/asapo | 25fddf9af6b215a6fc0da6108bc6b91dff813362 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | producer/event_monitor_producer/src/win_event.cpp | SergeyYakubov/asapo | 25fddf9af6b215a6fc0da6108bc6b91dff813362 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | producer/event_monitor_producer/src/win_event.cpp | SergeyYakubov/asapo | 25fddf9af6b215a6fc0da6108bc6b91dff813362 | [
"MIT",
"Apache-2.0",
"MIT-0",
"BSD-3-Clause"
] | null | null | null | #include "win_event.h"
#include <vector>
namespace asapo {
WinEvent::WinEvent(const FILE_NOTIFY_INFORMATION* win_event): win_event_{win_event} {
}
std::string WinEvent::FileName() const {
std::size_t len = win_event_->FileNameLength / sizeof(WCHAR);
std::vector<char> buffer(len + 1);
buffer[len] = 0;
// std::locale loc("");
// std::use_facet<std::ctype<wchar_t> >(loc).narrow(win_event_->FileName, win_event_->FileName + len, '_', &buffer[0]);
for (size_t i = 0; i < len; i++) {
buffer[i] = (char)win_event_->FileName[i];
}
return std::string(&buffer[0], &buffer[len]);
}
size_t WinEvent::Offset()const {
return win_event_->NextEntryOffset;
}
void WinEvent::Print() const {
printf("\nNew Event: ");
if (win_event_->Action == FILE_ACTION_ADDED) printf("FILE_ACTION_ADDED ");
if (win_event_->Action == FILE_ACTION_REMOVED) printf("FILE_ACTION_REMOVED ");
if (win_event_->Action == FILE_ACTION_MODIFIED) printf("FILE_ACTION_MODIFIED ");
if (win_event_->Action == FILE_ACTION_RENAMED_OLD_NAME) printf("FILE_ACTION_RENAMED_OLD_NAME ");
if (win_event_->Action == FILE_ACTION_RENAMED_NEW_NAME) printf("FILE_ACTION_RENAMED_NEW_NAME ");
printf("\n");
if (win_event_->FileNameLength > 0)
printf("Filename: %s\n", FileName().c_str());
}
bool WinEvent::IsFileModifiedEvent() const {
return win_event_->Action == FILE_ACTION_MODIFIED;
}
bool WinEvent::IsFileMovedEvent() const {
return win_event_->Action == FILE_ACTION_RENAMED_NEW_NAME;
}
bool WinEvent::ShouldInitiateTransfer() const {
return IsFileModifiedEvent() || IsFileMovedEvent();
}
bool WinEvent::ShouldBeProcessedAfterDelay() const {
return !IsFileMovedEvent();
}
}
| 33.115385 | 122 | 0.699768 | [
"vector"
] |
3f5f3016cf448f00c250f3c1a76f6368f64f2696 | 8,248 | cpp | C++ | ms/spectrum.cpp | alexandrovteam/ims-cpp | dcc12b4c50dbfdcde3f765af85fb8b3bb5cd7ec3 | [
"Apache-2.0"
] | 5 | 2016-03-29T14:58:07.000Z | 2018-05-24T13:58:38.000Z | ms/spectrum.cpp | alexandrovteam/ims-cpp | dcc12b4c50dbfdcde3f765af85fb8b3bb5cd7ec3 | [
"Apache-2.0"
] | null | null | null | ms/spectrum.cpp | alexandrovteam/ims-cpp | dcc12b4c50dbfdcde3f765af85fb8b3bb5cd7ec3 | [
"Apache-2.0"
] | null | null | null | #include "ms/spectrum.hpp"
#include "ms/periodic_table.hpp"
#include <vector>
#include <algorithm>
#include <cassert>
#include <cmath>
#include <algorithm>
#include <array>
#include <functional>
#include <numeric>
namespace ms {
void Spectrum::addCharge(int charge) {
for (auto& m : masses)
m -= charge * ms::electronMass;
}
static bool isNormalized(const Spectrum& p) {
if (p.intensities[0] != 1.0) return false;
for (size_t i = 1; i < p.size(); i++)
if (p.intensities[i - 1] < p.intensities[i]) return false;
return true;
}
Spectrum Spectrum::convolve(const Spectrum& other, double threshold) const {
if (this->isConvolutionUnit()) return other;
if (other.isConvolutionUnit()) return *this;
const auto& p1 = *this, p2 = other;
size_t n1 = p1.size(), n2 = p2.size();
assert(isNormalized(p1));
assert(isNormalized(p2));
Spectrum result;
for (size_t i = 0; i < n1; i++)
for (size_t j = 0; j < n2; j++) {
auto abundance = p1.intensities[i] * p2.intensities[j];
if (abundance > threshold) {
result.masses.push_back(p1.masses[i] + p2.masses[j]);
result.intensities.push_back(abundance);
} else {
if (j == 0) break;
n2 = j;
}
}
return result.normalize();
}
static void sortSpectrum(std::vector<double>& masses, std::vector<double>& intensities,
std::function<bool(size_t, size_t)> cmp) {
auto n = masses.size();
std::vector<size_t> index(masses.size());
std::iota(index.begin(), index.end(), 0);
std::sort(index.begin(), index.end(), cmp);
std::vector<double> tmp(n);
for (size_t i = 0; i < n; i++)
tmp[i] = masses[index[i]];
masses.swap(tmp);
for (size_t i = 0; i < n; i++)
tmp[i] = intensities[index[i]];
intensities.swap(tmp);
}
Spectrum& Spectrum::sortByIntensity(bool force) {
if (peak_order_ == PeakOrder::intensity && !force) return *this;
sortSpectrum(masses, intensities,
[&](size_t i, size_t j) { return intensities[i] > intensities[j]; });
peak_order_ = PeakOrder::intensity;
return *this;
}
Spectrum& Spectrum::sortByMass(bool force) {
if (peak_order_ == PeakOrder::mass && !force) return *this;
sortSpectrum(
masses, intensities, [&](size_t i, size_t j) { return masses[i] < masses[j]; });
peak_order_ = PeakOrder::mass;
return *this;
}
Spectrum& Spectrum::normalize() {
sortByIntensity();
auto top = intensities[0];
if (top > 0)
for (auto& item : intensities)
item /= top;
return *this;
}
static double sigmaAtResolvingPower(double mass, double resolving_power) {
if (resolving_power <= 0) return NAN;
auto fwhm = mass / resolving_power;
return fwhm / fwhm_to_sigma;
}
static double calculateSigmaAt(double mass, const InstrumentProfile* instrument) {
double resolving_power = instrument->resolvingPowerAt(mass);
return sigmaAtResolvingPower(mass, resolving_power);
}
double Spectrum::envelope(
const InstrumentProfile* instrument, double mass, size_t width) const {
double result = 0.0;
double sigma = calculateSigmaAt(mass, instrument);
for (size_t k = 0; k < size(); ++k) {
if (std::fabs(masses[k] - mass) > width * sigma) continue;
result += intensities[k] * std::exp(-0.5 * std::pow((masses[k] - mass) / sigma, 2));
}
return result;
}
EnvelopeGenerator::EnvelopeGenerator(
const Spectrum& p, const InstrumentProfile* instrument, size_t width)
: p_(p.copy().sortByMass()),
instrument_(instrument),
width_(width),
peak_index_(0),
empty_space_(false),
last_mz_(-std::numeric_limits<double>::min()) {
assert(p.size() > 0 && p.masses[0] > 0);
sigma_ = calculateSigmaAt(p_.masses[0], instrument_);
}
double EnvelopeGenerator::currentSigma() const {
return sigma_;
}
struct ExpTable {
std::vector<double> table;
const double step = 4e-3;
const double min = -18;
const double max = 0;
ExpTable() {
table.reserve((max - min) / step);
for (double x = min; x <= max; x += step)
table.push_back(std::exp(x));
}
double operator()(double x) const {
if (min > x)
return 0;
int idx = std::floor((x - min) / step);
assert(idx >= 0 && idx < table.size());
double diff = x - (min + idx * step);
// gives at most 1e-8 relative error with step=4e-3
return table[idx] * (1 + diff * (1 + diff / 2.0));
}
};
static ExpTable fastexp;
double EnvelopeGenerator::envelope(double mz) {
if (empty_space_) return 0.0; // no isotopic peaks nearby
double result = 0.0;
int k = peak_index_, n = p_.size();
while (k > 0 && mz - p_.masses[k - 1] < width_ * sigma_)
--k;
while (k < n && p_.masses[k] - mz <= width_ * sigma_) {
double sd_dist = (p_.masses[k] - mz) / sigma_;
result += p_.intensities[k] * fastexp(-0.5 * std::pow(sd_dist, 2));
++k;
}
return result;
}
double EnvelopeGenerator::operator()(double mz) {
if (last_mz_ > mz)
throw std::runtime_error("input to EnvelopeGenerator must be sorted");
if (mz > p_.masses[peak_index_] + width_ * sigma_)
empty_space_ = true; // the last peak's influence is now considered negligible
if (empty_space_ && peak_index_ + 1 < p_.size() &&
mz >= p_.masses[peak_index_ + 1] - width_ * sigma_) {
empty_space_ = false;
++peak_index_; // reached next peak
sigma_ = calculateSigmaAt(p_.masses[peak_index_], instrument_);
}
last_mz_ = mz;
return envelope(mz);
}
Spectrum Spectrum::envelopeCentroids(const InstrumentProfile* instrument,
double min_abundance, size_t points_per_fwhm, size_t centroid_bins) const {
if (this->masses.size() <= 1) return *this;
if (points_per_fwhm < 5)
throw std::logic_error("points_per_fwhm must be at least 5 for meaningful results");
if (centroid_bins < 3) throw std::logic_error("centroid_bins must be at least 3");
const size_t width = 6;
double min_mz = *std::min_element(this->masses.begin(), this->masses.end());
double max_mz = *std::max_element(this->masses.begin(), this->masses.end());
EnvelopeGenerator envelope(*this, instrument, width);
double sigma = envelope.currentSigma();
double step = (sigma * fwhm_to_sigma) / points_per_fwhm;
int n_steps = 0;
std::vector<double> mz_window(centroid_bins), int_window(centroid_bins);
size_t center = centroid_bins / 2, last_idx = centroid_bins - 1;
mz_window[center] = min_mz - width * sigma;
for (size_t j = 0; j < centroid_bins; j++) {
mz_window[j] = mz_window[center] + (int(j) - int(center)) * step;
int_window[j] = envelope(mz_window[j]);
++n_steps;
}
auto prev = [&](size_t idx) { return idx > 0 ? idx - 1 : centroid_bins - 1; };
auto next = [&](size_t idx) { return idx == centroid_bins - 1 ? 0 : idx + 1; };
auto rotateWindows = [&](int shift) -> void {
auto abs_shift = (shift + int(centroid_bins)) % centroid_bins;
std::rotate(mz_window.begin(), mz_window.begin() + abs_shift, mz_window.end());
std::rotate(int_window.begin(), int_window.begin() + abs_shift, int_window.end());
};
ms::Spectrum result;
for (;;) {
center = next(center);
auto next_mz = mz_window[last_idx] + step;
if (next_mz > max_mz + width * sigma) break;
last_idx = next(last_idx);
mz_window[last_idx] = next_mz;
int_window[last_idx] = envelope(next_mz);
sigma = envelope.currentSigma();
step = (sigma * fwhm_to_sigma) / points_per_fwhm;
++n_steps;
if (n_steps > 100000000)
throw std::runtime_error("error in envelopeCentroids calculation");
// check if it's a local maximum
if (!(int_window[prev(center)] < int_window[center] &&
int_window[center] >= int_window[next(center)]))
continue;
// skip low-intensity peaks
if (int_window[center] < min_abundance) continue;
double m, intensity;
auto shift = int(centroid_bins - 1 - last_idx);
rotateWindows(-shift);
std::tie(m, intensity) =
centroid(mz_window.begin(), mz_window.end(), int_window.begin());
rotateWindows(shift);
result.masses.push_back(m);
result.intensities.push_back(intensity);
}
if (result.size() == 0)
throw std::logic_error("the result contains no peaks, make min_abundance lower!");
return result.sortByIntensity().normalize().removeIntensitiesBelow(min_abundance);
}
}
| 30.548148 | 88 | 0.653613 | [
"vector"
] |
3f72665287091dd33919e84f73d1f6b0dc78adcf | 36,162 | cpp | C++ | latte-dock/app/wm/tracker/windowstracker.cpp | VaughnValle/lush-pop | cdfe9d7b6a7ebb89ba036ab9a4f07d8db6817355 | [
"MIT"
] | 64 | 2020-07-08T18:49:29.000Z | 2022-03-23T22:58:49.000Z | latte-dock/app/wm/tracker/windowstracker.cpp | VaughnValle/kanji-pop | 0153059f0c62a8aeb809545c040225da5d249bb8 | [
"MIT"
] | 1 | 2021-04-02T04:39:45.000Z | 2021-09-25T11:53:18.000Z | latte-dock/app/wm/tracker/windowstracker.cpp | VaughnValle/kanji-pop | 0153059f0c62a8aeb809545c040225da5d249bb8 | [
"MIT"
] | 11 | 2020-12-04T18:19:11.000Z | 2022-01-10T08:50:08.000Z | /*
* Copyright 2019 Michail Vourlakos <mvourlakos@gmail.com>
*
* This file is part of Latte-Dock
*
* Latte-Dock is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* Latte-Dock is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "windowstracker.h"
// local
#include "lastactivewindow.h"
#include "schemes.h"
#include "trackedlayoutinfo.h"
#include "trackedviewinfo.h"
#include "../abstractwindowinterface.h"
#include "../schemecolors.h"
#include "../../apptypes.h"
#include "../../lattecorona.h"
#include "../../layout/genericlayout.h"
#include "../../layouts/manager.h"
#include "../../view/view.h"
#include "../../view/positioner.h"
namespace Latte {
namespace WindowSystem {
namespace Tracker {
Windows::Windows(AbstractWindowInterface *parent)
: QObject(parent)
{
m_wm = parent;
m_extraViewHintsTimer.setInterval(600);
m_extraViewHintsTimer.setSingleShot(true);
connect(&m_extraViewHintsTimer, &QTimer::timeout, this, &Windows::updateExtraViewHints);
//! delayed application data
m_updateApplicationDataTimer.setInterval(1500);
m_updateApplicationDataTimer.setSingleShot(true);
connect(&m_updateApplicationDataTimer, &QTimer::timeout, this, &Windows::updateApplicationData);
init();
}
Windows::~Windows()
{
//! clear all the m_views tracking information
for (QHash<Latte::View *, TrackedViewInfo *>::iterator i=m_views.begin(); i!=m_views.end(); ++i) {
i.value()->deleteLater();
m_views[i.key()] = nullptr;
}
m_views.clear();
//! clear all the m_layouts tracking layouts
for (QHash<Latte::Layout::GenericLayout *, TrackedLayoutInfo *>::iterator i=m_layouts.begin(); i!=m_layouts.end(); ++i) {
i.value()->deleteLater();
m_layouts[i.key()] = nullptr;
}
m_layouts.clear();
}
void Windows::init()
{
connect(m_wm->corona(), &Plasma::Corona::availableScreenRectChanged, this, &Windows::updateAvailableScreenGeometries);
connect(m_wm, &AbstractWindowInterface::windowChanged, this, [&](WindowId wid) {
m_windows[wid] = m_wm->requestInfo(wid);
updateAllHints();
emit windowChanged(wid);
});
connect(m_wm, &AbstractWindowInterface::windowRemoved, this, [&](WindowId wid) {
m_windows.remove(wid);
//! application data
m_initializedApplicationData.removeAll(wid);
m_delayedApplicationData.removeAll(wid);
updateAllHints();
emit windowRemoved(wid);
});
connect(m_wm, &AbstractWindowInterface::windowAdded, this, [&](WindowId wid) {
if (!m_windows.contains(wid)) {
m_windows.insert(wid, m_wm->requestInfo(wid));
}
updateAllHints();
});
connect(m_wm, &AbstractWindowInterface::activeWindowChanged, this, [&](WindowId wid) {
//! for some reason this is needed in order to update properly activeness values
//! when the active window changes the previous active windows should be also updated
for (const auto view : m_views.keys()) {
WindowId lastWinId = m_views[view]->lastActiveWindow()->winId();
if ((lastWinId) != wid && m_windows.contains(lastWinId)) {
m_windows[lastWinId] = m_wm->requestInfo(lastWinId);
}
}
m_windows[wid] = m_wm->requestInfo(wid);
updateAllHints();
emit activeWindowChanged(wid);
});
connect(m_wm, &AbstractWindowInterface::currentDesktopChanged, this, [&] {
updateAllHints();
});
connect(m_wm, &AbstractWindowInterface::currentActivityChanged, this, [&] {
if (m_wm->corona()->layoutsManager()->memoryUsage() == MemoryUsage::MultipleLayouts) {
//! this is needed in MultipleLayouts because there is a chance that multiple
//! layouts are providing different available screen geometries in different Activities
updateAvailableScreenGeometries();
}
updateAllHints();
});
}
void Windows::initLayoutHints(Latte::Layout::GenericLayout *layout)
{
if (!m_layouts.contains(layout)) {
return;
}
setActiveWindowMaximized(layout, false);
setExistsWindowActive(layout, false);
setExistsWindowMaximized(layout, false);
setActiveWindowScheme(layout, nullptr);
}
void Windows::initViewHints(Latte::View *view)
{
if (!m_views.contains(view)) {
return;
}
setActiveWindowMaximized(view, false);
setActiveWindowTouching(view, false);
setActiveWindowTouchingEdge(view, false);
setExistsWindowActive(view, false);
setExistsWindowTouching(view, false);
setExistsWindowTouchingEdge(view, false);
setExistsWindowMaximized(view, false);
setIsTouchingBusyVerticalView(view, false);
setActiveWindowScheme(view, nullptr);
setTouchingWindowScheme(view, nullptr);
}
AbstractWindowInterface *Windows::wm()
{
return m_wm;
}
void Windows::addView(Latte::View *view)
{
if (m_views.contains(view)) {
return;
}
m_views[view] = new TrackedViewInfo(this, view);
updateAvailableScreenGeometries();
//! Consider Layouts
addRelevantLayout(view);
connect(view, &Latte::View::layoutChanged, this, [&, view]() {
addRelevantLayout(view);
});
connect(view, &Latte::View::isTouchingBottomViewAndIsBusyChanged, this, &Windows::updateExtraViewHints);
connect(view, &Latte::View::isTouchingTopViewAndIsBusyChanged, this, &Windows::updateExtraViewHints);
updateAllHints();
emit informationAnnounced(view);
}
void Windows::removeView(Latte::View *view)
{
if (!m_views.contains(view)) {
return;
}
m_views[view]->deleteLater();
m_views.remove(view);
updateRelevantLayouts();
}
void Windows::addRelevantLayout(Latte::View *view)
{
if (view->layout()) {
bool initializing {false};
if (!m_layouts.contains(view->layout())) {
initializing = true;
m_layouts[view->layout()] = new TrackedLayoutInfo(this, view->layout());
}
//! Update always the AllScreens tracking because there is a chance a view delayed to be assigned in a layout
//! and that could create a state the AllScreens tracking will be disabled if there is a View requesting
//! tracking and one that it does not during startup
updateRelevantLayouts();
if (initializing) {
updateHints(view->layout());
emit informationAnnouncedForLayout(view->layout());
}
}
}
void Windows::updateRelevantLayouts()
{
QList<Latte::Layout::GenericLayout*> orphanedLayouts;
//! REMOVE Orphaned Relevant layouts that have been removed or they don't contain any Views anymore
for (QHash<Latte::Layout::GenericLayout *, TrackedLayoutInfo *>::iterator i=m_layouts.begin(); i!=m_layouts.end(); ++i) {
bool hasView{false};
for (QHash<Latte::View *, TrackedViewInfo *>::iterator j=m_views.begin(); j!=m_views.end(); ++j) {
if (j.key() && i.key() && i.key() == j.key()->layout()) {
hasView = true;
break;
}
}
if (!hasView) {
if (i.value()) {
i.value()->deleteLater();
}
orphanedLayouts << i.key();
}
}
for(const auto &layout : orphanedLayouts) {
m_layouts.remove(layout);
}
//! UPDATE Enabled layout window tracking based on the Views that are requesting windows tracking
for (QHash<Latte::Layout::GenericLayout *, TrackedLayoutInfo *>::iterator i=m_layouts.begin(); i!=m_layouts.end(); ++i) {
bool hasViewEnabled{false};
for (QHash<Latte::View *, TrackedViewInfo *>::iterator j=m_views.begin(); j!=m_views.end(); ++j) {
if (i.key() == j.key()->layout() && j.value()->enabled()) {
hasViewEnabled = true;
break;
}
}
if (i.value()) {
i.value()->setEnabled(hasViewEnabled);
if (!hasViewEnabled) {
initLayoutHints(i.key());
}
}
}
}
//! Views Properties And Hints
bool Windows::enabled(Latte::View *view)
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->enabled();
}
void Windows::setEnabled(Latte::View *view, const bool enabled)
{
if (!m_views.contains(view) || m_views[view]->enabled() == enabled) {
return;
}
m_views[view]->setEnabled(enabled);
if (enabled) {
updateHints(view);
} else {
initViewHints(view);
}
updateRelevantLayouts();
emit enabledChanged(view);
}
bool Windows::activeWindowMaximized(Latte::View *view) const
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->activeWindowMaximized();
}
void Windows::setActiveWindowMaximized(Latte::View *view, bool activeMaximized)
{
if (!m_views.contains(view) || m_views[view]->activeWindowMaximized() == activeMaximized) {
return;
}
m_views[view]->setActiveWindowMaximized(activeMaximized);
emit activeWindowMaximizedChanged(view);
}
bool Windows::activeWindowTouching(Latte::View *view) const
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->activeWindowTouching();
}
void Windows::setActiveWindowTouching(Latte::View *view, bool activeTouching)
{
if (!m_views.contains(view) || m_views[view]->activeWindowTouching() == activeTouching) {
return;
}
m_views[view]->setActiveWindowTouching(activeTouching);
emit activeWindowTouchingChanged(view);
}
bool Windows::activeWindowTouchingEdge(Latte::View *view) const
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->activeWindowTouchingEdge();
}
void Windows::setActiveWindowTouchingEdge(Latte::View *view, bool activeTouchingEdge)
{
if (!m_views.contains(view) || m_views[view]->activeWindowTouchingEdge() == activeTouchingEdge) {
return;
}
m_views[view]->setActiveWindowTouchingEdge(activeTouchingEdge);
emit activeWindowTouchingEdgeChanged(view);
}
bool Windows::existsWindowActive(Latte::View *view) const
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->existsWindowActive();
}
void Windows::setExistsWindowActive(Latte::View *view, bool windowActive)
{
if (!m_views.contains(view) || m_views[view]->existsWindowActive() == windowActive) {
return;
}
m_views[view]->setExistsWindowActive(windowActive);
emit existsWindowActiveChanged(view);
}
bool Windows::existsWindowMaximized(Latte::View *view) const
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->existsWindowMaximized();
}
void Windows::setExistsWindowMaximized(Latte::View *view, bool windowMaximized)
{
if (!m_views.contains(view) || m_views[view]->existsWindowMaximized() == windowMaximized) {
return;
}
m_views[view]->setExistsWindowMaximized(windowMaximized);
emit existsWindowMaximizedChanged(view);
}
bool Windows::existsWindowTouching(Latte::View *view) const
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->existsWindowTouching();
}
void Windows::setExistsWindowTouching(Latte::View *view, bool windowTouching)
{
if (!m_views.contains(view) || m_views[view]->existsWindowTouching() == windowTouching) {
return;
}
m_views[view]->setExistsWindowTouching(windowTouching);
emit existsWindowTouchingChanged(view);
}
bool Windows::existsWindowTouchingEdge(Latte::View *view) const
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->existsWindowTouchingEdge();
}
void Windows::setExistsWindowTouchingEdge(Latte::View *view, bool windowTouchingEdge)
{
if (!m_views.contains(view) || m_views[view]->existsWindowTouchingEdge() == windowTouchingEdge) {
return;
}
m_views[view]->setExistsWindowTouchingEdge(windowTouchingEdge);
emit existsWindowTouchingEdgeChanged(view);
}
bool Windows::isTouchingBusyVerticalView(Latte::View *view) const
{
if (!m_views.contains(view)) {
return false;
}
return m_views[view]->isTouchingBusyVerticalView();
}
void Windows::setIsTouchingBusyVerticalView(Latte::View *view, bool viewTouching)
{
if (!m_views.contains(view) || m_views[view]->isTouchingBusyVerticalView() == viewTouching) {
return;
}
m_views[view]->setIsTouchingBusyVerticalView(viewTouching);
emit isTouchingBusyVerticalViewChanged(view);
}
SchemeColors *Windows::activeWindowScheme(Latte::View *view) const
{
if (!m_views.contains(view)) {
return nullptr;
}
return m_views[view]->activeWindowScheme();
}
void Windows::setActiveWindowScheme(Latte::View *view, WindowSystem::SchemeColors *scheme)
{
if (!m_views.contains(view) || m_views[view]->activeWindowScheme() == scheme) {
return;
}
m_views[view]->setActiveWindowScheme(scheme);
emit activeWindowSchemeChanged(view);
}
SchemeColors *Windows::touchingWindowScheme(Latte::View *view) const
{
if (!m_views.contains(view)) {
return nullptr;
}
return m_views[view]->touchingWindowScheme();
}
void Windows::setTouchingWindowScheme(Latte::View *view, WindowSystem::SchemeColors *scheme)
{
if (!m_views.contains(view) || m_views[view]->touchingWindowScheme() == scheme) {
return;
}
m_views[view]->setTouchingWindowScheme(scheme);
emit touchingWindowSchemeChanged(view);
}
LastActiveWindow *Windows::lastActiveWindow(Latte::View *view)
{
if (!m_views.contains(view)) {
return nullptr;
}
return m_views[view]->lastActiveWindow();
}
//! Layouts
bool Windows::enabled(Latte::Layout::GenericLayout *layout)
{
if (!m_layouts.contains(layout)) {
return false;
}
return m_layouts[layout]->enabled();
}
bool Windows::activeWindowMaximized(Latte::Layout::GenericLayout *layout) const
{
if (!m_layouts.contains(layout)) {
return false;
}
return m_layouts[layout]->activeWindowMaximized();
}
void Windows::setActiveWindowMaximized(Latte::Layout::GenericLayout *layout, bool activeMaximized)
{
if (!m_layouts.contains(layout) || m_layouts[layout]->activeWindowMaximized() == activeMaximized) {
return;
}
m_layouts[layout]->setActiveWindowMaximized(activeMaximized);
emit activeWindowMaximizedChangedForLayout(layout);
}
bool Windows::existsWindowActive(Latte::Layout::GenericLayout *layout) const
{
if (!m_layouts.contains(layout)) {
return false;
}
return m_layouts[layout]->existsWindowActive();
}
void Windows::setExistsWindowActive(Latte::Layout::GenericLayout *layout, bool windowActive)
{
if (!m_layouts.contains(layout) || m_layouts[layout]->existsWindowActive() == windowActive) {
return;
}
m_layouts[layout]->setExistsWindowActive(windowActive);
emit existsWindowActiveChangedForLayout(layout);
}
bool Windows::existsWindowMaximized(Latte::Layout::GenericLayout *layout) const
{
if (!m_layouts.contains(layout)) {
return false;
}
return m_layouts[layout]->existsWindowMaximized();
}
void Windows::setExistsWindowMaximized(Latte::Layout::GenericLayout *layout, bool windowMaximized)
{
if (!m_layouts.contains(layout) || m_layouts[layout]->existsWindowMaximized() == windowMaximized) {
return;
}
m_layouts[layout]->setExistsWindowMaximized(windowMaximized);
emit existsWindowMaximizedChangedForLayout(layout);
}
SchemeColors *Windows::activeWindowScheme(Latte::Layout::GenericLayout *layout) const
{
if (!m_layouts.contains(layout)) {
return nullptr;
}
return m_layouts[layout]->activeWindowScheme();
}
void Windows::setActiveWindowScheme(Latte::Layout::GenericLayout *layout, WindowSystem::SchemeColors *scheme)
{
if (!m_layouts.contains(layout) || m_layouts[layout]->activeWindowScheme() == scheme) {
return;
}
m_layouts[layout]->setActiveWindowScheme(scheme);
emit activeWindowSchemeChangedForLayout(layout);
}
LastActiveWindow *Windows::lastActiveWindow(Latte::Layout::GenericLayout *layout)
{
if (!m_layouts.contains(layout)) {
return nullptr;
}
return m_layouts[layout]->lastActiveWindow();
}
//! Windows
bool Windows::isValidFor(const WindowId &wid) const
{
if (!m_windows.contains(wid)) {
return false;
}
return m_windows[wid].isValid();
}
QIcon Windows::iconFor(const WindowId &wid)
{
if (!m_windows.contains(wid)) {
return QIcon();
}
if (m_windows[wid].icon().isNull()) {
AppData data = m_wm->appDataFor(wid);
QIcon icon = data.icon;
if (icon.isNull()) {
icon = m_wm->iconFor(wid);
}
m_windows[wid].setIcon(icon);
return icon;
}
return m_windows[wid].icon();
}
QString Windows::appNameFor(const WindowId &wid)
{
if (!m_windows.contains(wid)) {
return QString();
}
if(!m_initializedApplicationData.contains(wid) && !m_delayedApplicationData.contains(wid)) {
m_delayedApplicationData.append(wid);
m_updateApplicationDataTimer.start();
}
if (m_windows[wid].appName().isEmpty()) {
AppData data = m_wm->appDataFor(wid);
m_windows[wid].setAppName(data.name);
return data.name;
}
return m_windows[wid].appName();
}
void Windows::updateApplicationData()
{
if (m_delayedApplicationData.count() > 0) {
for(int i=0; i<m_delayedApplicationData.count(); ++i) {
auto wid = m_delayedApplicationData[i];
if (m_windows.contains(wid)) {
AppData data = m_wm->appDataFor(wid);
QIcon icon = data.icon;
if (icon.isNull()) {
icon = m_wm->iconFor(wid);
}
m_windows[wid].setIcon(icon);
m_windows[wid].setAppName(data.name);
m_initializedApplicationData.append(wid);
emit applicationDataChanged(wid);
}
}
}
m_delayedApplicationData.clear();
}
WindowInfoWrap Windows::infoFor(const WindowId &wid) const
{
if (!m_windows.contains(wid)) {
return WindowInfoWrap();
}
return m_windows[wid];
}
//! Windows Criteria Functions
bool Windows::intersects(Latte::View *view, const WindowInfoWrap &winfo)
{
return (!winfo.isMinimized() && !winfo.isShaded() && winfo.geometry().intersects(view->absoluteGeometry()));
}
bool Windows::isActive(const WindowInfoWrap &winfo)
{
return (winfo.isValid() && winfo.isActive() && !winfo.isMinimized());
}
bool Windows::isActiveInViewScreen(Latte::View *view, const WindowInfoWrap &winfo)
{
return (winfo.isValid() && winfo.isActive() && !winfo.isMinimized()
&& m_views[view]->availableScreenGeometry().contains(winfo.geometry().center()));
}
bool Windows::isMaximizedInViewScreen(Latte::View *view, const WindowInfoWrap &winfo)
{
//! updated implementation to identify the screen that the maximized window is present
//! in order to avoid: https://bugs.kde.org/show_bug.cgi?id=397700
return (winfo.isValid() && !winfo.isMinimized()
&& !winfo.isShaded()
&& winfo.isMaximized()
&& m_views[view]->availableScreenGeometry().contains(winfo.geometry().center()));
}
bool Windows::isTouchingView(Latte::View *view, const WindowSystem::WindowInfoWrap &winfo)
{
return (winfo.isValid() && intersects(view, winfo));
}
bool Windows::isTouchingViewEdge(Latte::View *view, const WindowInfoWrap &winfo)
{
if (winfo.isValid() && !winfo.isMinimized()) {
bool inViewThicknessEdge{false};
bool inViewLengthBoundaries{false};
QRect screenGeometry = view->screenGeometry();
bool inCurrentScreen{screenGeometry.contains(winfo.geometry().topLeft()) || screenGeometry.contains(winfo.geometry().bottomRight())};
if (inCurrentScreen) {
if (view->location() == Plasma::Types::TopEdge) {
inViewThicknessEdge = (winfo.geometry().y() == view->absoluteGeometry().bottom() + 1);
} else if (view->location() == Plasma::Types::BottomEdge) {
inViewThicknessEdge = (winfo.geometry().bottom() == view->absoluteGeometry().top() - 1);
} else if (view->location() == Plasma::Types::LeftEdge) {
inViewThicknessEdge = (winfo.geometry().x() == view->absoluteGeometry().right() + 1);
} else if (view->location() == Plasma::Types::RightEdge) {
inViewThicknessEdge = (winfo.geometry().right() == view->absoluteGeometry().left() - 1);
}
if (view->formFactor() == Plasma::Types::Horizontal) {
int yCenter = view->absoluteGeometry().center().y();
QPoint leftChecker(winfo.geometry().left(), yCenter);
QPoint rightChecker(winfo.geometry().right(), yCenter);
bool fulloverlap = (winfo.geometry().left()<=view->absoluteGeometry().left()) && (winfo.geometry().right()>=view->absoluteGeometry().right());
inViewLengthBoundaries = fulloverlap || view->absoluteGeometry().contains(leftChecker) || view->absoluteGeometry().contains(rightChecker);
} else if (view->formFactor() == Plasma::Types::Vertical) {
int xCenter = view->absoluteGeometry().center().x();
QPoint topChecker(xCenter, winfo.geometry().top());
QPoint bottomChecker(xCenter, winfo.geometry().bottom());
bool fulloverlap = (winfo.geometry().top()<=view->absoluteGeometry().top()) && (winfo.geometry().bottom()>=view->absoluteGeometry().bottom());
inViewLengthBoundaries = fulloverlap || view->absoluteGeometry().contains(topChecker) || view->absoluteGeometry().contains(bottomChecker);
}
}
return (inViewThicknessEdge && inViewLengthBoundaries);
}
return false;
}
void Windows::cleanupFaultyWindows()
{
for (const auto &key : m_windows.keys()) {
auto winfo = m_windows[key];
//! garbage windows removing
if (winfo.wid()<=0 || winfo.geometry() == QRect(0, 0, 0, 0)) {
//qDebug() << "Faulty Geometry ::: " << winfo.wid();
m_windows.remove(key);
}
}
}
void Windows::updateAvailableScreenGeometries()
{
for (const auto view : m_views.keys()) {
if (m_views[view]->enabled()) {
int currentScrId = view->positioner()->currentScreenId();
QRect tempAvailableScreenGeometry = m_wm->corona()->availableScreenRectWithCriteria(currentScrId, QString(), m_ignoreModes, {});
if (tempAvailableScreenGeometry != m_views[view]->availableScreenGeometry()) {
m_views[view]->setAvailableScreenGeometry(tempAvailableScreenGeometry);
updateHints(view);
}
}
}
}
void Windows::updateAllHints()
{
for (const auto view : m_views.keys()) {
updateHints(view);
}
for (const auto layout : m_layouts.keys()) {
updateHints(layout);
}
if (!m_extraViewHintsTimer.isActive()) {
m_extraViewHintsTimer.start();
}
}
void Windows::updateExtraViewHints()
{
for (const auto horView : m_views.keys()) {
if (!m_views.contains(horView) || !m_views[horView]->enabled() || !m_views[horView]->isTrackingCurrentActivity()) {
continue;
}
if (horView->formFactor() == Plasma::Types::Horizontal) {
bool touchingBusyVerticalView{false};
for (const auto verView : m_views.keys()) {
if (!m_views.contains(verView) || !m_views[verView]->enabled() || !m_views[verView]->isTrackingCurrentActivity()) {
continue;
}
bool sameScreen = (verView->positioner()->currentScreenId() == horView->positioner()->currentScreenId());
if (verView->formFactor() == Plasma::Types::Vertical && sameScreen) {
bool topTouch = verView->isTouchingTopViewAndIsBusy() && horView->location() == Plasma::Types::TopEdge;
bool bottomTouch = verView->isTouchingBottomViewAndIsBusy() && horView->location() == Plasma::Types::BottomEdge;
if (topTouch || bottomTouch) {
touchingBusyVerticalView = true;
break;
}
}
}
//qDebug() << " Touching Busy Vertical View :: " << horView->location() << " - " << horView->positioner()->currentScreenId() << " :: " << touchingBusyVerticalView;
setIsTouchingBusyVerticalView(horView, touchingBusyVerticalView);
}
}
}
void Windows::updateHints(Latte::View *view)
{
if (!m_views.contains(view) || !m_views[view]->enabled() || !m_views[view]->isTrackingCurrentActivity()) {
return;
}
bool foundActive{false};
bool foundActiveInCurScreen{false};
bool foundActiveTouchInCurScreen{false};
bool foundActiveEdgeTouchInCurScreen{false};
bool foundTouchInCurScreen{false};
bool foundTouchEdgeInCurScreen{false};
bool foundMaximizedInCurScreen{false};
bool foundActiveGroupTouchInCurScreen{false};
//! the notification window is not sending a remove signal and creates windows of geometry (0x0 0,0),
//! maybe a garbage collector here is a good idea!!!
bool existsFaultyWindow{false};
WindowId maxWinId;
WindowId activeWinId;
WindowId touchWinId;
WindowId touchEdgeWinId;
WindowId activeTouchWinId;
WindowId activeTouchEdgeWinId;
//qDebug() << " -- TRACKING REPORT (SCREEN)--";
//! First Pass
for (const auto &winfo : m_windows) {
if (!existsFaultyWindow && (winfo.wid()<=0 || winfo.geometry() == QRect(0, 0, 0, 0))) {
existsFaultyWindow = true;
}
if ( !m_wm->inCurrentDesktopActivity(winfo)
|| m_wm->hasBlockedTracking(winfo.wid())
|| winfo.isMinimized()) {
continue;
}
//qDebug() << " _ _ _ ";
//qDebug() << "TRACKING | WINDOW INFO :: " << winfo.wid() << " _ " << winfo.appName() << " _ " << winfo.geometry() << " _ " << winfo.display();
if (isActive(winfo)) {
foundActive = true;
}
if (isActiveInViewScreen(view, winfo)) {
foundActiveInCurScreen = true;
activeWinId = winfo.wid();
}
//! Maximized windows flags
if ((winfo.isActive() && isMaximizedInViewScreen(view, winfo)) //! active maximized windows have higher priority than the rest maximized windows
|| (!foundMaximizedInCurScreen && isMaximizedInViewScreen(view, winfo))) {
foundMaximizedInCurScreen = true;
maxWinId = winfo.wid();
}
//! Touching windows flags
bool touchingViewEdge = isTouchingViewEdge(view, winfo);
bool touchingView = isTouchingView(view, winfo);
if (touchingView) {
if (winfo.isActive()) {
foundActiveTouchInCurScreen = true;
activeTouchWinId = winfo.wid();
} else {
foundTouchInCurScreen = true;
touchWinId = winfo.wid();
}
}
if (touchingViewEdge) {
if (winfo.isActive()) {
foundActiveEdgeTouchInCurScreen = true;
activeTouchEdgeWinId = winfo.wid();
} else {
foundTouchEdgeInCurScreen = true;
touchEdgeWinId = winfo.wid();
}
}
//qDebug() << "TRACKING | ACTIVE:"<< foundActive << " ACT_CUR_SCR:" << foundTouchInCurScreen << " MAXIM:"<<foundMaximizedInCurScreen;
//qDebug() << "TRACKING | TOUCHING VIEW EDGE:"<< touchingViewEdge << " TOUCHING VIEW:" << foundTouchInCurScreen;
}
if (existsFaultyWindow) {
cleanupFaultyWindows();
}
//! PASS 2
if (foundActiveInCurScreen && !foundActiveTouchInCurScreen) {
//! Second Pass to track also Child windows if needed
//qDebug() << "Windows Array...";
//for (const auto &winfo : m_windows) {
// qDebug() << " - " << winfo.wid() << " - " << winfo.isValid() << " - " << winfo.display() << " - " << winfo.geometry() << " parent : " << winfo.parentId();
//}
//qDebug() << " - - - - - ";
WindowInfoWrap activeInfo = m_windows[activeWinId];
WindowId mainWindowId = activeInfo.isChildWindow() ? activeInfo.parentId() : activeWinId;
for (const auto &winfo : m_windows) {
if (!m_wm->inCurrentDesktopActivity(winfo)
|| m_wm->hasBlockedTracking(winfo.wid())
|| winfo.isMinimized()) {
continue;
}
bool inActiveGroup = (winfo.wid() == mainWindowId || winfo.parentId() == mainWindowId);
//! consider only windows that belong to active window group meaning the main window
//! and its children
if (!inActiveGroup) {
continue;
}
if (isTouchingView(view, winfo)) {
foundActiveGroupTouchInCurScreen = true;
break;
}
}
}
//! HACK: KWin Effects such as ShowDesktop have no way to be identified and as such
//! create issues with identifying properly touching and maximized windows. BUT when
//! they are enabled then NO ACTIVE window is found. This is a way to identify these
//! effects trigerring and disable the touch flags.
//! BUG: 404483
//! Disabled because it has fault identifications, e.g. when a window is maximized and
//! Latte or Plasma are showing their View settings
//foundMaximizedInCurScreen = foundMaximizedInCurScreen && foundActive;
//foundTouchInCurScreen = foundTouchInCurScreen && foundActive;
//! assign flags
setExistsWindowActive(view, foundActiveInCurScreen);
setActiveWindowTouching(view, foundActiveTouchInCurScreen || foundActiveGroupTouchInCurScreen);
setActiveWindowTouchingEdge(view, foundActiveEdgeTouchInCurScreen);
setActiveWindowMaximized(view, (maxWinId.toInt()>0 && (maxWinId == activeTouchWinId || maxWinId == activeTouchEdgeWinId)));
setExistsWindowMaximized(view, foundMaximizedInCurScreen);
setExistsWindowTouching(view, (foundTouchInCurScreen || foundActiveTouchInCurScreen || foundActiveGroupTouchInCurScreen));
setExistsWindowTouchingEdge(view, (foundActiveEdgeTouchInCurScreen || foundTouchEdgeInCurScreen));
//! update color schemes for active and touching windows
setActiveWindowScheme(view, (foundActiveInCurScreen ? m_wm->schemesTracker()->schemeForWindow(activeWinId) : nullptr));
if (foundActiveTouchInCurScreen) {
setTouchingWindowScheme(view, m_wm->schemesTracker()->schemeForWindow(activeTouchWinId));
} else if (foundActiveEdgeTouchInCurScreen) {
setTouchingWindowScheme(view, m_wm->schemesTracker()->schemeForWindow(activeTouchEdgeWinId));
} else if (foundMaximizedInCurScreen) {
setTouchingWindowScheme(view, m_wm->schemesTracker()->schemeForWindow(maxWinId));
} else if (foundTouchInCurScreen) {
setTouchingWindowScheme(view, m_wm->schemesTracker()->schemeForWindow(touchWinId));
} else if (foundTouchEdgeInCurScreen) {
setTouchingWindowScheme(view, m_wm->schemesTracker()->schemeForWindow(touchEdgeWinId));
} else {
setTouchingWindowScheme(view, nullptr);
}
//! update LastActiveWindow
if (foundActiveInCurScreen) {
m_views[view]->setActiveWindow(activeWinId);
}
//! Debug
//qDebug() << "TRACKING | _________ FINAL RESULTS ________";
//qDebug() << "TRACKING | SCREEN: " << view->positioner()->currentScreenId() << " , EDGE:" << view->location() << " , ENABLED:" << enabled(view);
//qDebug() << "TRACKING | activeWindowTouching: " << foundActiveTouchInCurScreen << " ,activeWindowMaximized: " << activeWindowMaximized(view);
//qDebug() << "TRACKING | existsWindowActive: " << foundActiveInCurScreen << " , existsWindowMaximized:" << existsWindowMaximized(view)
// << " , existsWindowTouching:"<<existsWindowTouching(view);
//qDebug() << "TRACKING | activeEdgeWindowTouch: " << activeWindowTouchingEdge(view) << " , existsEdgeWindowTouch:" << existsWindowTouchingEdge(view);
//qDebug() << "TRACKING | existsActiveGroupTouching: " << foundActiveGroupTouchInCurScreen;
}
void Windows::updateHints(Latte::Layout::GenericLayout *layout) {
if (!m_layouts.contains(layout) || !m_layouts[layout]->enabled() || !m_layouts[layout]->isTrackingCurrentActivity()) {
return;
}
bool foundActive{false};
bool foundActiveMaximized{false};
bool foundMaximized{false};
//! the notification window is not sending a remove signal and creates windows of geometry (0x0 0,0),
//! maybe a garbage collector here is a good idea!!!
bool existsFaultyWindow{false};
WindowId activeWinId;
WindowId maxWinId;
for (const auto &winfo : m_windows) {
if (!existsFaultyWindow && (winfo.wid()<=0 || winfo.geometry() == QRect(0, 0, 0, 0))) {
existsFaultyWindow = true;
}
if (!m_wm->inCurrentDesktopActivity(winfo)
|| m_wm->hasBlockedTracking(winfo.wid())
|| winfo.isMinimized()) {
continue;
}
if (isActive(winfo)) {
foundActive = true;
activeWinId = winfo.wid();
if (winfo.isMaximized() && !winfo.isMinimized()) {
foundActiveMaximized = true;
maxWinId = winfo.wid();
}
}
if (!foundActiveMaximized && winfo.isMaximized() && !winfo.isMinimized()) {
foundMaximized = true;
maxWinId = winfo.wid();
}
//qDebug() << "window geometry ::: " << winfo.geometry();
}
if (existsFaultyWindow) {
cleanupFaultyWindows();
}
//! HACK: KWin Effects such as ShowDesktop have no way to be identified and as such
//! create issues with identifying properly touching and maximized windows. BUT when
//! they are enabled then NO ACTIVE window is found. This is a way to identify these
//! effects trigerring and disable the touch flags.
//! BUG: 404483
//! Disabled because it has fault identifications, e.g. when a window is maximized and
//! Latte or Plasma are showing their View settings
//foundMaximizedInCurScreen = foundMaximizedInCurScreen && foundActive;
//foundTouchInCurScreen = foundTouchInCurScreen && foundActive;
//! assign flags
setExistsWindowActive(layout, foundActive);
setActiveWindowMaximized(layout, foundActiveMaximized);
setExistsWindowMaximized(layout, foundActiveMaximized || foundMaximized);
//! update color schemes for active and touching windows
setActiveWindowScheme(layout, (foundActive ? m_wm->schemesTracker()->schemeForWindow(activeWinId) : nullptr));
//! update LastActiveWindow
if (foundActive) {
m_layouts[layout]->setActiveWindow(activeWinId);
}
//! Debug
//qDebug() << " -- TRACKING REPORT (LAYOUT) --";
//qDebug() << "TRACKING | LAYOUT: " << layout->name() << " , ENABLED:" << enabled(layout);
//qDebug() << "TRACKING | existsActiveWindow: " << foundActive << " ,activeWindowMaximized: " << foundActiveMaximized;
//qDebug() << "TRACKING | existsWindowMaximized: " << existsWindowMaximized(layout);
}
}
}
}
| 32.2875 | 175 | 0.645512 | [
"geometry"
] |
3f8471f673ff14a59ede7b3224c53ac7cbc1d3e5 | 3,691 | cc | C++ | cpp/test/cpp_itemCreator_google_unittest/ItemCreatorUnitTests.cc | Eisdiele/GildedRose-Refactoring-Kata | 38f346f522d49a704a5f9b1465f0d0732bf73e43 | [
"MIT"
] | null | null | null | cpp/test/cpp_itemCreator_google_unittest/ItemCreatorUnitTests.cc | Eisdiele/GildedRose-Refactoring-Kata | 38f346f522d49a704a5f9b1465f0d0732bf73e43 | [
"MIT"
] | 9 | 2021-04-05T16:15:13.000Z | 2021-04-06T18:21:14.000Z | cpp/test/cpp_itemCreator_google_unittest/ItemCreatorUnitTests.cc | Eisdiele/GildedRose-Refactoring-Kata | 38f346f522d49a704a5f9b1465f0d0732bf73e43 | [
"MIT"
] | null | null | null | #include <gtest/gtest.h>
#include <tuple> // tuple is used for input of testparameters
//headers for tested ItemCreator:
#include "ItemCreator.h"
class ItemCreatorTestSuite :
public :: testing::TestWithParam <
std::tuple <
std::vector< itemtype >, // itemtype input for object declaration
std::vector< std::string >, // name
std::vector< itemtype > // itemtype expected from object Item::getType() method.
>
> {
public:
MetaItem* item;
ItemCreator iC;
std::string instan_expl {"BAD TESTINSTANTIATION: unequal length of parameter vectors."};
std::string type_expl {"Types: 0->[Aged Brie], 1->[Backstage passes], 2->[Common], 3->[Conjured], 4->[Sulfuras], 5->[Unspecified]"};
};
TEST_P(ItemCreatorTestSuite, ItemCreateTest) {
const std::vector< itemtype > v_it_input = std::get<0>(GetParam());
const std::vector< std::string > v_name = std::get<1>(GetParam());
const std::vector< itemtype > v_it_expected = std::get<2>(GetParam());
// check for correct Testinstantiation:
ASSERT_EQ( v_it_input.size(), v_it_expected.size() ) << instan_expl ;
ASSERT_EQ( v_it_input.size(), v_name.size() ) << instan_expl ;
// For each provided sample test for correct type creation.
for (int i = 0; i < v_it_input.size(); i++){
// create Item object via ItemCreate() method.
item = iC.ItemCreate( v_name.at(i), 1, 1, v_it_input.at(i) );
// Test if type is as expected.
EXPECT_EQ( item->getType(), v_it_expected.at(i) )
<< "Item object declared by ItemCreator::ItemCreate does not provide expected type ["
<< v_it_input.at(i) << "] by Item::getType()"
<< item->getType() << "."
<< std::endl << type_expl << std::endl;
}
}
// Test for correct itemtype in Item objects created by passing type explicitly.
INSTANTIATE_TEST_CASE_P(
ItemCreatorFromTYPETest,
ItemCreatorTestSuite,
::testing::Values(
std::make_tuple(
std::vector< itemtype > { type_agedbrie,
type_backstagepasses,
type_common,
type_conjured,
type_sulfuras },
std::vector< std::string > {"AB Item",
"BP Item",
"CM Item",
"CJ Item",
"SL Item"
},
std::vector< itemtype > { type_agedbrie,
type_backstagepasses,
type_common,
type_conjured,
type_sulfuras }
)
)
);
// Test for correct itemtype in Item objects created by passing no itemtype,
// but providing type information in name.
INSTANTIATE_TEST_CASE_P(
ItemCreatorFromNAMETest,
ItemCreatorTestSuite,
::testing::Values(
std::make_tuple(
std::vector< itemtype > { type_unspecified,
type_unspecified,
type_unspecified,
type_unspecified,
type_unspecified },
std::vector< std::string > { "Aged Brie Item",
"Backstage passes Item",
"Common Item",
"Conjured Item",
"Sulfuras Item" },
std::vector< itemtype > { type_agedbrie,
type_backstagepasses,
type_common,
type_conjured,
type_sulfuras }
)
)
);
| 36.186275 | 136 | 0.531021 | [
"object",
"vector"
] |
3f9ba0f60af8540d06141a63ec193289d55c7c58 | 2,745 | cpp | C++ | src/model/path.cpp | panzergame/dxfplotter | 95393027903c8e907c1d1ef7b4982d1aadc968c8 | [
"MIT"
] | 19 | 2020-04-08T16:38:27.000Z | 2022-03-30T19:53:18.000Z | src/model/path.cpp | panzergame/dxfplotter | 95393027903c8e907c1d1ef7b4982d1aadc968c8 | [
"MIT"
] | 3 | 2020-10-27T05:50:37.000Z | 2022-03-19T17:22:04.000Z | src/model/path.cpp | panzergame/dxfplotter | 95393027903c8e907c1d1ef7b4982d1aadc968c8 | [
"MIT"
] | 6 | 2020-06-15T13:00:58.000Z | 2022-02-09T13:18:04.000Z | #include <path.h>
#include <layer.h>
#include <fmt/format.h>
#include <geometry/cleaner.h>
namespace Model
{
void Path::updateGlobalVisibility()
{
const bool newGloballyVisible = visible() && m_layer->visible();
if (m_globallyVisible != newGloballyVisible) {
m_globallyVisible = newGloballyVisible;
emit globalVisibilityChanged(m_globallyVisible);
}
}
Path::Path(Geometry::Polyline &&basePolyline, const std::string &name, const PathSettings &settings)
:Renderable(name),
m_basePolyline(basePolyline),
m_settings(settings),
m_globallyVisible(true)
{
connect(this, &Path::visibilityChanged, this, &Path::updateGlobalVisibility);
}
Path::ListUPtr Path::FromPolylines(Geometry::Polyline::List &&polylines, const PathSettings &settings, const std::string &layerName)
{
const int size = polylines.size();
Path::ListUPtr paths(size);
for (int i = 0; i < size; ++i) {
static const char *pathNameFormat = "({}) {}";
const std::string pathName = fmt::format(pathNameFormat, layerName, i);
paths[i].reset(new Path(std::move(polylines[i]), pathName, settings));
}
return paths;
}
Layer &Path::layer()
{
return *m_layer;
}
const Layer &Path::layer() const
{
return *m_layer;
}
void Path::setLayer(Layer &layer)
{
m_layer = &layer;
updateGlobalVisibility();
connect(m_layer, &Layer::visibilityChanged, this, &Path::updateGlobalVisibility);
}
const Geometry::Polyline &Path::basePolyline() const
{
return m_basePolyline;
}
Geometry::Polyline::List Path::finalPolylines() const
{
return m_offsettedPath ? m_offsettedPath->polylines() : Geometry::Polyline::List{m_basePolyline};
}
Model::OffsettedPath *Path::offsettedPath() const
{
return m_offsettedPath.get();
}
void Path::offset(float margin, float minimumPolylineLength, float minimumArcLength)
{
Geometry::Polyline::List offsettedPolylines = m_basePolyline.offsetted(margin);
Geometry::Cleaner cleaner(std::move(offsettedPolylines), minimumPolylineLength, minimumArcLength);
const OffsettedPath::Direction direction = (margin > 0.0f) ?
OffsettedPath::Direction::LEFT : OffsettedPath::Direction::RIGHT;
m_offsettedPath = std::make_unique<OffsettedPath>(cleaner.polylines(), direction);
emit offsettedPathChanged();
}
void Path::resetOffset()
{
m_offsettedPath.reset();
emit offsettedPathChanged();
}
bool Path::isPoint() const
{
return m_basePolyline.isPoint();
}
const Model::PathSettings &Path::settings() const
{
return m_settings;
}
Model::PathSettings &Path::settings()
{
return m_settings;
}
Geometry::CuttingDirection Path::cuttingDirection() const
{
return (m_offsettedPath) ? m_offsettedPath->cuttingDirection() :
Geometry::CuttingDirection::FORWARD;
}
bool Path::globallyVisible() const
{
return m_globallyVisible;
}
}
| 22.317073 | 132 | 0.746084 | [
"geometry",
"model"
] |
3f9ffcc71535af28820f2953c1c9044ecf7ebb8a | 2,609 | cpp | C++ | src/GUI/StreamDirectory.cpp | rcstilborn/SecMon | f750d9c421dac1c5a795384ff8f7b7a29a0aece9 | [
"MIT"
] | 2 | 2021-12-17T17:35:07.000Z | 2022-01-11T12:38:00.000Z | src/GUI/StreamDirectory.cpp | rcstilborn/SecMon | f750d9c421dac1c5a795384ff8f7b7a29a0aece9 | [
"MIT"
] | null | null | null | src/GUI/StreamDirectory.cpp | rcstilborn/SecMon | f750d9c421dac1c5a795384ff8f7b7a29a0aece9 | [
"MIT"
] | 2 | 2018-01-15T06:10:07.000Z | 2021-07-08T19:40:49.000Z | /*
* HTTPStreamServer.cpp
*
* Created on: Aug 8, 2015
* Author: richard
*
* Copyright 2017 Richard Stilborn
* Licensed under the MIT License
*/
#include "StreamDirectory.h"
#include <boost/thread/lock_guard.hpp>
#include <glog/logging.h>
#include <cstddef>
#include <exception>
#include <iostream>
#include <utility>
#include <string>
#include <memory>
StreamDirectory::StreamDirectory(boost::asio::io_service& io_service)
: io_service_(io_service),
stream_id(0),
stream_list_(),
stream_list_mtx_() {
}
StreamDirectory::~StreamDirectory() {
boost::lock_guard<boost::mutex> guard(stream_list_mtx_);
stream_list_.clear();
}
void StreamDirectory::addStream(ScenePublisher::Stream& stream) {
boost::lock_guard<boost::mutex> guard(stream_list_mtx_);
std::shared_ptr<Stream> stream_ptr(new Stream(stream.image_ready, ++stream_id));
DLOG(INFO)<< "StreamDirectory::addStream() - " << stream.name << " mapped to " << stream_id << ".mjpeg";
stream_list_.insert(std::pair<const int, std::shared_ptr<Stream>>(stream_id, stream_ptr));
}
//void StreamDirectory::addStream(const std::string& name,
// boost::signals2::signal<void (std::shared_ptr<std::vector<unsigned char>>)> signal){
// boost::lock_guard<boost::mutex> guard(stream_list_mtx_);
// std::shared_ptr<Stream> stream_ptr(new Stream(signal, ++stream_id));
// std::cout << "StreamDirectory::addStream() - " << name << " mapped to " << stream_id << ".mjpeg" << std::endl;
// stream_list_.insert(std::pair<const int,std::shared_ptr<Stream>>(stream_id,stream_ptr));
//}
bool StreamDirectory::handleValidStream(const std::string& streamRequest, http::connection_ptr conn) {
// Strip file name down to int
std::size_t last_dot_pos = streamRequest.find_last_of(".");
if (last_dot_pos == std::string::npos) {
LOG(WARNING)<< "StreamDirectory::handleValidStream() - No extension found in requested stream " << streamRequest;
return false;
}
std::string filename = streamRequest.substr(1, last_dot_pos + 1);
int stream_id;
try {
stream_id = std::stoi(filename);
} catch (std::exception& e) {
LOG(WARNING)<< "StreamDirectory::handleValidStream() - Could not convert filename to integer " <<
filename << ". " << e.what();
return false;
}
auto it = stream_list_.find(stream_id);
if (it != stream_list_.end()) {
it->second->registerNewConnection(conn);
return true;
} else {
LOG(WARNING)<< "StreamDirectory::handleValidStream() - Could not find stream with id " << stream_id;
return false;
}
}
| 34.328947 | 118 | 0.682637 | [
"vector"
] |
3fa080ee8bdeada514cf0f0684e2d2a2237b0f94 | 1,413 | cpp | C++ | assignment1/31transpose3d.cpp | akashsharma99/2ndSemkiit | 023e03c4bac787455e0b5dacf6c305b25364b95c | [
"MIT"
] | null | null | null | assignment1/31transpose3d.cpp | akashsharma99/2ndSemkiit | 023e03c4bac787455e0b5dacf6c305b25364b95c | [
"MIT"
] | null | null | null | assignment1/31transpose3d.cpp | akashsharma99/2ndSemkiit | 023e03c4bac787455e0b5dacf6c305b25364b95c | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main()
{
int n;
cout<<"Enter side length of 3d matrix\n";
cin>>n;
int*** a=(int***)calloc(n,sizeof(int**));
for(int i=0;i<n;i++)
{
a[i]=(int**)calloc(n,sizeof(int*));
for(int j=0;j<n;j++)
{
a[i][j]=(int*)calloc(n,sizeof(int));
}
}
for(int i=0;i<n;i++)
{
cout<<"Enter elements of layer "<<i<<"\n";
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
cin>>a[i][j][k];
}
}
//transposing
int m=(n%2==0)?n/2:(n/2)+1;
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
{
int t=a[i][j][k];
a[i][j][k]=a[n-1-i][n-1-j][n-1-k];
a[n-1-i][n-1-j][n-1-k]=t;
}
}
}
//printing
cout <<"\nthe transposed matrix is\n";
for(int i=0;i<n;i++)
{
cout<<"elements of layer "<<i<<"\n";
for(int j=0;j<n;j++)
{
for(int k=0;k<n;k++)
cout<<a[i][j][k]<<"\t";
cout<<"\n";
}
}
return 0;
}
| 26.166667 | 59 | 0.304317 | [
"3d"
] |
3fba876ba7e0ed26d4b5ea3651afe3d036882bcc | 920 | cpp | C++ | 12. exam-17112019/04.mayan-calculator.cpp | ihristova11/cpp-fundamentals | a72a0fb9e302921760a81f0a3436039b34b0981f | [
"MIT"
] | null | null | null | 12. exam-17112019/04.mayan-calculator.cpp | ihristova11/cpp-fundamentals | a72a0fb9e302921760a81f0a3436039b34b0981f | [
"MIT"
] | null | null | null | 12. exam-17112019/04.mayan-calculator.cpp | ihristova11/cpp-fundamentals | a72a0fb9e302921760a81f0a3436039b34b0981f | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <vector>
#include <string>
using namespace std;
int main()
{
map<int, vector<string>> store;
int n, digit;
string t;
string line, temp;
cin >> n;
cin.ignore();
for (size_t i = 0; i < n; i++)
{
getline(cin, line);
int sizeOfDigit = line.size() / 10;
for (size_t k = 0; k < 10; k++)
{
for (size_t j = k * sizeOfDigit; j < k * sizeOfDigit + sizeOfDigit; j++)
{
string ch(1, line[j]);
temp.append(ch);
}
map<int, vector<string>>::iterator it;
it = store.find(k);
vector<string> v = { temp };
if (it == store.end())
{
store.insert(pair<int, vector<string>>(k, v));
}
else
{
store[k].push_back(temp);
}
temp = "";
}
}
cin >> t;
for (size_t i = 0; i < n; i++)
{
for (size_t m = 0; m < t.size(); m++)
{
digit = t[m] - '0';
cout << store[digit][i];
}
cout << endl;
}
return 0;
} | 14.375 | 75 | 0.525 | [
"vector"
] |
3fbcf8c27726ed4f600e469772ff0a74e7b0340c | 5,742 | hpp | C++ | Wrappers/EigenWrapper.hpp | petiaccja/MathterBench | e47ad69447a3031c24ed06c51435c60593719b26 | [
"Unlicense"
] | 1 | 2020-05-26T22:08:29.000Z | 2020-05-26T22:08:29.000Z | Wrappers/EigenWrapper.hpp | petiaccja/MathterBench | e47ad69447a3031c24ed06c51435c60593719b26 | [
"Unlicense"
] | null | null | null | Wrappers/EigenWrapper.hpp | petiaccja/MathterBench | e47ad69447a3031c24ed06c51435c60593719b26 | [
"Unlicense"
] | null | null | null | #pragma once
#include "../Libraries/Eigen/Dense"
#include "../Libraries/Eigen/LU"
#include <random>
class EigenWrapper {
public:
//----------------------------------
// Types
//----------------------------------
using Vec2 = Eigen::Vector2f;
using Vec3 = Eigen::Vector3f;
using Vec4 = Eigen::Vector4f;
using Mat22 = Eigen::Matrix<float, 2, 2>;
using Mat33 = Eigen::Matrix<float, 3, 3>;
using Mat44 = Eigen::Matrix<float, 4, 4>;
using Quat = Eigen::Quaternion<float>;
//----------------------------------
// Vector binary operators
//----------------------------------
template <class Vec>
static Vec MulVV(const Vec& lhs, const Vec& rhs);
template <class Vec>
static Vec AddVV(const Vec& lhs, const Vec& rhs);
template <class Vec>
static Vec DivVV(const Vec& lhs, const Vec& rhs);
template <class Vec>
static float Dot(const Vec& lhs, const Vec& rhs);
template <class Vec>
static Vec Cross(const Vec& lhs, const Vec& rhs);
//----------------------------------
// Vector unary operators
//----------------------------------
template <class Vec>
static float NormV(const Vec& arg);
template <class Vec>
static Vec NormalizeV(const Vec& arg);
//----------------------------------
// Matrix binary operators
//----------------------------------
template <class MatL, class MatR>
static auto MulMM(const MatL& lhs, const MatR& rhs);
template <class Scalar, int RowsL, int Match, int ColsR, int Options, int MaxRowsL, int MaxColsL, int MaxRowsR, int MaxColsR>
static auto MulMM_Impl(const Eigen::Matrix<Scalar, RowsL, Match, Options, MaxRowsL, MaxColsL>& lhs, const Eigen::Matrix<Scalar, Match, ColsR, Options, MaxRowsR, MaxColsR>& rhs)
-> Eigen::Matrix<Scalar, RowsL, ColsR>;
template <class Mat>
static Mat AddMM(const Mat& lhs, const Mat& rhs);
//----------------------------------
// Matrix unary operators
//----------------------------------
template <class Mat>
static auto Transpose(const Mat& arg);
template <class Scalar, int Rows, int Cols, int Options, int MaxRows, int MaxCols>
static auto Transpose_Impl(const Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>& arg)
-> Eigen::Matrix<Scalar, Cols, Rows, Options>;
template <class Mat>
static Mat Inverse(const Mat& arg);
template <class Mat>
static auto Determinant(const Mat& arg);
template <class Mat>
static auto Trace(const Mat& arg);
template <class Mat>
static Mat Pow3M(const Mat& arg);
//----------------------------------
// Extra
//----------------------------------
template <class Mat>
static auto SingularValueDec(const Mat& arg);
//----------------------------------
// Utility
//----------------------------------
template <class Vec>
static void RandomVec(Vec& vec);
template <class Mat>
static void RandomMat(Mat& mat);
//----------------------------------
// Members
//----------------------------------
static std::mt19937 rne;
static std::uniform_real_distribution<float> rng;
};
inline std::mt19937 EigenWrapper::rne;
inline std::uniform_real_distribution<float> EigenWrapper::rng(-1, 1);
template <class Vec>
Vec EigenWrapper::MulVV(const Vec& lhs, const Vec& rhs) {
return lhs.cwiseProduct(rhs);
}
template <class Vec>
Vec EigenWrapper::AddVV(const Vec& lhs, const Vec& rhs) {
return lhs.cwiseProduct(rhs);
}
template <class Vec>
Vec EigenWrapper::DivVV(const Vec& lhs, const Vec& rhs) {
return lhs.cwiseProduct(rhs);
}
template <class Vec>
float EigenWrapper::Dot(const Vec& lhs, const Vec& rhs) {
return lhs.dot(rhs);
}
template <class Vec>
Vec EigenWrapper::Cross(const Vec& lhs, const Vec& rhs) {
return lhs.cross(rhs);
}
template <class Vec>
float EigenWrapper::NormV(const Vec& arg) {
return arg.norm();
}
template <class Vec>
Vec EigenWrapper::NormalizeV(const Vec& arg) {
return arg.normalized();
}
template <class MatL, class MatR>
auto EigenWrapper::MulMM(const MatL& lhs, const MatR& rhs) {
return MulMM_Impl(lhs, rhs);
}
template <class Scalar, int RowsL, int Match, int ColsR, int Options, int MaxRowsL, int MaxColsL, int MaxRowsR, int MaxColsR>
auto EigenWrapper::MulMM_Impl(const Eigen::Matrix<Scalar, RowsL, Match, Options, MaxRowsL, MaxColsL>& lhs, const Eigen::Matrix<Scalar, Match, ColsR, Options, MaxRowsR, MaxColsR>& rhs)
-> Eigen::Matrix<Scalar, RowsL, ColsR> {
return lhs * rhs;
}
template <class Mat>
Mat EigenWrapper::AddMM(const Mat& lhs, const Mat& rhs) {
return lhs + rhs;
}
template <class Mat>
auto EigenWrapper::Transpose(const Mat& arg) {
return Transpose_Impl(arg);
}
template <class Scalar, int Rows, int Cols, int Options, int MaxRows, int MaxCols>
auto EigenWrapper::Transpose_Impl(const Eigen::Matrix<Scalar, Rows, Cols, Options, MaxRows, MaxCols>& arg) -> Eigen::Matrix<Scalar, Cols, Rows, Options> {
return arg.transpose();
}
template <class Mat>
Mat EigenWrapper::Inverse(const Mat& arg) {
return arg.inverse();
}
template <class Mat>
auto EigenWrapper::Determinant(const Mat& arg) {
return arg.determinant();
}
template <class Mat>
auto EigenWrapper::Trace(const Mat& arg) {
return arg.trace();
}
template <class Mat>
Mat EigenWrapper::Pow3M(const Mat& arg) {
return arg * arg * arg;
}
template <class Mat>
auto EigenWrapper::SingularValueDec(const Mat& arg) {
return arg.jacobiSvd();
}
template <class Vec>
void EigenWrapper::RandomVec(Vec& vec) {
return RandomMat(vec);
}
template <class Mat>
void EigenWrapper::RandomMat(Mat& mat) {
for (int j = 0; j < mat.cols(); ++j) {
for (int i = 0; i < mat.rows(); ++i) {
mat(i, j) = rng(rne);
}
}
}
| 26.957746 | 184 | 0.612853 | [
"vector"
] |
3fc5183877d2125445205780b806bc4df20d9405 | 2,667 | cpp | C++ | examples/ThirdPartyLibs/Gwen/Controls/Button.cpp | felipeek/bullet3 | 6a59241074720e9df119f2f86bc01765917feb1e | [
"Zlib"
] | 9,136 | 2015-01-02T00:41:45.000Z | 2022-03-31T15:30:02.000Z | examples/ThirdPartyLibs/Gwen/Controls/Button.cpp | felipeek/bullet3 | 6a59241074720e9df119f2f86bc01765917feb1e | [
"Zlib"
] | 2,424 | 2015-01-05T08:55:58.000Z | 2022-03-30T19:34:55.000Z | examples/ThirdPartyLibs/Gwen/Controls/Button.cpp | felipeek/bullet3 | 6a59241074720e9df119f2f86bc01765917feb1e | [
"Zlib"
] | 2,921 | 2015-01-02T10:19:30.000Z | 2022-03-31T02:48:42.000Z | /*
GWEN
Copyright (c) 2010 Facepunch Studios
See license in Gwen.h
*/
#include "Gwen/Gwen.h"
#include "Gwen/Skin.h"
#include "Gwen/Controls/Button.h"
#include "Gwen/Controls/ImagePanel.h"
using namespace Gwen;
using namespace Gwen::Controls;
GWEN_CONTROL_CONSTRUCTOR(Button)
{
m_Image = NULL;
m_bDepressed = false;
m_bCenterImage = false;
SetSize(100, 20);
SetMouseInputEnabled(true);
SetIsToggle(false);
SetAlignment(Gwen::Pos::Center);
SetTextPadding(Padding(3, 0, 3, 0));
m_bToggleStatus = false;
SetKeyboardInputEnabled(false);
SetTabable(false);
}
void Button::Render(Skin::Base* skin)
{
if (ShouldDrawBackground())
{
bool bDrawDepressed = IsDepressed() && IsHovered();
if (IsToggle()) bDrawDepressed = bDrawDepressed || GetToggleState();
bool bDrawHovered = IsHovered() && ShouldDrawHover();
skin->DrawButton(this, bDrawDepressed, bDrawHovered);
}
}
void Button::OnMouseClickLeft(int /*x*/, int /*y*/, bool bDown)
{
if (bDown)
{
m_bDepressed = true;
Gwen::MouseFocus = this;
onDown.Call(this);
}
else
{
if (IsHovered() && m_bDepressed)
{
OnPress();
}
m_bDepressed = false;
Gwen::MouseFocus = NULL;
onUp.Call(this);
}
Redraw();
}
void Button::OnPress()
{
if (IsToggle())
{
SetToggleState(!GetToggleState());
}
onPress.Call(this);
}
void Button::SetImage(const TextObject& strName, bool bCenter)
{
if (strName.GetUnicode() == L"")
{
if (m_Image)
{
delete m_Image;
m_Image = NULL;
}
return;
}
if (!m_Image)
{
m_Image = new ImagePanel(this);
}
m_Image->SetImage(strName);
m_Image->SizeToContents();
m_Image->SetPos(m_Padding.left, 2);
m_bCenterImage = bCenter;
int IdealTextPadding = m_Image->Right() + m_Padding.left + 4;
if (m_rTextPadding.left < IdealTextPadding)
{
m_rTextPadding.left = IdealTextPadding;
}
}
void Button::SetToggleState(bool b)
{
if (m_bToggleStatus == b) return;
m_bToggleStatus = b;
onToggle.Call(this);
if (m_bToggleStatus)
{
onToggleOn.Call(this);
}
else
{
onToggleOff.Call(this);
}
}
void Button::SizeToContents()
{
BaseClass::SizeToContents();
if (m_Image)
{
int height = m_Image->Height() + 4;
if (Height() < height)
{
SetHeight(height);
}
}
}
bool Button::OnKeySpace(bool bDown)
{
OnMouseClickLeft(0, 0, bDown);
return true;
}
void Button::AcceleratePressed()
{
OnPress();
}
void Button::Layout(Skin::Base* pSkin)
{
BaseClass::Layout(pSkin);
if (m_Image)
{
Gwen::Align::CenterVertically(m_Image);
if (m_bCenterImage)
Gwen::Align::CenterHorizontally(m_Image);
}
}
void Button::OnMouseDoubleClickLeft(int x, int y)
{
OnMouseClickLeft(x, y, true);
onDoubleClick.Call(this);
}; | 16.066265 | 70 | 0.68354 | [
"render"
] |
3fcbc52602ca6c776642729d0bb207d59ef63ce5 | 9,656 | hpp | C++ | src/lib/client/EqualizerPresetsControllerCommands.hpp | gerickson/openhlx | f23a825ca56ee226db393da14d81a7d4e9ae0b33 | [
"Apache-2.0"
] | 1 | 2021-05-21T21:10:09.000Z | 2021-05-21T21:10:09.000Z | src/lib/client/EqualizerPresetsControllerCommands.hpp | gerickson/openhlx | f23a825ca56ee226db393da14d81a7d4e9ae0b33 | [
"Apache-2.0"
] | 12 | 2021-06-12T16:42:30.000Z | 2022-02-01T18:44:42.000Z | src/lib/client/EqualizerPresetsControllerCommands.hpp | gerickson/openhlx | f23a825ca56ee226db393da14d81a7d4e9ae0b33 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2019-2021 Grant Erickson
* 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.
*
*/
/**
* @file
* This file defines objects for HLX client equalizer preset data
* model commands and their constituent requests and responses.
*
*/
#ifndef OPENHLXCLIENTEQUALIZERPRESETSCONTROLLERCOMMANDS_HPP
#define OPENHLXCLIENTEQUALIZERPRESETSCONTROLLERCOMMANDS_HPP
#include <OpenHLX/Client/CommandEqualizerBandRequestBases.hpp>
#include <OpenHLX/Client/CommandExchangeBasis.hpp>
#include <OpenHLX/Client/CommandNameSetRequestBasis.hpp>
#include <OpenHLX/Client/CommandQueryRequestBasis.hpp>
#include <OpenHLX/Client/CommandResponseBasis.hpp>
#include <OpenHLX/Common/CommandEqualizerPresetsRegularExpressionBases.hpp>
#include <OpenHLX/Common/Errors.hpp>
#include <OpenHLX/Model/EqualizerBandModel.hpp>
#include <OpenHLX/Model/EqualizerPresetModel.hpp>
namespace HLX
{
namespace Client
{
namespace Command
{
namespace EqualizerPresets
{
// MARK: Observer Requests, Responses, and Commands
/**
* @brief
* An object for a HLX client equalizer preset data model query
* command request buffer.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class QueryRequest :
virtual public Client::Command::RequestBasis,
public Client::Command::QueryRequestBasis
{
public:
QueryRequest(void) = default;
virtual ~QueryRequest(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier);
private:
// Explicitly hide base class initializers
using RequestBasis::Init;
};
/**
* @brief
* An object for a HLX client equalizer preset data model query
* command response regular expression.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class QueryResponse :
public ResponseBasis,
public Common::Command::EqualizerPresets::QueryRegularExpressionBasis
{
public:
QueryResponse(void) = default;
virtual ~QueryResponse(void) = default;
Common::Status Init(void);
private:
// Explicitly hide base class initializers
using ResponseBasis::Init;
};
/**
* @brief
* An object for a HLX client equalizer preset data model query
* command request / response pair.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class Query :
public ExchangeBasis
{
public:
Query(void) = default;
virtual ~Query(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier);
private:
QueryRequest mRequest;
QueryResponse mResponse;
};
// MARK: Mutator Requests, Responses, and Commands
// MARK: Equalizer Band Level Mutator Requests, Responses, and Commands
/**
* @brief
* An object for a HLX client equalizer preset band level data model
* property mutation command response regular expression.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class EqualizerBandResponse :
public ResponseBasis,
public Common::Command::EqualizerPresets::BandLevelRegularExpressionBasis
{
public:
EqualizerBandResponse(void) = default;
virtual ~EqualizerBandResponse(void) = default;
Common::Status Init(void);
private:
// Explicitly hide base class initializers
using ResponseBasis::Init;
};
/**
* @brief
* An object for a HLX client equalizer preset band level set data
* model property mutation command request buffer.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class SetEqualizerBandRequest :
public EqualizerBandSetRequestBasis
{
public:
SetEqualizerBandRequest(void) = default;
virtual ~SetEqualizerBandRequest(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier, const Model::EqualizerBandModel::IdentifierType &aEqualizerBandIdentifier, const Model::EqualizerBandModel::LevelType &aEqualizerBandLevel);
};
/**
* @brief
* An object for a HLX client equalizer preset band level data model
* property mutation command request / response pair.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class SetEqualizerBand :
public ExchangeBasis
{
public:
SetEqualizerBand(void) = default;
virtual ~SetEqualizerBand(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier, const Model::EqualizerBandModel::IdentifierType &aEqualizerBandIdentifier, const Model::EqualizerBandModel::LevelType &aEqualizerBandLevel);
private:
SetEqualizerBandRequest mRequest;
EqualizerBandResponse mResponse;
};
/**
* @brief
* An object for a HLX client equalizer preset band level increase
* data model property mutation command request buffer.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class IncreaseEqualizerBandRequest :
public EqualizerBandIncreaseRequestBasis
{
public:
IncreaseEqualizerBandRequest(void) = default;
virtual ~IncreaseEqualizerBandRequest(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier, const Model::EqualizerBandModel::IdentifierType &aEqualizerBandIdentifier);
};
/**
* @brief
* An object for a HLX client equalizer preset band level increase
* data model property mutation command request / response pair.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class IncreaseEqualizerBand :
public ExchangeBasis
{
public:
IncreaseEqualizerBand(void) = default;
virtual ~IncreaseEqualizerBand(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier, const Model::EqualizerBandModel::IdentifierType &aEqualizerBandIdentifier);
private:
IncreaseEqualizerBandRequest mRequest;
EqualizerBandResponse mResponse;
};
/**
* @brief
* An object for a HLX client equalizer preset band level decrease
* data model property mutation command request buffer.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class DecreaseEqualizerBandRequest :
public EqualizerBandDecreaseRequestBasis
{
public:
DecreaseEqualizerBandRequest(void) = default;
virtual ~DecreaseEqualizerBandRequest(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier, const Model::EqualizerBandModel::IdentifierType &aEqualizerBandIdentifier);
};
/**
* @brief
* An object for a HLX client equalizer preset band level decrease
* data model property mutation command request / response pair.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class DecreaseEqualizerBand :
public ExchangeBasis
{
public:
DecreaseEqualizerBand(void) = default;
virtual ~DecreaseEqualizerBand(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier, const Model::EqualizerBandModel::IdentifierType &aEqualizerBandIdentifier);
private:
DecreaseEqualizerBandRequest mRequest;
EqualizerBandResponse mResponse;
};
// MARK: Name Mutator Requests, Responses, and Commands
/**
* @brief
* An object for a HLX client equalizer preset name data model
* property mutation command request buffer.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class SetNameRequest :
public NameSetRequestBasis
{
public:
SetNameRequest(void) = default;
virtual ~SetNameRequest(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier, const char *aName);
};
/**
* @brief
* An object for a HLX client equalizer preset name data model
* property mutation command response regular expression.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class NameResponse :
public ResponseBasis,
public Common::Command::EqualizerPresets::NameRegularExpressionBasis
{
public:
NameResponse(void) = default;
virtual ~NameResponse(void) = default;
Common::Status Init(void);
private:
// Explicitly hide base class initializers
using ResponseBasis::Init;
};
/**
* @brief
* An object for a HLX client equalizer preset name data model
* property mutation command request / response pair.
*
* @ingroup client
* @ingroup command
* @ingroup equalizer-preset
*
*/
class SetName :
public ExchangeBasis
{
public:
SetName(void) = default;
virtual ~SetName(void) = default;
Common::Status Init(const Model::EqualizerPresetModel::IdentifierType &aEqualizerPresetIdentifier, const char *aName);
private:
SetNameRequest mRequest;
NameResponse mResponse;
};
}; // namespace EqualizerPresets
}; // namespace Command
}; // namespace Client
}; // namespace HLX
#endif // OPENHLXCLIENTEQUALIZERPRESETSCONTROLLERCOMMANDS_HPP
| 25.887399 | 243 | 0.738505 | [
"object",
"model"
] |
3fd378ad06750fc3998dcfb8bcbee4df4b4c71a7 | 5,402 | cpp | C++ | out/euler43.cpp | FardaleM/metalang | 171557c540f3e2c051ec39ea150afb740c1f615f | [
"BSD-2-Clause"
] | 22 | 2017-04-24T10:00:45.000Z | 2021-04-01T10:11:05.000Z | out/euler43.cpp | FardaleM/metalang | 171557c540f3e2c051ec39ea150afb740c1f615f | [
"BSD-2-Clause"
] | 12 | 2017-03-26T18:34:21.000Z | 2019-03-21T19:13:03.000Z | out/euler43.cpp | FardaleM/metalang | 171557c540f3e2c051ec39ea150afb740c1f615f | [
"BSD-2-Clause"
] | 7 | 2017-10-14T13:33:33.000Z | 2021-03-18T15:18:50.000Z | #include <iostream>
#include <vector>
int main() {
/*
The number, 1406357289, is a 0 to 9 pandigital number because it is made up of each of the digits 0 to 9 in some order, but it also has a rather interesting sub-string divisibility property.
Let d1 be the 1st digit, d2 be the 2nd digit, and so on. In this way, we note the following:
d2d3d4=406 is divisible by 2
d3d4d5=063 is divisible by 3
d4d5d6=635 is divisible by 5
d5d6d7=357 is divisible by 7
d6d7d8=572 is divisible by 11
d7d8d9=728 is divisible by 13
d8d9d10=289 is divisible by 17
Find the sum of all 0 to 9 pandigital numbers with this property.
d4 % 2 == 0
(d3 + d4 + d5) % 3 == 0
d6 = 5 ou d6 = 0
(d5 * 100 + d6 * 10 + d7 ) % 7 == 0
(d6 * 100 + d7 * 10 + d8 ) % 11 == 0
(d7 * 100 + d8 * 10 + d9 ) % 13 == 0
(d8 * 100 + d9 * 10 + d10 ) % 17 == 0
d4 % 2 == 0
d6 = 5 ou d6 = 0
(d3 + d4 + d5) % 3 == 0
(d5 * 2 + d6 * 3 + d7) % 7 == 0
*/
std::vector<bool> allowed( 10, true );
for (int i6 = 0; i6 < 2; i6++)
{
int d6 = i6 * 5;
if (allowed[d6])
{
allowed[d6] = false;
for (int d7 = 0; d7 < 10; d7++)
if (allowed[d7])
{
allowed[d7] = false;
for (int d8 = 0; d8 < 10; d8++)
if (allowed[d8])
{
allowed[d8] = false;
for (int d9 = 0; d9 < 10; d9++)
if (allowed[d9])
{
allowed[d9] = false;
for (int d10 = 1; d10 < 10; d10++)
if (allowed[d10] && (d6 * 100 + d7 * 10 + d8) % 11 == 0 && (d7 * 100 + d8 * 10 + d9) % 13 == 0 && (d8 * 100 + d9 * 10 + d10) % 17 == 0)
{
allowed[d10] = false;
for (int d5 = 0; d5 < 10; d5++)
if (allowed[d5])
{
allowed[d5] = false;
if ((d5 * 100 + d6 * 10 + d7) % 7 == 0)
for (int i4 = 0; i4 < 5; i4++)
{
int d4 = i4 * 2;
if (allowed[d4])
{
allowed[d4] = false;
for (int d3 = 0; d3 < 10; d3++)
if (allowed[d3])
{
allowed[d3] = false;
if ((d3 + d4 + d5) % 3 == 0)
for (int d2 = 0; d2 < 10; d2++)
if (allowed[d2])
{
allowed[d2] = false;
for (int d1 = 0; d1 < 10; d1++)
if (allowed[d1])
{
allowed[d1] = false;
std::cout << d1 << d2 << d3 << d4 << d5 << d6 << d7 << d8 << d9 << d10 << " + ";
allowed[d1] = true;
}
allowed[d2] = true;
}
allowed[d3] = true;
}
allowed[d4] = true;
}
}
allowed[d5] = true;
}
allowed[d10] = true;
}
allowed[d9] = true;
}
allowed[d8] = true;
}
allowed[d7] = true;
}
allowed[d6] = true;
}
}
std::cout << 0 << "\n";
}
| 50.485981 | 190 | 0.232506 | [
"vector"
] |
3fdd8773390c1cacc0550f9b762a7f2d86710ca3 | 4,895 | cpp | C++ | contributors/robert_gaisin/graph_traverser.cpp | AxoyTO/TheGraph | 4ced7206847f5bb22bd25a48ff09247c5b1218ef | [
"MIT"
] | 1 | 2022-02-07T15:52:51.000Z | 2022-02-07T15:52:51.000Z | contributors/robert_gaisin/graph_traverser.cpp | AxoyTO/TheGraph | 4ced7206847f5bb22bd25a48ff09247c5b1218ef | [
"MIT"
] | null | null | null | contributors/robert_gaisin/graph_traverser.cpp | AxoyTO/TheGraph | 4ced7206847f5bb22bd25a48ff09247c5b1218ef | [
"MIT"
] | 2 | 2022-02-07T15:53:00.000Z | 2022-02-12T13:31:36.000Z | #include "graph_traverser.hpp"
#include "graph_path.hpp"
#include <algorithm>
#include <atomic>
#include <cassert>
#include <climits>
#include <functional>
#include <list>
#include <mutex>
#include <optional>
#include <queue>
#include <thread>
namespace {
using uni_course_cpp::GraphPath;
const int MAX_WORKERS_COUNT = std::thread::hardware_concurrency();
constexpr int MAX_DISTANCE = INT_MAX;
constexpr int UNDEFINED_ID = -1;
} // namespace
namespace uni_course_cpp {
const GraphPath GraphTraverser::find_path(const VertexId& source_vertex_id,
const VertexId& destination_vertex_id,
bool fast) const {
assert(graph_.has_vertex(source_vertex_id));
assert(graph_.has_vertex(destination_vertex_id));
const int vertices_count = graph_.vertices().size();
std::vector<GraphPath::Distance> distances(vertices_count, MAX_DISTANCE);
distances[source_vertex_id] = 0;
std::vector<Edge::Duration> durations(vertices_count, MAX_DISTANCE);
durations[source_vertex_id] = 0;
std::queue<VertexId> queue;
queue.push(source_vertex_id);
std::vector<VertexId> previous_ids(vertices_count, UNDEFINED_ID);
while (!queue.empty()) {
const auto current_vertex_id = queue.front();
queue.pop();
const auto linked_vertex_map =
graph_.get_linked_vertex_ids(current_vertex_id);
for (auto vertex_iter = linked_vertex_map.begin();
vertex_iter != linked_vertex_map.end(); ++vertex_iter) {
const auto vertex_id = vertex_iter->first;
const auto duration = vertex_iter->second;
const auto distance =
distances[current_vertex_id] + (fast ? duration : 1);
const auto current_durations = durations[current_vertex_id] + duration;
if (distance < distances[vertex_id]) {
queue.push(vertex_id);
distances[vertex_id] = distance;
durations[vertex_id] = current_durations;
previous_ids[vertex_id] = current_vertex_id;
if (destination_vertex_id == vertex_id) {
break;
}
}
}
}
const auto path = [&destination_vertex_id, &source_vertex_id,
&previous_ids]() {
std::vector<VertexId> result;
VertexId vertex_id = destination_vertex_id;
while (vertex_id != source_vertex_id) {
result.push_back(vertex_id);
vertex_id = previous_ids[vertex_id];
}
result.push_back(source_vertex_id);
std::reverse(result.begin(), result.end());
return result;
}();
return GraphPath(std::move(path), durations[destination_vertex_id]);
}
const GraphPath GraphTraverser::find_shortest_path(
const VertexId& source_vertex_id,
const VertexId& destination_vertex_id) const {
return find_path(source_vertex_id, destination_vertex_id, false);
}
const GraphPath GraphTraverser::find_fastest_path(
const VertexId& source_vertex_id,
const VertexId& destination_vertex_id) const {
return find_path(source_vertex_id, destination_vertex_id, true);
}
std::vector<GraphPath> GraphTraverser::find_all_paths() const {
using JobCallback = std::function<void()>;
auto jobs = std::list<JobCallback>();
std::mutex jobs_mutex;
std::mutex paths_mutex;
std::atomic<int> finished_jobs_num = 0;
std::atomic<bool> should_terminate = false;
const auto& last_depth_vertex_ids = graph_.depth_map().back();
std::vector<GraphPath> paths;
paths.reserve(last_depth_vertex_ids.size());
for (const auto& vertex_id : last_depth_vertex_ids) {
jobs.push_back(
[&paths, &paths_mutex, &vertex_id, &finished_jobs_num, this]() {
GraphPath path = find_shortest_path(0, vertex_id);
{
std::lock_guard lock(paths_mutex);
paths.push_back(std::move(path));
}
finished_jobs_num++;
});
}
const auto worker = [&should_terminate, &jobs_mutex, &jobs]() {
while (true) {
if (should_terminate) {
return;
}
const auto job_optional = [&jobs,
&jobs_mutex]() -> std::optional<JobCallback> {
const std::lock_guard lock(jobs_mutex);
if (!jobs.empty()) {
const auto job = jobs.front();
jobs.pop_front();
return job;
}
return std::nullopt;
}();
if (job_optional.has_value()) {
const auto& job = job_optional.value();
job();
}
}
};
const auto threads_count =
std::min(MAX_WORKERS_COUNT, (int)last_depth_vertex_ids.size());
auto threads = std::vector<std::thread>();
threads.reserve(threads_count);
for (int i = 0; i < threads_count; i++) {
threads.push_back(std::thread(worker));
}
while (finished_jobs_num < last_depth_vertex_ids.size()) {
}
should_terminate = true;
for (auto& thread : threads) {
thread.join();
}
return paths;
}
} // namespace uni_course_cpp
| 30.030675 | 80 | 0.66476 | [
"vector"
] |
3fe052edb736f46246a7aac9bccae74416cc2cc7 | 1,291 | cpp | C++ | src/cbag/logging/logging.cpp | ayan-biswas/cbag | 0d08394cf39e90bc3acb4a94fd7b5a6560cf103c | [
"BSD-3-Clause"
] | 1 | 2020-01-07T04:44:17.000Z | 2020-01-07T04:44:17.000Z | src/cbag/logging/logging.cpp | skyworksinc/cbag | 0d08394cf39e90bc3acb4a94fd7b5a6560cf103c | [
"BSD-3-Clause"
] | null | null | null | src/cbag/logging/logging.cpp | skyworksinc/cbag | 0d08394cf39e90bc3acb4a94fd7b5a6560cf103c | [
"BSD-3-Clause"
] | 1 | 2020-01-07T04:45:13.000Z | 2020-01-07T04:45:13.000Z | #include <cbag/common/typedefs.h>
#include <cbag/logging/logging.h>
#include "spdlog/details/signal_handler.h"
#include <spdlog/sinks/rotating_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
namespace cbag {
constexpr cnt_t max_log_size = 1024 * 1024 * 10;
constexpr cnt_t num_log_file = 3;
void init_logging() {
if (spdlog::get("bag") == nullptr) {
spdlog::installCrashHandler();
std::vector<spdlog::sink_ptr> sinks;
sinks.push_back(std::make_shared<spdlog::sinks::rotating_file_sink_st>(
"bag.log", max_log_size, num_log_file));
auto stdout_sink = std::make_shared<spdlog::sinks::stdout_color_sink_st>();
stdout_sink->set_level(spdlog::level::warn);
sinks.push_back(std::move(stdout_sink));
auto logger = std::make_shared<spdlog::logger>("bag", sinks.begin(), sinks.end());
spdlog::register_logger(logger);
auto cbag_logger = logger->clone("cbag");
spdlog::register_logger(cbag_logger);
spdlog::flush_on(spdlog::level::warn);
}
}
std::shared_ptr<spdlog::logger> get_bag_logger() {
init_logging();
return spdlog::get("bag");
}
std::shared_ptr<spdlog::logger> get_cbag_logger() {
init_logging();
return spdlog::get("cbag");
}
} // namespace cbag
| 28.688889 | 90 | 0.675445 | [
"vector"
] |
3fe3275bdfb057139c2caa90cb0726a65070571f | 404 | cc | C++ | ch03/ex3-14.cc | ts25504/Cpp-Primer | d1c5960f5f0ba969b766224f177f6c29c13d0d22 | [
"MIT"
] | null | null | null | ch03/ex3-14.cc | ts25504/Cpp-Primer | d1c5960f5f0ba969b766224f177f6c29c13d0d22 | [
"MIT"
] | null | null | null | ch03/ex3-14.cc | ts25504/Cpp-Primer | d1c5960f5f0ba969b766224f177f6c29c13d0d22 | [
"MIT"
] | null | null | null | /*
* Exercise 3.14: Write a program to read a sequence of ints from cin and
* store those values in a vector.
*/
#include <iostream>
#include <vector>
int main()
{
std::vector<int> ivec;
int i;
while (std::cin >> i)
ivec.push_back(i);
for (auto iter = ivec.begin(); iter != ivec.end(); ++iter)
std::cout << *iter << " ";
std::cout << std::endl;
return 0;
}
| 18.363636 | 73 | 0.564356 | [
"vector"
] |
68472dd31b046f7a1aaf0bd73e700584a99ef43d | 24,041 | cc | C++ | open_spiel/games/euchre.cc | mcx/open_spiel | 062cbfc07621343e7d77209cb421ba690328142b | [
"Apache-2.0"
] | null | null | null | open_spiel/games/euchre.cc | mcx/open_spiel | 062cbfc07621343e7d77209cb421ba690328142b | [
"Apache-2.0"
] | null | null | null | open_spiel/games/euchre.cc | mcx/open_spiel | 062cbfc07621343e7d77209cb421ba690328142b | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 DeepMind Technologies Limited
//
// 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 "open_spiel/games/euchre.h"
#include <algorithm>
#include <iterator>
#include <map>
#include <vector>
#include "open_spiel/abseil-cpp/absl/algorithm/container.h"
#include "open_spiel/abseil-cpp/absl/strings/str_cat.h"
#include "open_spiel/abseil-cpp/absl/strings/str_format.h"
#include "open_spiel/abseil-cpp/absl/types/optional.h"
#include "open_spiel/game_parameters.h"
#include "open_spiel/spiel.h"
#include "open_spiel/spiel_globals.h"
#include "open_spiel/spiel_utils.h"
namespace open_spiel {
namespace euchre {
namespace {
const GameType kGameType{
/*short_name=*/"euchre",
/*long_name=*/"Euchre",
GameType::Dynamics::kSequential,
GameType::ChanceMode::kExplicitStochastic,
GameType::Information::kImperfectInformation,
GameType::Utility::kZeroSum,
GameType::RewardModel::kTerminal,
/*max_num_players=*/kNumPlayers,
/*min_num_players=*/kNumPlayers,
/*provides_information_state_string=*/false,
/*provides_information_state_tensor=*/true,
/*provides_observation_string=*/false,
/*provides_observation_tensor=*/false,
/*parameter_specification=*/
{
// Pass cards at the beginning of the hand.
{"allow_lone_defender", GameParameter(false)},
}};
std::shared_ptr<const Game> Factory(const GameParameters& params) {
return std::shared_ptr<const Game>(new EuchreGame(params));
}
REGISTER_SPIEL_GAME(kGameType, Factory);
std::map<Suit, Suit> same_color_suit {
{Suit::kClubs, Suit::kSpades}, {Suit::kSpades, Suit::kClubs},
{Suit::kDiamonds, Suit::kHearts}, {Suit::kHearts, Suit::kDiamonds}};
} // namespace
Suit CardSuit(int card, Suit trump_suit) {
Suit suit = CardSuit(card);
if (CardRank(card) == kJackRank && same_color_suit[suit] == trump_suit)
suit = trump_suit;
return suit;
}
// Highest rank belongs to right bower, then left bower, then usual ranking.
int CardRank(int card, Suit trump_suit) {
int rank = CardRank(card);
if (CardSuit(card) == trump_suit && rank == kJackRank) {
rank = 100; // Right bower (arbitrary value)
} else if (CardSuit(card, trump_suit) == trump_suit && rank == kJackRank) {
rank = 99; // Left bower (arbitrary value)
}
return rank;
}
EuchreGame::EuchreGame(const GameParameters& params)
: Game(kGameType, params),
allow_lone_defender_(ParameterValue<bool>("allow_lone_defender")) {}
EuchreState::EuchreState(std::shared_ptr<const Game> game,
bool allow_lone_defender)
: State(game),
allow_lone_defender_(allow_lone_defender) {}
std::string EuchreState::ActionToString(Player player, Action action) const {
if (history_.empty()) return DirString(action);
if (action == kPassAction) return "Pass";
if (action == kClubsTrumpAction) return "Clubs";
if (action == kDiamondsTrumpAction) return "Diamonds";
if (action == kHeartsTrumpAction) return "Hearts";
if (action == kSpadesTrumpAction) return "Spades";
if (action == kGoAloneAction) return "Alone";
if (action == kPlayWithPartnerAction) return "Partner";
return CardString(action);
}
std::string EuchreState::ToString() const {
std::string rv = "Dealer: ";
absl::StrAppend(&rv, DirString(dealer_), "\n\n");
absl::StrAppend(&rv, FormatDeal());
if (upcard_ != kInvalidAction)
absl::StrAppend(&rv, "\nUpcard: ", ActionToString(kInvalidPlayer, upcard_));
if (history_.size() > kFirstBiddingActionInHistory)
absl::StrAppend(&rv, FormatBidding());
if (discard_ != kInvalidAction) {
absl::StrAppend(&rv, "\nDealer discard: ",
ActionToString(kInvalidPlayer, discard_), "\n");
}
if (declarer_go_alone_.has_value()) {
absl::StrAppend(&rv, "\nDeclarer go alone: ");
if (declarer_go_alone_.value())
absl::StrAppend(&rv, "true\n");
else
absl::StrAppend(&rv, "false\n");
if (allow_lone_defender_) {
absl::StrAppend(&rv, "\nDefender go alone: ");
if (lone_defender_ != kInvalidPlayer)
absl::StrAppend(&rv, "true\n");
else
absl::StrAppend(&rv, "false\n");
}
}
if (num_cards_played_ > 0) absl::StrAppend(&rv, FormatPlay(), FormatPoints());
return rv;
}
std::array<std::string, kNumSuits> EuchreState::FormatHand(
int player, bool mark_voids) const {
// Current hand, except in the terminal state when we use the original hand
// to enable an easy review of the whole deal.
auto deal = IsTerminal() ? initial_deal_ : holder_;
std::array<std::string, kNumSuits> cards;
for (int suit = 0; suit < kNumSuits; ++suit) {
cards[suit].push_back(kSuitChar[suit]);
cards[suit].push_back(' ');
bool is_void = true;
for (int rank = kNumCardsPerSuit - 1; rank >= 0; --rank) {
if (player == deal[Card(Suit(suit), rank)]) {
cards[suit].push_back(kRankChar[rank]);
is_void = false;
}
}
if (is_void && mark_voids) absl::StrAppend(&cards[suit], "none");
}
return cards;
}
std::string EuchreState::FormatDeal() const {
std::string rv;
std::array<std::array<std::string, kNumSuits>, kNumPlayers> cards;
for (auto player : {kNorth, kEast, kSouth, kWest})
cards[player] = FormatHand(player, /*mark_voids=*/false);
constexpr int kColumnWidth = 8;
std::string padding(kColumnWidth, ' ');
for (int suit = kNumSuits - 1; suit >= 0; --suit)
absl::StrAppend(&rv, padding, cards[kNorth][suit], "\n");
for (int suit = kNumSuits - 1; suit >= 0; --suit)
absl::StrAppend(&rv, absl::StrFormat("%-8s", cards[kWest][suit]), padding,
cards[kEast][suit], "\n");
for (int suit = kNumSuits - 1; suit >= 0; --suit)
absl::StrAppend(&rv, padding, cards[kSouth][suit], "\n");
return rv;
}
std::string EuchreState::FormatBidding() const {
SPIEL_CHECK_GE(history_.size(), kFirstBiddingActionInHistory);
std::string rv;
absl::StrAppend(&rv, "\nBidding:");
absl::StrAppend(&rv, "\nNorth East South West\n");
if (dealer_ == 0) absl::StrAppend(&rv, absl::StrFormat("%-9s", ""));
if (dealer_ == 1) absl::StrAppend(&rv, absl::StrFormat("%-18s", ""));
if (dealer_ == 2) absl::StrAppend(&rv, absl::StrFormat("%-27s", ""));
for (int i = kFirstBiddingActionInHistory; i < history_.size(); ++i) {
if (i < kFirstBiddingActionInHistory + kNumPlayers - 1) {
// Players can pass or "order up" the upcard to the dealer.
if (history_[i].action == kPassAction)
absl::StrAppend(&rv, absl::StrFormat("%-9s", "Pass"));
else
absl::StrAppend(&rv, absl::StrFormat("%-9s", "Order up!"));
} else if (i == kFirstBiddingActionInHistory + kNumPlayers) {
// Dealer can pass or "pick up" the upcard.
if (history_[i].action == kPassAction)
absl::StrAppend(&rv, absl::StrFormat("%-9s", "Pass"));
else
absl::StrAppend(&rv, absl::StrFormat("%-9s", "Pick up!"));
} else {
absl::StrAppend(
&rv, absl::StrFormat(
"%-9s", ActionToString(kInvalidPlayer, history_[i].action)));
}
if (history_[i].player == kNumPlayers - 1) rv.push_back('\n');
if (history_[i].action > kPassAction) break;
}
absl::StrAppend(&rv, "\n");
return rv;
}
std::string EuchreState::FormatPlay() const {
SPIEL_CHECK_GT(num_cards_played_, 0);
std::string rv = "\nTricks:";
absl::StrAppend(&rv, "\nN E S W N E S");
for (int i = 0; i <= (num_cards_played_ - 1) / num_active_players_; ++i) {
Player player_id = tricks_[i].Leader();
absl::StrAppend(&rv, "\n", std::string(3 * player_id, ' '));
for (auto card : tricks_[i].Cards()) {
absl::StrAppend(&rv, CardString(card), " ");
player_id = (player_id + 1) % kNumPlayers;
while (!active_players_[player_id]) {
absl::StrAppend(&rv, " ");
player_id = (player_id + 1) % kNumPlayers;
}
}
}
return rv;
}
std::string EuchreState::FormatPoints() const {
std::string rv;
absl::StrAppend(&rv, "\n\nPoints:");
for (int i = 0; i < kNumPlayers; ++i)
absl::StrAppend(&rv, "\n", DirString(i), ": ", points_[i]);
return rv;
}
void EuchreState::InformationStateTensor(Player player,
absl::Span<float> values) const {
SPIEL_CHECK_GE(player, 0);
SPIEL_CHECK_LT(player, num_players_);
std::fill(values.begin(), values.end(), 0.0);
SPIEL_CHECK_EQ(values.size(), kInformationStateTensorSize);
if (upcard_ == kInvalidAction) return;
auto ptr = values.begin();
// Dealer position
ptr[static_cast<int>(dealer_)] = 1;
ptr += kNumPlayers;
// Upcard
ptr[upcard_] = 1;
ptr += kNumCards;
// Bidding [Clubs, Diamonds, Hearts, Spades, Pass]
for (int i = 0; i < num_passes_; ++i) {
ptr[kNumSuits + 1] = 1;
ptr += (kNumSuits + 1);
}
if (num_passes_ == 2 * kNumPlayers) return;
if (trump_suit_ != Suit::kInvalidSuit) {
ptr[static_cast<int>(trump_suit_)] = 1;
}
ptr += (kNumSuits + 1);
for (int i = 0; i < 2 * kNumPlayers - num_passes_ - 1; ++i)
ptr += (kNumSuits + 1);
// Go alone
if (declarer_go_alone_) ptr[0] = 1;
if (lone_defender_ == first_defender_) ptr[1] = 1;
if (lone_defender_ == second_defender_) ptr[2] = 1;
ptr += 3;
// Current hand
for (int i = 0; i < kNumCards; ++i)
if (holder_[i] == player) ptr[i] = 1;
ptr += kNumCards;
// History of tricks, presented in the format: N E S W N E S
int current_trick = std::min(num_cards_played_ / num_active_players_,
static_cast<int>(tricks_.size() - 1));
for (int i = 0; i < current_trick; ++i) {
Player leader = tricks_[i].Leader();
ptr += leader * kNumCards;
int offset = 0;
for (auto card : tricks_[i].Cards()) {
ptr[card] = 1;
ptr += kNumCards;
++offset;
while (!active_players_[(leader + offset) % kNumPlayers]) {
ptr += kNumCards;
++offset;
}
}
SPIEL_CHECK_EQ(offset, kNumPlayers);
ptr += (kNumPlayers - leader - 1) * kNumCards;
}
Player leader = tricks_[current_trick].Leader();
int offset = 0;
if (leader != kInvalidPlayer) {
auto cards = tricks_[current_trick].Cards();
ptr += leader * kNumCards;
for (auto card : cards) {
ptr[card] = 1;
ptr += kNumCards;
++offset;
while (!active_players_[(leader + offset) % kNumPlayers]) {
ptr += kNumCards;
++offset;
}
}
}
// Current trick may contain less than four cards.
if (offset < kNumPlayers) {
ptr += (kNumPlayers - offset) * kNumCards;
}
// Move to the end of current trick.
ptr += (kNumPlayers - std::max(leader, 0) - 1) * kNumCards;
// Skip over unplayed tricks.
ptr += (kNumTricks - current_trick - 1) * kTrickTensorSize;
SPIEL_CHECK_EQ(ptr, values.end());
}
std::vector<Action> EuchreState::LegalActions() const {
switch (phase_) {
case Phase::kDealerSelection:
return DealerSelectionLegalActions();
case Phase::kDeal:
return DealLegalActions();
case Phase::kBidding:
return BiddingLegalActions();
case Phase::kDiscard:
return DiscardLegalActions();
case Phase::kGoAlone:
return GoAloneLegalActions();
case Phase::kPlay:
return PlayLegalActions();
default:
return {};
}
}
std::vector<Action> EuchreState::DealerSelectionLegalActions() const {
SPIEL_CHECK_EQ(history_.size(), 0);
std::vector<Action> legal_actions;
legal_actions.reserve(kNumPlayers);
for (int i = 0; i < kNumPlayers; ++i) legal_actions.push_back(i);
return legal_actions;
}
std::vector<Action> EuchreState::DealLegalActions() const {
std::vector<Action> legal_actions;
legal_actions.reserve(kNumCards - num_cards_dealt_);
for (int i = 0; i < kNumCards; ++i) {
if (!holder_[i].has_value()) legal_actions.push_back(i);
}
SPIEL_CHECK_GT(legal_actions.size(), 0);
return legal_actions;
}
std::vector<Action> EuchreState::BiddingLegalActions() const {
std::vector<Action> legal_actions;
legal_actions.push_back(kPassAction);
Suit suit = CardSuit(upcard_);
if (num_passes_ < kNumPlayers) {
switch (suit) {
case Suit::kClubs:
legal_actions.push_back(kClubsTrumpAction);
break;
case Suit::kDiamonds:
legal_actions.push_back(kDiamondsTrumpAction);
break;
case Suit::kHearts:
legal_actions.push_back(kHeartsTrumpAction);
break;
case Suit::kSpades:
legal_actions.push_back(kSpadesTrumpAction);
break;
case Suit::kInvalidSuit:
SpielFatalError("Suit of upcard is invalid.");
}
} else {
switch (suit) {
case Suit::kClubs:
legal_actions.push_back(kDiamondsTrumpAction);
legal_actions.push_back(kHeartsTrumpAction);
legal_actions.push_back(kSpadesTrumpAction);
break;
case Suit::kDiamonds:
legal_actions.push_back(kClubsTrumpAction);
legal_actions.push_back(kHeartsTrumpAction);
legal_actions.push_back(kSpadesTrumpAction);
break;
case Suit::kHearts:
legal_actions.push_back(kClubsTrumpAction);
legal_actions.push_back(kDiamondsTrumpAction);
legal_actions.push_back(kSpadesTrumpAction);
break;
case Suit::kSpades:
legal_actions.push_back(kClubsTrumpAction);
legal_actions.push_back(kDiamondsTrumpAction);
legal_actions.push_back(kHeartsTrumpAction);
break;
case Suit::kInvalidSuit:
SpielFatalError("Suit of upcard is invalid.");
}
}
return legal_actions;
}
std::vector<Action> EuchreState::DiscardLegalActions() const {
std::vector<Action> legal_actions;
for (int card = 0; card < kNumCards; ++card) {
if (holder_[card] == current_player_ && card != upcard_) {
legal_actions.push_back(card);
}
}
SPIEL_CHECK_EQ(legal_actions.size(), kNumTricks);
return legal_actions;
}
std::vector<Action> EuchreState::GoAloneLegalActions() const {
std::vector<Action> legal_actions;
legal_actions.push_back(kGoAloneAction);
legal_actions.push_back(kPlayWithPartnerAction);
return legal_actions;
}
std::vector<Action> EuchreState::PlayLegalActions() const {
std::vector<Action> legal_actions;
// Check if we can follow suit.
if (num_cards_played_ % num_active_players_ != 0) {
Suit led_suit = CurrentTrick().LedSuit();
if (led_suit == trump_suit_) {
for (int rank = 0; rank < kNumCardsPerSuit; ++rank) {
if (holder_[Card(led_suit, rank)] == current_player_) {
legal_actions.push_back(Card(led_suit, rank));
}
}
if (holder_[left_bower_] == current_player_) {
// Left bower belongs to trump suit.
legal_actions.push_back(left_bower_);
}
} else {
for (int rank = 0; rank < kNumCardsPerSuit; ++rank) {
if (holder_[Card(led_suit, rank)] == current_player_ &&
Card(led_suit, rank) != left_bower_) {
legal_actions.push_back(Card(led_suit, rank));
}
}
}
}
if (!legal_actions.empty()) {
absl::c_sort(legal_actions); // Sort required because of left bower.
return legal_actions;
}
// Can't follow suit, so we can play any of the cards in our hand.
for (int card = 0; card < kNumCards; ++card) {
if (holder_[card] == current_player_) legal_actions.push_back(card);
}
return legal_actions;
}
std::vector<std::pair<Action, double>> EuchreState::ChanceOutcomes() const {
std::vector<std::pair<Action, double>> outcomes;
if (history_.empty()) {
outcomes.reserve(kNumPlayers);
const double p = 1.0 / kNumPlayers;
for (int dir = 0; dir < kNumPlayers; ++dir) {
outcomes.emplace_back(dir, p);
}
return outcomes;
}
int num_cards_remaining = kNumCards - num_cards_dealt_;
outcomes.reserve(num_cards_remaining);
const double p = 1.0 / num_cards_remaining;
for (int card = 0; card < kNumCards; ++card) {
if (!holder_[card].has_value()) outcomes.emplace_back(card, p);
}
return outcomes;
}
void EuchreState::DoApplyAction(Action action) {
switch (phase_) {
case Phase::kDealerSelection:
return ApplyDealerSelectionAction(action);
case Phase::kDeal:
return ApplyDealAction(action);
case Phase::kBidding:
return ApplyBiddingAction(action);
case Phase::kDiscard:
return ApplyDiscardAction(action);
case Phase::kGoAlone:
return ApplyGoAloneAction(action);
case Phase::kPlay:
return ApplyPlayAction(action);
case Phase::kGameOver:
SpielFatalError("Cannot act in terminal states");
}
}
void EuchreState::ApplyDealerSelectionAction(int selected_dealer) {
SPIEL_CHECK_EQ(history_.size(), 0);
dealer_ = selected_dealer;
phase_ = Phase::kDeal;
}
void EuchreState::ApplyDealAction(int card) {
if (num_cards_dealt_ == kNumPlayers * kNumTricks) {
initial_deal_ = holder_; // Preserve the initial deal for easy retrieval.
upcard_ = card;
++num_cards_dealt_;
phase_ = Phase::kBidding;
current_player_ = (dealer_ + 1) % kNumPlayers;
} else {
holder_[card] = (dealer_ + num_cards_dealt_) % kNumPlayers;
++num_cards_dealt_;
}
}
void EuchreState::ApplyBiddingAction(int action) {
if (action == kPassAction) {
++num_passes_;
if (num_passes_ == kNumPlayers * 2) {
phase_ = Phase::kGameOver;
current_player_ = kTerminalPlayerId;
} else {
current_player_ = (current_player_ + 1) % kNumPlayers;
}
} else {
// Trump suit selected.
declarer_ = current_player_;
first_defender_ = (declarer_ + 1) % kNumPlayers;
declarer_partner_ = (declarer_ + 2) % kNumPlayers;
second_defender_ = (declarer_ + 3) % kNumPlayers;
switch (action) {
case kClubsTrumpAction:
trump_suit_ = Suit::kClubs;
break;
case kDiamondsTrumpAction:
trump_suit_ = Suit::kDiamonds;
break;
case kHeartsTrumpAction:
trump_suit_ = Suit::kHearts;
break;
case kSpadesTrumpAction:
trump_suit_ = Suit::kSpades;
break;
default:
SpielFatalError("Invalid bidding action.");
}
left_bower_ = Card(same_color_suit[trump_suit_], kJackRank);
if (num_passes_ < kNumPlayers) {
// Top card was ordered up to dealer in first round of bidding.
holder_[upcard_] = dealer_;
phase_ = Phase::kDiscard;
current_player_ = dealer_;
} else {
// Trump suit selected in second round of bidding.
phase_ = Phase::kGoAlone;
}
}
}
void EuchreState::ApplyDiscardAction(int card) {
SPIEL_CHECK_TRUE(holder_[card] == current_player_);
discard_ = card;
holder_[card] = absl::nullopt;
phase_ = Phase::kGoAlone;
current_player_ = declarer_;
}
void EuchreState::ApplyGoAloneAction(int action) {
if (declarer_go_alone_.has_value() && allow_lone_defender_) {
if (action == kGoAloneAction) {
lone_defender_ = current_player_;
active_players_[(lone_defender_ + 2) % kNumPlayers] = false;
--num_active_players_;
phase_ = Phase::kPlay;
current_player_ = (dealer_ + 1) % kNumPlayers;
while (!active_players_[current_player_]) {
current_player_ = (current_player_ + 1) % kNumPlayers;
}
} else if (action == kPlayWithPartnerAction) {
if (current_player_ == (dealer_ + 1) % kNumPlayers ||
current_player_ == (dealer_ + 2) % kNumPlayers) {
current_player_ = (current_player_ + 2) % kNumPlayers;
} else {
phase_ = Phase::kPlay;
current_player_ = (dealer_ + 1) % kNumPlayers;
while (!active_players_[current_player_]) {
current_player_ = (current_player_ + 1) % kNumPlayers;
}
}
} else {
SpielFatalError("Invalid GoAlone action.");
}
} else {
if (action == kGoAloneAction) {
declarer_go_alone_ = true;
active_players_[declarer_partner_] = false;
--num_active_players_;
} else if (action == kPlayWithPartnerAction) {
declarer_go_alone_ = false;
} else {
SpielFatalError("Invalid GoAlone action.");
}
if (allow_lone_defender_) {
current_player_ = (dealer_ + 1) % kNumPlayers;
if (current_player_ == declarer_ || current_player_ == declarer_partner_)
current_player_ = (current_player_ + 1) % kNumPlayers;
} else {
phase_ = Phase::kPlay;
current_player_ = (dealer_ + 1) % kNumPlayers;
if (declarer_go_alone_.value() && current_player_ == declarer_partner_) {
current_player_ = (current_player_ + 1) % kNumPlayers;
}
}
}
}
void EuchreState::ApplyPlayAction(int card) {
SPIEL_CHECK_TRUE(holder_[card] == current_player_);
holder_[card] = absl::nullopt;
if (num_cards_played_ % num_active_players_ == 0) {
CurrentTrick() = Trick(current_player_, trump_suit_, card);
} else {
CurrentTrick().Play(current_player_, card);
}
// Update player and point totals.
Trick current_trick = CurrentTrick();
++num_cards_played_;
if (num_cards_played_ % num_active_players_ == 0) {
current_player_ = current_trick.Winner();
} else {
current_player_ = (current_player_ + 1) % kNumPlayers;
while (!active_players_[current_player_]) {
current_player_ = (current_player_ + 1) % kNumPlayers;
}
}
if (num_cards_played_ == num_active_players_ * kNumTricks) {
phase_ = Phase::kGameOver;
current_player_ = kTerminalPlayerId;
ComputeScore();
}
}
Player EuchreState::CurrentPlayer() const {
return current_player_;
}
void EuchreState::ComputeScore() {
SPIEL_CHECK_TRUE(IsTerminal());
std::vector<int> tricks_won(kNumPlayers, 0);
for (int i = 0; i < kNumTricks; ++i) {
tricks_won[tricks_[i].Winner()] += 1;
}
int makers_tricks_won = tricks_won[declarer_] + tricks_won[declarer_partner_];
int makers_score;
if (makers_tricks_won >= 0 && makers_tricks_won <= 2) {
if (lone_defender_ >= 0)
makers_score = -4;
else
makers_score = -2;
} else if (makers_tricks_won >= 3 && makers_tricks_won <= 4) {
makers_score = 1;
} else if (makers_tricks_won == 5) {
if (declarer_go_alone_.value())
makers_score = 4;
else
makers_score = 2;
} else {
SpielFatalError("Invalid number of tricks won by makers.");
}
for (Player i = 0; i < kNumPlayers; ++i) {
if (i == declarer_ || i == declarer_partner_)
points_[i] = makers_score;
else
points_[i] = -makers_score;
}
}
std::vector<double> EuchreState::Returns() const {
return points_;
}
Trick::Trick(Player leader, Suit trump_suit, int card)
: winning_card_(card),
led_suit_(CardSuit(card, trump_suit)),
trump_suit_(trump_suit),
leader_(leader),
winning_player_(leader),
cards_{card} {}
// TODO(jhtschultz) Find a simpler way of computing this.
void Trick::Play(Player player, int card) {
cards_.push_back(card);
bool new_winner = false;
if (winning_player_ == kInvalidPlayer) new_winner = true;
if (CardSuit(card, trump_suit_) == trump_suit_) {
if (CardSuit(winning_card_, trump_suit_) == trump_suit_) {
if (CardRank(card, trump_suit_) > CardRank(winning_card_, trump_suit_)) {
new_winner = true;
}
} else {
new_winner = true;
}
} else {
if (CardSuit(winning_card_, trump_suit_) != trump_suit_ &&
CardSuit(winning_card_, trump_suit_) == CardSuit(card, trump_suit_) &&
CardRank(card, trump_suit_) > CardRank(winning_card_, trump_suit_)) {
new_winner = true;
}
}
if (new_winner) {
winning_card_ = card;
winning_player_ = player;
}
}
} // namespace euchre
} // namespace open_spiel
| 33.576816 | 80 | 0.65538 | [
"vector"
] |
684e07a1819428e09ea067afc2d881180769af27 | 935 | cpp | C++ | Cpp/Codes/Practice/LeetCode/42 Trapping Rain Water.cpp | QuincyWork/AllCodes | 59fe045608dda924cb993dde957da4daff769438 | [
"MIT"
] | null | null | null | Cpp/Codes/Practice/LeetCode/42 Trapping Rain Water.cpp | QuincyWork/AllCodes | 59fe045608dda924cb993dde957da4daff769438 | [
"MIT"
] | null | null | null | Cpp/Codes/Practice/LeetCode/42 Trapping Rain Water.cpp | QuincyWork/AllCodes | 59fe045608dda924cb993dde957da4daff769438 | [
"MIT"
] | 1 | 2019-04-01T10:30:03.000Z | 2019-04-01T10:30:03.000Z | #include <gtest/gtest.h>
#include <deque>
using namespace std;
int trap(vector<int>& height)
{
if (height.size() <= 2)
{
return 0;
}
int result = 0;
deque<int> left;
for (int i=0; i<height.size(); ++i)
{
if (left.empty() || height[i] < left.front())
{
left.push_back(height[i]);
}
else
{
while (!left.empty())
{
result += left.front() - left.back();
left.pop_back();
}
left.push_back(height[i]);
}
}
//
deque<int> right;
for (int i = left.size()-1; i >= 0; --i)
{
if (right.empty() || left[i] < right.front())
{
right.push_back(left[i]);
}
else
{
while (!right.empty())
{
result += right.front() - right.back();
right.pop_back();
}
right.push_back(left[i]);
}
}
return result;
}
TEST(LeetCode, tTrap)
{
// 0 0
// 0,1,0,2,1,0,1,3,2,1,2,1
int d1[] = {0,1,0,2,1,0,1,3,2,1,2,1};
vector<int> v1(d1,d1+_countof(d1));
ASSERT_EQ(trap(v1),6);
} | 14.609375 | 47 | 0.541176 | [
"vector"
] |
684f1cd4c10717fdd1c20507575b22af92f02920 | 8,012 | cpp | C++ | src/keycolor.cpp | kode54/wayfire-plugins-extra | 11bbf1c5468138dea47ef162ac65d4a93914306b | [
"MIT"
] | null | null | null | src/keycolor.cpp | kode54/wayfire-plugins-extra | 11bbf1c5468138dea47ef162ac65d4a93914306b | [
"MIT"
] | null | null | null | src/keycolor.cpp | kode54/wayfire-plugins-extra | 11bbf1c5468138dea47ef162ac65d4a93914306b | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 2020 Scott Moreau
*
* 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 <wayfire/core.hpp>
#include <wayfire/view.hpp>
#include <wayfire/plugin.hpp>
#include <wayfire/output.hpp>
#include <wayfire/view-transform.hpp>
#include <wayfire/workspace-manager.hpp>
#include <wayfire/signal-definitions.hpp>
static const char *vertex_shader =
R"(
#version 100
attribute mediump vec2 position;
attribute mediump vec2 texcoord;
varying mediump vec2 uvpos;
void main() {
gl_Position = vec4(position.xy, 0.0, 1.0);
uvpos = texcoord;
}
)";
static const char *fragment_shader =
R"(
#version 100
@builtin_ext@
@builtin@
precision mediump float;
uniform mediump vec4 color;
uniform float threshold;
varying mediump vec2 uvpos;
void main()
{
vec4 c = get_pixel(uvpos);
vec4 vdiff = abs(vec4(color.r, color.g, color.b, 1.0) - c);
float diff = max(max(max(vdiff.r, vdiff.g), vdiff.b), vdiff.a);
if (diff < threshold) {
c *= color.a;
c.a = color.a;
}
gl_FragColor = c;
}
)";
static const std::string program_name = "keycolor_shader_program";
static int program_ref_count;
class keycolor_custom_data_t : public wf::custom_data_t
{
public:
OpenGL::program_t program;
};
class wf_keycolor : public wf::view_transformer_t
{
nonstd::observer_ptr<wf::view_interface_t> view;
wf::config::option_base_t::updated_callback_t option_changed;
wf::option_wrapper_t<wf::color_t> color{"keycolor/color"};
wf::option_wrapper_t<double> opacity{"keycolor/opacity"};
wf::option_wrapper_t<double> threshold{"keycolor/threshold"};
uint32_t get_z_order() override
{
return wf::TRANSFORMER_HIGHLEVEL;
}
wf::pointf_t transform_point(
wf::geometry_t view, wf::pointf_t point) override
{
return point;
}
wf::pointf_t untransform_point(
wf::geometry_t view, wf::pointf_t point) override
{
return point;
}
public:
wf_keycolor(wayfire_view view) : wf::view_transformer_t()
{
this->view = view;
option_changed = [=] ()
{
this->view->damage();
};
color.set_callback(option_changed);
opacity.set_callback(option_changed);
threshold.set_callback(option_changed);
}
void render_box(wf::texture_t src_tex, wlr_box _src_box,
wlr_box scissor_box, const wf::framebuffer_t& target_fb) override
{
auto src_box = _src_box;
int fb_h = target_fb.viewport_height;
src_box.x -= target_fb.geometry.x;
src_box.y -= target_fb.geometry.y;
float x = src_box.x, y = src_box.y, w = src_box.width, h = src_box.height;
nonstd::observer_ptr<keycolor_custom_data_t> data =
wf::get_core().get_data<keycolor_custom_data_t>(program_name);
static const float vertexData[] = {
-1.0f, -1.0f,
1.0f, -1.0f,
1.0f, 1.0f,
-1.0f, 1.0f
};
static const float texCoords[] = {
0.0f, 0.0f,
1.0f, 0.0f,
1.0f, 1.0f,
0.0f, 1.0f
};
OpenGL::render_begin(target_fb);
/* Upload data to shader */
glm::vec4 color_data{
((wf::color_t)color).r,
((wf::color_t)color).g,
((wf::color_t)color).b,
(double)opacity};
data->program.use(src_tex.type);
data->program.uniform4f("color", color_data);
data->program.uniform1f("threshold", threshold);
data->program.attrib_pointer("position", 2, 0, vertexData);
data->program.attrib_pointer("texcoord", 2, 0, texCoords);
GL_CALL(glActiveTexture(GL_TEXTURE0));
data->program.set_active_texture(src_tex);
/* Render it to target_fb */
target_fb.bind();
GL_CALL(glViewport(x, fb_h - y - h, w, h));
target_fb.logic_scissor(scissor_box);
GL_CALL(glEnable(GL_BLEND));
GL_CALL(glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA));
GL_CALL(glDrawArrays(GL_TRIANGLE_FAN, 0, 4));
/* Disable stuff */
GL_CALL(glDisable(GL_BLEND));
GL_CALL(glActiveTexture(GL_TEXTURE0));
GL_CALL(glBindTexture(GL_TEXTURE_2D, 0));
GL_CALL(glBindFramebuffer(GL_FRAMEBUFFER, 0));
data->program.deactivate();
OpenGL::render_end();
}
virtual ~wf_keycolor()
{}
};
class wayfire_keycolor : public wf::plugin_interface_t
{
const std::string transformer_name = "keycolor";
void add_transformer(wayfire_view view)
{
if (view->get_transformer(transformer_name))
{
return;
}
view->add_transformer(std::make_unique<wf_keycolor>(view),
transformer_name);
}
void pop_transformer(wayfire_view view)
{
if (view->get_transformer(transformer_name))
{
view->pop_transformer(transformer_name);
}
}
void remove_transformers()
{
for (auto& view : output->workspace->get_views_in_layer(wf::ALL_LAYERS))
{
pop_transformer(view);
}
}
public:
void init() override
{
grab_interface->name = transformer_name;
grab_interface->capabilities = 0;
if (!wf::get_core().get_data<keycolor_custom_data_t>(program_name))
{
std::unique_ptr<keycolor_custom_data_t> data =
std::make_unique<keycolor_custom_data_t>();
OpenGL::render_begin();
data->program.compile(vertex_shader, fragment_shader);
OpenGL::render_end();
wf::get_core().store_data(std::move(data), program_name);
}
program_ref_count++;
output->connect_signal("view-attached", &view_attached);
for (auto& view : output->workspace->get_views_in_layer(wf::ALL_LAYERS))
{
if (view->role == wf::VIEW_ROLE_DESKTOP_ENVIRONMENT)
{
continue;
}
add_transformer(view);
}
}
wf::signal_connection_t view_attached{[this] (wf::signal_data_t *data)
{
auto view = get_signaled_view(data);
if (view->role == wf::VIEW_ROLE_DESKTOP_ENVIRONMENT)
{
return;
}
if (!view->get_transformer(transformer_name))
{
add_transformer(view);
}
}
};
void fini() override
{
remove_transformers();
program_ref_count--;
if (program_ref_count)
{
return;
}
nonstd::observer_ptr<keycolor_custom_data_t> data =
wf::get_core().get_data<keycolor_custom_data_t>(program_name);
OpenGL::render_begin();
data->program.free_resources();
OpenGL::render_end();
wf::get_core().erase_data(program_name);
}
};
DECLARE_WAYFIRE_PLUGIN(wayfire_keycolor);
| 27.067568 | 82 | 0.625437 | [
"geometry",
"render",
"transform"
] |
6850a7da28c6d78d04bd2da64ceb13275247100d | 10,107 | cpp | C++ | third_party/gst-plugins-base/tests/examples/gl/gtk/filtervideooverlay/main.cpp | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 6 | 2020-09-22T18:07:15.000Z | 2021-10-21T01:34:04.000Z | third_party/gst-plugins-base/tests/examples/gl/gtk/filtervideooverlay/main.cpp | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 2 | 2020-11-10T13:17:39.000Z | 2022-03-30T11:22:14.000Z | third_party/gst-plugins-base/tests/examples/gl/gtk/filtervideooverlay/main.cpp | isabella232/aistreams | 209f4385425405676a581a749bb915e257dbc1c1 | [
"Apache-2.0"
] | 3 | 2020-09-26T08:40:35.000Z | 2021-10-21T01:33:56.000Z | /*
* GStreamer
* Copyright (C) 2008-2009 Julien Isorce <julien.isorce@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <gst/gst.h>
#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include "../gstgtk.h"
#ifdef HAVE_X11
#include <X11/Xlib.h>
#endif
static GstBusSyncReply create_window (GstBus* bus, GstMessage* message, GtkWidget* widget)
{
GtkAllocation allocation;
if (gst_gtk_handle_need_context (bus, message, NULL))
return GST_BUS_DROP;
// ignore anything but 'prepare-window-handle' element messages
if (GST_MESSAGE_TYPE (message) != GST_MESSAGE_ELEMENT)
return GST_BUS_PASS;
if (!gst_is_video_overlay_prepare_window_handle_message (message))
return GST_BUS_PASS;
g_print ("setting window handle %p\n", widget);
gst_video_overlay_set_gtk_window (GST_VIDEO_OVERLAY (GST_MESSAGE_SRC (message)), widget);
gtk_widget_get_allocation (widget, &allocation);
gst_video_overlay_set_render_rectangle (GST_VIDEO_OVERLAY (GST_MESSAGE_SRC (message)), allocation.x, allocation.y, allocation.width, allocation.height);
gst_message_unref (message);
return GST_BUS_DROP;
}
static gboolean
resize_cb (GtkWidget * widget, GdkEvent * event, gpointer sink)
{
GtkAllocation allocation;
gtk_widget_get_allocation (widget, &allocation);
gst_video_overlay_set_render_rectangle (GST_VIDEO_OVERLAY (sink), allocation.x, allocation.y, allocation.width, allocation.height);
return G_SOURCE_CONTINUE;
}
static void end_stream_cb(GstBus* bus, GstMessage* message, GstElement* pipeline)
{
GError *error = NULL;
gchar *details;
switch (GST_MESSAGE_TYPE (message)) {
case GST_MESSAGE_ERROR:
gst_message_parse_error (message, &error, &details);
g_print("Error %s\n", error->message);
g_print("Details %s\n", details);
/* fallthrough */
case GST_MESSAGE_EOS:
g_print("End of stream\n");
gst_element_set_state (pipeline, GST_STATE_NULL);
gst_object_unref(pipeline);
gtk_main_quit();
break;
case GST_MESSAGE_WARNING:
gst_message_parse_warning (message, &error, &details);
g_print("Warning %s\n", error->message);
g_print("Details %s\n", details);
break;
default:
break;
}
}
static gboolean expose_cb(GtkWidget* widget, cairo_t *cr, GstElement* videosink)
{
gst_video_overlay_expose (GST_VIDEO_OVERLAY (videosink));
return FALSE;
}
static void destroy_cb(GtkWidget* widget, GdkEvent* event, GstElement* pipeline)
{
g_print("Close\n");
gst_element_set_state (pipeline, GST_STATE_NULL);
gst_object_unref(pipeline);
gtk_main_quit();
}
static void button_state_null_cb(GtkWidget* widget, GstElement* pipeline)
{
gst_element_set_state (pipeline, GST_STATE_NULL);
g_print ("GST_STATE_NULL\n");
}
static void button_state_ready_cb(GtkWidget* widget, GstElement* pipeline)
{
gst_element_set_state (pipeline, GST_STATE_READY);
g_print ("GST_STATE_READY\n");
}
static void button_state_paused_cb(GtkWidget* widget, GstElement* pipeline)
{
gst_element_set_state (pipeline, GST_STATE_PAUSED);
g_print ("GST_STATE_PAUSED\n");
}
static void button_state_playing_cb(GtkWidget* widget, GstElement* pipeline)
{
gst_element_set_state (pipeline, GST_STATE_PLAYING);
g_print ("GST_STATE_PLAYING\n");
}
static gchar* slider_fps_cb (GtkScale* scale, gdouble value, GstElement* pipeline)
{
//change the video frame rate dynamically
return g_strdup_printf ("video framerate: %0.*g", gtk_scale_get_digits (scale), value);
}
gint main (gint argc, gchar *argv[])
{
#ifdef HAVE_X11
XInitThreads ();
#endif
gtk_init (&argc, &argv);
gst_init (&argc, &argv);
GstElement* pipeline = gst_pipeline_new ("pipeline");
//window that contains an area where the video is drawn
GtkWidget* window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
gtk_widget_set_size_request (window, 640, 480);
gtk_window_move (GTK_WINDOW (window), 300, 10);
gtk_window_set_title (GTK_WINDOW (window), "glimagesink implement the gstvideooverlay interface");
GdkGeometry geometry;
geometry.min_width = 1;
geometry.min_height = 1;
geometry.max_width = -1;
geometry.max_height = -1;
gtk_window_set_geometry_hints (GTK_WINDOW (window), window, &geometry, GDK_HINT_MIN_SIZE);
//window to control the states
GtkWidget* window_control = gtk_window_new (GTK_WINDOW_TOPLEVEL);
geometry.min_width = 1;
geometry.min_height = 1;
geometry.max_width = -1;
geometry.max_height = -1;
gtk_window_set_geometry_hints (GTK_WINDOW (window_control), window_control, &geometry, GDK_HINT_MIN_SIZE);
gtk_window_set_resizable (GTK_WINDOW (window_control), FALSE);
gtk_window_move (GTK_WINDOW (window_control), 10, 10);
GtkWidget* grid = gtk_grid_new ();
gtk_container_add (GTK_CONTAINER (window_control), grid);
//control state null
GtkWidget* button_state_null = gtk_button_new_with_label ("GST_STATE_NULL");
g_signal_connect (G_OBJECT (button_state_null), "clicked",
G_CALLBACK (button_state_null_cb), pipeline);
gtk_grid_attach (GTK_GRID (grid), button_state_null, 0, 1, 1, 1);
gtk_widget_show (button_state_null);
//control state ready
GtkWidget* button_state_ready = gtk_button_new_with_label ("GST_STATE_READY");
g_signal_connect (G_OBJECT (button_state_ready), "clicked",
G_CALLBACK (button_state_ready_cb), pipeline);
gtk_grid_attach (GTK_GRID (grid), button_state_ready, 0, 2, 1, 1);
gtk_widget_show (button_state_ready);
//control state paused
GtkWidget* button_state_paused = gtk_button_new_with_label ("GST_STATE_PAUSED");
g_signal_connect (G_OBJECT (button_state_paused), "clicked",
G_CALLBACK (button_state_paused_cb), pipeline);
gtk_grid_attach (GTK_GRID (grid), button_state_paused, 0, 3, 1, 1);
gtk_widget_show (button_state_paused);
//control state playing
GtkWidget* button_state_playing = gtk_button_new_with_label ("GST_STATE_PLAYING");
g_signal_connect (G_OBJECT (button_state_playing), "clicked",
G_CALLBACK (button_state_playing_cb), pipeline);
gtk_grid_attach (GTK_GRID (grid), button_state_playing, 0, 4, 1, 1);
gtk_widget_show (button_state_playing);
//change framerate
GtkWidget* slider_fps = gtk_scale_new_with_range (GTK_ORIENTATION_VERTICAL, 1, 30, 2);
g_signal_connect (G_OBJECT (slider_fps), "format-value",
G_CALLBACK (slider_fps_cb), pipeline);
gtk_grid_attach (GTK_GRID (grid), slider_fps, 1, 0, 1, 5);
gtk_widget_show (slider_fps);
gtk_widget_show (grid);
gtk_widget_show (window_control);
//configure the pipeline
g_signal_connect(G_OBJECT(window), "delete-event", G_CALLBACK(destroy_cb), pipeline);
GstElement* videosrc = gst_element_factory_make ("videotestsrc", "videotestsrc");
GstElement* upload = gst_element_factory_make ("glupload", "glupload");
GstElement* glfiltercube = gst_element_factory_make ("glfiltercube", "glfiltercube");
GstElement* videosink = gst_element_factory_make ("glimagesink", "glimagesink");
GstCaps *caps = gst_caps_new_simple("video/x-raw",
"width", G_TYPE_INT, 640,
"height", G_TYPE_INT, 480,
"framerate", GST_TYPE_FRACTION, 25, 1,
"format", G_TYPE_STRING, "RGBA",
NULL) ;
gst_bin_add_many (GST_BIN (pipeline), videosrc, upload, glfiltercube, videosink, NULL);
gboolean link_ok = gst_element_link_filtered(videosrc, upload, caps) ;
gst_caps_unref(caps) ;
if(!link_ok)
{
g_warning("Failed to link videosrc to glfiltercube!\n") ;
return -1;
}
if(!gst_element_link_many(upload, glfiltercube, videosink, NULL))
{
g_warning("Failed to link glfiltercube to videosink!\n") ;
return -1;
}
//area where the video is drawn
GtkWidget* area = gtk_drawing_area_new();
gtk_widget_set_redraw_on_allocate (area, TRUE);
gtk_container_add (GTK_CONTAINER (window), area);
gtk_widget_realize(area);
//set window id on this event
GstBus* bus = gst_pipeline_get_bus (GST_PIPELINE (pipeline));
gst_bus_set_sync_handler (bus, (GstBusSyncHandler) create_window, area, NULL);
gst_bus_add_signal_watch (bus);
g_signal_connect(bus, "message::error", G_CALLBACK(end_stream_cb), pipeline);
g_signal_connect(bus, "message::warning", G_CALLBACK(end_stream_cb), pipeline);
g_signal_connect(bus, "message::eos", G_CALLBACK(end_stream_cb), pipeline);
gst_object_unref (bus);
//needed when being in GST_STATE_READY, GST_STATE_PAUSED
//or resizing/obscuring the window
g_signal_connect(area, "draw", G_CALLBACK(expose_cb), videosink);
g_signal_connect(area, "configure-event", G_CALLBACK(resize_cb), videosink);
//start
GstStateChangeReturn ret = gst_element_set_state (pipeline, GST_STATE_PLAYING);
if (ret == GST_STATE_CHANGE_FAILURE)
{
g_print ("Failed to start up pipeline!\n");
return -1;
}
gtk_widget_show_all (window);
gtk_main();
return 0;
}
| 34.030303 | 156 | 0.705056 | [
"geometry"
] |
68514ae1c126be5dac1219ed3bdd2428166a914d | 3,338 | hpp | C++ | third_party/omr/gc/base/standard/CopyScanCacheChunkInHeap.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/gc/base/standard/CopyScanCacheChunkInHeap.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | third_party/omr/gc/base/standard/CopyScanCacheChunkInHeap.hpp | xiacijie/omr-wala-linkage | a1aff7aef9ed131a45555451abde4615a04412c1 | [
"Apache-2.0"
] | null | null | null | /*******************************************************************************
* Copyright (c) 1991, 2015 IBM Corp. and others
*
* This program and the accompanying materials are made available under
* the terms of the Eclipse Public License 2.0 which accompanies this
* distribution and is available at https://www.eclipse.org/legal/epl-2.0/
* or the Apache License, Version 2.0 which accompanies this distribution and
* is available at https://www.apache.org/licenses/LICENSE-2.0.
*
* This Source Code may also be made available under the following
* Secondary Licenses when the conditions for such availability set
* forth in the Eclipse Public License, v. 2.0 are satisfied: GNU
* General Public License, version 2 with the GNU Classpath
* Exception [1] and GNU General Public License, version 2 with the
* OpenJDK Assembly Exception [2].
*
* [1] https://www.gnu.org/software/classpath/license.html
* [2] http://openjdk.java.net/legal/assembly-exception.html
*
* SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception
*******************************************************************************/
/**
* @file
* @ingroup GC_Modron_Standard
*/
#if !defined(COPYSCANCACHECHUNKINHEAP_HPP_)
#define COPYSCANCACHECHUNKINHEAP_HPP_
#include "CopyScanCacheChunk.hpp"
#include "EnvironmentStandard.hpp"
class MM_Collector;
class MM_CopyScanCacheStandard;
class MM_MemorySubSpace;
/**
* @todo Provide class documentation
* @ingroup GC_Modron_Standard
*/
class MM_CopyScanCacheChunkInHeap : public MM_CopyScanCacheChunk
{
private:
void *_addrBase; /**< lowest address of allocated memory in heap */
void *_addrTop; /**< highest address of allocated memory in heap */
MM_MemorySubSpace *_memorySubSpace; /**< subspace memory is allocated with */
protected:
public:
private:
protected:
public:
/**
* Create new instance in heap allocated memory:
* 1. Put MM_HeapLinkedFreeHeader first to keep heap walkable
* 2. Put MM_CopyScanCacheChunkInHeap itself
* 3. Put number of scan caches MM_CopyScanCacheStandard to just barely exceed tlhMinimumSize.
* Such size should be small enough to easy to allocate and large enough to be reused as tlh
*
* @param[in] env current thread environment
* @param[in] nextChunk pointer to current chunk list head
* @param[in] memorySubSpace memory subspace to create chunk at
* @param[in] requestCollector collector issued a memory allocation request
* @param[out] sublistTail tail of sublist of scan caches created in this chunk
* @param[out] entries number of scan cache entries created in this chunk
* @return pointer to allocated chunk
*/
static MM_CopyScanCacheChunkInHeap *newInstance(MM_EnvironmentStandard *env, MM_CopyScanCacheChunk *nextChunk, MM_MemorySubSpace *memorySubSpace, MM_Collector *requestCollector,
MM_CopyScanCacheStandard **sublistTail, uintptr_t *entries);
virtual void kill(MM_EnvironmentBase *env);
/**
* Create a CopyScanCacheChunk object.
*/
MM_CopyScanCacheChunkInHeap(void *addBase, void*addrTop, MM_MemorySubSpace *memorySubSpace)
: MM_CopyScanCacheChunk()
, _addrBase(addBase)
, _addrTop(addrTop)
, _memorySubSpace(memorySubSpace)
{
_typeId = __FUNCTION__;
};
};
#endif /* COPYSCANCACHECHUNKINHEAP_HPP_ */
| 35.892473 | 178 | 0.72888 | [
"object"
] |
685a6f3e6372861a40d68ca076f55bf7be521ef0 | 5,255 | cpp | C++ | Sources/Post/Deferred/RendererDeferred.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | 1 | 2019-03-13T08:26:38.000Z | 2019-03-13T08:26:38.000Z | Sources/Post/Deferred/RendererDeferred.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | null | null | null | Sources/Post/Deferred/RendererDeferred.cpp | hhYanGG/Acid | f5543e9290aee5e25c6ecdafe8a3051054b203c0 | [
"MIT"
] | null | null | null | #include "RendererDeferred.hpp"
#include "Helpers/FileSystem.hpp"
#include "Lights/Light.hpp"
#include "Models/Shapes/ModelRectangle.hpp"
#include "Models/VertexModel.hpp"
#include "Renderer/Pipelines/Compute.hpp"
#include "Scenes/Scenes.hpp"
#include "Shadows/Shadows.hpp"
#include "Skyboxes/MaterialSkybox.hpp"
namespace acid
{
const uint32_t RendererDeferred::MAX_LIGHTS = 32;
RendererDeferred::RendererDeferred(const GraphicsStage &graphicsStage) :
IRenderer(graphicsStage),
m_descriptorSet(DescriptorsHandler()),
m_uniformScene(UniformHandler()),
m_pipeline(Pipeline(graphicsStage, PipelineCreate({"Shaders/Deferred/Deferred.vert", "Shaders/Deferred/Deferred.frag"},
VertexModel::GetVertexInput(), PIPELINE_MODE_POLYGON_NO_DEPTH, VK_POLYGON_MODE_FILL, VK_CULL_MODE_BACK_BIT, GetDefines()))),
m_model(ModelRectangle::Resource(-1.0f, 1.0f)),
m_brdf(ComputeBrdf(512)), // Texture::Resource("BrdfLut.png")
m_fog(Fog(Colour::WHITE, 0.001f, 2.0f, -0.1f, 0.3f))
{
}
RendererDeferred::~RendererDeferred()
{
}
void RendererDeferred::Render(const CommandBuffer &commandBuffer, const Vector4 &clipPlane, const ICamera &camera)
{
auto sceneSkyboxRender = Scenes::Get()->GetStructure()->GetComponent<MaterialSkybox>();
auto ibl = (sceneSkyboxRender == nullptr) ? nullptr : sceneSkyboxRender->GetCubemap(); // TODO: IBL cubemap.
// Updates uniforms.
auto lightColours = std::vector<Colour>(MAX_LIGHTS);
auto lightPositions = std::vector<Vector4>(MAX_LIGHTS);
int32_t lightCount = 0;
auto sceneLights = Scenes::Get()->GetStructure()->QueryComponents<Light>();
for (auto &light : sceneLights)
{
// auto position = *light->GetPosition();
// float radius = light->GetRadius();
// if (radius >= 0.0f && !camera.GetViewFrustum()->SphereInFrustum(position, radius))
// {
// continue;
// }
lightColours[lightCount] = light->GetColour();
lightPositions[lightCount] = Vector4(light->GetPosition(), light->GetRadius());
lightCount++;
if (lightCount >= MAX_LIGHTS)
{
break;
}
}
// Updates uniforms.
m_uniformScene.Push("lightColours", *lightColours.data(), sizeof(Colour) * MAX_LIGHTS);
m_uniformScene.Push("lightPositions", *lightPositions.data(), sizeof(Vector4) * MAX_LIGHTS);
m_uniformScene.Push("lightsCount", lightCount);
m_uniformScene.Push("projection", camera.GetProjectionMatrix());
m_uniformScene.Push("view", camera.GetViewMatrix());
m_uniformScene.Push("shadowSpace", Shadows::Get()->GetShadowBox().GetToShadowMapSpaceMatrix());
m_uniformScene.Push("fogColour", m_fog.GetColour());
m_uniformScene.Push("cameraPosition", camera.GetPosition());
m_uniformScene.Push("fogDensity", m_fog.GetDensity());
m_uniformScene.Push("fogGradient", m_fog.GetGradient());
m_uniformScene.Push("shadowDistance", Shadows::Get()->GetShadowBoxDistance());
m_uniformScene.Push("shadowTransition", Shadows::Get()->GetShadowTransition());
m_uniformScene.Push("shadowBias", Shadows::Get()->GetShadowBias());
m_uniformScene.Push("shadowDarkness", Shadows::Get()->GetShadowDarkness());
m_uniformScene.Push("shadowPCF", Shadows::Get()->GetShadowPcf());
// Updates descriptors.
m_descriptorSet.Push("UboScene", &m_uniformScene);
m_descriptorSet.Push("samplerPosition", m_pipeline.GetTexture(2));
m_descriptorSet.Push("samplerDiffuse", m_pipeline.GetTexture(3));
m_descriptorSet.Push("samplerNormal", m_pipeline.GetTexture(4));
m_descriptorSet.Push("samplerMaterial", m_pipeline.GetTexture(5));
m_descriptorSet.Push("samplerShadows", m_pipeline.GetTexture(0, 0));
m_descriptorSet.Push("samplerBrdf", m_brdf);
m_descriptorSet.Push("samplerIbl", ibl);
bool updateSuccess = m_descriptorSet.Update(m_pipeline);
if (!updateSuccess)
{
return;
}
// Draws the object.
m_pipeline.BindPipeline(commandBuffer);
m_descriptorSet.BindDescriptor(commandBuffer);
m_model->CmdRender(commandBuffer);
}
std::vector<PipelineDefine> RendererDeferred::GetDefines()
{
std::vector<PipelineDefine> result = {};
result.emplace_back(PipelineDefine("USE_IBL", "TRUE"));
result.emplace_back(PipelineDefine("MAX_LIGHTS", std::to_string(MAX_LIGHTS)));
return result;
}
std::shared_ptr<Texture> RendererDeferred::ComputeBrdf(const uint32_t &size)
{
auto result = std::make_shared<Texture>(size, size);
// Creates the pipeline.
CommandBuffer commandBuffer = CommandBuffer(true, VK_QUEUE_COMPUTE_BIT);
Compute compute = Compute(ComputeCreate("Shaders/Brdf.comp", size, size, 16, {}));
// Bind the pipeline.
compute.BindPipeline(commandBuffer);
// Updates descriptors.
DescriptorsHandler descriptorSet = DescriptorsHandler(compute);
descriptorSet.Push("outColour", result);
descriptorSet.Update(compute);
// Runs the compute pipeline.
descriptorSet.BindDescriptor(commandBuffer);
compute.CmdRender(commandBuffer);
commandBuffer.End();
commandBuffer.Submit();
#if ACID_VERBOSE
// Saves the brdf texture.
std::string filename = FileSystem::GetWorkingDirectory() + "/Brdf.png";
FileSystem::ClearFile(filename);
uint8_t *pixels = result->GetPixels();
Texture::WritePixels(filename, pixels, result->GetWidth(), result->GetHeight(), result->GetComponents());
delete[] pixels;
#endif
return result;
}
}
| 35.993151 | 127 | 0.742912 | [
"render",
"object",
"vector"
] |
685b73fa370cc9a3551e576b777cdb0d929b2b87 | 6,606 | cpp | C++ | main.cpp | Paristha/HaikuReporter | ab58002b78cc2987e4457089d7e0c8c9817c7378 | [
"MIT"
] | null | null | null | main.cpp | Paristha/HaikuReporter | ab58002b78cc2987e4457089d7e0c8c9817c7378 | [
"MIT"
] | null | null | null | main.cpp | Paristha/HaikuReporter | ab58002b78cc2987e4457089d7e0c8c9817c7378 | [
"MIT"
] | null | null | null | #include <cpr/cpr.h>
#include <fstream>
#include <iostream>
#include <nlohmann/json.hpp>
#include <vector>
#include <pybind11/embed.h>
namespace py = pybind11;
using namespace py::literals;
std::string PY_MODULE_PATH = "C:\\Users\\rapha\\PycharmProjects\\HaikuRecognizer";
std::string BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAAKNhLAEAAAAAzItOgprPgVhFZIc6JjgD74tIu34%3D4OlxvtQhLZ9p2E5kblp79f6rOOx33L0SZivMJm8prJpTvh5qRC";
std::vector<std::string> RULE_IDS;
bool makeRule(std::string value_text, std::string tag_text = "")
{
std::string json_body = R"({ "add": [ {"value": ")";
json_body += value_text;
json_body += R"(", "tag": ")";
json_body += tag_text;
json_body += R"("} ] })";
cpr::Response r = cpr::Post(cpr::Url{ "https://api.twitter.com/2/tweets/search/stream/rules" },
cpr::Payload{ {"dry_run", "false"} },
cpr::Header{ { "Content-Type", "application/json" },
{ "Authorization", "Bearer " + BEARER_TOKEN } },
cpr::Body{ json_body });
nlohmann::json item;
try {
item = nlohmann::json::parse(r.text);
}
catch (nlohmann::json::exception exc) {
if (!r.error.message.empty())
std::cerr << r.error.message << std::endl;
std::cerr << exc.what() << std::endl;
return false;
}
if (item.contains("errors") || r.status_code != 201) {
std::string error = "";
if (item.contains("errors")) {
for (const auto& rule : item["errors"]) {
RULE_IDS.push_back(rule["id"].dump());
}
error += "Rule(s) not accepted. Errors: " + item["errors"].dump() + "\n";
}
if (r.status_code != 201)
error += "HTTP Error Code: " + std::to_string(r.status_code);
std::cerr << error << std::endl;
return false;
}
for (const auto& rule : item["data"]) {
std::string rule_id = rule["id"].dump();
std::cout << "Rule successfully created with id " + rule_id << std::endl;
RULE_IDS.push_back(rule_id);
}
return true;
}
bool getRuleIDs() {
cpr::Response r = cpr::Get(cpr::Url{ "https://api.twitter.com/2/tweets/search/stream/rules" },
cpr::Header{ { "Authorization", "Bearer " + BEARER_TOKEN } });
nlohmann::json item;
try {
item = nlohmann::json::parse(r.text);
}
catch (nlohmann::json::exception exc) {
if (!r.error.message.empty())
std::cerr << r.error.message << std::endl;
std::cerr << exc.what() << std::endl;
return false;
}
if (r.status_code != 200) {
std::cerr << "HTTP Error Code: " + std::to_string(r.status_code) << std::endl;
return false;
}
std::cout << "Retrieved rule IDs: ";
std::vector<std::string> new_rule_ids;
for (const auto& rule : item["data"]) {
std::string rule_id = rule["id"].dump();
std::cout << rule_id << ", ";
new_rule_ids.push_back(rule_id);
}
std::cout << std::endl;
RULE_IDS = new_rule_ids;
return true;
}
bool deleteRules(std::vector<std::string> ids2delete) {
if (ids2delete.empty())
return true;
int num_rules2delete = ids2delete.size();
std::string json_body = R"({ "delete": { "ids": [)";
json_body += ids2delete.back();
ids2delete.pop_back();
if (!ids2delete.empty()) {
for (std::vector<std::string>::const_iterator i = ids2delete.begin(); i != ids2delete.end(); ++i) {
json_body += ", ";
json_body += *i;
}
}
json_body += "] } }";
std::cout << json_body << std::endl;
cpr::Response r = cpr::Post(cpr::Url{ "https://api.twitter.com/2/tweets/search/stream/rules" },
cpr::Payload{ {"dry_run", "false"} },
cpr::Header{ { "Content-Type", "application/json" },
{ "Authorization", "Bearer " + BEARER_TOKEN } },
cpr::Body{ json_body });
nlohmann::json item;
try {
item = nlohmann::json::parse(r.text);
}
catch (nlohmann::json::exception exc) {
if (!r.error.message.empty())
std::cerr << r.error.message << std::endl;
std::cerr << exc.what() << std::endl;
return false;
}
int num_rules_deleted = 0;
try {
num_rules_deleted = item["meta"]["summary"]["deleted"];
}
catch (nlohmann::json::exception exc) {
std::cerr << exc.what() << std::endl;
if (r.status_code != 200)
std::cerr << "HTTP Error Code: " + std::to_string(r.status_code) << std::endl;
return false;
}
if (num_rules2delete == num_rules_deleted) {
std::cout << item["meta"]["summary"]["deleted"].dump() + " rules successfully deleted" << std::endl;
return true;
}
else {
std::cout << num_rules2delete - num_rules_deleted << " rules not deleted" << std::endl;
if (r.status_code != 200)
std::cerr << "HTTP Error Code: " + std::to_string(r.status_code) << std::endl;
return false;
}
}
void streamTweets(std::ofstream& output_file, int timeout = 10000) {
cpr::Response r2 = cpr::Get(cpr::Url{ "https://api.twitter.com/2/tweets/search/stream" },
cpr::Header{ { "Authorization", "Bearer " + BEARER_TOKEN } },
cpr::WriteCallback([&](std::string data) -> bool {
std::cout << "Here is the data:\n" + data + "\nEND\n";
nlohmann::json item;
try {
item = nlohmann::json::parse(data);
}
catch (nlohmann::json::exception exc) {
; // Do nothing; stream pushes empty lines to stay open
}
std::string text = item["data"]["text"].dump();
output_file << "START\n" + item["data"]["text"].dump() + "\nEND\n";
return true;
}),
cpr::Timeout{timeout});
}
int main()
{
std::cout << "WHAT\n";
py::scoped_interpreter python;
auto math = py::module::import("math");
double root_two = math.attr("sqrt")(2.0).cast<double>();
std::cout << "The square root of 2 is: " << root_two << "\n";
py::object path = py::module_::import("sys").attr("path");
py::print(path);
std::cout << "WHAT3\n";
path.attr("append")(PY_MODULE_PATH);
std::cout << "WHAT4\n";
py::object is_haiku = py::module_::import("HaikuRecognizer").attr("haiku");
std::cout << "WHAT5\n";
std::string answer = is_haiku("no").cast<std::string>();
if (answer.empty()) {
std::cout << "Not a Haiku\n";;
}
else {
std::cout << answer + "\nEND\n";
}
std::string answer2 = is_haiku("a b c d e f g h i j k l m n o p q").cast<std::string>();
if (answer2.empty()) {
std::cout << "Not a Haiku\n";;
}
else {
std::cout << answer2 + "\nEND\n";
}
std::string rule = "(#breakingnews OR #news OR #localnews OR #breaking OR from:BreakingNews OR from:BBCBreaking OR from:cnnbrk OR from:WSJbreakingnews OR from:Reuters OR from:CBSTopNews OR from:AJELive OR from:SkyNewsBreak OR from:ABCNewsLive OR from:TWCBreaking) lang:en -is:retweet";
std::string tag = "news in english";
if (!makeRule(rule, tag))
return 1;
if (!getRuleIDs())
return 1;
//std::ofstream output_file;
//output_file.open("tweets.txt");
//int timeout = 900000;
//streamTweets(output_file, timeout);
//output_file.close();
if (!deleteRules(RULE_IDS))
return 1;
return 0;
} | 29.756757 | 286 | 0.636391 | [
"object",
"vector"
] |
6860e868585b1fdf0964b500465d7b6d4f30c35d | 1,473 | cpp | C++ | vectors.cpp | Mohamed742/C-AIMS-SA-2018 | a59ba718872dfae0f8ee216b10dbb66db3e8a921 | [
"Apache-2.0"
] | null | null | null | vectors.cpp | Mohamed742/C-AIMS-SA-2018 | a59ba718872dfae0f8ee216b10dbb66db3e8a921 | [
"Apache-2.0"
] | null | null | null | vectors.cpp | Mohamed742/C-AIMS-SA-2018 | a59ba718872dfae0f8ee216b10dbb66db3e8a921 | [
"Apache-2.0"
] | null | null | null | //#include<iostream>
//#include<vector>
//using namespace std;
#include <iostream>
#include <vector>
#include <algorithm>
#include<cmath>
using namespace std;
int main()
{
int i = 0 ;
// Create a vector containing integers
std::vector<int> vec = {};
// Add two more integers to vector
for (i ; i <= 7; i++){
vec.push_back(i+2);
}
for( int t : vec)
cout << t << endl;
// dtermine the max and min element in vec
auto max_min = std::minmax_element (vec.begin(),vec.end());
std::cout << "min is: " << *max_min.first <<'\n';
std::cout << "max is: " << *max_min.second <<'\n';
sort(vec.begin(), vec.end());
cout << "Sorted elemnt in vec \n";
for (auto u : vec)
cout << u <<endl;
//reverse function
cout << "reverse";
reverse(vec.begin(),vec.end());
vector <int> :: iterator it;
for (it = vec.begin(); it != vec.end(); it++)
cout << (*it) << " ";
//round the value of vector
vector<double> vec1 = {0.12 , 11.568,0.000005,21.658,17.5};
for (double x : vec1)
cout << round(x) << endl;
std::vector<int> vec2 = {12,17,5,3,6};
sort(vec2.begin(),vec2.end());
cout<< " The sort of vec2"<<endl;
for(auto l : vec2)
{
cout<<l<<'\t';}
// reverse order of vector
cout << " The reverse of vec2" <<endl;
reverse(vec2.begin(),vec2.end());
for(auto l : vec2)
cout<< l<<'\t';
return 0;
}
| 22.318182 | 61 | 0.532247 | [
"vector"
] |
6866adcfbbe9cc9c4e88a7bdb4f4213c87b8d5a1 | 4,453 | cpp | C++ | C3D/C3D-v1.1/src/caffe/test/test_convolution3d_layer.cpp | Blssel/ClassicalAlgorZoo | b3cd08961d971658cfc9ebd98760c7207f7b322e | [
"MIT"
] | null | null | null | C3D/C3D-v1.1/src/caffe/test/test_convolution3d_layer.cpp | Blssel/ClassicalAlgorZoo | b3cd08961d971658cfc9ebd98760c7207f7b322e | [
"MIT"
] | null | null | null | C3D/C3D-v1.1/src/caffe/test/test_convolution3d_layer.cpp | Blssel/ClassicalAlgorZoo | b3cd08961d971658cfc9ebd98760c7207f7b322e | [
"MIT"
] | null | null | null | /*
* test_convolution3d_layer.cpp
*
* Created on: Jul 13, 2016
* Author: dutran
*/
#include <vector>
#include "gtest/gtest.h"
#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/layers/convolution3d_layer.hpp"
#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"
namespace caffe {
#ifndef CPU_ONLY
extern cudaDeviceProp CAFFE_TEST_CUDA_PROP;
#endif
template <typename TypeParam>
class Convolution3DLayerTest : public MultiDeviceTest<TypeParam> {
typedef typename TypeParam::Dtype Dtype;
protected:
Convolution3DLayerTest()
: blob_bottom_(new Blob<Dtype>()),
blob_top_(new Blob<Dtype>()) {}
virtual void SetUp() {
Caffe::set_random_seed(1701);
FillerParameter filler_param;
filler_param.set_value(1.);
GaussianFiller<Dtype> filler(filler_param);
static const int shape_values[] = {2, 3, 5, 5, 5};
vector<int> shape_size(shape_values, shape_values + 5);
blob_bottom_->Reshape(shape_size);
filler.Fill(this->blob_bottom_);
blob_bottom_vec_.push_back(blob_bottom_);
blob_top_vec_.push_back(blob_top_);
}
virtual ~Convolution3DLayerTest() {
delete blob_bottom_;
delete blob_top_;
}
Blob<Dtype>* const blob_bottom_;
Blob<Dtype>* const blob_top_;
vector<Blob<Dtype>*> blob_bottom_vec_;
vector<Blob<Dtype>*> blob_top_vec_;
};
TYPED_TEST_CASE(Convolution3DLayerTest, TestDtypesAndDevices);
TYPED_TEST(Convolution3DLayerTest, TestSetUp) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
Convolution3DParameter* convolution3d_param =
layer_param.mutable_convolution3d_param();
convolution3d_param->set_kernel_size(3);
convolution3d_param->set_kernel_depth(3);
convolution3d_param->set_stride(2);
convolution3d_param->set_temporal_stride(2);
convolution3d_param->set_num_output(6);
shared_ptr<Convolution3DLayer<Dtype> > layer(
new Convolution3DLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
EXPECT_EQ(this->blob_top_->shape(0), 2);
EXPECT_EQ(this->blob_top_->shape(1), 6);
EXPECT_EQ(this->blob_top_->shape(2), 2);
EXPECT_EQ(this->blob_top_->shape(3), 2);
EXPECT_EQ(this->blob_top_->shape(4), 2);
}
TYPED_TEST(Convolution3DLayerTest, TestSimpleConvolution) {
typedef typename TypeParam::Dtype Dtype;
// We will simply see if the convolution layer carries out averaging well.
FillerParameter filler_param;
filler_param.set_value(1.);
ConstantFiller<Dtype> filler(filler_param);
filler.Fill(this->blob_bottom_);
LayerParameter layer_param;
Convolution3DParameter* convolution3d_param =
layer_param.mutable_convolution3d_param();
convolution3d_param->set_kernel_size(3);
convolution3d_param->set_kernel_depth(3);
convolution3d_param->set_stride(2);
convolution3d_param->set_temporal_stride(2);
convolution3d_param->set_num_output(6);
convolution3d_param->mutable_weight_filler()->set_type("constant");
convolution3d_param->mutable_weight_filler()->set_value(1);
convolution3d_param->mutable_bias_filler()->set_type("constant");
convolution3d_param->mutable_bias_filler()->set_value(0.1);
shared_ptr<Layer<Dtype> > layer(
new Convolution3DLayer<Dtype>(layer_param));
layer->SetUp(this->blob_bottom_vec_, this->blob_top_vec_);
layer->Forward(this->blob_bottom_vec_, this->blob_top_vec_);
// After the convolution, the output should all have output values 81.1
const Dtype* top_data;
top_data = this->blob_top_->cpu_data();
for (int i = 0; i < this->blob_top_->count(); ++i) {
EXPECT_NEAR(top_data[i], 81.1, 1e-4);
}
}
TYPED_TEST(Convolution3DLayerTest, TestGradient) {
typedef typename TypeParam::Dtype Dtype;
LayerParameter layer_param;
Convolution3DParameter* convolution3d_param =
layer_param.mutable_convolution3d_param();
convolution3d_param->set_kernel_size(3);
convolution3d_param->set_kernel_depth(3);
convolution3d_param->set_stride(2);
convolution3d_param->set_temporal_stride(2);
convolution3d_param->set_num_output(2);
convolution3d_param->mutable_weight_filler()->set_type("gaussian");
convolution3d_param->mutable_bias_filler()->set_type("gaussian");
Convolution3DLayer<Dtype> layer(layer_param);
GradientChecker<Dtype> checker(1e-2, 1e-3);
checker.CheckGradientExhaustive(&layer, this->blob_bottom_vec_, this->blob_top_vec_);
}
} // namespace caffe
| 30.923611 | 87 | 0.760386 | [
"shape",
"vector"
] |
6874b1547a1271371b34486b2359f9a6682ebb76 | 3,271 | cpp | C++ | Components/Curve_PolylineLoft.cpp | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 28 | 2017-03-01T04:09:18.000Z | 2022-02-01T13:33:50.000Z | Components/Curve_PolylineLoft.cpp | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 3 | 2017-03-09T05:22:49.000Z | 2017-08-02T18:38:05.000Z | Components/Curve_PolylineLoft.cpp | elix22/IogramSource | 3a4ce55d94920e060776b4aa4db710f57a4280bc | [
"MIT"
] | 17 | 2017-03-01T14:00:01.000Z | 2022-02-08T06:36:54.000Z | //
// Copyright (c) 2016 - 2017 Mesh Consultants Inc.
// 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 "Curve_PolylineLoft.h"
#include <assert.h>
#include "Geomlib_PolylineLoft.h"
#include "Polyline.h"
using namespace Urho3D;
String Curve_PolylineLoft::iconTexture = "Textures/Icons/Curve_PolylineLoft.png";
Curve_PolylineLoft::Curve_PolylineLoft(Context* context) : IoComponentBase(context, 1, 1)
{
SetName("LoftPolylines");
SetFullName("Loft Polylines");
SetDescription("Perform loft operation on a list of polylines");
SetGroup(IoComponentGroup::CURVE);
SetSubgroup("Operators");
inputSlots_[0]->SetName("PolylineList");
inputSlots_[0]->SetVariableName("L");
inputSlots_[0]->SetDescription("List of polylines to loft");
inputSlots_[0]->SetVariantType(VariantType::VAR_VARIANTMAP);
inputSlots_[0]->SetDataAccess(DataAccess::LIST);
outputSlots_[0]->SetName("Mesh");
outputSlots_[0]->SetVariableName("M");
outputSlots_[0]->SetDescription("Lofted mesh");
outputSlots_[0]->SetVariantType(VariantType::VAR_VARIANTMAP);
outputSlots_[0]->SetDataAccess(DataAccess::ITEM);
}
void Curve_PolylineLoft::SolveInstance(
const Vector<Variant>& inSolveInstance,
Vector<Variant>& outSolveInstance
)
{
assert(inSolveInstance.Size() == inputSlots_.Size());
assert(outSolveInstance.Size() == outputSlots_.Size());
///////////////////
// VERIFY & EXTRACT
// Verify input slot 0
if (inSolveInstance[0].GetType() != VariantType::VAR_VARIANTVECTOR) {
URHO3D_LOGWARNING("L must be a list of polylines.");
outSolveInstance[0] = Variant();
return;
}
VariantVector polyList = inSolveInstance[0].GetVariantVector();
for (unsigned i = 0; i < polyList.Size(); ++i) {
if (!Polyline_Verify(polyList[i])) {
URHO3D_LOGWARNING("L must contain only valid polylines.");
outSolveInstance[0] = Variant();
return;
}
}
///////////////////
// COMPONENT'S WORK
Variant mesh;
bool success = Geomlib::PolylineLoft(polyList, mesh);
if (!success) {
URHO3D_LOGWARNING("PolylineLoft operation failed.");
outSolveInstance[0] = Variant();
return;
}
/////////////////
// ASSIGN OUTPUTS
outSolveInstance[0] = mesh;
} | 34.072917 | 90 | 0.71232 | [
"mesh",
"vector"
] |
687cd5f291d2bb386799832e10f46e4a9cd326c4 | 834 | hpp | C++ | src/GBuffer.hpp | Hyiker/OGLab | 7fef68c1996398aaf7a0434e5e821e788d3a4ee1 | [
"MIT"
] | null | null | null | src/GBuffer.hpp | Hyiker/OGLab | 7fef68c1996398aaf7a0434e5e821e788d3a4ee1 | [
"MIT"
] | null | null | null | src/GBuffer.hpp | Hyiker/OGLab | 7fef68c1996398aaf7a0434e5e821e788d3a4ee1 | [
"MIT"
] | null | null | null | #ifndef GBUFFER_H
#define GBUFFER_H
#include "Camera.hpp"
#include "Framebuffer.hpp"
#include "Scene.hpp"
#include "Shader.hpp"
#include "Texture.hpp"
class GBuffer {
Texture m_position, m_depth, m_normal, m_albedo;
Framebuffer m_framebuffer;
ShaderProgram m_shader;
int m_width, m_height;
public:
GBuffer(ShaderProgram&& shaderProgram, int width = 1080, int height = 1080)
: m_shader{std::move(shaderProgram)},
m_width{width},
m_height{height} {}
void init();
void render(const Scene& scene, const Camera& cam);
const Texture& getDepth() const { return m_depth; }
const Texture& getPosition() const { return m_position; }
const Texture& getNormal() const { return m_normal; }
const Texture& getAlbedo() const { return m_albedo; }
};
#endif /* GBUFFER_H */
| 29.785714 | 79 | 0.684652 | [
"render"
] |
6894c09cb38d5d7e169dd33086d17599130f842b | 2,669 | hpp | C++ | include/vcd/types/variable.hpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | 1 | 2019-04-30T17:56:23.000Z | 2019-04-30T17:56:23.000Z | include/vcd/types/variable.hpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | null | null | null | include/vcd/types/variable.hpp | qedalab/vcd_assert | 40da307e60600fc4a814d4bba4679001f49f4375 | [
"BSD-2-Clause"
] | 4 | 2018-08-01T08:32:00.000Z | 2019-12-18T06:34:33.000Z | // ============================================================================
// Copyright 2018 Paul le Roux and Calvin Maree
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
// ============================================================================
#ifndef LIBVCD_TYPES_VARIABLE_HPP
#define LIBVCD_TYPES_VARIABLE_HPP
#include "./enums.hpp"
#include <string>
#include <string_view>
#include <cstddef>
namespace VCD {
/// View of Variable
struct VariableView {
VarType type = VarType::reg; /// Variable type
std::size_t size = 0; /// Variable size
std::string_view identifier_code; /// Variable identifier code
std::string_view reference; /// Variable reference
};
/// Immutable variable object
class Variable {
std::size_t id_code_; /// Variable identifier code index
std::string ref_; /// Variable reference
public:
/// Variable constructor
/// \param id_code The variable identifier code index
/// \param reference The variable reference
Variable(std::size_t id_code, std::string reference) noexcept;
/// Get the variable identifier code index
/// \returns The variable identifier code index
std::size_t get_id_code_index() const noexcept;
/// Get the variable reference index
/// \returns View of the variable reference string
std::string_view get_reference() const noexcept;
};
} // namespace
#endif //LIBVCD_TYPES_VARIABLE_HPP
| 38.128571 | 79 | 0.704758 | [
"object"
] |
68959431b4dfe996ce4a7ddd34ecc3b98677a4d9 | 12,460 | hh | C++ | catg.hh | bitsofcotton/ca | f67b044264eaa4b84485fc65419fe037ba0315ae | [
"BSD-3-Clause"
] | null | null | null | catg.hh | bitsofcotton/ca | f67b044264eaa4b84485fc65419fe037ba0315ae | [
"BSD-3-Clause"
] | 6 | 2017-04-15T08:47:59.000Z | 2020-10-15T12:43:17.000Z | catg.hh | bitsofcotton/ca | f67b044264eaa4b84485fc65419fe037ba0315ae | [
"BSD-3-Clause"
] | null | null | null | /*
BSD 3-Clause License
Copyright (c) 2020-2021, bitsofcotton
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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.
*/
#if !defined(_CATG_)
using std::move;
using std::vector;
using std::pair;
using std::make_pair;
using std::swap;
using std::cerr;
using std::flush;
template <typename T> class CatG {
public:
typedef SimpleVector<T> Vec;
typedef SimpleMatrix<T> Mat;
inline CatG() { ; }
inline CatG(const int& size0, const vector<Vec>& in);
inline ~CatG() { ; }
inline T score(const Vec& in);
Vec cut;
T distance;
T origin;
const Mat& tayl(const int& size, const int& in);
};
template <typename T> inline CatG<T>::CatG(const int& size0, const vector<Vec>& in) {
const auto size(abs(size0));
SimpleMatrix<T> A(in.size(), size + 2);
for(int i = 0; i < in.size(); i ++)
tayl(size, in[i].size());
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
for(int i = 0; i < in.size(); i ++) {
A.row(i).setVector(0, makeProgramInvariant(tayl(size, in[i].size()) * in[i]).first);
A(i, A.cols() - 1) = T(int(1));
}
auto Pt(A.QR());
const auto R(Pt * A);
Vec one(Pt.cols());
SimpleVector<bool> fix(one.size());
one.I(T(int(1)));
fix.I(false);
const auto on(Pt.projectionPt(one));
vector<pair<T, int> > fidx;
vector<int> pidx;
fidx.reserve(on.size());
pidx.resize(on.size(), 0);
if(0 < size0) {
for(int i = 0; i < on.size(); i ++)
fidx.emplace_back(make_pair(abs(on[i]), i));
} else {
for(int i = 0; i < on.size(); i ++) {
T score(0);
for(int j = 0; j < in.size(); j ++) {
const auto lscore(abs(on[i] + on[j]));
if(score == T(int(0)) || lscore < score) {
score = lscore;
pidx[i] = j;
}
}
fidx.emplace_back(make_pair(score, i));
}
}
sort(fidx.begin(), fidx.end());
for(int n_fixed = 0, idx = 0;
n_fixed < Pt.rows() - 1 && idx < fidx.size();
n_fixed ++, idx ++) {
const auto& iidx(fidx[idx].second);
if(fix[iidx]) continue;
const auto orth(Pt.col(iidx));
const auto n2(orth.dot(orth));
if(n2 <= Pt.epsilon) continue;
#if defined(_OPENMP)
#pragma omp parallel for schedule(static, 1)
#endif
for(int j = 0; j < Pt.cols(); j ++)
Pt.setCol(j, Pt.col(j) - orth * Pt.col(j).dot(orth) / n2);
fix[iidx] = true;
if(size0 < 0)
fix[pidx[iidx]] = true;
}
cut = R.solve(Pt * one);
std::vector<T> s;
s.reserve(in.size());
assert(in.size() == A.rows());
for(int i = 0; i < A.rows(); i ++)
s.emplace_back(A.row(i).dot(cut));
std::sort(s.begin(), s.end());
distance = origin = T(int(0));
for(int i = 0; i < s.size() - 1; i ++)
if(distance <= s[i + 1] - s[i]) {
distance = s[i + 1] - s[i];
origin = (s[i + 1] + s[i]) / T(int(2));
}
return;
}
template <typename T> const typename CatG<T>::Mat& CatG<T>::tayl(const int& size, const int& in) {
static vector<Mat> t;
if(in < t.size()) {
if(t[in].rows() && t[in].cols())
return t[in];
} else
t.resize(in + 1, Mat());
t[in].resize(size, in);
for(int i = 0; i < size; i ++)
t[in].row(i) = taylor<T>(in, T(i) * T(in) / T(size));
return t[in];
}
template <typename T> inline T CatG<T>::score(const Vec& in) {
const auto size(cut.size() - 2);
assert(0 < size);
SimpleVector<T> sv(cut.size());
sv.setVector(0, makeProgramInvariant<T>(tayl(size, in.size()) * in).first);
sv[sv.size() - 1] = T(int(1));
return sv.dot(cut) - origin;
}
template <typename T> vector<pair<vector<SimpleVector<T> >, vector<int> > > crush(const vector<SimpleVector<T> >& v, const int& cs, const int& count) {
assert(0 <= count);
vector<pair<vector<SimpleVector<T> >, vector<int> > > result;
if(! v.size() || !v[0].size()) return result;
auto MM(v[0].dot(v[0]));
for(int i = 1; i < v.size(); i ++)
MM = max(MM, v[i].dot(v[i]));
MM = sqrt(MM) * T(int(2));
int t(0);
result.emplace_back(pair<vector<SimpleVector<T> >, vector<int> >());
result[0].first.reserve(v.size());
result[0].second.reserve(v.size());
for(int i = 0; i < v.size(); i ++) {
result[0].first.emplace_back(v[i] / MM);
result[0].second.emplace_back(i);
}
vector<pair<T, pair<int, bool> > > sidx;
sidx.emplace_back(make_pair(T(int(0)), make_pair(0, false)));
while(sidx.size() < (count ? count : v.size())) {
sort(sidx.begin(), sidx.end());
int iidx(sidx.size() - 1);
for( ; - 1 <= iidx; iidx --)
if(iidx < 0 || (! sidx[iidx].second.second &&
abs(cs) + 1 < result[sidx[iidx].second.first].first.size()) )
break;
if(iidx < 0) break;
const auto& t(sidx[iidx].second.first);
CatG<T> catg(cs, result[t].first);
if(catg.cut.size()) {
vector<SimpleVector<T> > left;
vector<SimpleVector<T> > right;
vector<int> lidx;
vector<int> ridx;
left.reserve(result[t].first.size());
right.reserve(result[t].first.size());
lidx.reserve(result[t].first.size());
ridx.reserve(result[t].first.size());
for(int i = 0; i < result[t].first.size(); i ++) {
const auto score(catg.score(result[t].first[i]));
(score < T(int(0)) ? left : right).emplace_back(move(result[t].first[i]));
(score < T(int(0)) ? lidx : ridx).emplace_back(result[t].second[i]);
}
if((abs(cs) + 1 < left.size() || abs(cs) + 1 < right.size()) && left.size() && right.size()) {
if(left.size() < right.size()) {
swap(left, right);
swap(lidx, ridx);
}
result[t].first = move(left);
result[t].second = move(lidx);
sidx[iidx].first = catg.distance;
sidx[iidx].second = make_pair(t, false);
result.emplace_back(make_pair(move(right), move(ridx)));
sidx.emplace_back(make_pair(catg.distance, make_pair(sidx.size(), false)));
} else {
result[t].first = move(left);
result[t].second = move(lidx);
result[t].first.reserve(result[t].first.size() + right.size());
result[t].second.reserve(result[t].second.size() + ridx.size());
for(int i = 0; i < right.size(); i ++) {
result[t].first.emplace_back(move(right[i]));
result[t].second.emplace_back(move(ridx[i]));
}
sidx[iidx].first = catg.distance;
sidx[iidx].second.second = true;
}
} else {
sidx[iidx].first = catg.distance;
sidx[iidx].second.second = true;
}
}
for(int i = 0; i < result.size(); i ++)
for(int j = 0; j < result[i].first.size(); j ++)
result[i].first[j] *= MM;
return result;
}
template <typename T> static inline vector<pair<vector<SimpleVector<T> >, vector<int> > > crush(const vector<SimpleVector<T> >& v, const int& cs) {
return crush<T>(v, cs, max(int(2), int(sqrt(T(v.size())))));
}
template <typename T> static inline vector<pair<vector<SimpleVector<T> >, vector<int> > > crush(const vector<SimpleVector<T> >& v) {
return crush<T>(v, v[0].size());
}
template <typename T> vector<pair<vector<SimpleVector<T> >, vector<int> > > crushWithOrder(const vector<T>& v, const int& cs, const int& count) {
vector<SimpleVector<T> > work;
vector<int> edge;
// N.B. it's O(v.size()^3 * cs^2).
work.reserve((v.size() * v.size() * v.size() - 19 * v.size() + 30) / 6);
edge.reserve(v.size() - 1);
edge.emplace_back(0);
for(int i = 3; i < v.size(); i ++) {
SimpleVector<T> buf(i);
for(int j = 0; j <= v.size() - i; j ++) {
for(int k = j; k < j + i; k ++)
buf[k - j] = v[k];
if(count < 0) {
vector<T> wbuf;
wbuf.reserve(buf.size());
for(int k = 0; k < buf.size(); k ++)
wbuf.emplace_back(buf[k]);
std::sort(wbuf.begin(), wbuf.end());
for(int k = 0; k < buf.size(); k ++)
buf[k] = wbuf[k];
}
work.emplace_back(buf);
}
edge.emplace_back(work.size());
}
auto whole_crush(crush<T>(work, cs, count == - 1 ? 0 : abs(count)));
vector<pair<vector<SimpleVector<T> >, vector<int> > > res;
res.reserve(whole_crush.size());
for(int i = 0; i < whole_crush.size(); i ++) {
vector<int> idx;
const auto& sec(whole_crush[i].second);
idx.reserve(sec.size());
for(int j = 0; j < sec.size(); j ++)
idx.emplace_back(sec[j] - *std::lower_bound(edge.begin(), edge.end(), sec[j]));
res.emplace_back(make_pair(move(whole_crush[i].first), move(idx)));
}
return res;
}
template <typename T> static inline vector<pair<vector<SimpleVector<T> >, vector<int> > > crushWithOrder(const vector<T>& v, const int& cs) {
return crushWithOrder<T>(v, cs, max(int(2), int(sqrt(T(v.size())))));
}
template <typename T, typename feeder> class P012L {
public:
typedef SimpleVector<T> Vec;
typedef SimpleMatrix<T> Mat;
inline P012L() { varlen = 0; }
inline P012L(const int& stat, const int& var, const int& step = 1) {
assert(0 < stat && 1 < var && 0 < step);
f = feeder(stat + (this->step = step) - 1 + (varlen = var) - 1);
}
inline ~P012L() { ; }
T next(const T& in);
feeder f;
private:
int varlen;
int step;
};
template <typename T, typename feeder> inline T P012L<T,feeder>::next(const T& in) {
static const T zero(int(0));
const auto d(f.next(in));
auto M(zero);
for(int i = 0; i < d.size(); i ++) {
if(! isfinite(d[i])) return zero;
M = max(M, abs(d[i]));
}
M *= T(int(2));
if(! f.full || M <= zero) return zero;
vector<SimpleVector<T> > cache;
cache.reserve(d.size() - varlen + 2);
for(int i = 0; i < d.size() - varlen - step + 2; i ++) {
cache.emplace_back(d.subVector(i, varlen) / M);
cache[cache.size() - 1][cache[cache.size() - 1].size() - 1] = d[i + varlen + step - 2] / M;
}
const auto cat(crush<T>(cache, cache[0].size(), cache[0].size()));
SimpleVector<T> work(varlen);
for(int i = 1; i < work.size(); i ++)
work[i - 1] = d[i - work.size() + d.size()] / M;
work[work.size() - 1] = zero;
const auto vdp(makeProgramInvariant<T>(work));
auto res(zero);
auto sscore(zero);
for(int i = 0; i < cat.size(); i ++) {
if(! cat[i].first.size()) continue;
Mat pw(cat[i].first.size(), cat[i].first[0].size() + 1);
Vec avg(Vec(pw.row(0) = makeProgramInvariant<T>(cat[i].first[0]).first));
for(int j = 1; j < pw.rows(); j ++)
avg += (pw.row(j) = makeProgramInvariant<T>(cat[i].first[j]).first);
avg /= T(int(pw.rows()));
const auto q(pw.rows() <= pw.cols() || ! pw.rows() ? Vec() : linearInvariant<T>(pw));
work[work.size() - 1] = q.size() ?
revertProgramInvariant<T>(make_pair(
- (q.dot(vdp.first) - q[varlen - 1] * vdp.first[varlen - 1])
/ q[varlen - 1], vdp.second) ) :
revertProgramInvariant<T>(make_pair(avg[varlen - 1], vdp.second));
T score(0);
for(int j = 0; j < work.size(); j ++)
score += work[j] * revertProgramInvariant<T>(make_pair(avg[j], vdp.second));
res += q.size() ? abs(score) * work[work.size() - 1] : score * work[work.size() - 1];
sscore += abs(score);
}
return res * M / sscore;
}
#define _CATG_
#endif
| 36.115942 | 151 | 0.593499 | [
"vector"
] |
68a6c3fc5ce015097d8515a680627a83add1d87b | 606 | cpp | C++ | algorithms/cpp/668.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | 3 | 2016-10-01T10:15:09.000Z | 2017-07-09T02:53:36.000Z | algorithms/cpp/668.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | algorithms/cpp/668.cpp | viing937/leetcode | e21ca52c98bddf59e43522c0aace5e8cf84350eb | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int findKthNumber(int m, int n, int k) {
int left = 1, right = m * n;
while (left < right) {
int mid = left + (right-left)/2;
int cnt = 0;
for (int i = 0; i < m; i++)
cnt += min(mid / (i+1), n);
if (cnt < k)
left = mid + 1;
else
right = mid;
}
return left;
}
};
int main() {
Solution solution;
solution.findKthNumber(2, 3, 6);
return 0;
}
| 20.896552 | 44 | 0.457096 | [
"vector"
] |
68ae6d799db81909e1da5bfffbce35c17f27abd7 | 438 | cpp | C++ | src/Box.cpp | perezite/o2-blocks-ng | 3165918b943fb73bbd1c456c95ba645b57965536 | [
"MIT"
] | null | null | null | src/Box.cpp | perezite/o2-blocks-ng | 3165918b943fb73bbd1c456c95ba645b57965536 | [
"MIT"
] | null | null | null | src/Box.cpp | perezite/o2-blocks-ng | 3165918b943fb73bbd1c456c95ba645b57965536 | [
"MIT"
] | null | null | null | #include "Box.h"
#include "Math.h"
#include <algorithm>
namespace sb
{
Vector2f Box::random() const
{
float x = sb::random(-_size.x / 2, _size.x / 2);
float y = sb::random(-_size.y / 2, _size.y / 2);
return Vector2f(x, y);
}
float Box::getBoundingRadius() const
{
float diameter = std::max(_size.x, _size.y);
return diameter / 2;
}
Shape * Box::clone() const
{
return new Box(*this);
}
}
| 17.52 | 51 | 0.579909 | [
"shape"
] |
68b6e488613db6d2a48763c4544f56765ab3ffda | 6,073 | cpp | C++ | src/selfie_perception/src/road_line.cpp | KNR-Selfie/selfie_carolocup2020 | 5d6331962e4752c9e9c4fcc88ebd3093e4d96b85 | [
"BSD-3-Clause"
] | 10 | 2019-08-17T14:50:13.000Z | 2021-07-19T17:21:13.000Z | src/selfie_perception/src/road_line.cpp | KNR-Selfie/selfie_carolocup2020 | 5d6331962e4752c9e9c4fcc88ebd3093e4d96b85 | [
"BSD-3-Clause"
] | 16 | 2019-05-27T18:50:09.000Z | 2020-02-11T00:23:50.000Z | src/selfie_perception/src/road_line.cpp | KNR-Selfie/selfie_carolocup2020 | 5d6331962e4752c9e9c4fcc88ebd3093e4d96b85 | [
"BSD-3-Clause"
] | 3 | 2020-01-21T15:03:24.000Z | 2021-05-02T06:40:50.000Z | #include <selfie_perception/road_line.h>
RoadLine::RoadLine()
{
// init straight line with 0.2 offset
coeff_.clear();
coeff_.push_back(0.2);
coeff_.push_back(0);
coeff_.push_back(0);
}
void RoadLine::pfSetup(int num_particles, int num_control_points, float std_min, float std_max)
{
pf_num_particles_ = num_particles;
pf_num_points_ = num_control_points;
pf_std_min_ = std_min;
pf_std_max_ = std_max;
pf_.setNumParticles(num_particles);
pf_.setNumPoints(num_control_points);
}
void RoadLine::pfInit()
{
if (!pf_.initialized() && exist_)
{
float poly_topview_x = TOPVIEW_MAX_X;
float p_top_y = getPolyY(coeff_, TOPVIEW_MAX_X);
if (p_top_y < TOPVIEW_MIN_Y || p_top_y > TOPVIEW_MAX_Y)
{
pf_.setPolyDegree_(2);
for (int i = 1; i < 20; ++i)
{
p_top_y = getPolyY(coeff_, TOPVIEW_MAX_X - 0.05 * i);
if (p_top_y > TOPVIEW_MIN_Y && p_top_y < TOPVIEW_MAX_Y)
{
poly_topview_x = TOPVIEW_MAX_X - 0.05 * i;
break;
}
}
}
float increment = (poly_topview_x - TOPVIEW_MIN_X) / (pf_num_points_ - 1);
std::vector<cv::Point2f> init_points;
for (int i = 0; i < pf_num_points_; ++i)
{
cv::Point2f p;
p.x = i * increment + TOPVIEW_MIN_X;
p.y = getPolyY(coeff_, p.x);
init_points.push_back(p);
}
pf_.init(init_points);
}
}
bool RoadLine::pfExecute()
{
if (!exist_)
return false;
if (!pf_.initialized())
{
pf_.reset();
pfInit();
}
pf_.prediction(pf_std_min_, pf_std_max_);
pf_.updateWeights(points_);
pf_.resample();
coeff_ = pf_.getBestCoeff();
degree_ = pf_.getBestDegree();
return true;
}
void RoadLine::pfReset()
{
pf_.reset();
}
void RoadLine::aprox()
{
if(!polyfit(points_, degree_, coeff_))
{
coeff_.clear();
coeff_.push_back(0.2);
coeff_.push_back(0);
coeff_.push_back(0);
}
}
int RoadLine::pointsSize()
{
if (points_.empty())
return 0;
return points_.size() - 1;
}
void RoadLine::calcParams()
{
if (!exist_)
{
points_.clear();
is_short_ = true;
length_ = 0;
return;
}
length_ = cv::arcLength(points_, false);
if (length_ > length_not_short_)
is_short_ = false;
else
is_short_ = true;
}
void RoadLine::addBottomPoint(bool force)
{
if (!exist_)
return;
if (force || points_[0].x < ((TOPVIEW_MIN_X + TOPVIEW_MAX_X) / 3))
{
cv::Point2f p;
p.x = TOPVIEW_MIN_X;
if (force)
{
p.y = points_[pointsSize()].y;
}
else
{
p.y = points_[0].y;
}
points_.insert(points_.begin(), p);
}
}
void RoadLine::generateForDensity()
{
if (!exist_)
{
return;
}
if (pointsSize() / length_ > points_density_ * 2)
{
return;
}
for (int i = 0; i < pointsSize(); ++i)
{
float distance = getDistance(points_[i], points_[i + 1]);
if (distance > 1 / points_density_)
{
int add = distance * points_density_;
cv::Point2f p;
float x1 = points_[i].x;
float y1 = points_[i].y;
float x_dif = (points_[i + 1].x - points_[i].x) / (add + 1);
float y_dif = (points_[i + 1].y - points_[i].y) / (add + 1);
for (int j = 0; j < add; ++j)
{
p.x = x1 + x_dif * (j + 1);
p.y = y1 + y_dif * (j + 1);
points_.insert(points_.begin() + i + 1, p);
++i;
}
}
}
}
float RoadLine::getDistance(cv::Point2f p1, cv::Point2f p2)
{
float dx = (p1.x - p2.x);
float dy = (p1.y - p2.y);
return sqrtf(dx * dx + dy * dy);
}
void RoadLine::reset()
{
exist_ = false;
degree_ = 2;
length_ = 0;
is_short_ = true;
points_.clear();
pf_.reset();
// init straight line with 0.2 offset
coeff_.clear();
coeff_.push_back(0.2);
coeff_.push_back(0);
coeff_.push_back(0);
}
void RoadLine::reduceTopPoints(float ratio)
{
if (points_.empty())
return;
int begin = points_.size() * (1 - ratio);
points_.erase(points_.begin() + begin, points_.end());
}
cv::Point2f RoadLine::getPointNextToBottom(float min_dist_to_bottom)
{
for(int i = 1; i < pointsSize(); ++i)
{
if (points_[i].x - points_[0].x > min_dist_to_bottom)
return points_[i];
}
return points_[pointsSize() - 1];
}
void RoadLine::reducePointsToStraight(int check_to_index)
{
if(pointsSize() == 0)
return;
points_.erase(points_.begin() + check_to_index, points_.end());
// generate for density
for (int i = 0; i < pointsSize(); ++i)
{
float distance = getDistance(points_[i], points_[i + 1]);
if (distance > 1 / 20)
{
int add = distance * 20;
cv::Point2f p;
float x1 = points_[i].x;
float y1 = points_[i].y;
float x_dif = (points_[i + 1].x - points_[i].x) / (add + 1);
float y_dif = (points_[i + 1].y - points_[i].y) / (add + 1);
for (int j = 0; j < add; ++j)
{
p.x = x1 + x_dif * (j + 1);
p.y = y1 + y_dif * (j + 1);
points_.insert(points_.begin() + i + 1, p);
++i;
}
}
}
float max = 0;
int index_max = -1;
float A = getA(points_[0], points_[pointsSize() - 1]);
float C = points_[0].y - (A * points_[0].x);
float sqrtf_m = sqrtf(A * A + 1);
for(int i = 2; i < pointsSize(); ++i)
{
float distance = std::abs(A * points_[i].x - points_[i].y + C) / sqrtf_m;
if(distance > max)
{
max = distance;
index_max = i;
}
}
if (max > 0.01 && index_max > 4)
{
points_.erase(points_.begin() + index_max, points_.end());
}
}
float RoadLine::getA(cv::Point2f p1, cv::Point2f p2)
{
return (p2.y - p1.y) / (p2.x - p1.x);
}
float RoadLine::getMaxDiffonX()
{
if(pointsSize() == 0)
return 0;
float dist = 0;
for(int i = 1; i < pointsSize(); ++i)
{
float dist_now = points_[i].x - points_[i - 1].x;
if (dist_now > dist)
{
dist = dist_now;
}
}
return dist;
}
int RoadLine::getIndexOnMerge()
{
for(int i = 1; i < pointsSize(); ++i)
{
float dist_now = points_[i].x - points_[i - 1].x;
if (dist_now > 0.3)
{
return i - 1;
}
}
return pointsSize();
}
| 20.243333 | 95 | 0.574675 | [
"vector"
] |
68bb9a56bcdf04db2d4b4617ed215353f236cb7c | 35,488 | cpp | C++ | src/BLR/BLRMatrixMPI.cpp | michaelneuder/STRUMPACK | 3fe3f3b5732943ed9761e787be4a25749d91db8b | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/BLR/BLRMatrixMPI.cpp | michaelneuder/STRUMPACK | 3fe3f3b5732943ed9761e787be4a25749d91db8b | [
"BSD-3-Clause-LBNL"
] | null | null | null | src/BLR/BLRMatrixMPI.cpp | michaelneuder/STRUMPACK | 3fe3f3b5732943ed9761e787be4a25749d91db8b | [
"BSD-3-Clause-LBNL"
] | null | null | null | /*
* STRUMPACK -- STRUctured Matrices PACKage, Copyright (c) 2014, The
* Regents of the University of California, through Lawrence Berkeley
* National Laboratory (subject to receipt of any required approvals
* from the U.S. Dept. of Energy). All rights reserved.
*
* If you have questions about your rights to use or distribute this
* software, please contact Berkeley Lab's Technology Transfer
* Department at TTD@lbl.gov.
*
* NOTICE. This software is owned by the U.S. Department of Energy. As
* such, the U.S. Government has been granted for itself and others
* acting on its behalf a paid-up, nonexclusive, irrevocable,
* worldwide license in the Software to reproduce, prepare derivative
* works, and perform publicly and display publicly. Beginning five
* (5) years after the date permission to assert copyright is obtained
* from the U.S. Department of Energy, and subject to any subsequent
* five (5) year renewals, the U.S. Government is granted for itself
* and others acting on its behalf a paid-up, nonexclusive,
* irrevocable, worldwide license in the Software to reproduce,
* prepare derivative works, distribute copies to the public, perform
* publicly and display publicly, and to permit others to do so.
*
* Developers: Pieter Ghysels, Francois-Henry Rouet, Xiaoye S. Li.
* (Lawrence Berkeley National Lab, Computational Research
* Division).
*
*/
#include <cassert>
#include <memory>
#include <functional>
#include <algorithm>
#include "BLRMatrixMPI.hpp"
#include "BLRTileBLAS.hpp"
#include "misc/Tools.hpp"
namespace strumpack {
namespace BLR {
ProcessorGrid2D::ProcessorGrid2D(const MPIComm& comm)
: ProcessorGrid2D(comm, comm.size()) {}
ProcessorGrid2D::ProcessorGrid2D(const MPIComm& comm, int P)
: comm_(comm) {
npcols_ = std::floor(std::sqrt((float)P));
nprows_ = P / npcols_;
if (comm_.is_null()) {
active_ = false;
return;
}
auto rank = comm_.rank();
active_ = rank < nprows_ * npcols_;
if (active_) {
prow_ = rank % nprows_;
pcol_ = rank / nprows_;
}
for (int i=0; i<nprows_; i++)
if (i == prow_) rowcomm_ = comm_.sub(i, npcols_, nprows_);
else comm_.sub(i, npcols_, nprows_);
for (int i=0; i<npcols_; i++)
if (i == pcol_) colcomm_ = comm_.sub(i*nprows_, nprows_, 1);
else comm_.sub(i*nprows_, nprows_, 1);
}
template<typename scalar_t> BLRMatrixMPI<scalar_t>::BLRMatrixMPI() {}
template<typename scalar_t> void
BLRMatrixMPI<scalar_t>::fill(scalar_t v) {
for (std::size_t i=0; i<brows_; i++)
for (std::size_t j=0; j<bcols_; j++)
if (grid_->is_local(i, j)) {
std::unique_ptr<DenseTile<scalar_t>> t
(new DenseTile<scalar_t>(tilerows(i), tilecols(j)));
t->D().fill(v);
block(i, j) = std::move(t);
}
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::memory() const {
std::size_t mem = 0;
for (auto& b : blocks_) mem += b->memory();
return mem;
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::nonzeros() const {
std::size_t nnz = 0;
for (auto& b : blocks_) nnz += b->nonzeros();
return nnz;
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::rank() const {
std::size_t mrank = 0;
for (auto& b : blocks_) mrank = std::max(mrank, b->maximum_rank());
return mrank;
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::total_memory() const {
return Comm().all_reduce(memory(), MPI_SUM);
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::total_nonzeros() const {
return Comm().all_reduce(nonzeros(), MPI_SUM);
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::max_rank() const {
return Comm().all_reduce(this->rank(), MPI_MAX);
}
template<typename scalar_t> void
BLRMatrixMPI<scalar_t>::print(const std::string& name) {
std::cout << "BLR(" << name << ")="
<< rows() << "x" << cols() << ", "
<< rowblocks() << "x" << colblocks() << ", "
<< (float(nonzeros()) / (rows()*cols()) * 100.) << "%"
<< " [" << std::endl;
for (std::size_t i=0; i<brows_; i++) {
for (std::size_t j=0; j<bcols_; j++) {
auto& tij = tile(i, j);
if (tij.is_low_rank())
std::cout << "LR:" << tij.rows() << "x"
<< tij.cols() << "/" << tij.rank() << " ";
else std::cout << "D:" << tij.rows() << "x" << tij.cols() << " ";
}
std::cout << std::endl;
}
std::cout << "];" << std::endl;
}
template<typename scalar_t> int
BLRMatrixMPI<scalar_t>::rg2p(std::size_t i) const {
return grid_->rg2p(rg2t(i));
}
template<typename scalar_t> int
BLRMatrixMPI<scalar_t>::cg2p(std::size_t j) const {
return grid_->cg2p(cg2t(j));
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::rg2t(std::size_t i) const {
return std::distance
(roff_.begin(), std::upper_bound(roff_.begin(), roff_.end(), i)) - 1;
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::cg2t(std::size_t j) const {
return std::distance
(coff_.begin(), std::upper_bound(coff_.begin(), coff_.end(), j)) - 1;
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::rl2g(std::size_t i) const {
assert(i < rl2g_.size());
assert(rl2g_.size() == std::size_t(lrows()));
return rl2g_[i];
}
template<typename scalar_t> std::size_t
BLRMatrixMPI<scalar_t>::cl2g(std::size_t j) const {
assert(j < cl2g_.size());
assert(cl2g_.size() == std::size_t(lcols()));
return cl2g_[j];
}
template<typename scalar_t> const scalar_t&
BLRMatrixMPI<scalar_t>::operator()(std::size_t i, std::size_t j) const {
return ltile_dense(rl2t_[i], cl2t_[j]).D()(rl2l_[i], cl2l_[j]);
}
template<typename scalar_t> scalar_t&
BLRMatrixMPI<scalar_t>::operator()(std::size_t i, std::size_t j) {
return ltile_dense(rl2t_[i], cl2t_[j]).D()(rl2l_[i], cl2l_[j]);
}
template<typename scalar_t> const scalar_t&
BLRMatrixMPI<scalar_t>::global(std::size_t i, std::size_t j) const {
std::size_t rt = rg2t(i), ct = cg2t(j);
return tile_dense(rt, ct).D()(i - roff_[rt], j - coff_[ct]);
}
template<typename scalar_t> scalar_t&
BLRMatrixMPI<scalar_t>::global(std::size_t i, std::size_t j) {
std::size_t rt = rg2t(i), ct = cg2t(j);
return tile_dense(rt, ct).D()(i - roff_[rt], j - coff_[ct]);
}
template<typename scalar_t> BLRMatrixMPI<scalar_t>::BLRMatrixMPI
(const ProcessorGrid2D& grid, const vec_t& Rt, const vec_t& Ct)
: grid_(&grid) {
brows_ = Rt.size();
bcols_ = Ct.size();
roff_.resize(brows_+1);
coff_.resize(bcols_+1);
std::partial_sum(Rt.begin(), Rt.end(), roff_.begin()+1);
std::partial_sum(Ct.begin(), Ct.end(), coff_.begin()+1);
rows_ = roff_.back();
cols_ = coff_.back();
if (grid_->active()) {
lbrows_ = brows_ / grid_->nprows() +
(grid_->prow() < int(brows_ % grid_->nprows()));
lbcols_ = bcols_ / grid_->npcols() +
(grid_->pcol() < int(bcols_ % grid_->npcols()));
blocks_.resize(lbrows_ * lbcols_);
}
lrows_ = lcols_ = 0;
for (std::size_t b=grid_->prow(); b<brows_; b+=grid_->nprows())
lrows_ += roff_[b+1] - roff_[b];
for (std::size_t b=grid_->pcol(); b<bcols_; b+=grid_->npcols())
lcols_ += coff_[b+1] - coff_[b];
rl2t_.resize(lrows_);
cl2t_.resize(lcols_);
rl2l_.resize(lrows_);
cl2l_.resize(lcols_);
rl2g_.resize(lrows_);
cl2g_.resize(lcols_);
for (std::size_t b=grid_->prow(), l=0, lb=0;
b<brows_; b+=grid_->nprows()) {
for (std::size_t i=0; i<roff_[b+1]-roff_[b]; i++) {
rl2t_[l] = lb;
rl2l_[l] = i;
rl2g_[l] = i + roff_[b];
l++;
}
lb++;
}
for (std::size_t b=grid_->pcol(), l=0, lb=0;
b<bcols_; b+=grid_->npcols()) {
for (std::size_t i=0; i<coff_[b+1]-coff_[b]; i++) {
cl2t_[l] = lb;
cl2l_[l] = i;
cl2g_[l] = i + coff_[b];
l++;
}
lb++;
}
}
template<typename scalar_t> DenseTile<scalar_t>
BLRMatrixMPI<scalar_t>::bcast_dense_tile_along_row
(std::size_t i, std::size_t j) const {
DenseTile<scalar_t> t(tilerows(i), tilecols(j));
int src = j % grid()->npcols();
auto& c = grid()->row_comm();
if (c.rank() == src) t = tile_dense(i, j);
c.broadcast_from(t.D().data(), t.rows()*t.cols(), src);
return t;
}
template<typename scalar_t> DenseTile<scalar_t>
BLRMatrixMPI<scalar_t>::bcast_dense_tile_along_col
(std::size_t i, std::size_t j) const {
DenseTile<scalar_t> t(tilerows(i), tilecols(j));
int src = i % grid()->nprows();
auto& c = grid()->col_comm();
if (c.rank() == src) t = tile_dense(i, j);
c.broadcast_from(t.D().data(), t.rows()*t.cols(), src);
return t;
}
template<typename scalar_t>
std::vector<std::unique_ptr<BLRTile<scalar_t>>>
BLRMatrixMPI<scalar_t>::bcast_row_of_tiles_along_cols
(std::size_t i, std::size_t j0, std::size_t j1) const {
int src = i % grid()->nprows();
std::size_t msg_size = 0, nr_tiles = 0;;
std::vector<std::int64_t> ranks;
if (grid()->is_local_row(i)) {
for (std::size_t j=j0; j<j1; j++)
if (grid()->is_local_col(j)) {
msg_size += tile(i, j).nonzeros();
ranks.push_back(tile(i, j).is_low_rank() ?
tile(i, j).rank() : -1);
}
} else {
for (std::size_t j=j0; j<j1; j++)
if (grid()->is_local_col(j))
nr_tiles++;
ranks.resize(nr_tiles);
}
std::vector<std::unique_ptr<BLRTile<scalar_t>>> Tij;
if (ranks.empty()) return Tij;
ranks.push_back(msg_size);
grid()->col_comm().broadcast_from(ranks, src);
msg_size = ranks.back();
std::vector<scalar_t> buf(msg_size);
auto ptr = buf.data();
if (grid()->is_local_row(i)) {
for (std::size_t j=j0; j<j1; j++)
if (grid()->is_local_col(j)) {
auto& t = tile(i, j);
if (tile(i, j).is_low_rank()) {
std::copy(t.U().data(), t.U().end(), ptr);
ptr += t.U().rows()*t.U().cols();
std::copy(t.V().data(), t.V().end(), ptr);
ptr += t.V().rows()*t.V().cols();
} else {
std::copy(t.D().data(), t.D().end(), ptr);
ptr += t.D().rows()*t.D().cols();
}
}
}
grid()->col_comm().broadcast_from(buf, src);
Tij.reserve(nr_tiles);
ptr = buf.data();
auto m = tilerows(i);
for (std::size_t j=j0; j<j1; j++)
if (grid()->is_local_col(j)) {
auto r = ranks[Tij.size()];
auto n = tilecols(j);
if (r != -1) {
auto t = new LRTile<scalar_t>(m, n, r);
std::copy(ptr, ptr+m*r, t->U().data()); ptr += m*r;
std::copy(ptr, ptr+r*n, t->V().data()); ptr += r*n;
Tij.emplace_back(t);
} else {
auto t = new DenseTile<scalar_t>(m, n);
std::copy(ptr, ptr+m*n, t->D().data()); ptr += m*n;
Tij.emplace_back(t);
}
}
return Tij;
}
template<typename scalar_t>
std::vector<std::unique_ptr<BLRTile<scalar_t>>>
BLRMatrixMPI<scalar_t>::bcast_col_of_tiles_along_rows
(std::size_t i0, std::size_t i1, std::size_t j) const {
int src = j % grid()->npcols();
std::size_t msg_size = 0, nr_tiles = 0;;
std::vector<std::int64_t> ranks;
if (grid()->is_local_col(j)) {
for (std::size_t i=i0; i<i1; i++)
if (grid()->is_local_row(i)) {
msg_size += tile(i, j).nonzeros();
ranks.push_back(tile(i, j).is_low_rank() ?
tile(i, j).rank() : -1);
}
} else {
for (std::size_t i=i0; i<i1; i++)
if (grid()->is_local_row(i))
nr_tiles++;
ranks.resize(nr_tiles);
}
std::vector<std::unique_ptr<BLRTile<scalar_t>>> Tij;
if (ranks.empty()) return Tij;
ranks.push_back(msg_size);
grid()->row_comm().broadcast_from(ranks, src);
msg_size = ranks.back();
std::vector<scalar_t> buf(msg_size);
auto ptr = buf.data();
if (grid()->is_local_col(j)) {
for (std::size_t i=i0; i<i1; i++)
if (grid()->is_local_row(i)) {
auto& t = tile(i, j);
if (tile(i, j).is_low_rank()) {
std::copy(t.U().data(), t.U().end(), ptr);
ptr += t.U().rows()*t.U().cols();
std::copy(t.V().data(), t.V().end(), ptr);
ptr += t.V().rows()*t.V().cols();
} else {
std::copy(t.D().data(), t.D().end(), ptr);
ptr += t.D().rows()*t.D().cols();
}
}
}
grid()->row_comm().broadcast_from(buf, src);
Tij.reserve(nr_tiles);
ptr = buf.data();
auto n = tilecols(j);
for (std::size_t i=i0; i<i1; i++)
if (grid()->is_local_row(i)) {
auto r = ranks[Tij.size()];
auto m = tilerows(i);
if (r != -1) {
auto t = new LRTile<scalar_t>(m, n, r);
std::copy(ptr, ptr+m*r, t->U().data()); ptr += m*r;
std::copy(ptr, ptr+r*n, t->V().data()); ptr += r*n;
Tij.emplace_back(t);
} else {
auto t = new DenseTile<scalar_t>(m, n);
std::copy(ptr, ptr+m*n, t->D().data()); ptr += m*n;
Tij.emplace_back(t);
}
}
return Tij;
}
template<typename scalar_t> void
BLRMatrixMPI<scalar_t>::compress_tile
(std::size_t i, std::size_t j, const Opts_t& opts) {
auto t = tile(i, j).compress(opts);
if (t->rank()*(t->rows() + t->cols()) < t->rows()*t->cols())
block(i, j) = std::move(t);
}
template<typename scalar_t> std::vector<int>
BLRMatrixMPI<scalar_t>::factor(const Opts_t& opts) {
adm_t adm(rowblocks(), colblocks());
adm.fill(true);
return factor(adm, opts);
}
template<typename scalar_t> std::vector<int>
BLRMatrixMPI<scalar_t>::factor(const adm_t& adm, const Opts_t& opts) {
std::vector<int> piv, piv_tile;
if (!grid()->active()) return piv;
DenseTile<scalar_t> Tii;
for (std::size_t i=0; i<rowblocks(); i++) {
if (grid()->is_local_row(i)) {
// LU factorization of diagonal tile
if (grid()->is_local_col(i))
piv_tile = tile(i, i).LU();
else piv_tile.resize(tilerows(i));
grid()->row_comm().broadcast_from(piv_tile, i % grid()->npcols());
int r0 = tileroff(i);
std::transform
(piv_tile.begin(), piv_tile.end(), std::back_inserter(piv),
[r0](int p) -> int { return p + r0; });
Tii = bcast_dense_tile_along_row(i, i);
}
if (grid()->is_local_col(i))
Tii = bcast_dense_tile_along_col(i, i);
if (grid()->is_local_row(i)) {
for (std::size_t j=i+1; j<colblocks(); j++) {
if (grid()->is_local_col(j)) {
if (adm(i, j)) compress_tile(i, j, opts);
tile(i, j).laswp(piv_tile, true);
trsm(Side::L, UpLo::L, Trans::N, Diag::U,
scalar_t(1.), Tii, tile(i, j));
}
}
}
if (grid()->is_local_col(i)) {
for (std::size_t j=i+1; j<rowblocks(); j++) {
if (grid()->is_local_row(j)) {
if (adm(j, i)) compress_tile(j, i, opts);
trsm(Side::R, UpLo::U, Trans::N, Diag::N,
scalar_t(1.), Tii, tile(j, i));
}
}
}
auto Tij = bcast_row_of_tiles_along_cols(i, i+1, rowblocks());
auto Tki = bcast_col_of_tiles_along_rows(i+1, rowblocks(), i);
for (std::size_t k=i+1, lk=0; k<rowblocks(); k++) {
if (grid()->is_local_row(k)) {
for (std::size_t j=i+1, lj=0; j<colblocks(); j++) {
if (grid()->is_local_col(j)) {
// this uses .D, assuming tile(k, j) is dense
gemm(Trans::N, Trans::N, scalar_t(-1.), *(Tki[lk]),
*(Tij[lj]), scalar_t(1.), tile_dense(k, j).D());
lj++;
}
}
lk++;
}
}
}
return piv;
}
template<typename scalar_t> std::vector<int>
BLRMatrixMPI<scalar_t>::partial_factor(BLRMPI_t& A11, BLRMPI_t& A12,
BLRMPI_t& A21, BLRMPI_t& A22,
const adm_t& adm,
const Opts_t& opts) {
assert(A11.rows() == A12.rows() && A11.cols() == A21.cols() &&
A21.rows() == A22.rows() && A12.cols() == A22.cols());
assert(A11.grid() == A12.grid() && A11.grid() == A21.grid() &&
A11.grid() == A22.grid());
auto B1 = A11.rowblocks();
auto B2 = A22.rowblocks();
auto g = A11.grid();
std::vector<int> piv, piv_tile;
if (!g->active()) return piv;
DenseTile<scalar_t> Tii;
for (std::size_t i=0; i<B1; i++) {
if (g->is_local_row(i)) {
// LU factorization of diagonal tile
if (g->is_local_col(i))
piv_tile = A11.tile(i, i).LU();
else piv_tile.resize(A11.tilerows(i));
g->row_comm().broadcast_from(piv_tile, i % g->npcols());
int r0 = A11.tileroff(i);
std::transform
(piv_tile.begin(), piv_tile.end(), std::back_inserter(piv),
[r0](int p) -> int { return p + r0; });
Tii = A11.bcast_dense_tile_along_row(i, i);
}
if (g->is_local_col(i))
Tii = A11.bcast_dense_tile_along_col(i, i);
if (g->is_local_row(i)) {
// update trailing columns of A11
for (std::size_t j=i+1; j<B1; j++) {
if (g->is_local_col(j)) {
if (adm(i, j)) A11.compress_tile(i, j, opts);
// apply pivots, solve with L
A11.tile(i, j).laswp(piv_tile, true);
trsm(Side::L, UpLo::L, Trans::N, Diag::U,
scalar_t(1.), Tii, A11.tile(i, j));
}
}
// update trailing columns of A12
for (std::size_t j=0; j<B2; j++) {
if (g->is_local_col(j)) {
A12.compress_tile(i, j, opts);
A12.tile(i, j).laswp(piv_tile, true);
trsm(Side::L, UpLo::L, Trans::N, Diag::U,
scalar_t(1.), Tii, A12.tile(i, j));
}
}
}
if (g->is_local_col(i)) {
// update trailing rows of A11
for (std::size_t j=i+1; j<B1; j++) {
if (g->is_local_row(j)) {
if (adm(j, i)) A11.compress_tile(j, i, opts);
trsm(Side::R, UpLo::U, Trans::N, Diag::N,
scalar_t(1.), Tii, A11.tile(j, i));
}
}
// update trailing rows of A21
for (std::size_t j=0; j<B2; j++) {
if (g->is_local_row(j)) {
A21.compress_tile(j, i, opts);
trsm(Side::R, UpLo::U, Trans::N, Diag::N,
scalar_t(1.), Tii, A21.tile(j, i));
}
}
}
auto Tij = A11.bcast_row_of_tiles_along_cols(i, i+1, B1);
auto Tij2 = A12.bcast_row_of_tiles_along_cols(i, 0, B2);
auto Tki = A11.bcast_col_of_tiles_along_rows(i+1, B1, i);
auto Tk2i = A21.bcast_col_of_tiles_along_rows(0, B2, i);
for (std::size_t k=i+1, lk=0; k<B1; k++) {
if (g->is_local_row(k)) {
for (std::size_t j=i+1, lj=0; j<B1; j++) {
if (g->is_local_col(j)) {
gemm(Trans::N, Trans::N, scalar_t(-1.),
*(Tki[lk]), *(Tij[lj]), scalar_t(1.),
A11.tile_dense(k, j).D());
lj++;
}
}
lk++;
}
}
for (std::size_t k=0, lk=0; k<B2; k++) {
if (g->is_local_row(k)) {
for (std::size_t j=i+1, lj=0; j<B1; j++) {
if (g->is_local_col(j)) {
gemm(Trans::N, Trans::N, scalar_t(-1.),
*(Tk2i[lk]), *(Tij[lj]), scalar_t(1.),
A21.tile_dense(k, j).D());
lj++;
}
}
lk++;
}
}
for (std::size_t k=i+1, lk=0; k<B1; k++) {
if (g->is_local_row(k)) {
for (std::size_t j=0, lj=0; j<B2; j++) {
if (g->is_local_col(j)) {
gemm(Trans::N, Trans::N, scalar_t(-1.),
*(Tki[lk]), *(Tij2[lj]), scalar_t(1.),
A12.tile_dense(k, j).D());
lj++;
}
}
lk++;
}
}
for (std::size_t k=0, lk=0; k<B2; k++) {
if (g->is_local_row(k)) {
for (std::size_t j=0, lj=0; j<B2; j++) {
if (g->is_local_col(j)) {
gemm(Trans::N, Trans::N, scalar_t(-1.),
*(Tk2i[lk]), *(Tij2[lj]), scalar_t(1.),
A22.tile_dense(k, j).D());
lj++;
}
}
lk++;
}
}
}
return piv;
}
template<typename scalar_t> void
BLRMatrixMPI<scalar_t>::laswp(const std::vector<int>& piv, bool fwd) {
if (!fwd) {
std::cerr << "BLRMPI::laswp not implemented for fwd == false"
<< std::endl;
abort();
}
auto p = piv.data();
for (std::size_t i=0; i<rowblocks(); i++)
if (grid()->is_local_row(i)) {
std::vector<int> tpiv;
auto r0 = tileroff(i);
std::transform
(p, p+tilerows(i), std::back_inserter(tpiv),
[r0](int pi) -> int { return pi - r0; });
for (std::size_t j=0; j<colblocks(); j++)
if (grid()->is_local_col(j))
tile(i, j).laswp(tpiv, true);
p += tilerows(i);
}
}
template<typename scalar_t> void
BLRMatrixMPI<scalar_t>::compress(const Opts_t& opts) {
for (auto& b : blocks_) {
if (b->is_low_rank()) continue;
auto t = b->compress(opts);
if (t->rank()*(t->rows() + t->cols()) < t->rows()*t->cols())
b = std::move(t);
}
}
template<typename scalar_t> BLRMatrixMPI<scalar_t>
BLRMatrixMPI<scalar_t>::from_ScaLAPACK
(const DistM_t& A, const ProcessorGrid2D& g, const Opts_t& opts) {
auto l = opts.leaf_size();
std::size_t
nrt = std::max(1, int(std::ceil(float(A.rows()) / l))),
nct = std::max(1, int(std::ceil(float(A.cols()) / l)));
vec_t Rt(nrt, l), Ct(nct, l);
Rt.back() = A.rows() - (nrt-1) * l;
Ct.back() = A.cols() - (nct-1) * l;
return from_ScaLAPACK(A, g, Rt, Ct);
}
#if 1
template<typename scalar_t> BLRMatrixMPI<scalar_t>
BLRMatrixMPI<scalar_t>::from_ScaLAPACK
(const DistM_t& A, const ProcessorGrid2D& g,
const vec_t& Rt, const vec_t& Ct) {
BLRMPI_t B(g, Rt, Ct);
auto P = B.Comm().size();
std::vector<std::vector<scalar_t>> sbuf(P);
if (A.active()) {
assert(A.fixed());
const auto lm = A.lrows();
const auto ln = A.lcols();
const auto nprows = A.nprows();
std::unique_ptr<int[]> work(new int[lm+ln]);
auto pr = work.get();
auto pc = pr + lm;
for (int r=0; r<lm; r++)
pr[r] = B.rg2p(A.rowl2g_fixed(r));
for (int c=0; c<ln; c++)
pc[c] = B.cg2p(A.coll2g_fixed(c)) * nprows;
{ // reserve space for the send buffers
std::vector<std::size_t> cnt(sbuf.size());
for (int c=0; c<ln; c++)
for (int r=0, pcc=pc[c]; r<lm; r++)
cnt[pr[r]+pcc]++;
for (std::size_t p=0; p<sbuf.size(); p++)
sbuf[p].reserve(cnt[p]);
}
for (int c=0; c<ln; c++)
for (int r=0, pcc=pc[c]; r<lm; r++)
sbuf[pr[r]+pcc].push_back(A(r,c));
}
std::vector<scalar_t,NoInit<scalar_t>> rbuf;
std::vector<scalar_t*> pbuf;
B.Comm().all_to_all_v(sbuf, rbuf, pbuf);
B.fill(0.);
if (B.active()) {
const auto lm = B.lrows();
const auto ln = B.lcols();
const auto nprows = A.nprows();
std::unique_ptr<int[]> work(new int[lm+ln]);
auto pr = work.get();
auto pc = pr + lm;
for (std::size_t r=0; r<lm; r++)
pr[r] = A.rowg2p(B.rl2g(r));
for (std::size_t c=0; c<ln; c++)
pc[c] = A.colg2p(B.cl2g(c)) * nprows;
for (std::size_t c=0; c<ln; c++)
for (std::size_t r=0, pcc=pc[c]; r<lm; r++)
B(r, c) = *(pbuf[pr[r]+pcc]++);
}
return B;
}
#else
template<typename scalar_t> BLRMatrixMPI<scalar_t>
BLRMatrixMPI<scalar_t>::from_ScaLAPACK
(const DistM_t& A, const ProcessorGrid2D& g,
const vec_t& Rt, const vec_t& Ct) {
BLRMPI_t B(g, Rt, Ct);
for (std::size_t j=0; j<B.colblocks(); j++)
for (std::size_t i=0; i<B.rowblocks(); i++) {
int dest = g.g2p(i, j);
if (g.is_local(i, j)) {
auto t = std::unique_ptr<DenseTile<scalar_t>>
(new DenseTile<scalar_t>(B.tilerows(i), B.tilecols(j)));
copy(B.tilerows(i), B.tilecols(j), A,
B.tileroff(i), B.tilecoff(j), t->D(), dest, A.ctxt_all());
B.block(i, j) = std::move(t);
} else {
DenseM_t dummy;
copy(B.tilerows(i), B.tilecols(j), A,
B.tileroff(i), B.tilecoff(j), dummy, dest, A.ctxt_all());
}
}
return B;
}
#endif
template<typename scalar_t> DistributedMatrix<scalar_t>
BLRMatrixMPI<scalar_t>::to_ScaLAPACK(const BLACSGrid* g) const {
DistM_t A(g, rows(), cols());
to_ScaLAPACK(A);
return A;
}
#if 1
template<typename scalar_t> void
BLRMatrixMPI<scalar_t>::to_ScaLAPACK(DistM_t& A) const {
if (A.rows() != int(rows()) || A.cols() != int(cols()))
A.resize(rows(), cols());
int P = A.Comm().size();
std::vector<std::vector<scalar_t>> sbuf(P);
if (active()) {
assert(A.fixed());
const auto lm = lrows();
const auto ln = lcols();
const auto nprows = A.nprows();
std::unique_ptr<int[]> work(new int[lm+ln]);
auto pr = work.get();
auto pc = pr + lm;
for (std::size_t r=0; r<lm; r++)
pr[r] = A.rowg2p_fixed(rl2g(r));
for (std::size_t c=0; c<ln; c++)
pc[c] = A.colg2p_fixed(cl2g(c)) * nprows;
{ // reserve space for the send buffers
std::vector<std::size_t> cnt(sbuf.size());
for (std::size_t c=0; c<ln; c++)
for (std::size_t r=0, pcc=pc[c]; r<lm; r++)
cnt[pr[r]+pcc]++;
for (std::size_t p=0; p<sbuf.size(); p++)
sbuf[p].reserve(cnt[p]);
}
for (std::size_t c=0; c<ln; c++)
for (std::size_t r=0, pcc=pc[c]; r<lm; r++)
sbuf[pr[r]+pcc].push_back(this->operator()(r,c));
}
std::vector<scalar_t,NoInit<scalar_t>> rbuf;
std::vector<scalar_t*> pbuf;
A.Comm().all_to_all_v(sbuf, rbuf, pbuf);
if (A.active()) {
const auto lm = A.lrows();
const auto ln = A.lcols();
const auto nprows = A.nprows();
std::unique_ptr<int[]> work(new int[lm+ln]);
auto pr = work.get();
auto pc = pr + lm;
for (int r=0; r<lm; r++)
pr[r] = rg2p(A.rowl2g_fixed(r));
for (int c=0; c<ln; c++)
pc[c] = cg2p(A.coll2g_fixed(c)) * nprows;
for (int c=0; c<ln; c++)
for (int r=0, pcc=pc[c]; r<lm; r++)
A(r,c) = *(pbuf[pr[r]+pcc]++);
}
}
#else
template<typename scalar_t> void
BLRMatrixMPI<scalar_t>::to_ScaLAPACK
(DistributedMatrix<scalar_t>& A) const {
if (A.rows() != int(rows()) || A.cols() != int(cols()))
A.resize(rows(), cols());
DenseM_t B;
for (std::size_t j=0; j<colblocks(); j++)
for (std::size_t i=0; i<rowblocks(); i++) {
if (grid()->is_local(i, j))
B = block(i, j)->dense();
copy(tilerows(i), tilecols(j), B, grid()->g2p(i, j),
A, tileroff(i), tilecoff(j), A.ctxt_all());
}
}
#endif
// explicit template instantiations
template class BLRMatrixMPI<float>;
template class BLRMatrixMPI<double>;
template class BLRMatrixMPI<std::complex<float>>;
template class BLRMatrixMPI<std::complex<double>>;
template<typename scalar_t> void
trsv(UpLo ul, Trans ta, Diag d, const BLRMatrixMPI<scalar_t>& a,
BLRMatrixMPI<scalar_t>& b) {
// std::cout << "TODO trsv" << std::endl;
trsm(Side::L, ul, ta, d, scalar_t(1.), a, b);
}
template<typename scalar_t> void
gemv(Trans ta, scalar_t alpha, const BLRMatrixMPI<scalar_t>& a,
const BLRMatrixMPI<scalar_t>& x, scalar_t beta,
BLRMatrixMPI<scalar_t>& y) {
// std::cout << "TODO gemv" << std::endl;
gemm(ta, Trans::N, alpha, a, x, beta, y);
}
template<typename scalar_t> void
trsm(Side s, UpLo ul, Trans ta, Diag d,
scalar_t alpha, const BLRMatrixMPI<scalar_t>& a,
BLRMatrixMPI<scalar_t>& b) {
if (!a.active()) return;
if (s != Side::L) {
std::cerr << "trsm BLRMPI operation not implemented" << std::endl;
abort();
}
assert(a.rows() == a.cols() && a.cols() == b.rows());
if (ul == UpLo::L) {
for (std::size_t i=0; i<a.rowblocks(); i++) {
if (a.grid()->is_local_row(i)) {
auto Aii = a.bcast_dense_tile_along_row(i, i);
for (std::size_t k=0; k<b.colblocks(); k++)
if (b.grid()->is_local_col(k))
trsm(s, ul, ta, d, alpha, Aii, b.tile(i, k));
}
auto Aji = a.bcast_col_of_tiles_along_rows(i+1, a.rowblocks(), i);
auto Bik = b.bcast_row_of_tiles_along_cols(i, 0, b.colblocks());
for (std::size_t j=i+1, lj=0; j<a.rowblocks(); j++) {
if (b.grid()->is_local_row(j)) {
for (std::size_t k=0, lk=0; k<b.colblocks(); k++) {
if (b.grid()->is_local_col(k)) {
gemm(Trans::N, Trans::N, scalar_t(-1.),
*(Aji[lj]), *(Bik[lk]), alpha, b.tile_dense(j, k).D());
lk++;
}
}
lj++;
}
}
}
} else { // ul == UpLo::U
for (int i=a.rowblocks()-1; i>=0; i--) {
if (a.grid()->is_local_row(i)) {
auto Aii = a.bcast_dense_tile_along_row(i, i);
for (std::size_t k=0; k<b.colblocks(); k++)
if (b.grid()->is_local_col(k))
trsm(s, ul, ta, d, alpha, Aii, b.tile(i, k));
}
auto Aji = a.bcast_col_of_tiles_along_rows(0, i, i);
auto Bik = b.bcast_row_of_tiles_along_cols(i, 0, b.colblocks());
for (int j=0, lj=0; j<i; j++) {
if (b.grid()->is_local_row(j)) {
for (std::size_t k=0, lk=0; k<b.colblocks(); k++) {
if (b.grid()->is_local_col(k)) {
gemm(Trans::N, Trans::N, scalar_t(-1.),
*(Aji[lj]), *(Bik[lk]), alpha, b.tile_dense(j, k).D());
lk++;
}
}
lj++;
}
}
}
}
}
template<typename scalar_t> void
gemm(Trans ta, Trans tb, scalar_t alpha, const BLRMatrixMPI<scalar_t>& a,
const BLRMatrixMPI<scalar_t>& b, scalar_t beta,
BLRMatrixMPI<scalar_t>& c) {
if (!a.active()) return;
if (ta != Trans::N || tb != Trans::N) {
std::cerr << "gemm BLRMPI operations not implemented" << std::endl;
abort();
}
assert(a.rows() == c.rows() && a.cols() == b.rows() &&
b.cols() == c.cols());
for (std::size_t k=0; k<a.colblocks(); k++) {
auto Aik = a.bcast_col_of_tiles_along_rows(0, a.rowblocks(), k);
auto Bkj = b.bcast_row_of_tiles_along_cols(k, 0, b.colblocks());
for (std::size_t j=0, lj=0; j<c.colblocks(); j++) {
if (c.grid()->is_local_col(j)) {
for (std::size_t i=0, li=0; i<c.rowblocks(); i++) {
if (c.grid()->is_local_row(i)) {
gemm(ta, tb, alpha, *(Aik[li]), *(Bkj[lj]),
beta, c.tile_dense(i, j).D());
li++;
}
}
lj++;
}
}
}
}
template void trsv(UpLo, Trans, Diag, const BLRMatrixMPI<float>&, BLRMatrixMPI<float>&);
template void trsv(UpLo, Trans, Diag, const BLRMatrixMPI<double>&, BLRMatrixMPI<double>&);
template void trsv(UpLo, Trans, Diag, const BLRMatrixMPI<std::complex<float>>&, BLRMatrixMPI<std::complex<float>>&);
template void trsv(UpLo, Trans, Diag, const BLRMatrixMPI<std::complex<double>>&, BLRMatrixMPI<std::complex<double>>&);
template void gemv(Trans, float, const BLRMatrixMPI<float>&, const BLRMatrixMPI<float>&, float, BLRMatrixMPI<float>&);
template void gemv(Trans, double, const BLRMatrixMPI<double>&, const BLRMatrixMPI<double>&, double, BLRMatrixMPI<double>&);
template void gemv(Trans, std::complex<float>, const BLRMatrixMPI<std::complex<float>>&, const BLRMatrixMPI<std::complex<float>>&, std::complex<float>, BLRMatrixMPI<std::complex<float>>&);
template void gemv(Trans, std::complex<double>, const BLRMatrixMPI<std::complex<double>>&, const BLRMatrixMPI<std::complex<double>>&, std::complex<double>, BLRMatrixMPI<std::complex<double>>&);
template void trsm(Side, UpLo, Trans, Diag, float, const BLRMatrixMPI<float>&, BLRMatrixMPI<float>&);
template void trsm(Side, UpLo, Trans, Diag, double, const BLRMatrixMPI<double>&, BLRMatrixMPI<double>&);
template void trsm(Side, UpLo, Trans, Diag, std::complex<float>, const BLRMatrixMPI<std::complex<float>>&, BLRMatrixMPI<std::complex<float>>&);
template void trsm(Side, UpLo, Trans, Diag, std::complex<double>, const BLRMatrixMPI<std::complex<double>>&, BLRMatrixMPI<std::complex<double>>&);
template void gemm(Trans, Trans, float, const BLRMatrixMPI<float>&, const BLRMatrixMPI<float>&, float, BLRMatrixMPI<float>&);
template void gemm(Trans, Trans, double, const BLRMatrixMPI<double>&, const BLRMatrixMPI<double>&, double, BLRMatrixMPI<double>&);
template void gemm(Trans, Trans, std::complex<float>, const BLRMatrixMPI<std::complex<float>>&, const BLRMatrixMPI<std::complex<float>>&, std::complex<float>, BLRMatrixMPI<std::complex<float>>&);
template void gemm(Trans, Trans, std::complex<double>, const BLRMatrixMPI<std::complex<double>>&, const BLRMatrixMPI<std::complex<double>>&, std::complex<double>, BLRMatrixMPI<std::complex<double>>&);
} // end namespace BLR
} // end namespace strumpack
| 38.53203 | 204 | 0.520739 | [
"vector",
"transform"
] |
68cba301e290d6ea33933e03f0ea98aab60f539d | 216 | cpp | C++ | Core/ScriptManager.cpp | anonymousthing/Sulphur | 65820d66ab8dd736e5ce64901177dbdf2ef48100 | [
"Unlicense"
] | null | null | null | Core/ScriptManager.cpp | anonymousthing/Sulphur | 65820d66ab8dd736e5ce64901177dbdf2ef48100 | [
"Unlicense"
] | null | null | null | Core/ScriptManager.cpp | anonymousthing/Sulphur | 65820d66ab8dd736e5ce64901177dbdf2ef48100 | [
"Unlicense"
] | null | null | null | #include "ScriptManager.h"
#include "ScriptLoader.h"
ScriptManager::ScriptManager(Game *game) : game(game) {
}
void ScriptManager::loadScripts() {
std::vector<Script *> scripts = ScriptLoader::loadScripts();
}
| 16.615385 | 61 | 0.722222 | [
"vector"
] |
68cd9265d24b7b5a938afde1f581bee63c37802d | 2,440 | cpp | C++ | api_cpp/examples/000-Getting_started/01-api_creation.cpp | NihonBinary/kortex | 9f3cceaae38cb67a748898d4f709fe4d1f420ba9 | [
"BSD-3-Clause"
] | null | null | null | api_cpp/examples/000-Getting_started/01-api_creation.cpp | NihonBinary/kortex | 9f3cceaae38cb67a748898d4f709fe4d1f420ba9 | [
"BSD-3-Clause"
] | null | null | null | api_cpp/examples/000-Getting_started/01-api_creation.cpp | NihonBinary/kortex | 9f3cceaae38cb67a748898d4f709fe4d1f420ba9 | [
"BSD-3-Clause"
] | null | null | null | /*
* KINOVA (R) KORTEX (TM)
*
* Copyright (c) 2018 Kinova inc. All rights reserved.
*
* This software may be modified and distributed
* under the terms of the BSD 3-Clause license.
*
* Refer to the LICENSE file for details.
*
*/
#include <SessionManager.h>
#include <DeviceConfigClientRpc.h>
#include <BaseClientRpc.h>
#include <RouterClient.h>
#include <TransportClientTcp.h>
namespace k_api = Kinova::Api;
#define IP_ADDRESS "192.168.1.10"
#define PORT 10000
void example_api_creation()
{
// -----------------------------------------------------------
// How to create an API with the SessionManager, DeviceConfigClient and BaseClient services
auto error_callback = [](k_api::KError err){ cout << "_________ callback error _________" << err.toString(); };
auto transport = new k_api::TransportClientTcp();
auto router = new k_api::RouterClient(transport, error_callback);
transport->connect(IP_ADDRESS, PORT);
// Set session data connection information
auto create_session_info = k_api::Session::CreateSessionInfo();
create_session_info.set_username("admin");
create_session_info.set_password("admin");
create_session_info.set_session_inactivity_timeout(60000); // (milliseconds)
create_session_info.set_connection_inactivity_timeout(2000); // (milliseconds)
// Session manager service wrapper
std::cout << "Creating session for communication" << std::endl;
auto session_manager = new k_api::SessionManager(router);
session_manager->CreateSession(create_session_info);
std::cout << "Session created" << std::endl;
// Create DeviceConfigClient and BaseClient
auto device_config = new k_api::DeviceConfig::DeviceConfigClient(router);
auto base = new k_api::Base::BaseClient(router);
// -----------------------------------------------------------
// Now you're ready to use the API
// ...
// -----------------------------------------------------------
// After you're done, here's how to tear down the API
// Close API session
session_manager->CloseSession();
// Deactivate the router and cleanly disconnect from the transport object
router->SetActivationStatus(false);
transport->disconnect();
// Destroy the API
delete base;
delete device_config;
delete session_manager;
delete router;
delete transport;
}
int main(int argc, char **argv)
{
example_api_creation();
} | 32.105263 | 115 | 0.659426 | [
"object"
] |
68e9c78356fd25cb42b207aeca639c92206b1259 | 2,612 | hpp | C++ | plugins/community/repos/Bogaudio/src/DADSRHPlus.hpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 233 | 2018-07-02T16:49:36.000Z | 2022-02-27T21:45:39.000Z | plugins/community/repos/Bogaudio/src/DADSRHPlus.hpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-09T11:32:15.000Z | 2022-01-07T01:45:43.000Z | plugins/community/repos/Bogaudio/src/DADSRHPlus.hpp | guillaume-plantevin/VeeSeeVSTRack | 76fafc8e721613669d6f5ae82a0f58ce923a91e1 | [
"Zlib",
"BSD-3-Clause"
] | 24 | 2018-07-14T21:55:30.000Z | 2021-05-04T04:20:34.000Z | #pragma once
#include "bogaudio.hpp"
#include "dadsrh_core.hpp"
extern Model* modelDADSRHPlus;
namespace bogaudio {
struct DADSRHPlus : TriggerOnLoadModule {
enum ParamsIds {
DELAY_PARAM,
ATTACK_PARAM,
DECAY_PARAM,
SUSTAIN_PARAM,
RELEASE_PARAM,
HOLD_PARAM,
ATTACK_SHAPE_PARAM,
DECAY_SHAPE_PARAM,
RELEASE_SHAPE_PARAM,
TRIGGER_PARAM,
MODE_PARAM,
LOOP_PARAM,
SPEED_PARAM,
RETRIGGER_PARAM,
NUM_PARAMS
};
enum InputsIds {
DELAY_INPUT,
ATTACK_INPUT,
DECAY_INPUT,
SUSTAIN_INPUT,
RELEASE_INPUT,
HOLD_INPUT,
TRIGGER_INPUT,
NUM_INPUTS
};
enum OutputsIds {
DELAY_OUTPUT,
ATTACK_OUTPUT,
DECAY_OUTPUT,
SUSTAIN_OUTPUT,
RELEASE_OUTPUT,
ENV_OUTPUT,
INV_OUTPUT,
TRIGGER_OUTPUT,
NUM_OUTPUTS
};
enum LightsIds {
DELAY_LIGHT,
ATTACK_LIGHT,
DECAY_LIGHT,
SUSTAIN_LIGHT,
RELEASE_LIGHT,
ATTACK_SHAPE1_LIGHT,
ATTACK_SHAPE2_LIGHT,
ATTACK_SHAPE3_LIGHT,
DECAY_SHAPE1_LIGHT,
DECAY_SHAPE2_LIGHT,
DECAY_SHAPE3_LIGHT,
RELEASE_SHAPE1_LIGHT,
RELEASE_SHAPE2_LIGHT,
RELEASE_SHAPE3_LIGHT,
NUM_LIGHTS
};
DADSRHCore _core;
DADSRHPlus() : TriggerOnLoadModule(
NUM_PARAMS,
NUM_INPUTS,
NUM_OUTPUTS,
NUM_LIGHTS
)
, _core(
params[DELAY_PARAM],
params[ATTACK_PARAM],
params[DECAY_PARAM],
params[SUSTAIN_PARAM],
params[RELEASE_PARAM],
params[HOLD_PARAM],
params[ATTACK_SHAPE_PARAM],
params[DECAY_SHAPE_PARAM],
params[RELEASE_SHAPE_PARAM],
params[TRIGGER_PARAM],
params[MODE_PARAM],
params[LOOP_PARAM],
params[SPEED_PARAM],
params[RETRIGGER_PARAM],
&inputs[DELAY_INPUT],
&inputs[ATTACK_INPUT],
&inputs[DECAY_INPUT],
&inputs[SUSTAIN_INPUT],
&inputs[RELEASE_INPUT],
&inputs[HOLD_INPUT],
inputs[TRIGGER_INPUT],
&outputs[DELAY_OUTPUT],
&outputs[ATTACK_OUTPUT],
&outputs[DECAY_OUTPUT],
&outputs[SUSTAIN_OUTPUT],
&outputs[RELEASE_OUTPUT],
outputs[ENV_OUTPUT],
outputs[INV_OUTPUT],
outputs[TRIGGER_OUTPUT],
lights[DELAY_LIGHT],
lights[ATTACK_LIGHT],
lights[DECAY_LIGHT],
lights[SUSTAIN_LIGHT],
lights[RELEASE_LIGHT],
lights[ATTACK_SHAPE1_LIGHT],
lights[ATTACK_SHAPE2_LIGHT],
lights[ATTACK_SHAPE3_LIGHT],
lights[DECAY_SHAPE1_LIGHT],
lights[DECAY_SHAPE2_LIGHT],
lights[DECAY_SHAPE3_LIGHT],
lights[RELEASE_SHAPE1_LIGHT],
lights[RELEASE_SHAPE2_LIGHT],
lights[RELEASE_SHAPE3_LIGHT],
_triggerOnLoad,
_shouldTriggerOnLoad
) {
onReset();
}
void onReset() override {
_core.reset();
}
void step() override {
_core.step();
}
bool shouldTriggerOnNextLoad() override {
return _core._stage != _core.STOPPED_STAGE;
}
};
} // namespace bogaudio
| 17.890411 | 45 | 0.746937 | [
"model"
] |
68ef84adeeeed310b67f59bd5de771950da810e7 | 1,022 | cpp | C++ | 46.permutations.cpp | pancl1411/leetcode_c- | aa909cb241bf65b36cc881eefee0c908d2152295 | [
"MIT"
] | 2 | 2020-12-13T05:14:08.000Z | 2021-01-17T07:39:16.000Z | 46.permutations.cpp | pancl1411/leetcode_c- | aa909cb241bf65b36cc881eefee0c908d2152295 | [
"MIT"
] | null | null | null | 46.permutations.cpp | pancl1411/leetcode_c- | aa909cb241bf65b36cc881eefee0c908d2152295 | [
"MIT"
] | 1 | 2021-01-17T07:39:18.000Z | 2021-01-17T07:39:18.000Z | /*
* @lc app=leetcode id=46 lang=cpp
*
* [46] Permutations
*/
// @lc code=start
#include <vector>
#include <unordered_set>
class Solution {
public:
std::vector<std::vector<int>> permute(std::vector<int>& nums) {
std::vector<int> selected;
backtrace(nums, selected);
return answer;
}
private:
std::vector<std::vector<int>> answer;
std::unordered_set<int> is_have;
void backtrace(std::vector<int>& nums, std::vector<int>& selected)
{
if (selected.size() == nums.size())
{
answer.push_back(selected);
return;
}
for (int index = 0; index < nums.size(); index++)
{
if (!is_have.count(nums[index]))
{
selected.push_back(nums[index]);
is_have.insert(nums[index]);
backtrace(nums, selected);
selected.pop_back();
is_have.erase(nums[index]);
}
}
}
};
// @lc code=end
| 23.227273 | 70 | 0.514677 | [
"vector"
] |
68f2ba4fc31e07748a816a73dc40e65584d4b774 | 1,618 | cpp | C++ | lanelet2/lanelet2_validation/src/validators/CurvatureTooBig.cpp | adamlm/autoware.ai | 25191e3f9df3c89cb817e58f6eb6cbd482c45590 | [
"Apache-2.0"
] | 2 | 2019-07-17T16:54:03.000Z | 2020-01-31T08:56:39.000Z | lanelet2_validation/src/validators/CurvatureTooBig.cpp | poggenhans/Lanelet2 | b0fec771d27a95d480e15c8e15895d2dd9f3ed0e | [
"BSD-3-Clause"
] | null | null | null | lanelet2_validation/src/validators/CurvatureTooBig.cpp | poggenhans/Lanelet2 | b0fec771d27a95d480e15c8e15895d2dd9f3ed0e | [
"BSD-3-Clause"
] | 1 | 2021-06-01T21:08:37.000Z | 2021-06-01T21:08:37.000Z | #include "validators/mapping/CurvatureTooBig.h"
#include <iostream>
#include "ValidatorFactory.h"
#include "lanelet2_core/geometry/Point.h"
namespace lanelet {
namespace validation {
namespace {
RegisterMapValidator<CurvatureTooBigChecker> reg1;
} // namespace
Issues CurvatureTooBigChecker::operator()(const LaneletMap& map) {
Issues issues;
for (auto& lanelet : map.laneletLayer) {
checkCurvature(issues, utils::to2D(lanelet.leftBound()), lanelet.id());
checkCurvature(issues, utils::to2D(lanelet.rightBound()), lanelet.id());
}
return issues;
}
double CurvatureTooBigChecker::computeCurvature(const BasicPoint2d& p1, const BasicPoint2d& p2, const BasicPoint2d& p3) {
auto dp = 0.5 * (p3 - p1);
auto ddp = p3 - 2.0 * p2 + p1;
auto denom = std::pow(dp.x() * dp.x() + dp.y() * dp.y(), 3.0 / 2.0);
if (std::fabs(denom) < 1e-20) {
denom = 1e-20;
}
return static_cast<double>((ddp.y() * dp.x() - dp.y() * ddp.x()) / denom);
}
void CurvatureTooBigChecker::checkCurvature(Issues& issues, const ConstLineString2d& line, const Id& laneletId) {
auto lineHyb = utils::toHybrid(line);
if (lineHyb.size() >= 3) {
for (size_t i = 1; i < lineHyb.size() - 1; ++i) {
if (std::fabs(computeCurvature(lineHyb[i - 1], lineHyb[i], lineHyb[i + 1])) > 0.5) {
issues.emplace_back(Severity::Warning, Primitive::Lanelet, laneletId,
"Curvature at point " + std::to_string(line[i].id()) +
" is bigger than 0.5. This can confuse algorithms using this map.");
}
}
}
}
} // namespace validation
} // namespace lanelet
| 35.173913 | 121 | 0.647713 | [
"geometry"
] |
68f494a178e617f388d969becd09d69f68f0ab97 | 11,439 | tpp | C++ | Core/src.tpp/SplitMerge$en-us.tpp | koz4k/soccer | 7bceea654b50c5c0e18effd38e79249bd295e0a4 | [
"MIT"
] | 1 | 2018-09-28T17:04:11.000Z | 2018-09-28T17:04:11.000Z | Core/src.tpp/SplitMerge$en-us.tpp | koz4k/soccer | 7bceea654b50c5c0e18effd38e79249bd295e0a4 | [
"MIT"
] | 1 | 2021-04-06T21:57:39.000Z | 2021-04-06T21:57:39.000Z | Core/src.tpp/SplitMerge$en-us.tpp | koz4k/soccer | 7bceea654b50c5c0e18effd38e79249bd295e0a4 | [
"MIT"
] | 3 | 2017-08-26T12:06:05.000Z | 2019-11-22T16:57:47.000Z | topic "Split, Join, Merge";
[2 $$0,0#00000000000000000000000000000000:Default]
[i448;a25;kKO9;2 $$1,0#37138531426314131252341829483380:class]
[l288;2 $$2,2#27521748481378242620020725143825:desc]
[0 $$3,0#96390100711032703541132217272105:end]
[H6;0 $$4,0#05600065144404261032431302351956:begin]
[i448;a25;kKO9;2 $$5,0#37138531426314131252341829483370:item]
[l288;a4;*@5;1 $$6,6#70004532496200323422659154056402:requirement]
[l288;i1121;b17;O9;~~~.1408;2 $$7,0#10431211400427159095818037425705:param]
[i448;b42;O9;2 $$8,8#61672508125594000341940100500538:tparam]
[b42;2 $$9,9#13035079074754324216151401829390:normal]
[{_}
[ {{10000@(113.42.0) [s0;%% [*@7;4 Split, Join, Merge]]}}&]
[s0;i448;a25;kKO9;@(0.0.255) &]
[s0;%% [* Utility functions for splitting and joining Strings and WStrings.]&]
[s0;*%% &]
[ {{10000F(128)G(128)@1 [s0;%% [* Function List]]}}&]
[s3; &]
[s5;:Split`(int`,const char`*`,const char`*`(`*`)`(const char`*`)`,bool`): [_^Vector^ V
ector]<[_^String^ String]>_[* Split]([@(0.0.255) int]_[*@3 maxcount],
[@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) const]_[@(0.0.255) char]_`*_(`*
[*@3 text`_filter])([@(0.0.255) const]_[@(0.0.255) char]_`*), [@(0.0.255) bool]_[*@3 ignore
empty]_`=_[@(0.0.255) true])&]
[s5;:Split`(int`,const char`*`,int`(`*`)`(int`)`,bool`): [_^Vector^ Vector]<[_^String^ St
ring]>_[* Split]([@(0.0.255) int]_[*@3 maxcount], [@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s
], [@(0.0.255) int]_(`*[*@3 filter])([@(0.0.255) int]), [@(0.0.255) bool]_[*@3 ignoreempty]_
`=_[@(0.0.255) true])&]
[s5;:Split`(int`,const char`*`,int`,bool`): [_^Vector^ Vector]<[_^String^ String]>_[* Split
]([@(0.0.255) int]_[*@3 maxcount], [@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s],
[@(0.0.255) int]_[*@3 chr], [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s5;:Split`(int`,const char`*`,const char`*`,bool`): [_^Vector^ Vector]<[_^String^ String
]>_[* Split]([@(0.0.255) int]_[*@3 maxcount], [@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s],
[@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 text], [@(0.0.255) bool]_[*@3 ignoreempty]_`=_
[@(0.0.255) true])&]
[s5;:Split`(const char`*`,const char`*`(`*`)`(const char`*`)`,bool`): [_^Vector^ Vector
]<[_^String^ String]>_[* Split]([@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s],
[@(0.0.255) const]_[@(0.0.255) char]_`*_(`*[*@3 text`_filter])([@(0.0.255) const]_[@(0.0.255) c
har]_`*), [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s5;:Split`(const char`*`,int`(`*`)`(int`)`,bool`): [_^Vector^ Vector]<[_^String^ String]>
_[* Split]([@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) int]_(`*[*@3 filter])(
[@(0.0.255) int]), [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s5;:Split`(const char`*`,int`,bool`): [_^Vector^ Vector]<[_^String^ String]>_[* Split]([@(0.0.255) c
onst]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) int]_[*@3 chr], [@(0.0.255) bool]_[*@3 ignoree
mpty]_`=_[@(0.0.255) true])&]
[s5;:Split`(const char`*`,const char`*`,bool`): [_^Vector^ Vector]<[_^String^ String]>_[* S
plit]([@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) const]_[@(0.0.255) char]_
`*[*@3 text], [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s5;:Split`(int`,const wchar`*`,const wchar`*`(`*`)`(const wchar`*`)`,bool`): [_^Vector^ V
ector]<[_^WString^ WString]>_[* Split]([@(0.0.255) int]_[*@3 maxcount],
[@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) const]_[_^wchar^ wchar]_`*_(`*[*@3 t
ext`_filter])([@(0.0.255) const]_wchar_`*), [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) t
rue])&]
[s5;:Split`(int`,const wchar`*`,int`(`*`)`(int`)`,bool`): [_^Vector^ Vector]<[_^WString^ W
String]>_[* Split]([@(0.0.255) int]_[*@3 maxcount], [@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s
], [@(0.0.255) int]_(`*[*@3 filter])([@(0.0.255) int]), [@(0.0.255) bool]_[*@3 ignoreempty]_
`=_[@(0.0.255) true])&]
[s5;:Split`(int`,const wchar`*`,int`,bool`): [_^Vector^ Vector]<[_^WString^ WString]>_[* Sp
lit]([@(0.0.255) int]_[*@3 maxcount], [@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s],
[@(0.0.255) int]_[*@3 chr], [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s5;:Split`(int`,const wchar`*`,const wchar`*`,bool`): [_^Vector^ Vector]<[_^WString^ WSt
ring]>_[* Split]([@(0.0.255) int]_[*@3 maxcount], [@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s
], [@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 text], [@(0.0.255) bool]_[*@3 ignoreempty]_`=
_[@(0.0.255) true])&]
[s5;:Split`(const wchar`*`,const wchar`*`(`*`)`(const wchar`*`)`,bool`): [_^Vector^ Vec
tor]<[_^WString^ WString]>_[* Split]([@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s],
[@(0.0.255) const]_[_^wchar^ wchar]_`*_(`*[*@3 text`_filter])([@(0.0.255) const]_wchar_`*
), [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s5;:Split`(const wchar`*`,int`(`*`)`(int`)`,bool`): [_^Vector^ Vector]<[_^WString^ WStri
ng]>_[* Split]([@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) int]_(`*[*@3 filter
])([@(0.0.255) int]), [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s5;:Split`(const wchar`*`,int`,bool`): [_^Vector^ Vector]<[_^WString^ WString]>_[* Split](
[@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) int]_[*@3 chr],
[@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s5;:Split`(const wchar`*`,const wchar`*`,bool`): [_^Vector^ Vector]<[_^WString^ WString]>
_[* Split]([@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) const]_[_^wchar^ wchar]_
`*[*@3 text], [@(0.0.255) bool]_[*@3 ignoreempty]_`=_[@(0.0.255) true])&]
[s2;%% Splits text [%-*@3 s] into subtexts originating between delimiters.
Delimiter can be defined as single character [%-*@3 chr], text
filter function [%-*@3 text`_filter ](returns position after delimiter
or NULL if delimiter is not at current character), character
filter function [%-*@3 filter] (returns non`-zero for delimiter
character) or as string [%-*@3 text]. If [%-*@3 ignoreempty] is true
(default), empty subtexts are ignored. [%-*@3 maxcount] can define
upper limit of number of subtexts.&]
[s3;%% &]
[s4;%% &]
[s5;:Join`(const Vector`<String`>`&`,const String`&`,bool`): [_^String^ String]_[* Join](
[@(0.0.255) const]_[_^Vector^ Vector]<[_^String^ String]>`&_[*@3 im],
[@(0.0.255) const]_[_^String^ String][@(0.0.255) `&]_[*@3 delim], [@(0.0.255) bool]_[*@3 igno
reempty]_`=_[@(0.0.255) false])&]
[s5;:Join`(const Vector`<WString`>`&`,const WString`&`,bool`): [_^WString^ WString]_[* Jo
in]([@(0.0.255) const]_[_^Vector^ Vector]<[_^WString^ WString]>`&_[*@3 im],
[@(0.0.255) const]_[_^WString^ WString][@(0.0.255) `&]_[*@3 delim], [@(0.0.255) bool]_[*@3 ig
noreempty]_`=_[@(0.0.255) false])&]
[s2;%% Joins texts from [%-*@3 im], inserting [%-*@3 delim] between them.
If [%-*@3 ignoreempty] is true, empty texts are ignored. Note that
the default value of [%-*@3 ignoreempty] is the opposite of one
in Split.&]
[s3;%% &]
[s4;%% &]
[s5;:SplitTo`(const char`*`,int`,bool`,String`&`.`.`.`): [@(0.0.255) bool]_[* SplitTo]([@(0.0.255) c
onst]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) int]_[*@3 delim], [@(0.0.255) bool]_[*@3 ignor
eempty], [_^String^ String][@(0.0.255) `&]_[*@3 p1][@(0.0.255) ...])&]
[s5;:SplitTo`(const char`*`,int`,String`&`.`.`.`): [@(0.0.255) bool]_[* SplitTo]([@(0.0.255) c
onst]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) int]_[*@3 delim], [_^String^ String][@(0.0.255) `&
]_[*@3 p1][@(0.0.255) ...])&]
[s5;:SplitTo`(const char`*`,int`(`*`)`(int`)`,String`&`.`.`.`): [@(0.0.255) bool]_[* Spli
tTo]([@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) int]_(`*[*@3 filter])([@(0.0.255) i
nt]), String[@(0.0.255) `&]_[*@3 p1][@(0.0.255) ...])&]
[s5;:SplitTo`(const char`*`,const char`*`,bool`,String`&`.`.`.`): [@(0.0.255) bool]_[* Sp
litTo]([@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) const]_[@(0.0.255) char]_
`*[*@3 delim], [@(0.0.255) bool]_[*@3 ignoreempty], [_^String^ String][@(0.0.255) `&]_[*@3 p1
][@(0.0.255) ...])&]
[s5;:SplitTo`(const char`*`,const char`*`,String`&`.`.`.`): [@(0.0.255) bool]_[* SplitTo](
[@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 s], [@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 d
elim], [_^String^ String][@(0.0.255) `&]_[*@3 p1][@(0.0.255) ...])&]
[s5;:SplitTo`(const wchar`*`,int`,bool`,WString`&`.`.`.`): [@(0.0.255) bool]_[* SplitTo](
[@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) int]_[*@3 delim],
[@(0.0.255) bool]_[*@3 ignoreempty], [_^WString^ WString][@(0.0.255) `&]_[*@3 p1][@(0.0.255) .
..])&]
[s5;:SplitTo`(const wchar`*`,int`,WString`&`.`.`.`): [@(0.0.255) bool]_[* SplitTo]([@(0.0.255) c
onst]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) int]_[*@3 delim], [_^WString^ WString][@(0.0.255) `&
]_[*@3 p1][@(0.0.255) ...])&]
[s5;:SplitTo`(const wchar`*`,int`(`*`)`(int`)`,WString`&`.`.`.`): [@(0.0.255) bool]_[* Sp
litTo]([@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) int]_(`*[*@3 filter])([@(0.0.255) i
nt]), WString[@(0.0.255) `&]_[*@3 p1][@(0.0.255) ...])&]
[s5;:SplitTo`(const wchar`*`,const wchar`*`,bool`,WString`&`.`.`.`): [@(0.0.255) bool]_
[* SplitTo]([@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) const]_[_^wchar^ wchar
]_`*[*@3 delim], [@(0.0.255) bool]_[*@3 ignoreempty], [_^WString^ WString][@(0.0.255) `&]_[*@3 p
1][@(0.0.255) ...])&]
[s5;:SplitTo`(const wchar`*`,const wchar`*`,WString`&`.`.`.`): [@(0.0.255) bool]_[* Split
To]([@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 s], [@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 d
elim], [_^WString^ WString][@(0.0.255) `&]_[*@3 p1][@(0.0.255) ...])&]
[s2;%% Splits text into one or more targets substrings, inserting
them into string variables (current implementation supports up
to 8 output strings). Returns true if the source text contains
enough substrings. Delimiter can be defined as single character
[%-*@3 chr], character filter function [%-*@3 filter] (returns non`-zero
for delimiter character) or as string [%-*@3 text]. If [%-*@3 ignoreempty]
is true (default), empty subtexts are ignored. [%-*@3 maxcount]
can define upper limit of number of subtexts.&]
[s3;%% &]
[s4;%% &]
[s5;:Merge`(const char`*`,String`&`.`.`.`): [_^String^ String]_[* Merge]([@(0.0.255) const]_
[@(0.0.255) char]_`*[*@3 delim], [_^String^ String][@(0.0.255) `&]_[*@3 p1][@(0.0.255) ...])&]
[s5;:Merge`(const wchar`*`,WString`&`.`.`.`): [_^WString^ WString]_[* Merge]([@(0.0.255) co
nst]_[_^wchar^ wchar]_`*[*@3 delim], [_^WString^ WString][@(0.0.255) `&]_[*@3 p1][@(0.0.255) .
..])&]
[s2;%% Merges substrings. Returns source strings concatenated with
delimiter put between them, however empty strings are ignored
(means Merge(`";`", `"1`", `"`") results in `"1`", not `"1;`").&]
[s3;%% &]
[s4;%% &]
[s5;:MergeWith`(String`&`,const char`*`,String`&`.`.`.`): [@(0.0.255) void]_[* MergeWith](
[_^String^ String][@(0.0.255) `&]_[*@3 dest], [@(0.0.255) const]_[@(0.0.255) char]_`*[*@3 del
im], [_^String^ String][@(0.0.255) `&]_[*@3 p1][@(0.0.255) ...])&]
[s5;:MergeWith`(WString`&`,const wchar`*`,WString`&`.`.`.`): [@(0.0.255) void]_[* MergeWi
th]([_^WString^ WString][@(0.0.255) `&]_[*@3 dest], [@(0.0.255) const]_[_^wchar^ wchar]_`*[*@3 d
elim], [_^WString^ WString][@(0.0.255) `&]_[*@3 p1][@(0.0.255) ...])&]
[s2;%% Merges substrings with dest. [%-*@3 dest] and source strings
concatenated with delimiter put between them are stored, however
empty strings are ignored.&]
[s3;%% ]] | 70.177914 | 102 | 0.566833 | [
"vector"
] |
d0ffb72ded3c8353ccf44a1b96e81de7f06d02f6 | 3,656 | cpp | C++ | Sun.cpp | stusona/solar-tracker | 0eb43e0e8c1d7a3abb36db8db631563abaff579d | [
"MIT"
] | 1 | 2020-05-26T23:57:02.000Z | 2020-05-26T23:57:02.000Z | Sun.cpp | stusona/solar-tracker | 0eb43e0e8c1d7a3abb36db8db631563abaff579d | [
"MIT"
] | null | null | null | Sun.cpp | stusona/solar-tracker | 0eb43e0e8c1d7a3abb36db8db631563abaff579d | [
"MIT"
] | null | null | null | /*
* Sun.cpp
*/
#include "Sun.h"
#include <math.h>
/*
* Sun constructor
*/
Sun::Sun()
{ }
/*
* Get current date/time, format is YYYY-MM-DD.HH:mm:ss
*/
const std::string Sun::currentDateTime()
{
time_t now = time(0);
struct tm tstruct;
char buf[80];
tstruct = *localtime(&now);
// Visit http://en.cppreference.com/w/cpp/chrono/c/strftime
// for more information about date/time format
strftime(buf, sizeof(buf), "%Y-%m-%d.%X", &tstruct);
return buf;
}
/*
* Sun's azimuth and elevation given a datetime and lat/long.
*
* Using a simplified, yet accurate sun
* position calculator based on Blanco-Muriel et al.'s SPA algorithm closely
* matches altitude, azimuth values returned by NOAA calculator. This variation was
* converted from Javascript
*/
vec_t Sun::getPosition(float latitude, float longitude)
{
vec_t cartesianPosition; // return vector
std::string dateTime;
dateTime = currentDateTime();
int year = stoi(dateTime.substr(0,4));
int month = stoi(dateTime.substr(5,2));
int day = stoi(dateTime.substr(8,2));
int UTHour = stoi(dateTime.substr(11,2));
int UTMinute = stoi(dateTime.substr(14,2));
float pi = 3.14159265358979323;
float twopi = (2*pi);
float rad = (pi/180);
float EarthMeanRadius = 6371.01; // In km
float AstronomicalUnit = 149597890.; // In km
float DecimalHours = UTHour + (UTMinute ) / 60.0;
long liAux1 = (month-14)/12;
long liAux2=(1461*(year + 4800 + liAux1))/4 + (367*(month - 2-12*liAux1))/12- (3*(year + 4900 + liAux1)/100)/4 + day - 32075;
float JulianDate = (liAux2) - 0.5 + DecimalHours/24.0;
float ElapsedJulianDays = JulianDate-2451545.0;
float Omega=2.1429-0.0010394594*ElapsedJulianDays;
float MeanLongitude = 4.8950630+ 0.017202791698*ElapsedJulianDays; // Radians
float MeanAnomaly = 6.2400600+ 0.0172019699*ElapsedJulianDays;
float EclipticLongitude = MeanLongitude + 0.03341607*sin( MeanAnomaly ) + 0.00034894*sin( 2*MeanAnomaly )-0.0001134 -0.0000203*sin(Omega);
float EclipticObliquity = 0.4090928 - 6.2140e-9*ElapsedJulianDays +0.0000396*cos(Omega);
float Sin_EclipticLongitude= sin( EclipticLongitude );
float Y = cos( EclipticObliquity ) * Sin_EclipticLongitude;
float X = cos( EclipticLongitude );
float RightAscension = atan2( Y, X );
if ( RightAscension < 0.0 ) RightAscension = RightAscension + twopi;
float Declination = asin( sin( EclipticObliquity )* Sin_EclipticLongitude );
float GreenwichMeanSiderealTime = 6.6974243242 + 0.0657098283*ElapsedJulianDays + DecimalHours;
float LocalMeanSiderealTime = (GreenwichMeanSiderealTime*15 + longitude)*rad;
float HourAngle = LocalMeanSiderealTime - RightAscension;
float LatitudeInRadians = latitude*rad;
float Cos_Latitude = cos( LatitudeInRadians );
float Sin_Latitude = sin( LatitudeInRadians );
float Cos_HourAngle= cos( HourAngle );
float UTSunCoordinatesZenithAngle = (acos( Cos_Latitude*Cos_HourAngle*cos(Declination) + sin( Declination )*Sin_Latitude));
Y = -sin( HourAngle );
X = tan( Declination )*Cos_Latitude - Sin_Latitude*Cos_HourAngle;
float UTSunCoordinatesAzimuth = atan2( Y, X );
if ( UTSunCoordinatesAzimuth < 0.0 )
UTSunCoordinatesAzimuth = UTSunCoordinatesAzimuth + twopi;
//UTSunCoordinatesAzimuth = UTSunCoordinatesAzimuth/rad;
float Parallax = (EarthMeanRadius/AstronomicalUnit) * sin(UTSunCoordinatesZenithAngle);
UTSunCoordinatesZenithAngle = (UTSunCoordinatesZenithAngle + Parallax);
float elevation = pi/2. - UTSunCoordinatesZenithAngle;
cartesianPosition.x = cos(UTSunCoordinatesAzimuth) * cos(elevation);
cartesianPosition.y = sin(UTSunCoordinatesAzimuth) * cos(elevation);
cartesianPosition.z = sin(elevation);
return cartesianPosition;
}
| 39.311828 | 139 | 0.740974 | [
"vector"
] |
19010046ed9a53c1754686a90eef6c6ea3d8ec4d | 1,078 | hh | C++ | inc/Game.hh | arnauruana/opengl-practice | 77274ab7351efc853b05f8cbcc30a66a63861ba6 | [
"MIT"
] | 1 | 2021-11-01T18:48:47.000Z | 2021-11-01T18:48:47.000Z | inc/Game.hh | arnauruana/opengl-practice | 77274ab7351efc853b05f8cbcc30a66a63861ba6 | [
"MIT"
] | null | null | null | inc/Game.hh | arnauruana/opengl-practice | 77274ab7351efc853b05f8cbcc30a66a63861ba6 | [
"MIT"
] | null | null | null | #ifndef _GAME_INCLUDE
#define _GAME_INCLUDE
#include "Scene.hh"
/*
Singleton that represents our whole application.
*/
class Game
{
public:
static const uint DEFAULT_WINDOW_WIDTH = 640;
static const uint DEFAULT_WINDOW_HEIGHT = 480;
static const uint FPS = 60;
public:
Game() {}
static Game& instance()
{
static Game game;
return game;
}
void init();
bool update(int time);
void render();
bool getKey(int keyId) const;
bool getSpecialKey(int keyId) const;
void keyPressed(int keyId);
void keyReleased(int keyId);
void specialKeyPressed(int keyId);
void specialKeyReleased(int keyId);
void mousePressed(int buttonId);
void mouseReleased(int buttonId);
void mouseMoved(int posX, int posY);
private:
void toggleFullScreen();
void enableFullScreen();
void disableFullScreen();
void saveWindowContext();
void restoreWindowContext();
private:
bool bPlay;
bool key[256];
bool skey[256];
bool mouseA;
bool windowF;
uint windowH;
uint windowW;
uint windowX;
uint windowY;
bool soundA;
Scene scene;
};
#endif // _GAME_INCLUDE
| 14.767123 | 49 | 0.729128 | [
"render"
] |
190fe78054f94061c2f940c5ae5f1eb470fbb19e | 5,627 | hpp | C++ | elfcat2/src/elf/include/parser.hpp | a-kosak-mbx/ELFTools | 58be05f4b05d96b0860a1dba1df67724ef340a3a | [
"MIT"
] | 1 | 2021-07-09T01:31:42.000Z | 2021-07-09T01:31:42.000Z | elfcat2/src/elf/include/parser.hpp | a-kosak-mbx/ELFTools | 58be05f4b05d96b0860a1dba1df67724ef340a3a | [
"MIT"
] | 1 | 2021-07-01T23:42:53.000Z | 2021-07-01T23:42:53.000Z | elfcat2/src/elf/include/parser.hpp | a-kosak-mbx/ELFTools | 58be05f4b05d96b0860a1dba1df67724ef340a3a | [
"MIT"
] | 4 | 2021-06-30T14:47:25.000Z | 2021-07-09T01:17:25.000Z | #pragma once
#include <array>
#include <memory>
#include <tuple>
#include <vector>
#include <set>
#include "defs.hpp"
//#include "elf32.hpp"
//#include "elf64.hpp"
//#include "elfxx.hpp"
using InfoTuple = std::tuple<std::string, std::string, std::string>;
struct RangeType {
virtual ~RangeType() = default;
virtual bool needs_class() const = 0;
virtual bool needs_id() const = 0;
virtual std::string id() const = 0;
virtual std::string class_() const = 0;
virtual bool always_highlight() const = 0;
std::string span_attributes() const;
virtual bool skippable() const = 0;
virtual bool is_end() const;
};
template<bool needs_class_v = false, bool needs_id_v = false, bool skippable_v = false>
struct ConfigurableRangeType : RangeType {
bool needs_class() const {
return needs_class_v;
}
bool needs_id() const {
return needs_id_v;
}
std::string id() const {
return "";
}
std::string class_() const {
return "";
}
bool always_highlight() const {
return false;
}
std::string span_attributes() const {
return "";
}
bool skippable() const {
return skippable_v;
}
};
struct RangeTypeEnd : ConfigurableRangeType<> {
bool is_end() const;
};
struct RangeTypeIdent : ConfigurableRangeType<> {
std::string id() const;
};
struct RangeTypeFileHeader : ConfigurableRangeType<> {
std::string id() const;
};
struct RangeTypeHeaderField : ConfigurableRangeType<false, true> {
RangeTypeHeaderField(const std::string& v);
std::string id() const;
bool always_highlight() const;
const std::string value;
inline static const std::set<std::string> highlight_values = {
"magic",
"ver",
"abi_ver",
"pad",
"e_version",
"e_flags",
"e_ehsize",
"e_shstrndx",
};
};
struct RangeTypeProgramHeader : ConfigurableRangeType<true, true> {
RangeTypeProgramHeader(uint32_t v);
std::string id() const;
std::string class_() const;
const uint32_t value;
};
struct RangeTypeSectionHeader : ConfigurableRangeType<true, true> {
RangeTypeSectionHeader(uint32_t v);
std::string id() const;
std::string class_() const;
const uint32_t value;
};
struct RangeTypePhdrField : ConfigurableRangeType<true> {
RangeTypePhdrField(const std::string& v);
std::string class_() const;
std::string value;
};
struct RangeTypeShdrField : ConfigurableRangeType<true> {
RangeTypeShdrField(const std::string& v);
std::string class_() const;
std::string value;
};
struct RangeTypeSegment : ConfigurableRangeType<true, true, true> {
RangeTypeSegment(uint16_t v);
std::string id() const;
std::string class_() const;
bool always_highlight() const;
const uint16_t value;
};
struct RangeTypeSection : ConfigurableRangeType<true, true, true> {
RangeTypeSection(uint16_t v);
std::string id() const;
std::string class_() const;
bool always_highlight() const;
const uint16_t value;
};
struct RangeTypeSegmentSubrange : ConfigurableRangeType<true, false, true> {
std::string class_() const;
bool always_highlight() const;
};
// Interval tree that allows querying point for all intervals that intersect it should be better.
// We can't beat O(n * m) but the average case should improve.
struct Ranges {
~Ranges();
Ranges(size_t capacity);
void add_range(size_t start, size_t end, RangeType* range_type);
size_t lookup_range_ends(size_t point) const;
std::vector<std::vector<RangeType*>> data;
};
struct ParsedIdent {
static ParsedIdent from_bytes(const std::vector<uint8_t>& buf);
std::array<uint8_t, 4> magic;
uint8_t class_;
uint8_t endianness;
uint8_t version;
uint8_t abi;
uint8_t abi_ver;
};
struct StrTab {
static StrTab empty();
void populate(const std::vector<uint8_t>& section, size_t section_size);
std::string get(size_t idx) const;
std::vector<uint8_t> strings;
size_t section_size;
};
struct Note {
static std::tuple<Note, size_t> from_bytes(const std::vector<uint8_t>& buf, uint8_t endianness);
static std::tuple<uint32_t, uint32_t, uint32_t> read_header(const std::vector<uint8_t>& buf, uint8_t endianness);
std::vector<uint8_t> name;
std::vector<uint8_t> desc;
uint32_t ntype;
};
struct ParsedPhdr {
uint32_t ptype;
std::string flags;
size_t file_offset;
size_t file_size;
size_t vaddr;
size_t memsz;
size_t alignment;
};
struct ParsedShdr {
size_t name;
uint32_t shtype;
uint64_t flags;
size_t addr;
size_t file_offset;
size_t size;
size_t link;
size_t info;
size_t addralign;
size_t entsize;
};
struct ParsedElf {
static ParsedElf from_bytes(const std::string& filename, const std::vector<uint8_t>& buf);
void push_file_info();
void push_ident_info(const ParsedIdent& ident);
void add_ident_ranges();
std::optional<ParsedShdr> find_strtab_shdr(const std::vector<ParsedShdr>& shdrs);
void parse_string_tables();
void parse_notes(uint8_t endianness);
void parse_note_area(size_t area_start, size_t area_size, uint8_t endianness);
std::string filename;
size_t file_size;
std::vector<std::tuple<std::string, std::string, std::string>> information;
std::vector<uint8_t> contents;
Ranges ranges;
std::vector<ParsedPhdr> phdrs;
std::vector<ParsedShdr> shdrs;
StrTab strtab;
uint16_t shstrndx;
StrTab shnstrtab;
std::vector<Note> notes;
};
| 21.894942 | 117 | 0.672472 | [
"vector"
] |
1910a2b2cd52822831f5d038c54c8f21f56b781d | 4,673 | hpp | C++ | obbox.hpp | edydfang/PathTracing | 4e756575d3345ae76febf1f34132f8c056694c99 | [
"MIT"
] | 3 | 2022-01-06T09:10:04.000Z | 2022-01-16T06:30:28.000Z | obbox.hpp | edwardfang/PathTracing | 4e756575d3345ae76febf1f34132f8c056694c99 | [
"MIT"
] | 1 | 2020-12-16T08:01:28.000Z | 2020-12-16T08:07:19.000Z | obbox.hpp | edydfang/PathTracing | 4e756575d3345ae76febf1f34132f8c056694c99 | [
"MIT"
] | null | null | null | #pragma once
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#pragma region
#include "commonenum.hpp"
#include "geometry.hpp"
#include "hittable.hpp"
#include "aabb.hpp"
#include <vector>
#include <iostream>
#pragma endregion
namespace pathtracing
{
using std::move;
struct OBBox final : public Hittable
{
//---------------------------------------------------------------------
// Constructors and Destructors
//---------------------------------------------------------------------
Oriented_axis m_o_axis;
double m_rotate_radian;
Vector3 m_origin, m_edge_lens;
std::vector<AABB> aabb;
// origin: left front bottom intersection (smallest axis magnatitude)
// clockwise rotate
explicit OBBox(Vector3 origin, Vector3 edge_lens, Vector3 e, Vector3 f, Reflection_t reflection_t,
double rotate_radian = 0, Oriented_axis o_axis = Oriented_axis::NA) noexcept
: m_o_axis(o_axis), m_rotate_radian(rotate_radian), m_origin(move(origin)), m_edge_lens(edge_lens), Hittable(e, f, reflection_t)
{
// up down left right front back
Vector3 ulf = Vector3(m_origin.m_x, m_origin.m_y + m_edge_lens.m_y, m_origin.m_z);
Vector3 urb = Vector3(m_origin.m_x + m_edge_lens.m_x, m_origin.m_y + m_edge_lens.m_y, m_origin.m_z + m_edge_lens.m_z);
Vector3 dlf = Vector3(m_origin.m_x, m_origin.m_y, m_origin.m_z);
Vector3 drb = Vector3(m_origin.m_x + m_edge_lens.m_x, m_origin.m_y, m_origin.m_z + m_edge_lens.m_z);
Vector3 ulb = Vector3(m_origin.m_x, m_origin.m_y + m_edge_lens.m_y, m_origin.m_z + m_edge_lens.m_z);
Vector3 drf = Vector3(m_origin.m_x + m_edge_lens.m_x, m_origin.m_y, m_origin.m_z);
Vector3 urf = Vector3(m_origin.m_x + m_edge_lens.m_x, m_origin.m_y + m_edge_lens.m_y, m_origin.m_z);
Vector3 dlb = Vector3(m_origin.m_x, m_origin.m_y, m_origin.m_z + m_edge_lens.m_z);
aabb.push_back(AABB(AABB_t::XOZ, ulf, urb, e, f, reflection_t));
aabb.push_back(AABB(AABB_t::XOZ, dlf, drb, e, f, reflection_t));
aabb.push_back(AABB(AABB_t::YOZ, dlf, ulb, e, f, reflection_t));
aabb.push_back(AABB(AABB_t::YOZ, drf, urb, e, f, reflection_t));
aabb.push_back(AABB(AABB_t::XOY, dlf, urf, e, f, reflection_t));
aabb.push_back(AABB(AABB_t::XOY, dlb, urb, e, f, reflection_t));
}
OBBox(const OBBox &obbox) noexcept = default;
OBBox(OBBox &&obbox) noexcept = default;
~OBBox() = default;
// Assignment Operators
//---------------------------------------------------------------------
OBBox &operator=(const OBBox &obbox) = default;
OBBox &operator=(OBBox &&obbox) = default;
bool Intersect(const Ray &ray) const
{
const Ray *r;
// First rotate the ray
if (m_o_axis == Oriented_axis::NA || m_rotate_radian == 0)
{
r = &ray;
}
else
{
const Ray new_ray = Ray(Rotate(m_o_axis, m_rotate_radian, ray.m_o, m_origin),
Rotate(m_o_axis, m_rotate_radian, ray.m_d), ray.m_tmin, ray.m_tmax, ray.m_depth);
r = &new_ray;
}
// then check all four AABB
bool hit = false;
for (int i = 0; i < 6; i++)
{
if (aabb[i].Intersect(*r))
{
hit = true;
// record_id(i);
}
}
ray.m_tmax = r->m_tmax;
return hit;
}
/*
void record_id(short hit_id)
{
m_hit_id = hit_id;
}
*/
Vector3 get_intersection_normal(const Ray &ray) const
{
const Ray *r;
// First rotate the ray
if (m_o_axis == Oriented_axis::NA || m_rotate_radian == 0)
{
r = &ray;
}
else
{
const Ray new_ray = Ray(Rotate(m_o_axis, m_rotate_radian, ray.m_o, m_origin),
Rotate(m_o_axis, m_rotate_radian, ray.m_d), ray.m_tmin, ray.m_tmax, ray.m_depth);
r = &new_ray;
}
short hit_id;
for (int i = 0; i < 6; i++)
{
if (aabb[i].Intersect(*r))
{
hit_id = i;
break;
// record_id(i);
}
}
Vector3 inter_normal = aabb[hit_id].get_intersection_normal(*r);
// return the rotated normal
return inter_normal;
}
Vector3 get_color(Vector3 intersect_point) const
{
return Vector3();
}
}; // namespace pathtracing
} // namespace pathtracing | 36.224806 | 136 | 0.543762 | [
"geometry",
"vector"
] |
191fe72f156b55e34f801a09ba4b6935659f8e58 | 20,960 | cpp | C++ | kuri_system_coordinator/src/soloplayer.cpp | kucars/kuri_mbzirc_challenge_3 | 9942aae773eb4d32971b43223e4fea1554c1c8c8 | [
"BSD-3-Clause"
] | 4 | 2019-03-02T12:55:51.000Z | 2019-07-23T08:45:17.000Z | kuri_system_coordinator/src/soloplayer.cpp | kucars/kuri_mbzirc_challenge_3 | 9942aae773eb4d32971b43223e4fea1554c1c8c8 | [
"BSD-3-Clause"
] | 2 | 2019-07-23T08:40:18.000Z | 2019-07-23T13:22:18.000Z | kuri_system_coordinator/src/soloplayer.cpp | kucars/kuri_mbzirc_challenge_3 | 9942aae773eb4d32971b43223e4fea1554c1c8c8 | [
"BSD-3-Clause"
] | 2 | 2018-06-08T01:40:13.000Z | 2019-07-23T11:24:22.000Z | /***************************************************************************
* Copyright (C) 2016 - 2017 by *
* Tarek Taha, KURI <tataha@tarektaha.com> *
* Randa Almadhoun <randa.almadhoun@kustar.ac.ae> *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Steet, Fifth Floor, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include <ros/ros.h>
#include <ros/package.h>
#include <geometry_msgs/TwistStamped.h>
#include <geometry_msgs/PoseStamped.h>
#include <mavros_msgs/CommandBool.h>
#include <mavros_msgs/SetMode.h>
#include <mavros_msgs/State.h>
#include <mavros_msgs/PositionTarget.h>
#include <mavros_msgs/GlobalPositionTarget.h>
#include <geometry_msgs/PoseArray.h>
#include <sensor_msgs/RegionOfInterest.h>
#include <std_msgs/Float64.h>
#include <std_msgs/Bool.h>
#include <std_msgs/Int64.h>
#include <nav_msgs/Path.h>
#include <tf/tf.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>
#include <tf_conversions/tf_eigen.h>
#include <tf/transform_datatypes.h>
#include <sensor_msgs/NavSatFix.h>
#include <nav_msgs/Odometry.h>
#include "geo.h"
#include <actionlib/client/simple_action_client.h>
#include "kuri_msgs/TrackingAction.h"
#include "kuri_msgs/TrackingActionFeedback.h"
#include "kuri_msgs/TrackingActionGoal.h"
#include "kuri_msgs/TrackingActionResult.h"
#include "kuri_msgs/TrackingGoal.h"
#include "kuri_msgs/TrackingResult.h"
#include "kuri_object_tracking/Object2Track.h"
#include "kuri_object_tracking/Object2TrackRequest.h"
#include "kuri_object_tracking/Object2TrackResponse.h"
#include "kuri_msgs/Object.h"
enum SOLO_STATES
{
INITIATION,
EXPLORING,
PICKING,
WAITING_FOR_DROP,
DROPPING
};
geometry_msgs::PoseStamped localPoseH; //with respect to home position
geometry_msgs::PoseStamped localPoseR; //with respect to a defined reference (ex: zurich, or one of the arena corners)
sensor_msgs::NavSatFix globalPose;
ros::Time objectLastTracked;
bool firstDataFlag = true;
int count = 0 ;
double tolerance = 0.3;
double errorX = 0;
double errorY = 0;
double errorZ = 0;
double errorW = 0;
double w = 0;
double yaw = 0;
float prevErrorX;
float prevErrorY;
float prevErrorZ;
float prevErrorW;
double tolerance2Goal = 0;
bool homePoseFlag = false;
bool transformDoneFlag = false;
std_msgs::Bool finishedFlag;
float pX;
float pY;
float pZ;
float pW;
float iX;
float iY;
float iZ;
float iW;
float dX;
float dY;
float dZ;
float dW;
float aX;
float aY;
float aZ;
float aW;
int stateNum;
double kp;
double ki;
double kd;
double kpx;
double kix;
double kdx;
double kpy;
double kiy;
double kdy;
double kpz;
double kiz;
double kdz;
double home_lat;
double home_lon;
geometry_msgs ::TwistStamped twist;
std::vector<sensor_msgs::NavSatFix> globalWaypoints;
geometry_msgs::PoseArray newLocalWaypoints;
geometry_msgs::PoseStamped goalPose;
geometry_msgs::PoseStamped idlePose;
geometry_msgs::PoseStamped dropZonePose;
nav_msgs::Path path;
mavros_msgs::State UAVState;
int currentState = INITIATION;
geometry_msgs ::Point real;
void mavrosStateCallback(const mavros_msgs::State::ConstPtr& msg)
{
UAVState = *msg;
}
void readWaypointsFromFile()
{
if(homePoseFlag)
{
count = 0;
double wpt_lat_ref,wpt_lon_ref;
ros::param::param("~ref_lat", wpt_lat_ref, 47.3977419);
ros::param::param("~ref_lon", wpt_lon_ref, 8.5455938);
std::string str1 = ros::package::getPath("kuri_system_coordinator")+"/config/exploration_waypoints_50.txt";
const char * filename1 = str1.c_str();
assert(filename1 != NULL);
filename1 = strdup(filename1);
FILE *file1 = fopen(filename1, "r");
if (!file1)
{
std::cout<<"\nCan not open File";
fclose(file1);
}
double locationx,locationy,locationz,qy;
geometry_msgs::PoseStamped pose;
std::cout<<" The local waypoints map reference: "<<(double)wpt_lat_ref<<" "<<(double)wpt_lon_ref<<std::endl;
double lat,lon;
float alt;
while (!feof(file1))
{
map_projection_global_init(wpt_lat_ref, wpt_lon_ref,1);
fscanf(file1,"%lf %lf %lf %lf\n",&locationx,&locationy,&locationz,&qy);
pose.pose.position.x = locationx;
pose.pose.position.y = locationy;
pose.pose.position.z = locationz;
pose.pose.orientation.x = qy;
path.poses.push_back(pose);
globallocalconverter_toglobal(locationy,locationx,locationz,&lat,&lon,&alt);
globalPose.latitude = lat;
globalPose.longitude = lon;
globalPose.altitude = alt*-1;
globalWaypoints.push_back(globalPose);
//convert to local with repsect to the uav home position
map_projection_global_init(home_lat, home_lon,1);
printf(" uav home position: x %f y %f \n",home_lat,home_lon);
float p_x,p_y,p_z;
globallocalconverter_tolocal(globalPose.latitude,globalPose.longitude, -1*globalPose.altitude,&p_y,&p_x,&p_z);
geometry_msgs::Pose pt;
pt.position.x = p_x;
pt.position.y = p_y;
pt.position.z = p_z;
printf(" new local pose: x %f y %f z %f \n",p_x,p_y,p_z);
newLocalWaypoints.poses.push_back(pt);
}
fclose(file1);
goalPose.pose.position.x = newLocalWaypoints.poses[count].position.x;
goalPose.pose.position.y = newLocalWaypoints.poses[count].position.y;
goalPose.pose.position.z = newLocalWaypoints.poses[count].position.z;
std::cout<<"**************** transformation Done ***************** "<<std::endl;
transformDoneFlag = true;
}
}
void localPoseCb(const geometry_msgs::PoseStamped::ConstPtr& msg)
{
localPoseH.pose.position.x= msg->pose.position.x;
localPoseH.pose.position.y= msg->pose.position.y;
localPoseH.pose.position.z= msg->pose.position.z;
if(currentState == EXPLORING)
{
errorX = goalPose.pose.position.x - localPoseH.pose.position.x;
errorY = goalPose.pose.position.y - localPoseH.pose.position.y;
errorZ = goalPose.pose.position.z - localPoseH.pose.position.z;
double dist = sqrt(errorX*errorX + errorY*errorY + errorZ*errorZ);
//std::cout<<"WayPoint["<<count<<"] Dist:"<<dist<<" Goal Pose X:"<<goalPose.pose.position.x<<" y:"<<goalPose.pose.position.y<<" z:"<<goalPose.pose.position.z<< " uav local pose x: "<<localPoseH.pose.position.x<<" y: "<< localPoseH.pose.position.y<<" z: "<< localPoseH.pose.position.z<<std::endl;
if(dist < tolerance)
{
count++;
if(count<newLocalWaypoints.poses.size())
{
std::cout<<"New WayPoint["<<count<<"] Dist:"<<dist<<" Goal Pose X:"<<goalPose.pose.position.x<<" y:"<<goalPose.pose.position.y<<" z:"<<goalPose.pose.position.z<< " uav local pose x: "<<localPoseH.pose.position.x<<" y: "<< localPoseH.pose.position.y<<" z: "<< localPoseH.pose.position.z<<std::endl;
//std::cout<<"new waypoints x: "<<newLocalWaypoints.poses[count].position.x<<" y: "<< newLocalWaypoints.poses[count].position.y<<" z: "<< newLocalWaypoints.poses[count].position.z<<std::endl;
// ROS_INFO("UAV %i : Sending a New uav local WayPoint(x,y,z):(%g,%g,%g)",uav_id,newLocalWaypoints.poses[count].position.x,newLocalWaypoints.poses[count].position.y,newLocalWaypoints.poses[count].position.z);
// ROS_INFO("UAV %i : Sending a New uav global WayPoint(x,y,z):(%g,%g,%g)",uav_id,globalWaypoints[count].latitude,globalWaypoints[count].longitude,globalWaypoints[count].altitude);
goalPose.pose.position.x = newLocalWaypoints.poses[count].position.x;
goalPose.pose.position.y = newLocalWaypoints.poses[count].position.y;
goalPose.pose.position.z = newLocalWaypoints.poses[count].position.z;
}
if(count>=newLocalWaypoints.poses.size())
{
transformDoneFlag=false;
idlePose.pose.position.x = newLocalWaypoints.poses[count-1].position.x;
idlePose.pose.position.y = newLocalWaypoints.poses[count-1].position.y;
idlePose.pose.position.z = newLocalWaypoints.poses[count-1].position.z;
currentState = PICKING;
//std::cout<<"uav_state: PICKING "<<currentState<<std::endl;
ROS_INFO("uav_state: PICKING ");
count=0;
newLocalWaypoints.poses.erase(newLocalWaypoints.poses.begin(),newLocalWaypoints.poses.end());
globalWaypoints.erase(globalWaypoints.begin(), globalWaypoints.end());
}
}
}
}
void trackedObjectCb(const kuri_msgs::ObjectConstPtr &msg)
{
objectLastTracked = ros::Time::now();
//ROS_INFO("Got object %d in sight", msg->object_id);
if(currentState == EXPLORING)
{
currentState = PICKING;
ROS_INFO("TRANSITIONING FROM EXPLORING:>> PICKING STATE");
twist.twist.linear.x = 0;
twist.twist.linear.y = 0;
twist.twist.linear.z = 0;
twist.twist.angular.z = 0;
}
//ROS_INFO("Got object %d in sight", msg->object_id);
if(currentState == WAITING_FOR_DROP)
{
if(localPoseH.pose.position.z < 4){
twist.twist.linear.x = 0;
twist.twist.linear.y = 0;
twist.twist.linear.z = 1;
}
}
if(currentState == PICKING)
{
ROS_INFO("PICKING object %d", msg->object_id);
real.x= 0 ; //msg ->latitude;
real.y= 0 ; //msg ->longitude;
real.z= 0 ; //msg ->altitude;
w = yaw ;
errorX = msg->pose.pose.position.x - real.x;
errorY = msg->pose.pose.position.y - real.y;
errorZ = msg->pose.pose.position.z - real.z ;
errorW = w;
if (firstDataFlag )
{
prevErrorX = errorX;
prevErrorY = errorY;
prevErrorZ = errorZ;
prevErrorW = errorW;
firstDataFlag = false;
twist.twist.linear.x = 0;
twist.twist.linear.y = 0;
twist.twist.linear.z = 0;
twist.twist.angular.z = 0;
}
else
{
errorX = msg->pose.pose.position.x;
errorY = msg->pose.pose.position.y;
errorZ = msg->pose.pose.position.z;
float mul = 10.0, error = 0.05;//will be different for camera if calibrated
/*
errorX *= mul;
errorY *= mul;
errorZ *= mul;
*/
errorW = 0;
pX = kpx * errorX;
pY = kpy * errorY;
pZ = kpz * errorZ;
pW = kp * errorW;
iX += kix * errorX;
iY += kiy * errorY;
iZ += kiz * errorZ;
iW += ki * errorW;
dX = kdx * (errorX - prevErrorX);
dY = kdy * (errorY - prevErrorY);
dZ = kdz * (errorZ - prevErrorZ);
dW = kd * (errorW - prevErrorW);
prevErrorX = errorX;
prevErrorY = errorY;
prevErrorZ = errorZ;
prevErrorW = errorW;
// PID conroller
aX = pX + iX + dX ;
aY = pY + iY + dY ;
aZ = pZ +iZ + dZ ;
aW = 10 * pW +iW + dW ;
if(fabs(errorX) > error || fabs(errorY) > error)
{
mul = 20;
aZ = 0;
}
if(localPoseH.pose.position.z > 4.0 && fabs(errorX) < error || fabs(errorY) < error){
aZ = 0.2;
}
aX *= -mul;
aY *= -mul;
// filling velocity commands
twist.twist.linear.x = aY;
twist.twist.linear.y = aX; //X and Y are flipped in the simulator, or camera rotated
twist.twist.linear.z = aZ*-20;
twist.twist.angular.z = aW;
twist.header.stamp = ros::Time::now();
/*
ROS_INFO("Error X: %0.2f \n", errorX);
ROS_INFO("Error Y: %0.2f \n", errorY);
ROS_INFO("Error Z: %0.2f \n", errorZ);
//ROS_INFO("derivative X: %0.2f \n", dX);
//ROS_INFO("derivative Y: %0.2f \n", dY);
//ROS_INFO("derivative Z: %0.2f \n", dZ);
//ROS_INFO("derivative W: %0.2f \n", dZ);
//ROS_INFO("W: %0.2f \n", w);*/
ROS_INFO("Action X: %0.2f \n", aX);
ROS_INFO("Action Y: %0.2f \n", aY);
ROS_INFO("Action Z: %0.2f \n", aZ);
ROS_INFO("Action W: %0.2f \n", aW);
double dist = sqrt(errorX*errorX+ errorY*errorY + errorZ*errorZ);
if (dist < tolerance2Goal)
{
twist.twist.linear.x = 0;
twist.twist.linear.y = 0;
twist.twist.linear.z = 0;
twist.twist.angular.z = 0;
}
//ROS_INFO("localPoseH.pose.position.z W: %0.2f \n", localPoseH.pose.position.z);
if(localPoseH.pose.position.z < 1.0)//assume object picked?
{
currentState = WAITING_FOR_DROP;
}
}
}
}
void globalPoseCb(const sensor_msgs::NavSatFix::ConstPtr& msg)
{
double lat,lon,alt;
lat=msg->latitude;
lon=msg->longitude;
alt=msg->altitude;
if(!homePoseFlag)
{
std::cout<<"Setting GPS home pose\n";
if(lat != 0 && lon != 0)
{
std::cout<<" - GPS home pose set\n";
home_lat = lat;
home_lon = lon;
homePoseFlag=true;
}
}
if(homePoseFlag)
{
geometry_msgs::Point pt;
pt.x = home_lat;
pt.y = home_lon;
}
}
void headingCallback(const std_msgs::Float64::ConstPtr& msg)
{
yaw = msg->data * 3.14159265359 / 180.0 ;
}
int main(int argc , char **argv)
{
ros::init(argc , argv , "playing_solo");
ros::NodeHandle nh;
ros::NodeHandle nhPrivate( "~" );
ros::Rate loopRate(20);
int UAVId = 2;
std::cout<<"starting"<<std::endl;
std::cout<<"UAVId: "<<UAVId<<std::endl;
//publishers and subscribers
ros::Subscriber statePub = nh.subscribe<mavros_msgs::State>
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/mavros/state", 10, mavrosStateCallback);
ros::Publisher localPosePub = nh.advertise<geometry_msgs::PoseStamped>
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/mavros/setpoint_position/local", 10);
ros::ServiceClient armingClient = nh.serviceClient<mavros_msgs::CommandBool>
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/mavros/cmd/arming");
ros::ServiceClient setModeClient = nh.serviceClient<mavros_msgs::SetMode>
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/mavros/set_mode");
ros::Subscriber currentPose = nh.subscribe
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/mavros/local_position/pose", 10, localPoseCb);
ros::Subscriber globalPoseSub = nh.subscribe
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/mavros/global_position/global", 10, globalPoseCb);
ros::Subscriber trackedObjSub = nh.subscribe
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/tracked_object/object", 10, trackedObjectCb);
//ros::Subscriber globalPoseSub;
ros::Publisher velPub = nh.advertise<geometry_msgs ::TwistStamped>
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/mavros/setpoint_velocity/cmd_vel", 10);
ros::Subscriber compassSub = nh.subscribe
("/uav_"+boost::lexical_cast<std::string>(UAVId)+"/mavros/global_position/compass_hdg", 10, headingCallback);
nh.param("kp", kp, 0.05);
nh.param("ki", ki, 0.0);
nh.param("kd", kd, 0.05);
nh.param("kpx", kpx, 0.05);
nh.param("kix", kix, 0.0);
nh.param("kdx", kdx, 0.05);
nh.param("kpy", kpy, 0.05);
nh.param("kiy", kiy, 0.0);
nh.param("kdy", kdy, 0.05);
nh.param("kp", kpz, 0.05);
nh.param("ki", kiz, 0.0);
nh.param("kd", kdz, 0.05);
nh.param("tolerance_2_goal", tolerance2Goal, 0.2);
goalPose.pose.position.x = 0;
goalPose.pose.position.y = 0;
goalPose.pose.position.z = 0;
geometry_msgs ::TwistStamped stopTwist;
stopTwist.twist.linear.x = 0;
stopTwist.twist.linear.y = 0;
stopTwist.twist.linear.z = 0;
stopTwist.twist.angular.z = 0;
ros::ServiceClient objectsTrackingServiceClient = nh.serviceClient<kuri_object_tracking::Object2Track>("trackObjectService");
kuri_object_tracking::Object2Track objSRV;
bool objectTrackingInitiated = false;
// wait for FCU connection
while(ros::ok() && UAVState.connected)
{
ros::spinOnce();
loopRate.sleep();
}
idlePose.pose.position.x = 0;
idlePose.pose.position.y = 0;
idlePose.pose.position.z = 7;
mavros_msgs::SetMode offb_set_mode;
offb_set_mode.request.custom_mode = "OFFBOARD";
mavros_msgs::CommandBool arm_cmd;
arm_cmd.request.value = true;
//TODO:
// - Check FCU are correct
// - Perform System Checks
// - Offboard launch
// - Follow the waypoints
// - Find objects (object tracker)
// - Once found Pick
// - Hover at X altitude
// - Ask permission to drop
// - if granted go, otherwise, wait
// - Go again and continue
ros::Time lastRequest = ros::Time::now();
ros::Time statusUpdate = ros::Time::now();
ros::Time waitingForOFF = ros::Time::now();
while(ros::ok())
{
switch(currentState)
{
case INITIATION:
/* This code overrides the RC mode and is dangerous when performing tests: re-use in real flight tests*/
if( UAVState.mode != "OFFBOARD" && (ros::Time::now() - lastRequest > ros::Duration(1.0)))
{
if( setModeClient.call(offb_set_mode) && offb_set_mode.response.success)
{
ROS_INFO("Offboard enabled");
}
else
{
ROS_ERROR("Failed Enabling offboard");
}
lastRequest = ros::Time::now();
}
if( UAVState.mode != "OFFBOARD")
{
if(ros::Time::now() - waitingForOFF > ros::Duration(0.5))
{
std::cout<<"USE RC to set the system in offboard mode => Current Mode is: "<<UAVState.mode<<"\n"; fflush(stdout);
waitingForOFF = ros::Time::now();
}
}
else
{
if( !UAVState.armed && (ros::Time::now() - lastRequest > ros::Duration(1.0)))
{
if( armingClient.call(arm_cmd) && arm_cmd.response.success)
{
ROS_INFO("ARMING Command send through mavros, check messages related to safety switch");
currentState = EXPLORING;
ROS_INFO("TRANSITIONING FROM INITIATION STATE:>> EXPLORING STATE");
readWaypointsFromFile();
}
else
{
ROS_INFO("Sending Arming message FAILED!");
}
lastRequest = ros::Time::now();
}
}
localPosePub.publish(idlePose);
break;
case EXPLORING:
//once the transform to local in terms of the home position is done
if(transformDoneFlag)
{
if(!objectTrackingInitiated)
{
/*
goal.uav_id = 2;
objectsTrackingClient.sendGoal(goal,&objectTrackingDoneCallBack, &objectTrackingActiveCallback, &objectTrackingFeedbackCallback);
*/
objSRV.request.color = "all";
if(objectsTrackingServiceClient.call(objSRV))
{
ROS_INFO("Object Tracking: Call successfull");
}
else
{
ROS_ERROR("Object Tracking: Failed to call service");
}
objectTrackingInitiated = true;
}
localPosePub.publish(goalPose);
}
else
{
localPosePub.publish(idlePose);
}
case PICKING:
// Failsafe: if we don't get tracking info for more than 500ms, then stop in place, or go back to exploring?
if(ros::Time::now() - objectLastTracked > ros::Duration(0.5))
{
stopTwist.header.stamp = ros::Time::now();
velPub.publish(stopTwist);
ROS_INFO("TRANSITIONING FROM INITIATION PICKING:>> EXPLORING STATE");
currentState = EXPLORING;
}
else
{
velPub.publish(twist);
}
break;
case WAITING_FOR_DROP:
//hold position?
case DROPPING://Insert dropzone GPS location, or nearby, and can use camera to detect drop zone.
dropZonePose.pose.position.x = -19.0;
dropZonePose.pose.position.y = 0.0;
dropZonePose.pose.position.z = 7;
localPosePub.publish(dropZonePose);
default:
ROS_ERROR("Unknown State");
}
if(ros::Time::now() - statusUpdate > ros::Duration(1.0))
{
std::cout<<"Current Mode is: "<<UAVState.mode<<"\n"; fflush(stdout);
statusUpdate = ros::Time::now();
}
ros::spinOnce();
loopRate.sleep();
}
}
| 34.081301 | 305 | 0.619275 | [
"object",
"vector",
"transform"
] |
19222da5c4add78301baeb169abf18696c1c9179 | 605 | cpp | C++ | src/send.cpp | b1ackturtle/Etherimg | 5084cc8de256190f648ec864d2b4f6d2ed9cf2b8 | [
"MIT"
] | null | null | null | src/send.cpp | b1ackturtle/Etherimg | 5084cc8de256190f648ec864d2b4f6d2ed9cf2b8 | [
"MIT"
] | null | null | null | src/send.cpp | b1ackturtle/Etherimg | 5084cc8de256190f648ec864d2b4f6d2ed9cf2b8 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <unistd.h>
#include <chrono>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "lib.h"
#include "etherimg.h"
int main(int argc, char *argv[])
{
cv::VideoCapture cam(atoi(argv[2]));
cam.set(CV_CAP_PROP_FRAME_WIDTH, atoi(argv[3]));
cam.set(CV_CAP_PROP_FRAME_HEIGHT, atoi(argv[4]));
cv::Mat img;
while(1) {
cam >> img;
imshow("test", img);
etherimg_send(argv[1], img);
if(cv::waitKey(20) == 'q') break;
}
return 0;
}
| 17.285714 | 51 | 0.647934 | [
"vector"
] |
1929a6338bbc4cf14f164784ede773884f58e9bf | 16,917 | cpp | C++ | third-party/llvm/llvm-src/unittests/Frontend/OpenACCTest.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | third-party/llvm/llvm-src/unittests/Frontend/OpenACCTest.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | third-party/llvm/llvm-src/unittests/Frontend/OpenACCTest.cpp | jhh67/chapel | f041470e9b88b5fc4914c75aa5a37efcb46aa08f | [
"ECL-2.0",
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | //===- llvm/unittest/Frontend/OpenACCTest.cpp - OpenACC Frontend tests ----===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Frontend/OpenACC/ACC.h.inc"
#include "gtest/gtest.h"
using namespace llvm;
using namespace acc;
namespace {
static const Clause AllClauses[] = {ACCC_unknown,
ACCC_async,
ACCC_attach,
ACCC_auto,
ACCC_bind,
ACCC_capture,
ACCC_collapse,
ACCC_copy,
ACCC_copyin,
ACCC_copyout,
ACCC_create,
ACCC_default,
ACCC_default_async,
ACCC_delete,
ACCC_detach,
ACCC_device,
ACCC_device_num,
ACCC_deviceptr,
ACCC_device_resident,
ACCC_device_type,
ACCC_finalize,
ACCC_firstprivate,
ACCC_gang,
ACCC_host,
ACCC_if,
ACCC_if_present,
ACCC_independent,
ACCC_link,
ACCC_no_create,
ACCC_nohost,
ACCC_num_gangs,
ACCC_num_workers,
ACCC_present,
ACCC_private,
ACCC_read,
ACCC_reduction,
ACCC_self,
ACCC_seq,
ACCC_tile,
ACCC_unknown,
ACCC_use_device,
ACCC_vector,
ACCC_vector_length,
ACCC_wait,
ACCC_worker,
ACCC_write};
TEST(OpenACCTest, DirectiveHelpers) {
EXPECT_EQ(getOpenACCDirectiveKind(""), ACCD_unknown);
EXPECT_EQ(getOpenACCDirectiveKind("dummy"), ACCD_unknown);
EXPECT_EQ(getOpenACCDirectiveKind("atomic"), ACCD_atomic);
EXPECT_EQ(getOpenACCDirectiveKind("cache"), ACCD_cache);
EXPECT_EQ(getOpenACCDirectiveKind("data"), ACCD_data);
EXPECT_EQ(getOpenACCDirectiveKind("declare"), ACCD_declare);
EXPECT_EQ(getOpenACCDirectiveKind("enter data"), ACCD_enter_data);
EXPECT_EQ(getOpenACCDirectiveKind("exit data"), ACCD_exit_data);
EXPECT_EQ(getOpenACCDirectiveKind("host_data"), ACCD_host_data);
EXPECT_EQ(getOpenACCDirectiveKind("init"), ACCD_init);
EXPECT_EQ(getOpenACCDirectiveKind("kernels"), ACCD_kernels);
EXPECT_EQ(getOpenACCDirectiveKind("kernels loop"), ACCD_kernels_loop);
EXPECT_EQ(getOpenACCDirectiveKind("loop"), ACCD_loop);
EXPECT_EQ(getOpenACCDirectiveKind("parallel"), ACCD_parallel);
EXPECT_EQ(getOpenACCDirectiveKind("parallel loop"), ACCD_parallel_loop);
EXPECT_EQ(getOpenACCDirectiveKind("routine"), ACCD_routine);
EXPECT_EQ(getOpenACCDirectiveKind("serial"), ACCD_serial);
EXPECT_EQ(getOpenACCDirectiveKind("serial loop"), ACCD_serial_loop);
EXPECT_EQ(getOpenACCDirectiveKind("set"), ACCD_set);
EXPECT_EQ(getOpenACCDirectiveKind("shutdown"), ACCD_shutdown);
EXPECT_EQ(getOpenACCDirectiveKind("unknown"), ACCD_unknown);
EXPECT_EQ(getOpenACCDirectiveKind("update"), ACCD_update);
EXPECT_EQ(getOpenACCDirectiveKind("wait"), ACCD_wait);
EXPECT_EQ(getOpenACCDirectiveName(ACCD_atomic), "atomic");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_cache), "cache");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_data), "data");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_declare), "declare");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_enter_data), "enter data");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_exit_data), "exit data");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_host_data), "host_data");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_init), "init");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_kernels), "kernels");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_kernels_loop), "kernels loop");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_loop), "loop");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_parallel), "parallel");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_parallel_loop), "parallel loop");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_routine), "routine");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_serial), "serial");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_serial_loop), "serial loop");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_set), "set");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_shutdown), "shutdown");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_unknown), "unknown");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_update), "update");
EXPECT_EQ(getOpenACCDirectiveName(ACCD_wait), "wait");
}
TEST(OpenACCTest, ClauseHelpers) {
EXPECT_EQ(getOpenACCClauseKind(""), ACCC_unknown);
EXPECT_EQ(getOpenACCClauseKind("dummy"), ACCC_unknown);
EXPECT_EQ(getOpenACCClauseKind("async"), ACCC_async);
EXPECT_EQ(getOpenACCClauseKind("attach"), ACCC_attach);
EXPECT_EQ(getOpenACCClauseKind("auto"), ACCC_auto);
EXPECT_EQ(getOpenACCClauseKind("bind"), ACCC_bind);
EXPECT_EQ(getOpenACCClauseKind("capture"), ACCC_capture);
EXPECT_EQ(getOpenACCClauseKind("collapse"), ACCC_collapse);
EXPECT_EQ(getOpenACCClauseKind("copy"), ACCC_copy);
EXPECT_EQ(getOpenACCClauseKind("copyin"), ACCC_copyin);
EXPECT_EQ(getOpenACCClauseKind("copyout"), ACCC_copyout);
EXPECT_EQ(getOpenACCClauseKind("create"), ACCC_create);
EXPECT_EQ(getOpenACCClauseKind("default"), ACCC_default);
EXPECT_EQ(getOpenACCClauseKind("default_async"), ACCC_default_async);
EXPECT_EQ(getOpenACCClauseKind("delete"), ACCC_delete);
EXPECT_EQ(getOpenACCClauseKind("detach"), ACCC_detach);
EXPECT_EQ(getOpenACCClauseKind("device"), ACCC_device);
EXPECT_EQ(getOpenACCClauseKind("device_num"), ACCC_device_num);
EXPECT_EQ(getOpenACCClauseKind("deviceptr"), ACCC_deviceptr);
EXPECT_EQ(getOpenACCClauseKind("device_resident"), ACCC_device_resident);
EXPECT_EQ(getOpenACCClauseKind("device_type"), ACCC_device_type);
EXPECT_EQ(getOpenACCClauseKind("finalize"), ACCC_finalize);
EXPECT_EQ(getOpenACCClauseKind("firstprivate"), ACCC_firstprivate);
EXPECT_EQ(getOpenACCClauseKind("gang"), ACCC_gang);
EXPECT_EQ(getOpenACCClauseKind("host"), ACCC_host);
EXPECT_EQ(getOpenACCClauseKind("if"), ACCC_if);
EXPECT_EQ(getOpenACCClauseKind("if_present"), ACCC_if_present);
EXPECT_EQ(getOpenACCClauseKind("independent"), ACCC_independent);
EXPECT_EQ(getOpenACCClauseKind("link"), ACCC_link);
EXPECT_EQ(getOpenACCClauseKind("no_create"), ACCC_no_create);
EXPECT_EQ(getOpenACCClauseKind("nohost"), ACCC_nohost);
EXPECT_EQ(getOpenACCClauseKind("num_gangs"), ACCC_num_gangs);
EXPECT_EQ(getOpenACCClauseKind("num_workers"), ACCC_num_workers);
EXPECT_EQ(getOpenACCClauseKind("present"), ACCC_present);
EXPECT_EQ(getOpenACCClauseKind("private"), ACCC_private);
EXPECT_EQ(getOpenACCClauseKind("read"), ACCC_read);
EXPECT_EQ(getOpenACCClauseKind("reduction"), ACCC_reduction);
EXPECT_EQ(getOpenACCClauseKind("self"), ACCC_self);
EXPECT_EQ(getOpenACCClauseKind("seq"), ACCC_seq);
EXPECT_EQ(getOpenACCClauseKind("tile"), ACCC_tile);
EXPECT_EQ(getOpenACCClauseKind("unknown"), ACCC_unknown);
EXPECT_EQ(getOpenACCClauseKind("use_device"), ACCC_use_device);
EXPECT_EQ(getOpenACCClauseKind("vector"), ACCC_vector);
EXPECT_EQ(getOpenACCClauseKind("vector_length"), ACCC_vector_length);
EXPECT_EQ(getOpenACCClauseKind("wait"), ACCC_wait);
EXPECT_EQ(getOpenACCClauseKind("worker"), ACCC_worker);
EXPECT_EQ(getOpenACCClauseKind("write"), ACCC_write);
EXPECT_EQ(getOpenACCClauseName(ACCC_async), "async");
EXPECT_EQ(getOpenACCClauseName(ACCC_attach), "attach");
EXPECT_EQ(getOpenACCClauseName(ACCC_auto), "auto");
EXPECT_EQ(getOpenACCClauseName(ACCC_bind), "bind");
EXPECT_EQ(getOpenACCClauseName(ACCC_capture), "capture");
EXPECT_EQ(getOpenACCClauseName(ACCC_collapse), "collapse");
EXPECT_EQ(getOpenACCClauseName(ACCC_copy), "copy");
EXPECT_EQ(getOpenACCClauseName(ACCC_copyin), "copyin");
EXPECT_EQ(getOpenACCClauseName(ACCC_copyout), "copyout");
EXPECT_EQ(getOpenACCClauseName(ACCC_create), "create");
EXPECT_EQ(getOpenACCClauseName(ACCC_default), "default");
EXPECT_EQ(getOpenACCClauseName(ACCC_default_async), "default_async");
EXPECT_EQ(getOpenACCClauseName(ACCC_delete), "delete");
EXPECT_EQ(getOpenACCClauseName(ACCC_detach), "detach");
EXPECT_EQ(getOpenACCClauseName(ACCC_device), "device");
EXPECT_EQ(getOpenACCClauseName(ACCC_device_num), "device_num");
EXPECT_EQ(getOpenACCClauseName(ACCC_deviceptr), "deviceptr");
EXPECT_EQ(getOpenACCClauseName(ACCC_device_resident), "device_resident");
EXPECT_EQ(getOpenACCClauseName(ACCC_device_type), "device_type");
EXPECT_EQ(getOpenACCClauseName(ACCC_finalize), "finalize");
EXPECT_EQ(getOpenACCClauseName(ACCC_firstprivate), "firstprivate");
EXPECT_EQ(getOpenACCClauseName(ACCC_gang), "gang");
EXPECT_EQ(getOpenACCClauseName(ACCC_host), "host");
EXPECT_EQ(getOpenACCClauseName(ACCC_if), "if");
EXPECT_EQ(getOpenACCClauseName(ACCC_if_present), "if_present");
EXPECT_EQ(getOpenACCClauseName(ACCC_independent), "independent");
EXPECT_EQ(getOpenACCClauseName(ACCC_link), "link");
EXPECT_EQ(getOpenACCClauseName(ACCC_no_create), "no_create");
EXPECT_EQ(getOpenACCClauseName(ACCC_nohost), "nohost");
EXPECT_EQ(getOpenACCClauseName(ACCC_num_gangs), "num_gangs");
EXPECT_EQ(getOpenACCClauseName(ACCC_num_workers), "num_workers");
EXPECT_EQ(getOpenACCClauseName(ACCC_present), "present");
EXPECT_EQ(getOpenACCClauseName(ACCC_private), "private");
EXPECT_EQ(getOpenACCClauseName(ACCC_read), "read");
EXPECT_EQ(getOpenACCClauseName(ACCC_reduction), "reduction");
EXPECT_EQ(getOpenACCClauseName(ACCC_self), "self");
EXPECT_EQ(getOpenACCClauseName(ACCC_seq), "seq");
EXPECT_EQ(getOpenACCClauseName(ACCC_tile), "tile");
EXPECT_EQ(getOpenACCClauseName(ACCC_unknown), "unknown");
EXPECT_EQ(getOpenACCClauseName(ACCC_use_device), "use_device");
EXPECT_EQ(getOpenACCClauseName(ACCC_vector), "vector");
EXPECT_EQ(getOpenACCClauseName(ACCC_vector_length), "vector_length");
EXPECT_EQ(getOpenACCClauseName(ACCC_wait), "wait");
EXPECT_EQ(getOpenACCClauseName(ACCC_worker), "worker");
EXPECT_EQ(getOpenACCClauseName(ACCC_write), "write");
}
static void expectAllowedClauses(Directive Dir, unsigned Version,
const ArrayRef<Clause> &AllowedClauses) {
SmallSet<Clause, 30> AllowedClausesSet;
for (Clause Cl : AllowedClauses) {
EXPECT_TRUE(isAllowedClauseForDirective(Dir, Cl, Version));
AllowedClausesSet.insert(Cl);
}
for (Clause Cl : AllClauses) {
if (!AllowedClausesSet.contains(Cl)) {
EXPECT_FALSE(isAllowedClauseForDirective(Dir, Cl, Version));
}
}
}
TEST(OpenACCTest, AllowedClause) {
expectAllowedClauses(ACCD_atomic, 3, {});
expectAllowedClauses(ACCD_cache, 3, {});
expectAllowedClauses(ACCD_unknown, 3, {});
expectAllowedClauses(ACCD_parallel, 0, {}); // Version starts at 1
expectAllowedClauses(ACCD_data, 3,
{ACCC_if, ACCC_attach, ACCC_copy, ACCC_copyin,
ACCC_copyout, ACCC_create, ACCC_default, ACCC_deviceptr,
ACCC_no_create, ACCC_present});
expectAllowedClauses(ACCD_declare, 3,
{ACCC_copy, ACCC_copyin, ACCC_copyout, ACCC_create,
ACCC_present, ACCC_deviceptr, ACCC_device_resident,
ACCC_link});
expectAllowedClauses(
ACCD_enter_data, 3,
{ACCC_async, ACCC_if, ACCC_wait, ACCC_attach, ACCC_create, ACCC_copyin});
expectAllowedClauses(ACCD_exit_data, 3,
{ACCC_async, ACCC_if, ACCC_wait, ACCC_finalize,
ACCC_copyout, ACCC_delete, ACCC_detach});
expectAllowedClauses(ACCD_host_data, 3,
{ACCC_if, ACCC_if_present, ACCC_use_device});
expectAllowedClauses(ACCD_init, 3,
{ACCC_device_num, ACCC_device_type, ACCC_if});
expectAllowedClauses(ACCD_kernels, 3,
{ACCC_attach, ACCC_copy, ACCC_copyin, ACCC_copyout,
ACCC_create, ACCC_device_type, ACCC_no_create,
ACCC_present, ACCC_deviceptr, ACCC_async, ACCC_default,
ACCC_if, ACCC_num_gangs, ACCC_num_workers, ACCC_self,
ACCC_vector_length, ACCC_wait});
expectAllowedClauses(
ACCD_kernels_loop, 3,
{ACCC_copy, ACCC_copyin, ACCC_copyout, ACCC_create,
ACCC_device_type, ACCC_no_create, ACCC_present, ACCC_private,
ACCC_deviceptr, ACCC_attach, ACCC_async, ACCC_collapse,
ACCC_default, ACCC_gang, ACCC_if, ACCC_num_gangs,
ACCC_num_workers, ACCC_reduction, ACCC_self, ACCC_tile,
ACCC_vector, ACCC_vector_length, ACCC_wait, ACCC_worker,
ACCC_auto, ACCC_independent, ACCC_seq});
expectAllowedClauses(ACCD_loop, 3,
{ACCC_device_type, ACCC_private, ACCC_collapse,
ACCC_gang, ACCC_reduction, ACCC_tile, ACCC_vector,
ACCC_worker, ACCC_auto, ACCC_independent, ACCC_seq});
expectAllowedClauses(ACCD_parallel, 3,
{ACCC_async, ACCC_wait, ACCC_num_gangs,
ACCC_num_workers, ACCC_vector_length, ACCC_device_type,
ACCC_if, ACCC_self, ACCC_reduction,
ACCC_copy, ACCC_copyin, ACCC_copyout,
ACCC_create, ACCC_no_create, ACCC_present,
ACCC_deviceptr, ACCC_attach, ACCC_private,
ACCC_firstprivate, ACCC_default});
expectAllowedClauses(
ACCD_parallel_loop, 3,
{ACCC_attach, ACCC_copy, ACCC_copyin, ACCC_copyout,
ACCC_create, ACCC_deviceptr, ACCC_device_type, ACCC_firstprivate,
ACCC_no_create, ACCC_present, ACCC_private, ACCC_tile,
ACCC_wait, ACCC_async, ACCC_collapse, ACCC_default,
ACCC_gang, ACCC_if, ACCC_num_gangs, ACCC_num_workers,
ACCC_reduction, ACCC_self, ACCC_vector, ACCC_vector_length,
ACCC_worker, ACCC_auto, ACCC_independent, ACCC_seq});
expectAllowedClauses(ACCD_routine, 3,
{ACCC_bind, ACCC_device_type, ACCC_nohost, ACCC_gang,
ACCC_seq, ACCC_vector, ACCC_worker});
expectAllowedClauses(ACCD_serial, 3,
{ACCC_attach, ACCC_copy, ACCC_copyin, ACCC_copyout,
ACCC_create, ACCC_deviceptr, ACCC_device_type,
ACCC_firstprivate, ACCC_no_create, ACCC_present,
ACCC_private, ACCC_wait, ACCC_async, ACCC_default,
ACCC_if, ACCC_reduction, ACCC_self});
expectAllowedClauses(
ACCD_serial_loop, 3,
{ACCC_attach, ACCC_copy, ACCC_copyin, ACCC_copyout,
ACCC_create, ACCC_deviceptr, ACCC_device_type, ACCC_firstprivate,
ACCC_no_create, ACCC_present, ACCC_private, ACCC_wait,
ACCC_async, ACCC_collapse, ACCC_default, ACCC_gang,
ACCC_if, ACCC_reduction, ACCC_self, ACCC_tile,
ACCC_vector, ACCC_worker, ACCC_auto, ACCC_independent,
ACCC_seq});
expectAllowedClauses(
ACCD_set, 3,
{ACCC_default_async, ACCC_device_num, ACCC_device_type, ACCC_if});
expectAllowedClauses(ACCD_shutdown, 3,
{ACCC_device_num, ACCC_device_type, ACCC_if});
expectAllowedClauses(ACCD_update, 3,
{ACCC_async, ACCC_wait, ACCC_device_type, ACCC_if,
ACCC_if_present, ACCC_self, ACCC_host, ACCC_device});
expectAllowedClauses(ACCD_wait, 3, {ACCC_async, ACCC_if});
}
} // namespace
| 50.801802 | 80 | 0.661583 | [
"vector"
] |
192b521e2fcd309bee6983c4f0376c873a690bfe | 27,228 | cc | C++ | statechart/internal/model_builder_test.cc | google/statechar | d283cefab5a051a91c21be46d97bc18407fd7628 | [
"Apache-2.0"
] | 93 | 2018-05-02T06:31:13.000Z | 2022-03-30T07:32:47.000Z | statechart/internal/model_builder_test.cc | google/statechar | d283cefab5a051a91c21be46d97bc18407fd7628 | [
"Apache-2.0"
] | 2 | 2019-07-10T18:15:27.000Z | 2022-01-01T19:41:18.000Z | statechart/internal/model_builder_test.cc | google/statechar | d283cefab5a051a91c21be46d97bc18407fd7628 | [
"Apache-2.0"
] | 31 | 2018-06-03T08:31:54.000Z | 2021-10-16T22:52:44.000Z | // Copyright 2018 The StateChart 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 "statechart/internal/model_builder.h"
#include <memory>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "statechart/internal/model.h"
#include "statechart/internal/model/model.h"
#include "statechart/internal/testing/mock_executable_content.h"
#include "statechart/internal/testing/mock_runtime.h"
#include "statechart/internal/testing/mock_state.h"
#include "statechart/internal/testing/mock_transition.h"
#include "statechart/internal/testing/state_chart_builder.h"
#include "statechart/platform/map_util.h"
#include "statechart/platform/protobuf.h"
#include "statechart/platform/test_util.h"
#include "statechart/proto/state_chart.pb.h"
// The following tests must be written, once support for them has been added to
// ModelBuilder:
//
// 1) Building parallel states.
// 2) Building the final state.
// 5) Child states
// 7) Invoke
// 8) History
// 9) Initial ID/transition on a parallel state.
namespace state_chart {
namespace {
using ::gtl::InsertOrDie;
using ::gtl::InsertOrUpdate;
using ::testing::_;
using ::testing::DoAll;
using ::testing::ElementsAre;
using ::testing::EqualsProtobuf;
using ::testing::InSequence;
using ::testing::NiceMock;
using ::testing::Return;
using ::testing::SetArgPointee;
#define TEST_MODEL_BUILDER_DEFAULT(method) \
ON_CALL(*this, method(_)) \
.WillByDefault(testing::Invoke(this, &TestModelBuilder::Real##method));
#define TEST_MODEL_BUILDER_DELEGATE(return_type, arg_type, method) \
return_type Real##method(arg_type e) { return ModelBuilder::method(e); }
class TestModelBuilder : public ModelBuilder {
public:
explicit TestModelBuilder(const config::StateChart& state_chart)
: ModelBuilder(state_chart) {
TEST_MODEL_BUILDER_DEFAULT(BuildExecutableContent);
TEST_MODEL_BUILDER_DEFAULT(BuildExecutableBlock);
TEST_MODEL_BUILDER_DEFAULT(BuildDataModelBlock);
TEST_MODEL_BUILDER_DEFAULT(BuildRaise);
TEST_MODEL_BUILDER_DEFAULT(BuildLog);
TEST_MODEL_BUILDER_DEFAULT(BuildAssign);
TEST_MODEL_BUILDER_DEFAULT(BuildSend);
TEST_MODEL_BUILDER_DEFAULT(BuildIf);
TEST_MODEL_BUILDER_DEFAULT(BuildForEach);
TEST_MODEL_BUILDER_DEFAULT(BuildState);
TEST_MODEL_BUILDER_DEFAULT(BuildTransitionsForState);
}
MOCK_METHOD1(BuildExecutableContent,
model::ExecutableContent*(const config::ExecutableElement&));
MOCK_METHOD1(BuildExecutableBlock,
model::ExecutableContent*(
const proto2::RepeatedPtrField<config::ExecutableElement>&));
MOCK_METHOD1(BuildDataModelBlock,
model::ExecutableContent*(const config::DataModel&));
MOCK_METHOD1(BuildRaise, model::Raise*(const config::Raise&));
MOCK_METHOD1(BuildLog, model::Log*(const config::Log&));
MOCK_METHOD1(BuildAssign, model::Assign*(const config::Assign&));
MOCK_METHOD1(BuildSend, model::Send*(const config::Send&));
MOCK_METHOD1(BuildIf, model::If*(const config::If&));
MOCK_METHOD1(BuildForEach, model::ForEach*(const config::ForEach&));
MOCK_METHOD1(BuildState, model::State*(const config::StateElement&));
MOCK_METHOD1(BuildTransitionsForState, bool(model::State*));
using ModelBuilder::all_elements_;
using ModelBuilder::datamodel_block_;
using ModelBuilder::initial_transition_;
using ModelBuilder::states_config_map_;
using ModelBuilder::states_map_;
using ModelBuilder::top_level_states_;
protected:
// Delegates to parent (real) implementations.
TEST_MODEL_BUILDER_DELEGATE(model::ExecutableContent*,
const config::ExecutableElement&,
BuildExecutableContent);
TEST_MODEL_BUILDER_DELEGATE(
model::ExecutableContent*,
const proto2::RepeatedPtrField<config::ExecutableElement>&,
BuildExecutableBlock);
TEST_MODEL_BUILDER_DELEGATE(model::ExecutableContent*,
const config::DataModel&, BuildDataModelBlock);
TEST_MODEL_BUILDER_DELEGATE(model::Raise*, const config::Raise&, BuildRaise);
TEST_MODEL_BUILDER_DELEGATE(model::Log*, const config::Log&, BuildLog);
TEST_MODEL_BUILDER_DELEGATE(model::Assign*, const config::Assign&,
BuildAssign);
TEST_MODEL_BUILDER_DELEGATE(model::Send*, const config::Send&, BuildSend);
TEST_MODEL_BUILDER_DELEGATE(model::If*, const config::If&, BuildIf);
TEST_MODEL_BUILDER_DELEGATE(model::ForEach*, const config::ForEach&,
BuildForEach);
TEST_MODEL_BUILDER_DELEGATE(model::State*, const config::StateElement&,
BuildState);
TEST_MODEL_BUILDER_DELEGATE(bool, model::State*, BuildTransitionsForState);
};
class ModelBuilderTest : public ::testing::Test {
protected:
void Reset() { builder_.reset(new NiceMock<TestModelBuilder>(state_chart_)); }
MockRuntime runtime_;
config::StateChart state_chart_;
std::unique_ptr<TestModelBuilder> builder_;
};
TEST_F(ModelBuilderTest, BuildExecutableBlock) {
Reset();
const model::ExecutableContent* block = nullptr;
// Empty case.
proto2::RepeatedPtrField<config::ExecutableElement> elements;
block = builder_->BuildExecutableBlock(elements);
ASSERT_EQ(nullptr, block);
config::ExecutableBlockBuilder(&elements).AddRaise("foo").AddRaise("bar");
MockExecutableContent executable_foo;
MockExecutableContent executable_bar;
{
InSequence s;
EXPECT_CALL(*builder_,
BuildExecutableContent(EqualsProtobuf(elements.Get(0))))
.WillOnce(Return(&executable_foo));
EXPECT_CALL(*builder_,
BuildExecutableContent(EqualsProtobuf(elements.Get(1))))
.WillOnce(Return(&executable_bar));
}
block = builder_->BuildExecutableBlock(elements);
ASSERT_NE(nullptr, block);
// Show that the new executable runs both of the above individual executables.
InSequence s;
EXPECT_CALL(executable_foo, Execute(&runtime_));
EXPECT_CALL(executable_bar, Execute(&runtime_));
block->Execute(&runtime_);
}
TEST_F(ModelBuilderTest, BuildDataModelBlock) {
Reset();
config::DataModel data_model;
// Empty case.
const model::ExecutableContent* block = nullptr;
block = builder_->BuildDataModelBlock(data_model);
ASSERT_EQ(nullptr, block);
config::DataModelBuilder(&data_model)
.AddDataFromExpr("id1", "expr1")
.AddDataFromSrc("id2", "expr2");
block = builder_->BuildDataModelBlock(data_model);
ASSERT_NE(nullptr, block);
// Now show that the individual data assignment executables were correctly
// created by running them against a MockRuntime.
InSequence s;
EXPECT_CALL(runtime_.GetDefaultMockDatamodel(), Declare("id1"))
.WillOnce(Return(true));
EXPECT_CALL(runtime_.GetDefaultMockDatamodel(),
AssignExpression("id1", "expr1"))
.WillOnce(Return(true));
EXPECT_CALL(runtime_.GetDefaultMockDatamodel(), Declare("id2"))
.WillOnce(Return(true));
EXPECT_CALL(runtime_.GetDefaultMockDatamodel(),
AssignExpression("id2", "expr2"))
.WillOnce(Return(true));
block->Execute(&runtime_);
}
TEST_F(ModelBuilderTest, BuildExecutableContent) {
Reset();
{ // Raise
config::ExecutableElement e;
e.mutable_raise()->set_event("event");
model::Raise* expected = new model::Raise("event");
EXPECT_CALL(*builder_, BuildRaise(EqualsProtobuf(e.raise())))
.WillOnce(Return(expected));
EXPECT_EQ(expected, builder_->BuildExecutableContent(e));
}
{ // Log
config::ExecutableElement e;
e.mutable_log()->set_expr("expr");
model::Log* expected = new model::Log("", "expr");
EXPECT_CALL(*builder_, BuildLog(EqualsProtobuf(e.log())))
.WillOnce(Return(expected));
EXPECT_EQ(expected, builder_->BuildExecutableContent(e));
}
{ // Assign
config::ExecutableElement e;
e.mutable_assign()->set_expr("expr");
model::Assign* expected = new model::Assign("", "expr");
EXPECT_CALL(*builder_, BuildAssign(EqualsProtobuf(e.assign())))
.WillOnce(Return(expected));
EXPECT_EQ(expected, builder_->BuildExecutableContent(e));
}
{ // Send
using model::Expr;
config::ExecutableElement e;
auto* send = e.mutable_send();
send->set_event("event");
send->set_targetexpr("targetexpr");
send->set_id("id");
auto* expected = new model::Send("event", Expr("targetexpr"), "id", "");
EXPECT_CALL(*builder_, BuildSend(EqualsProtobuf(e.send())))
.WillOnce(Return(expected));
EXPECT_EQ(expected, builder_->BuildExecutableContent(e));
}
{ // If
config::ExecutableElement e;
e.mutable_if_();
auto* expected = new model::If({});
EXPECT_CALL(*builder_, BuildIf(EqualsProtobuf(e.if_())))
.WillOnce(Return(expected));
EXPECT_EQ(expected, builder_->BuildExecutableContent(e));
}
{ // ForEach
config::ExecutableElement e;
e.mutable_foreach();
auto* expected = new model::ForEach("", "", "", nullptr);
EXPECT_CALL(*builder_, BuildForEach(EqualsProtobuf(e.foreach ())))
.WillOnce(Return(expected));
EXPECT_EQ(expected, builder_->BuildExecutableContent(e));
}
}
TEST_F(ModelBuilderTest, BuildIf) {
Reset();
// We'll take advantage of ExecutableBlockBuilder to configure the If, since
// it has a nice interface. We'll end up just using config[0] in the test.
proto2::RepeatedPtrField<config::ExecutableElement> config;
config::ExecutableBlockBuilder(&config)
.AddIf("cond1")
.AddRaise("raise1a")
.AddRaise("raise1b")
.ElseIf("cond2")
.AddRaise("raise2")
.Else()
.AddRaise("raise3")
.EndIf();
const config::If& if_config = config.Get(0).if_();
EXPECT_CALL(*builder_,
BuildExecutableBlock(ElementsAre(
EqualsProtobuf(if_config.cond_executable(0).executable(0)),
EqualsProtobuf(if_config.cond_executable(0).executable(1)))));
EXPECT_CALL(*builder_, BuildExecutableBlock(ElementsAre(EqualsProtobuf(
if_config.cond_executable(1).executable(0)))));
EXPECT_CALL(*builder_, BuildExecutableBlock(ElementsAre(EqualsProtobuf(
if_config.cond_executable(2).executable(0)))));
std::unique_ptr<model::If> if_executable(builder_->BuildIf(if_config));
// FYI: We do not test the BuildIf() returned the correct instance of
// model::If, only that the necessary calls to build its constructor arguments
// took place (above), and that the returned pointer is non-null.
ASSERT_NE(nullptr, if_executable);
}
// Test building an if statement with an empty executable block.
TEST_F(ModelBuilderTest, BuildIfWithEmptyExecutableBlock) {
Reset();
proto2::RepeatedPtrField<config::ExecutableElement> if_with_no_block;
config::ExecutableBlockBuilder(&if_with_no_block).AddIf("cond1").EndIf();
const config::If& if_config = if_with_no_block.Get(0).if_();
std::unique_ptr<model::If> if_executable(builder_->BuildIf(if_config));
ASSERT_NE(nullptr, if_executable);
// Test the executable by executing it.
EXPECT_CALL(runtime_.GetDefaultMockDatamodel(),
EvaluateBooleanExpression("cond1", _))
.WillOnce(DoAll(SetArgPointee<1>(true), Return(true)));
EXPECT_TRUE(if_executable->Execute(&runtime_));
}
TEST_F(ModelBuilderTest, BuildForEach) {
Reset();
proto2::RepeatedPtrField<config::ExecutableElement> config;
config::ExecutableBlockBuilder(&config)
.AddForEach("array", "item", "index")
.AddRaise("e1")
.AddRaise("e2")
.EndForEach();
const config::ForEach& for_each_config = config.Get(0).foreach ();
EXPECT_CALL(*builder_, BuildExecutableBlock(ElementsAre(
EqualsProtobuf(for_each_config.executable(0)),
EqualsProtobuf(for_each_config.executable(1)))));
std::unique_ptr<model::ForEach> for_each_executable(
builder_->BuildForEach(for_each_config));
// FYI: We do not test the BuildForEach() returned the correct instance of
// model::ForEach, only that the necessary calls to build its constructor
// arguments took place (above), and that the returned pointer is non-null.
ASSERT_NE(nullptr, for_each_executable);
}
// Test building a for each statement with an empty executable block body.
TEST_F(ModelBuilderTest, BuildForEachWithEmptyBody) {
Reset();
proto2::RepeatedPtrField<config::ExecutableElement> config;
config::ExecutableBlockBuilder(&config)
.AddForEach("[]", "item", "index")
// Empty body.
.EndForEach();
const config::ForEach& for_each_config = config.Get(0).foreach ();
EXPECT_CALL(*builder_, BuildExecutableBlock(ElementsAre()));
std::unique_ptr<model::ForEach> for_each_executable(
builder_->BuildForEach(for_each_config));
ASSERT_NE(nullptr, for_each_executable);
}
TEST_F(ModelBuilderTest, BuildStateElement_State_Simple) {
Reset();
config::StateElement e;
config::StateBuilder state_builder(e.mutable_state(), "id");
const auto* state = builder_->BuildState(e);
ASSERT_TRUE(state != nullptr);
EXPECT_EQ("id", state->id());
EXPECT_FALSE(state->IsFinal());
EXPECT_THAT(state->GetTransitions(), ElementsAre());
EXPECT_EQ(nullptr, state->GetInitialTransition());
EXPECT_EQ(nullptr, state->GetParent());
EXPECT_TRUE(state->IsAtomic());
EXPECT_FALSE(state->IsCompound());
EXPECT_EQ(nullptr, state->GetDatamodelBlock());
EXPECT_EQ(nullptr, state->GetOnEntry());
EXPECT_EQ(nullptr, state->GetOnExit());
}
TEST_F(ModelBuilderTest, BuildStateElement_State_ExecutableContent) {
Reset();
// Show creation of executable blocks for each of <datamodel>, <onentry>,
// <onexit>.
config::StateElement e;
config::StateBuilder state_builder(e.mutable_state(), "id");
state_builder.OnEntry().AddRaise("on_entry_event");
state_builder.OnExit().AddRaise("on_exit_event");
MockExecutableContent datamodel_executable;
EXPECT_CALL(*builder_,
BuildDataModelBlock(EqualsProtobuf(e.state().datamodel())))
.WillOnce(Return(&datamodel_executable));
MockExecutableContent on_entry_executable;
EXPECT_CALL(*builder_, BuildExecutableBlock(
ElementsAre(EqualsProtobuf(e.state().onentry(0)))))
.WillOnce(Return(&on_entry_executable));
MockExecutableContent on_exit_executable;
EXPECT_CALL(*builder_, BuildExecutableBlock(
ElementsAre(EqualsProtobuf(e.state().onexit(0)))))
.WillOnce(Return(&on_exit_executable));
const auto* state = builder_->BuildState(e);
EXPECT_EQ(&datamodel_executable, state->GetDatamodelBlock());
EXPECT_EQ(&on_entry_executable, state->GetOnEntry());
EXPECT_EQ(&on_exit_executable, state->GetOnExit());
}
TEST_F(ModelBuilderTest, BuildStateElement_State_Final) {
Reset();
config::StateElement e;
config::FinalStateBuilder state_builder(e.mutable_final(), "id");
state_builder.OnEntry().AddRaise("event1");
state_builder.OnExit().AddRaise("event2");
MockExecutableContent on_entry_executable;
EXPECT_CALL(*builder_, BuildExecutableBlock(
ElementsAre(EqualsProtobuf(e.final().onentry(0)))))
.WillOnce(Return(&on_entry_executable));
MockExecutableContent on_exit_executable;
EXPECT_CALL(*builder_, BuildExecutableBlock(
ElementsAre(EqualsProtobuf(e.final().onexit(0)))))
.WillOnce(Return(&on_exit_executable));
const auto* state = builder_->BuildState(e);
ASSERT_TRUE(state != nullptr);
EXPECT_EQ("id", state->id());
EXPECT_TRUE(state->IsFinal());
EXPECT_THAT(state->GetTransitions(), ElementsAre());
EXPECT_EQ(nullptr, state->GetInitialTransition());
EXPECT_EQ(nullptr, state->GetParent());
EXPECT_TRUE(state->IsAtomic());
EXPECT_FALSE(state->IsCompound());
EXPECT_EQ(nullptr, state->GetDatamodelBlock());
EXPECT_EQ(&on_entry_executable, state->GetOnEntry());
EXPECT_EQ(&on_exit_executable, state->GetOnExit());
}
TEST_F(ModelBuilderTest, Build) {
config::StateChartBuilder sc_builder(&state_chart_, "test");
sc_builder.DataModel().AddDataFromExpr("id", "expr");
sc_builder.AddState("A");
sc_builder.AddState("B");
sc_builder.AddFinalState("F");
Reset();
MockExecutableContent datamodel_executable;
EXPECT_CALL(*builder_,
BuildDataModelBlock(EqualsProtobuf(state_chart_.datamodel())))
.WillOnce(Return(&datamodel_executable));
InSequence sequence;
MockState state_A("A");
EXPECT_CALL(*builder_, BuildState(EqualsProtobuf(state_chart_.state(0))))
.WillOnce(Return(&state_A));
MockState state_B("B");
EXPECT_CALL(*builder_, BuildState(EqualsProtobuf(state_chart_.state(1))))
.WillOnce(Return(&state_B));
// Build() uses states_map_ to find all the states in the SC when building
// transitions. If the states are not in the map, we won't build transitions.
gtl::InsertOrDie(&builder_->states_map_, "A", &state_A);
gtl::InsertOrDie(&builder_->states_map_, "B", &state_B);
MockState state_F("F", true);
EXPECT_CALL(*builder_, BuildState(EqualsProtobuf(state_chart_.state(2))))
.WillOnce(Return(&state_F));
// For each state, we also expect a call to build transitions for that state,
// but only after the states have all been constructed.
EXPECT_CALL(*builder_, BuildTransitionsForState(&state_A))
.WillOnce(Return(true));
EXPECT_CALL(*builder_, BuildTransitionsForState(&state_B))
.WillOnce(Return(true));
EXPECT_CALL(*builder_, BuildTransitionsForState(&state_F)).Times(0);
builder_->Build();
EXPECT_EQ(&datamodel_executable, builder_->datamodel_block_);
EXPECT_THAT(builder_->top_level_states_,
ElementsAre(&state_A, &state_B, &state_F));
}
TEST_F(ModelBuilderTest, Build_InitialTransition) {
config::StateChartBuilder sc_builder(&state_chart_, "test");
sc_builder.AddState("A");
sc_builder.AddState("B");
Reset();
// The default is to make the first state in document order be the initial
// transition state.
builder_->Build();
ASSERT_NE(nullptr, builder_->initial_transition_);
EXPECT_EQ(nullptr, builder_->initial_transition_->GetSourceState());
const auto& targets = builder_->initial_transition_->GetTargetStates();
EXPECT_EQ(1, targets.size());
EXPECT_EQ("A", targets[0]->id());
// This time explicitly set the initial to "B".
sc_builder.AddInitial("B");
Reset();
builder_->Build();
ASSERT_NE(nullptr, builder_->initial_transition_);
EXPECT_EQ(nullptr, builder_->initial_transition_->GetSourceState());
const auto& targets2 = builder_->initial_transition_->GetTargetStates();
EXPECT_EQ(1, targets2.size());
EXPECT_EQ("B", targets2[0]->id());
}
TEST_F(ModelBuilderTest, BuildTransitionsForState) {
// Tests missing from this case:
//
// 1) Transition type (internal/external)
// 2) Transition conditions
// 3) Transition to self (explicit)
// 4) Transition to self (implicit)
// 5) Sub-states
// 6) Initial transition
// 7) Empty executable.
Reset();
// BuildTransitionsForState() uses the states_config_map_ to retrieve the
// original config element, and then iterates through each transition config.
// Empty case first.
MockState state_A("A");
config::StateElement e;
gtl::InsertOrUpdate(&builder_->states_config_map_, "A", &e);
builder_->BuildTransitionsForState(&state_A);
EXPECT_THAT(state_A.GetTransitions(), ElementsAre());
config::StateBuilder s_builder(e.mutable_state(), "A");
s_builder.AddTransition({"t1_event1", "t1_event2"}, {"B", "C"})
.AddRaise("t1_foo")
.AddRaise("t1_bar");
s_builder.AddTransition({"t2_event1"}, {"D"}, "some_condition")
.AddRaise("t2_foo");
gtl::InsertOrUpdate(&builder_->states_config_map_, "A", &e);
MockState state_B("B");
MockState state_C("C");
MockState state_D("D");
gtl::InsertOrDie(&builder_->states_map_, "B", &state_B);
gtl::InsertOrDie(&builder_->states_map_, "C", &state_C);
gtl::InsertOrDie(&builder_->states_map_, "D", &state_D);
MockExecutableContent t1_executable;
EXPECT_CALL(*builder_,
BuildExecutableBlock(ElementsAre(
EqualsProtobuf(e.state().transition(0).executable(0)),
EqualsProtobuf(e.state().transition(0).executable(1)))))
.WillOnce(Return(&t1_executable));
MockExecutableContent t2_executable;
EXPECT_CALL(*builder_, BuildExecutableBlock(ElementsAre(EqualsProtobuf(
e.state().transition(1).executable(0)))))
.WillOnce(Return(&t2_executable));
builder_->BuildTransitionsForState(&state_A);
const auto& transitions = state_A.GetTransitions();
EXPECT_EQ(2, transitions.size());
EXPECT_EQ(&state_A, transitions[0]->GetSourceState());
EXPECT_EQ("", transitions[0]->GetCondition());
EXPECT_THAT(transitions[0]->GetTargetStates(),
ElementsAre(&state_B, &state_C));
EXPECT_THAT(transitions[0]->GetEvents(),
ElementsAre("t1_event1", "t1_event2"));
EXPECT_EQ(&t1_executable, transitions[0]->GetExecutable());
EXPECT_EQ(&state_A, transitions[1]->GetSourceState());
EXPECT_THAT(transitions[1]->GetTargetStates(), ElementsAre(&state_D));
EXPECT_THAT(transitions[1]->GetEvents(), ElementsAre("t2_event1"));
EXPECT_EQ("some_condition", transitions[1]->GetCondition());
EXPECT_EQ(&t2_executable, transitions[1]->GetExecutable());
}
TEST_F(ModelBuilderTest, BuildTransitionsForState_StripEventWildcards) {
// Show that we correctly strip suffixes of ".*" and ".", but leave the
// special wild-card event "*" alone.
Reset();
MockState state_A("A");
config::StateElement e;
config::StateBuilder s_builder(e.mutable_state(), "A");
s_builder.AddTransition({"event1.foo", "event2.", "event3.*", "*"}, {});
gtl::InsertOrUpdate(&builder_->states_config_map_, "A", &e);
builder_->BuildTransitionsForState(&state_A);
const auto& transitions = state_A.GetTransitions();
ASSERT_EQ(1, transitions.size());
EXPECT_THAT(transitions[0]->GetEvents(),
ElementsAre("event1.foo", "event2", "event3", "*"));
}
TEST_F(ModelBuilderTest, BuildCompoundState) {
config::StateElement e;
config::StateBuilder s_builder(e.mutable_state(), "A");
s_builder.AddState("B");
s_builder.AddState("C");
model::State* state_A = nullptr;
Reset();
state_A = builder_->BuildState(e);
// Check that the children are correct.
ASSERT_EQ(2, state_A->GetChildren().size());
EXPECT_EQ("B", state_A->GetChildren()[0]->id());
EXPECT_EQ("C", state_A->GetChildren()[1]->id());
// Check that initial transition is correct.
ASSERT_EQ(1, state_A->GetInitialTransition()->GetTargetStates().size());
EXPECT_EQ(state_A->GetInitialTransition()->GetTargetStates()[0],
state_A->GetChildren()[0]);
// Switch the initial transition.
s_builder.AddInitialId("C");
Reset();
state_A = builder_->BuildState(e);
// Check that the children are correct.
ASSERT_EQ(2, state_A->GetChildren().size());
EXPECT_EQ("B", state_A->GetChildren()[0]->id());
EXPECT_EQ("C", state_A->GetChildren()[1]->id());
// Check that initial transition is correct.
ASSERT_EQ(1, state_A->GetInitialTransition()->GetTargetStates().size());
EXPECT_EQ(state_A->GetInitialTransition()->GetTargetStates()[0],
state_A->GetChildren()[1]);
}
TEST_F(ModelBuilderTest, CreateModelAndReset) {
// Show that when CreateModelAndReset() is called, we return a new ModelImpl
// with the states, initial transition, datamodel_binding and datamodel
// executables.
config::StateChartBuilder sc_builder(&state_chart_, "test");
sc_builder.DataModel().AddDataFromExpr("id", "expr");
sc_builder.AddState("A");
sc_builder.AddState("B");
Reset();
MockState state_A("A");
EXPECT_CALL(*builder_, BuildState(EqualsProtobuf(state_chart_.state(0))))
.WillOnce(Return(&state_A));
MockState state_B("B");
EXPECT_CALL(*builder_, BuildState(EqualsProtobuf(state_chart_.state(1))))
.WillOnce(Return(&state_B));
MockExecutableContent datamodel_executable;
EXPECT_CALL(*builder_,
BuildDataModelBlock(EqualsProtobuf(state_chart_.datamodel())))
.WillOnce(Return(&datamodel_executable));
// Prevent default delegation to parent for creating transitions.
EXPECT_CALL(*builder_, BuildTransitionsForState(_))
.WillRepeatedly(Return(true));
builder_->Build();
std::unique_ptr<Model> model(builder_->CreateModelAndReset());
EXPECT_EQ(config::StateChart::BINDING_EARLY, model->GetDatamodelBinding());
EXPECT_EQ(&datamodel_executable, model->GetDatamodelBlock());
EXPECT_THAT(model->GetTopLevelStates(), ElementsAre(&state_A, &state_B));
EXPECT_THAT(model->GetInitialTransition()->GetTargetStates(),
ElementsAre(&state_A));
}
TEST_F(ModelBuilderTest, BuildParallelState) {
config::StateElement e;
config::ParallelBuilder s_builder(e.mutable_parallel(), "A");
s_builder.AddState("B");
s_builder.AddState("C");
model::State* state_A = nullptr;
Reset();
state_A = builder_->BuildState(e);
// Check that the children are correct.
ASSERT_EQ(2, state_A->GetChildren().size());
EXPECT_EQ("B", state_A->GetChildren()[0]->id());
EXPECT_EQ("C", state_A->GetChildren()[1]->id());
// Check that initial transition is correct.
ASSERT_EQ(2, state_A->GetInitialTransition()->GetTargetStates().size());
EXPECT_EQ(state_A->GetInitialTransition()->GetTargetStates(),
state_A->GetChildren());
}
TEST_F(ModelBuilderTest, BuildStateElement_Parallel_ExecutableContent) {
Reset();
// Show creation of executable blocks for each of <datamodel>, <onentry>,
// <onexit>.
config::StateElement e;
config::ParallelBuilder state_builder(e.mutable_parallel(), "id");
state_builder.OnEntry().AddRaise("on_entry_event");
state_builder.OnExit().AddRaise("on_exit_event");
MockExecutableContent datamodel_executable;
EXPECT_CALL(*builder_,
BuildDataModelBlock(EqualsProtobuf(e.parallel().datamodel())))
.WillOnce(Return(&datamodel_executable));
MockExecutableContent on_entry_executable;
EXPECT_CALL(*builder_, BuildExecutableBlock(ElementsAre(
EqualsProtobuf(e.parallel().onentry(0)))))
.WillOnce(Return(&on_entry_executable));
MockExecutableContent on_exit_executable;
EXPECT_CALL(
*builder_,
BuildExecutableBlock(ElementsAre(EqualsProtobuf(e.parallel().onexit(0)))))
.WillOnce(Return(&on_exit_executable));
const auto* state = builder_->BuildState(e);
EXPECT_EQ(&datamodel_executable, state->GetDatamodelBlock());
EXPECT_EQ(&on_entry_executable, state->GetOnEntry());
EXPECT_EQ(&on_exit_executable, state->GetOnExit());
}
} // namespace
} // namespace state_chart
| 35.315175 | 80 | 0.713347 | [
"model"
] |
192c48eed8791c8cf833b155a1566c3bd0ab79d5 | 5,935 | cpp | C++ | src/multicolorledbar.cpp | tzhuan/llcon | c5a4b7abcc62ce3aad334dfa650ff3512c4262be | [
"BSD-3-Clause"
] | 1 | 2016-10-16T00:33:31.000Z | 2016-10-16T00:33:31.000Z | src/multicolorledbar.cpp | tzhuan/llcon | c5a4b7abcc62ce3aad334dfa650ff3512c4262be | [
"BSD-3-Clause"
] | 1 | 2020-09-27T14:24:16.000Z | 2020-09-27T14:24:16.000Z | src/multicolorledbar.cpp | tzhuan/llcon | c5a4b7abcc62ce3aad334dfa650ff3512c4262be | [
"BSD-3-Clause"
] | null | null | null | /******************************************************************************\
* Copyright (c) 2004-2011
*
* Author(s):
* Volker Fischer
*
* Description:
* Implements a multi color LED bar
*
******************************************************************************
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 2 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
\******************************************************************************/
#include "multicolorledbar.h"
/* Implementation *************************************************************/
CMultiColorLEDBar::CMultiColorLEDBar ( QWidget* parent, Qt::WindowFlags f )
: QFrame ( parent, f )
{
// set total number of LEDs
iNumLEDs = NUM_STEPS_INP_LEV_METER;
// create layout and set spacing to zero
pMainLayout = new QVBoxLayout ( this );
pMainLayout->setAlignment ( Qt::AlignHCenter );
pMainLayout->setMargin ( 0 );
pMainLayout->setSpacing ( 0 );
// create LEDs
vecpLEDs.Init ( iNumLEDs );
for ( int iLEDIdx = iNumLEDs - 1; iLEDIdx >= 0; iLEDIdx-- )
{
// create LED object
vecpLEDs[iLEDIdx] = new cLED ( parent );
// add LED to layout with spacer (do not add spacer on the bottom of the
// first LED)
if ( iLEDIdx < iNumLEDs - 1 )
{
pMainLayout->addStretch();
}
pMainLayout->addWidget ( vecpLEDs[iLEDIdx]->getLabelPointer() );
}
}
CMultiColorLEDBar::~CMultiColorLEDBar()
{
// clean up the LED objects
for ( int iLEDIdx = 0; iLEDIdx < iNumLEDs; iLEDIdx++ )
{
delete vecpLEDs[iLEDIdx];
}
}
void CMultiColorLEDBar::changeEvent ( QEvent* curEvent )
{
// act on enabled changed state
if ( curEvent->type() == QEvent::EnabledChange )
{
// reset all LEDs
Reset ( this->isEnabled() );
}
}
void CMultiColorLEDBar::Reset ( const bool bEnabled )
{
// update state of all LEDs
for ( int iLEDIdx = 0; iLEDIdx < iNumLEDs; iLEDIdx++ )
{
// different reset behavoiur for enabled and disabled control
if ( bEnabled )
{
vecpLEDs[iLEDIdx]->setColor ( cLED::RL_GREY );
}
else
{
vecpLEDs[iLEDIdx]->setColor ( cLED::RL_DISABLED );
}
}
}
void CMultiColorLEDBar::setValue ( const int value )
{
if ( this->isEnabled() )
{
// update state of all LEDs for current level value
for ( int iLEDIdx = 0; iLEDIdx < iNumLEDs; iLEDIdx++ )
{
// set active LED color if value is above current LED index
if ( iLEDIdx < value )
{
// check which color we should use (green, yellow or red)
if ( iLEDIdx < YELLOW_BOUND_INP_LEV_METER )
{
// green region
vecpLEDs[iLEDIdx]->setColor ( cLED::RL_GREEN );
}
else
{
if ( iLEDIdx < RED_BOUND_INP_LEV_METER )
{
// yellow region
vecpLEDs[iLEDIdx]->setColor ( cLED::RL_YELLOW );
}
else
{
// red region
vecpLEDs[iLEDIdx]->setColor ( cLED::RL_RED );
}
}
}
else
{
// we use grey LED for inactive state
vecpLEDs[iLEDIdx]->setColor ( cLED::RL_GREY );
}
}
}
}
CMultiColorLEDBar::cLED::cLED ( QWidget* parent ) :
BitmCubeRoundDisabled ( QString::fromUtf8 ( ":/png/LEDs/res/CLEDDisabledSmall.png" ) ),
BitmCubeRoundGrey ( QString::fromUtf8 ( ":/png/LEDs/res/HLEDGreySmall.png" ) ),
BitmCubeRoundGreen ( QString::fromUtf8 ( ":/png/LEDs/res/HLEDGreenSmall.png" ) ),
BitmCubeRoundYellow ( QString::fromUtf8 ( ":/png/LEDs/res/HLEDYellowSmall.png" ) ),
BitmCubeRoundRed ( QString::fromUtf8 ( ":/png/LEDs/res/HLEDRedSmall.png" ) )
{
// create LED label
pLEDLabel = new QLabel ( "", parent );
// bitmap defines minimum size of the label
pLEDLabel->setMinimumSize (
BitmCubeRoundGrey.width(), BitmCubeRoundGrey.height() );
// set initial bitmap
pLEDLabel->setPixmap ( BitmCubeRoundGrey );
eCurLightColor = RL_GREY;
}
void CMultiColorLEDBar::cLED::setColor ( const ELightColor eNewColor )
{
// only update LED if color has changed
if ( eNewColor != eCurLightColor )
{
switch ( eNewColor )
{
case RL_DISABLED:
pLEDLabel->setPixmap ( BitmCubeRoundDisabled );
break;
case RL_GREY:
pLEDLabel->setPixmap ( BitmCubeRoundGrey );
break;
case RL_GREEN:
pLEDLabel->setPixmap ( BitmCubeRoundGreen );
break;
case RL_YELLOW:
pLEDLabel->setPixmap ( BitmCubeRoundYellow );
break;
case RL_RED:
pLEDLabel->setPixmap ( BitmCubeRoundRed );
break;
}
eCurLightColor = eNewColor;
}
}
| 32.081081 | 92 | 0.529065 | [
"object"
] |
19301a21b9a40ea4269e551a0d5d98564cbea537 | 12,302 | cpp | C++ | compression/Lz4LegacyReader.cpp | djp952/io | 620c3e27b2b22279f0c13f5f5067b9ac06a55790 | [
"BSD-2-Clause",
"bzip2-1.0.6"
] | null | null | null | compression/Lz4LegacyReader.cpp | djp952/io | 620c3e27b2b22279f0c13f5f5067b9ac06a55790 | [
"BSD-2-Clause",
"bzip2-1.0.6"
] | null | null | null | compression/Lz4LegacyReader.cpp | djp952/io | 620c3e27b2b22279f0c13f5f5067b9ac06a55790 | [
"BSD-2-Clause",
"bzip2-1.0.6"
] | null | null | null | //---------------------------------------------------------------------------
// Copyright (c) 2016 Michael G. Brehm
//
// 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.
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// LZ4 Library
// Copyright (c) 2011-2016, Yann Collet
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
// ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//---------------------------------------------------------------------------
#include "stdafx.h"
#include "Lz4LegacyReader.h"
#pragma warning(push, 4) // Enable maximum compiler warnings
namespace zuki::io::compression {
//---------------------------------------------------------------------------
// Lz4LegacyReader Constructor
//
// Arguments:
//
// stream - The stream the compressed data is read from
Lz4LegacyReader::Lz4LegacyReader(Stream^ stream) : Lz4LegacyReader(stream, false)
{
}
//---------------------------------------------------------------------------
// Lz4LegacyReader Constructor
//
// Arguments:
//
// stream - The stream the compressed data is read from
// leaveopen - Flag to leave the base stream open after disposal
Lz4LegacyReader::Lz4LegacyReader(Stream^ stream, bool leaveopen) : m_disposed(false), m_stream(stream), m_leaveopen(leaveopen),
m_hasmagic(false), m_outavail(0), m_outpos(0)
{
if(Object::ReferenceEquals(stream, nullptr)) throw gcnew ArgumentNullException("stream");
// Allocate the managed output buffer for this instance
m_out = gcnew array<unsigned __int8>(LEGACY_BLOCKSIZE);
}
//---------------------------------------------------------------------------
// Lz4LegacyReader Destructor
Lz4LegacyReader::~Lz4LegacyReader()
{
if(m_disposed) return;
// Destroy the managed output data buffer
delete m_out;
// Optionally dispose of the input stream instance
if(!m_leaveopen) delete m_stream;
m_disposed = true;
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::BaseStream::get
//
// Accesses the underlying base stream instance
Stream^ Lz4LegacyReader::BaseStream::get(void)
{
CHECK_DISPOSED(m_disposed);
return m_stream;
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::CanRead::get
//
// Gets a value indicating whether the current stream supports reading
bool Lz4LegacyReader::CanRead::get(void)
{
CHECK_DISPOSED(m_disposed);
return m_stream->CanRead;
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::CanSeek::get
//
// Gets a value indicating whether the current stream supports seeking
bool Lz4LegacyReader::CanSeek::get(void)
{
CHECK_DISPOSED(m_disposed);
return false;
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::CanWrite::get
//
// Gets a value indicating whether the current stream supports writing
bool Lz4LegacyReader::CanWrite::get(void)
{
CHECK_DISPOSED(m_disposed);
return false;
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::Flush
//
// Clears all buffers for this stream and causes any buffered data to be written
//
// Arguments:
//
// NONE
void Lz4LegacyReader::Flush(void)
{
CHECK_DISPOSED(m_disposed);
m_stream->Flush();
}
//--------------------------------------------------------------------------
// Lz4LegacyReader::Length::get
//
// Gets the length in bytes of the stream
__int64 Lz4LegacyReader::Length::get(void)
{
CHECK_DISPOSED(m_disposed);
throw gcnew NotSupportedException();
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::Position::get
//
// Gets the current position within the stream
__int64 Lz4LegacyReader::Position::get(void)
{
CHECK_DISPOSED(m_disposed);
throw gcnew NotSupportedException();
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::Position::set
//
// Sets the current position within the stream
void Lz4LegacyReader::Position::set(__int64 value)
{
UNREFERENCED_PARAMETER(value);
CHECK_DISPOSED(m_disposed);
throw gcnew NotSupportedException();
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::Read
//
// Reads a sequence of bytes from the current stream and advances the position within the stream
//
// Arguments:
//
// buffer - Destination data buffer
// offset - Offset within buffer to begin copying data
// count - Maximum number of bytes to write into the destination buffer
int Lz4LegacyReader::Read(array<unsigned __int8>^ buffer, int offset, int count)
{
unsigned int nextblock; // Next compressed block size
int out = 0; // Total bytes read from the stream
CHECK_DISPOSED(m_disposed);
if(Object::ReferenceEquals(buffer, nullptr)) throw gcnew ArgumentNullException("buffer");
if(offset < 0) throw gcnew ArgumentOutOfRangeException("offset");
if(count < 0) throw gcnew ArgumentOutOfRangeException("count");
if((offset + count) > buffer->Length) throw gcnew ArgumentException("The sum of offset and count is larger than the buffer length");
if(count == 0) return 0; // No output buffer to read into
msclr::lock lock(m_lock); // Serialize access to the buffer
// Wait to check the magic number of the input stream until the first Read() attempt
if(!m_hasmagic) {
// Verify that the first 4 bytes of the stream are the legacy magic number
if(!ReadLE32(m_stream, nextblock) || (nextblock != LEGACY_MAGICNUMBER)) throw gcnew InvalidDataException();
m_hasmagic = true;
}
do {
// If there is no more output data available, decompress some more
if(m_outavail == 0) {
// Get the length of the next block of data to be decompressed; if there
// is insufficient data left in the stream, decompression is finished
if(!ReadLE32(m_stream, nextblock)) break;
if((nextblock == 0) || (nextblock > Int32::MaxValue)) throw gcnew InvalidDataException();
// Read the next entire block of compressed data from the input stream
array<unsigned __int8>^ in = gcnew array<unsigned __int8>(nextblock);
if(m_stream->Read(in, 0, nextblock) != (int)nextblock) throw gcnew InvalidDataException();
// Pin both the input and output buffers so the LZ4 API can access them
pin_ptr<unsigned __int8> pinin = &in[0];
pin_ptr<unsigned __int8> pinout = &m_out[0];
// Decompress the next block of data into the output buffer
m_outavail = LZ4_decompress_safe(reinterpret_cast<char const*>(pinin), reinterpret_cast<char*>(pinout), nextblock, m_out->Length);
if(m_outavail <= 0) throw gcnew InvalidDataException();
m_outpos = 0; // Reset the stored buffer offset
delete in; // Dispose of the input buffer
}
// Copy data from the decompression buffer into the output buffer
int next = Math::Min(m_outavail, count);
Array::Copy(m_out, m_outpos, buffer, offset, next);
m_outpos += next; // Move offset into the decompression buffer
m_outavail -= next; // Reduce length of the decompression buffer
out += next; // Increment the amount of data written to the caller
count -= next; // Decrement the amount of data still to read
} while(count > 0);
return out;
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::ReadLE32 (static, private)
//
// Reads an unsigned 32 bit value from an input stream
//
// Arguments:
//
// stream - Stream instance from which to read the value
// value - Value read from the stream
bool Lz4LegacyReader::ReadLE32(Stream^ stream, unsigned int% value)
{
if(Object::ReferenceEquals(stream, nullptr)) throw gcnew ArgumentNullException();
array<unsigned __int8>^ buffer = gcnew array<unsigned __int8>(4);
if(stream->Read(buffer, 0, 4) != 4) return false;
// Convert the 4 individual bytes into a single unsigned 32-bit value
value = (buffer[0] << 0) | (buffer[1] << 8) | (buffer[2] << 16) | (buffer[3] << 24);
return true;
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::Seek
//
// Sets the position within the current stream
//
// Arguments:
//
// offset - Byte offset relative to origin
// origin - Reference point used to obtain the new position
__int64 Lz4LegacyReader::Seek(__int64 offset, SeekOrigin origin)
{
UNREFERENCED_PARAMETER(offset);
UNREFERENCED_PARAMETER(origin);
CHECK_DISPOSED(m_disposed);
throw gcnew NotSupportedException();
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::SetLength
//
// Sets the length of the current stream
//
// Arguments:
//
// value - Desired length of the current stream in bytes
void Lz4LegacyReader::SetLength(__int64 value)
{
UNREFERENCED_PARAMETER(value);
CHECK_DISPOSED(m_disposed);
throw gcnew NotSupportedException();
}
//---------------------------------------------------------------------------
// Lz4LegacyReader::Write
//
// Writes a sequence of bytes to the current stream and advances the current position
//
// Arguments:
//
// buffer - Source data buffer
// offset - Offset within buffer to begin copying from
// count - Maximum number of bytes to read from the source buffer
void Lz4LegacyReader::Write(array<unsigned __int8>^ buffer, int offset, int count)
{
UNREFERENCED_PARAMETER(buffer);
UNREFERENCED_PARAMETER(offset);
UNREFERENCED_PARAMETER(count);
CHECK_DISPOSED(m_disposed);
throw gcnew NotSupportedException();
}
//---------------------------------------------------------------------------
} // zuki::io::compression
#pragma warning(pop)
| 34.653521 | 134 | 0.622663 | [
"object"
] |
19325c96b4e0bd2057998826f7e978e229627f4d | 2,994 | cpp | C++ | devel/framework/particleemitterpool.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | null | null | null | devel/framework/particleemitterpool.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | null | null | null | devel/framework/particleemitterpool.cpp | madeso/hopper | ccf330c8f400678f5f5dceea25c0374ed99be511 | [
"WTFPL"
] | 2 | 2019-04-26T03:00:59.000Z | 2022-01-04T17:36:28.000Z |
#include "particleemitterpool.h"
// #include "particleemittermanager.h"
CParticleEmitterPool::CParticleEmitterPool(
Ogre::String name,Ogre::String emitterType, unsigned int maxEmitters )
:mName( name ),
mMaxEmitters( maxEmitters ),
mEmitterType( emitterType ) {
//mEmitters.reserve( mMaxEmitters );
mEmitters.resize( mMaxEmitters );
for( std::vector<CParticleEmitter*>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it ) {
(*it)=0;
}
// precreate emitters
int n=0;
for( std::vector<CParticleEmitter*>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it ) {
(*it)=new CParticleEmitter(
mName + "_emitter#" + Ogre::StringConverter::toString( n ),
mEmitterType );
n++;
}
mPoolIterator=mEmitters.begin();
}
CParticleEmitterPool::~CParticleEmitterPool() {
for( std::vector<CParticleEmitter*>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it ) {
//if( (*it) != 0 )
delete( (*it) );
}
}
void CParticleEmitterPool::emit( unsigned int aNumParticles, Ogre::Vector3 position ) {
/*
int n=0;
for( std::vector<CParticleEmitter*>::iterator it = mEmitters.begin(); it != mEmitters.end(); ++it ) {
if( (*it) != 0 ) {
if( (*it)->numberOfParticles() == 0 ) {
(*it)->setPosition( position );
(*it)->addParticle( aNumParticles );
break;
}
}
else {
(*it) = new CParticleEmitter(
mName + "_emitter#" + Ogre::StringConverter::toString( n ),
mEmitterTypeID );
(*it)->setPosition( position );
(*it)->addParticle( aNumParticles );
}
n++;
}
*/
(*mPoolIterator)->setPosition( position );
(*mPoolIterator)->addParticle( aNumParticles );
(*mPoolIterator)->emit( true );
++mPoolIterator;
if( mPoolIterator == mEmitters.end() )
mPoolIterator=mEmitters.begin();
}
/*
void CParticleEmitterPool::emit( unsigned int emitterTypeID, unsigned int numParticles, Ogre::Vector3 position ) {
if( (*mPoolIterator) != 0 )
delete( (*mPoolIterator) );
(*mPoolIterator)=new CParticleEmitter(
mName + "_emitter#" + Ogre::StringConverter::toString( std::distance(mEmitters.begin(), mPoolIterator) ),
CParticleEmitterManager::getInstance()->getTypeName( emitterTypeID ) );
(*mPoolIterator)->setPosition( position );
(*mPoolIterator)->addParticle( numParticles );
(*mPoolIterator)->emit( true );
++mPoolIterator;
if( mPoolIterator == mEmitters.end() )
mPoolIterator=mEmitters.begin();
}
*/
void CParticleEmitterPool::update() {
for( std::vector<CParticleEmitter*>::const_iterator it = mEmitters.begin(); it != mEmitters.end(); ++it ) {
//if( (*it) != 0 ) {
(*it)->update();
// (*it)->emit( false );
//}
}
}
| 23.761905 | 114 | 0.58016 | [
"vector"
] |
1936d4ffae92b90dd84423b253839b34d77877f7 | 949 | cpp | C++ | Engine/src/Content/icPathingLoader.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | Engine/src/Content/icPathingLoader.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | Engine/src/Content/icPathingLoader.cpp | binofet/ice | dee91da76df8b4f46ed4727d901819d8d20aefe3 | [
"MIT"
] | null | null | null | #include "Content/icContentLoader.h"
#include "AI/Pathing/icPathingSystemI.h"
#include "AI/Pathing/icAStar.h"
//#include "AI/Pathing/icThetaStar.h"
//#include "AI/Pathing/icVisibilityAStar.h"
#include "Core/IO/icFile.h"
/*! Audio loader
*
* @param szFileName Name of the pathing file to load
* @param[in/out] ppObj Storage place for pointer to pathing object
* @returns ICRESULT Success/failure of pathing load
**/
template<>
ICRESULT icContentLoader::Load<icPathingSystemI>(const char* szFileName,
icPathingSystemI** ppObj)
{
icAStar* astar = new icAStar();
if (ICEOK(astar->Load(szFileName)))
{
*ppObj = astar;
//m_pAudio->LoadSource(szFileName);
//m_pAudio->GetSound(szFileName, ppObj);
return IC_OK;
}
delete astar;
*ppObj = 0;
return IC_FAIL_GEN;
}// END FUNCTION Load<icPathingSystemI>(const char* szFileName, icPathingSystemI** ppObj)
| 27.911765 | 89 | 0.67334 | [
"object"
] |
1937a6d0bbccd1440decadfebd28c539fc577f7f | 18,349 | cpp | C++ | source/Plugins/ElypseFirefox/Elypse/main.cpp | DragonJoker/Elypse | 5dce65ba97fb830349d157da77d9dc151cccc70e | [
"MIT"
] | 9 | 2017-12-06T17:21:56.000Z | 2020-11-15T14:06:07.000Z | source/Plugins/ElypseFirefox/Elypse/main.cpp | DragonJoker/Elypse | 5dce65ba97fb830349d157da77d9dc151cccc70e | [
"MIT"
] | null | null | null | source/Plugins/ElypseFirefox/Elypse/main.cpp | DragonJoker/Elypse | 5dce65ba97fb830349d157da77d9dc151cccc70e | [
"MIT"
] | 1 | 2020-01-08T05:20:05.000Z | 2020-01-08T05:20:05.000Z | #include "stdafx.h"
#define ___NO_NAMESPACE_OGRE___
#include "main.h"
#include <ElypseFrameListener.h>
#include <ElypseInstance.h>
#include <ElypseController.h>
#include <ElypseLogs.h>
#include <Version.h>
#if ELYPSE_WINDOWS
# include <CompInfo.h>
# define M_SUBCLASS_WINDOW( p_windowHandle, p_function) ((WNDPROC) SetWindowLongPtr( p_windowHandle, GWLP_WNDPROC, (LPARAM)(WNDPROC)(p_function)))
# include <RegistryManager.h>
# include <RegistryKey.h>
# undef SetCurrentDirectory
#endif
#include <File.h>
#include <Execute.h>
#include <StringUtils.h>
//#include "Firefox/np_class.h"
using namespace General::Computer;
using namespace General::Utils;
ElypsePluginInstance * g_main;
PluginInstanceMap g_mainMap;
#define VERBOSE( X) EMUSE_CONSOLE_MESSAGE_DEBUG(X)
namespace
{
const char * c_updaterName = "ElypsePlayer_Updater.exe";
const char * c_installerName = "ElypsePlayer_Installer.exe";
const char * c_updaterParams = "-update";
}
/*
Initialisation Sequence :
1) NS_PluginInitialize
2) NS_NewPluginInstance
|- Cconstructor
|- InitParams
3) init
--------------------------
Destruction Sequence :
1) shut
2) NS_DestroyPluginInstance
|- Destructor
3) NS_PluginShutdown
*/
NPError NS_PluginInitialize()
{
#if ELYPSE_WINDOWS
#ifdef ____MUSE_DEBUG____
AllocConsole();
freopen( "CONOUT$" , "w+" , stdout );
std::cout << "gn�" << std::endl;
// m_useConsole = true;
#endif
VERBOSE( "Global::NS_PluginInitialize" );
#endif
return NPERR_NO_ERROR;
}
void NS_PluginShutdown()
{
VERBOSE( "Global::NS_PluginShutdown" );
// Sleep( 5000);
}
NPBool ElypsePluginInstance :: isInitialized()
{
// VERBOSE( "ElypsePluginInstance :: isInitialized");
return m_initialized;
}
const char * ElypsePluginInstance :: getVersion()
{
VERBOSE( "ElypsePluginInstance :: getVersion" );
return NPN_UserAgent( m_instance );
}
nsPluginInstanceBase * NS_NewPluginInstance( nsPluginCreateData * aCreateDataStruct )
{
VERBOSE( "Global::NS_NewPluginInstance" );
if ( ! aCreateDataStruct )
{
return NULL;
}
ElypsePluginInstance * l_plugin = new ElypsePluginInstance( aCreateDataStruct->instance );
l_plugin->InitParams( aCreateDataStruct );
return l_plugin;
}
void NS_DestroyPluginInstance( nsPluginInstanceBase * p_pluginInstance )
{
VERBOSE( "Global::NS_DestroyPluginInstance" );
if ( p_pluginInstance != NULL )
{
delete( ElypsePluginInstance * )p_pluginInstance;
}
}
ElypsePluginInstance :: ~ElypsePluginInstance()
{
VERBOSE( "ElypsePluginInstance :: ~ElypsePluginInstance" );
// if (g_main == this)
{
g_main = NULL;
}
}
String ElypsePluginInstance :: _urlDecode( const String & p_url )
{
String l_string;
char l_buf[10];
unsigned long l_ulong;
for ( unsigned int i = 0 ; i < p_url.length() ; i ++ )
{
if ( p_url[i] == '%' )
{
l_buf[0] = p_url[i + 1];
l_buf[1] = p_url[i + 2];
l_buf[2] = 0;
l_ulong = strtoul( l_buf, NULL, 16 );
i += 2;
l_string.push_back( ( char )l_ulong );
}
else
{
l_string.push_back( p_url[i] );
}
}
return l_string;
}
void ElypsePluginInstance :: _checkInstall()
{
#if ELYPSE_WINDOWS
ComputerInfo l_info;
if ( l_info.GetOSMajorVersion() > 5 || l_info.GetOSMajorVersion() == 5 && l_info.GetOSMinorVersion() > 1 )
{
char * l_userProfile = std::getenv( "userprofile" );
m_installPath = l_userProfile;
if ( m_installPath.empty() )
{
return;
}
m_installPath = m_installPath / "AppData" / "Roaming" / "FDSSoftMedia" / "Elypse";
}
else
{
RegistryManager<String> l_registry;
RegistryKey * l_key = l_registry.GetKey( "SOFTWARE\\MICROSOFT\\WINDOWS\\CURRENTVERSION" );
if ( l_key == NULL )
{
return;
}
m_installPath = l_key->GetStringValue( "ProgramFilesDir" );
if ( m_installPath.empty() )
{
return;
}
m_installPath = m_installPath / "FDSSoftMedia" / "Elypse";
}
#endif
}
String ElypsePluginInstance :: _getUserAgent()
{
NPObject * l_window;
NPVariant l_vdoc;
NPVariant l_vurl;
String l_ua;
NPError l_error = NPN_GetValue( m_instance, NPNVWindowNPObject, & l_window );
if ( l_error == NPERR_NO_ERROR )
{
if ( NPN_GetProperty( m_instance, l_window, NPN_GetStringIdentifier( "navigator" ), & l_vdoc ) )
{
if ( NPN_GetProperty( m_instance, l_vdoc.value.objectValue, NPN_GetStringIdentifier( "userAgent" ), & l_vurl ) )
{
l_ua = std::string( l_vurl.value.stringValue.UTF8Characters );
NPN_ReleaseVariantValue( & l_vurl );
}
NPN_ReleaseVariantValue( & l_vdoc );
}
}
return l_ua;
}
void ElypsePluginInstance :: _getClientSite()
{
NPObject * l_window;
NPVariant l_vdoc;
NPVariant l_vurl;
NPN_GetValue( m_instance, NPNVWindowNPObject, & l_window );
NPN_GetProperty( m_instance, l_window, NPN_GetStringIdentifier( "document" ), & l_vdoc );
NPN_GetProperty( m_instance, l_vdoc.value.objectValue, NPN_GetStringIdentifier( "URL" ), & l_vurl );
m_url = std::string( l_vurl.value.stringValue.UTF8Characters );
m_url = m_url.substr( 0, m_url.find_last_of( '/' ) + 1 );
m_url = _urlDecode( m_url );
if ( m_url.find( "file://localhost/" ) != String::npos )
{
m_url = "file://" + string::replace( m_url.substr( strlen( "file://localhost/" ) ), "/", "\\" );
}
else if ( m_url.find( "file:///" ) != String::npos )
{
m_url = "file://" + string::replace( m_url.substr( strlen( "file:///" ) ), "/", "\\" );
}
else if ( m_url.find( "file://" ) != String::npos )
{
m_url = "file://" + string::replace( m_url.substr( strlen( "file://" ) ), "/", "\\" );
}
NPN_ReleaseVariantValue( & l_vdoc );
NPN_ReleaseVariantValue( & l_vurl );
}
ElypsePluginInstance :: ElypsePluginInstance( NPP p_instance )
: nsPluginInstanceBase()
, m_instance( p_instance )
, m_initialized( FALSE )
, m_rightButton( false )
, m_leftButton( false )
, m_middleButton( false )
, m_useConsole( false )
, m_focus( false )
, m_firefox( false )
, m_noInit( false )
, m_ogre( NULL )
, m_plugin( NULL )
, m_width( 0.0f )
, m_height( 0.0f )
#if ELYPSE_WINDOWS
, m_hook( NULL )
, m_windowHandle( NULL )
, m_oldProc( NULL )
#endif
{
g_main = this;
VERBOSE( "ElypsePluginInstance :: ElypsePluginInstance : begin" );
m_plugin = new ElypsePlugin_Firefox;
m_plugin->SetNPPInstance( m_instance );
m_instance->pdata = this;
m_plugin->InitGDI();
_checkInstall();
if ( m_installPath.empty() )
{
m_plugin->SetGraphicalStatus( StatusErrorDirectories );
// m_plugin->MajorError( "Probleme : ne peut trouver les repertoires necessaires\nVeuillez reinstaller l'application.", "Erreur majeure");
return;
}
m_plugin->SetInstallPath( m_installPath );
_getClientSite();
m_plugin->SetImagePath( m_installPath + "\\cfg\\" );
String l_tempString;
if ( ! DirectoryExists( m_installPath / "rsc" ) )
{
DirectoryCreate( m_installPath / "rsc" );
}
if ( ! DirectoryExists( m_installPath / "cfg" ) )
{
DirectoryCreate( m_installPath / "cfg" );
}
try
{
m_ogre = new ElypseInstance( m_installPath, m_plugin );
}
catch ( ... )
{
m_plugin->SetGraphicalStatus( StatusErrorOgre );
}
m_plugin->SetBaseUrl( m_url );
m_ogre->SetCurrentDirectory( m_url );
VERBOSE( "ElypsePluginInstance :: ElypsePluginInstance : end" );
}
void ElypsePluginInstance :: InitParams( nsPluginCreateData * p_data )
{
VERBOSE( "ElypsePluginInstance :: InitParams : begin" );
// std::cout << "InitParams : " << std::endl;
if ( m_ogre == NULL )
{
return;
}
// std::cout << "InitParams2 : " << std::endl;
for ( int i = 0 ; i < p_data->argc ; i ++ )
{
String l_paramValue = p_data->argv[i];
String l_paramName = p_data->argn[i];
string :: toLowerCase( l_paramName );
VERBOSE( "ElypsePluginInstance :: InitParams -> param found : " + l_paramName + " = " + l_paramValue );
if ( l_paramName == "showdebug" && l_paramValue == "1" )
{
if ( ! m_useConsole )
{
m_useConsole = ElypseController::GetSingletonPtr()->ShowConsole();
// std::cout << "yargh ZOOOB? " << std::endl;
}
}
else if ( l_paramName == "file" )
{
Url l_url( l_paramValue );
if ( l_url.GetProtocol() == HTTP )
{
m_ogre->SetFileUrl( l_url );
}
else
{
m_ogre->SetFileUrl( Url( m_url + l_paramValue ) );
}
}
/*
else if (l_paramName == "instancename")
{
m_ogre->SetInstanceName( l_paramValue);
}
*/
else if ( l_paramName == "startupscript" )
{
m_ogre->SetStartupScript( l_paramValue );
}
else if ( l_paramName == "requiredversion" )
{
int l_version = parseInt( l_paramValue );
// std::cout << "needed version : " << l_version << " // " << ELYPSE_VERSION << std::endl;
// std::cout << "param value : " << l_paramValue << std::endl;
if ( ! CHECK_ELYPSE_VERSION( l_version ) )
{
_updatePlayer();
m_plugin->SetGraphicalStatus( StatusErrorUpdating );
m_noInit = true;
}
}
else if ( l_paramName == "renderer" )
{
m_ogre->UseDirectX( l_paramValue == "DirectX" );
}
else if ( l_paramName == "downloadfiles" )
{
m_ogre->SetDownloadFiles( l_paramValue != "false" );
}
else if ( l_paramName == "antialiasing" )
{
m_ogre->SetAntialiasing( parseInt( l_paramValue ) );
}
else
{
VERBOSE( "ElypsePluginInstance :: InitParams -> unknown param : " + l_paramName );
}
}
VERBOSE( "ElypsePluginInstance :: InitParams : end" );
}
NPBool ElypsePluginInstance :: init( NPWindow * p_window )
{
VERBOSE( "ElypsePluginInstance :: init : begin" );
if ( p_window == NULL )
{
return TRUE;
}
m_initialized = TRUE;
m_width = float( p_window->width );
m_height = float( p_window->height );
m_plugin->SetSize( p_window->width, p_window->height );
#if ELYPSE_WINDOWS
m_windowHandle = ( HWND ) p_window->window;
m_oldProc = M_SUBCLASS_WINDOW( m_windowHandle, static_cast <WNDPROC>( ProcessMessage ) );
m_plugin->SetHandle( m_windowHandle );
g_mainMap.insert( PluginInstanceMap::value_type( m_windowHandle, this ) );
if ( m_windowHandle == NULL || m_ogre == NULL )
{
return TRUE;
}
m_hook = ::SetWindowsHookEx( WH_GETMESSAGE, GetMessageProc, NULL, GetCurrentThreadId() );
#endif
// std::cout << "User Agent : " << _getUserAgent() << std::endl;
m_firefox = ( _getUserAgent().find( "Firefox" ) != String::npos );
m_ogre->SetHandle( ToString( reinterpret_cast<intptr_t>( m_windowHandle ) ) );
// m_ogre->SetFilePath( m_url);
m_ogre->SetMain( true );
if ( ! m_noInit )
{
m_ogre->Init( p_window->width, p_window->height, String() );
}
// NPN_SetValue( m_instance, NPPVpluginScriptableNPObject, this);
// NPN_CreateObject(
VERBOSE( "ElypsePluginInstance :: init : end" );
return TRUE;
}
NPError ElypsePluginInstance :: GetValue( NPPVariable aVariable, void * aValue )
{
NPError rv = NPERR_NO_ERROR;
// if (aVariable == NPPVpluginScriptableInstance)
// {
// // addref happens in getter, so we don't addref here
// np_elypsePlugin * scriptablePeer = getScriptablePeer();
// if (scriptablePeer != NULL)
// {
// * (nsISupports **) aValue = scriptablePeer;
// }
// else
// {
// rv = NPERR_OUT_OF_MEMORY_ERROR;
// }
// }
// else if (aVariable == NPPVpluginScriptableIID)
// {
// static nsIID scriptableIID = NP_ELYPSEPLUGIN_IID;
// nsIID * ptr = (nsIID *) NPN_MemAlloc( sizeof( nsIID));
// if (ptr != NULL)
// {
// * ptr = scriptableIID;
// * (nsIID **) aValue = ptr;
// }
// else
// {
// rv = NPERR_OUT_OF_MEMORY_ERROR;
// }
// }
// else if (aVariable == NPPVpluginScriptableNPObject)
// {
// //workaround needed. using the scriptable Object does litteraly nothing in Firefox, as of right now ( 14/04/2009)
// if ( ! m_firefox)
// {
// *(NPObject **)(aValue) = Private_ScriptableObject();
// }
//
// return NPERR_NO_ERROR;
// }
// else
// {
//// std::cout << aVariable << std::endl;
// }
return rv;
}
//nsScriptablePeer * ElypsePluginInstance :: getScriptablePeer()
//{
// if ( ! mScriptablePeer)
// {
// mScriptablePeer = new nsScriptablePeer( m_plugin);
// if ( ! mScriptablePeer)
// {
// return NULL;
// }
//
// NS_ADDREF( mScriptablePeer);
// }
//
// // add reference for the caller requesting the object
// NS_ADDREF( mScriptablePeer);
//
// return mScriptablePeer;
//}
void ElypsePluginInstance :: shut()
{
VERBOSE( "ElypsePluginInstance :: shut : begin" );
m_plugin->CloseGDI();
const PluginInstanceMap::iterator & iter = g_mainMap.find( m_windowHandle );
if ( iter != g_mainMap.end() )
{
VERBOSE( "ElypsePluginInstance :: shut : instance erased from map" );
g_mainMap.erase( iter );
}
else
{
VERBOSE( "ElypsePluginInstance :: shut : instance NOT erased from map" );
}
#ifndef ____MUSE_DEBUG____
if ( g_mainMap.empty() )
{
// FreeConsole();
}
#endif
g_main = NULL;
if ( m_ogre != NULL )
{
m_initialized = FALSE;
m_ogre->WaitForDeletion();
if ( ElypseController::GetSingletonPtr() != NULL && m_ogre->IsMain() )
{
ElypseController::GetSingletonPtr()->WaitForThreadEnded();
// ElypseController::GetSingletonPtr()->DeleteOgre();
ElypseController::Destroy();
}
delete m_ogre;
m_ogre = NULL;
}
delete m_plugin;
m_plugin = NULL;
#if ELYPSE_WINDOWS
if ( m_oldProc != NULL )
{
M_SUBCLASS_WINDOW( m_windowHandle, m_oldProc );
}
if ( m_hook != NULL )
{
UnhookWindowsHookEx( m_hook );
}
#endif
m_windowHandle = NULL;
VERBOSE( "ElypsePluginInstance :: shut : end" );
}
#if ELYPSE_WINDOWS
LRESULT CALLBACK ElypsePluginInstance :: ProcessMessage( HWND p_windowHandle, UINT p_message, WPARAM p_wParam, LPARAM p_lParam )
{
VERBOSE( "message : " << p_message );
switch ( p_message )
{
case WM_SETFOCUS:
{
const PluginInstanceMap::iterator & ifind = g_mainMap.find( GetFocus() );
if ( ifind != g_mainMap.end() )
{
g_main = ifind->second;
g_main->OnSetFocus();
}
break;
}
case WM_KILLFOCUS:
{
const PluginInstanceMap::iterator & ifind = g_mainMap.find( p_windowHandle );
if ( ifind != g_mainMap.end() )
{
g_main = ifind->second;
g_main->OnKillFocus();
}
break;
}
case WM_MOUSEMOVE:
{
if ( g_main != NULL )
{
g_main->OnMouseMove( MAKEPOINTS( p_lParam ) );
}
break;
}
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
{
const PluginInstanceMap::iterator & ifind = g_mainMap.find( p_windowHandle );
if ( ifind != g_mainMap.end() )
{
g_main = ifind->second;
g_main->OnLButtonDown( MAKEPOINTS( p_lParam ) );
}
break;
}
case WM_LBUTTONUP:
{
if ( g_main != NULL )
{
g_main->OnLButtonUp( MAKEPOINTS( p_lParam ) );
}
break;
}
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
{
const PluginInstanceMap::iterator & ifind = g_mainMap.find( p_windowHandle );
if ( ifind != g_mainMap.end() )
{
g_main = ifind->second;
g_main->OnRButtonDown( MAKEPOINTS( p_lParam ) );
}
break;
}
case WM_RBUTTONUP:
{
if ( g_main != NULL )
{
g_main->OnRButtonUp( MAKEPOINTS( p_lParam ) );
}
break;
}
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
{
const PluginInstanceMap::iterator & ifind = g_mainMap.find( p_windowHandle );
if ( ifind != g_mainMap.end() )
{
g_main = ifind->second;
g_main->OnMButtonDown( MAKEPOINTS( p_lParam ) );
}
break;
}
case WM_MBUTTONUP:
{
if ( g_main != NULL )
{
g_main->OnMButtonUp( MAKEPOINTS( p_lParam ) );
}
break;
}
case WM_MOUSEWHEEL:
{
short l_delta = GET_WHEEL_DELTA_WPARAM( p_wParam );
if ( g_main != NULL )
{
g_main->OnMouseWheel( l_delta, MAKEPOINTS( p_lParam ) );
}
break;
}
case WM_SYSKEYUP:
{
if ( g_main != NULL )
{
g_main->OnSysKeyUp( UINT( p_wParam ) );
}
break;
}
case WM_SYSKEYDOWN:
{
if ( g_main != NULL )
{
g_main->OnSysKeyDown( UINT( p_wParam ), LOWORD( p_lParam ), HIWORD( p_lParam ) );
}
break;
}
case WM_KEYDOWN:
{
if ( g_main != NULL )
{
g_main->OnKeyDown( UINT( p_wParam ), LOWORD( p_lParam ), HIWORD( p_lParam ) );
}
break;
}
case WM_KEYUP:
{
if ( g_main != NULL )
{
g_main->OnKeyUp( UINT( p_wParam ) );
}
break;
}
case WM_PAINT:
{
if ( g_main != NULL )
{
g_main->m_plugin->Paint();
}
//Note : do not remove that -_-.
return DefWindowProc( p_windowHandle, p_message, p_wParam, p_lParam );
}
default:
{
// VERBOSE( "message end by default : " << p_message);
LRESULT l_res = DefWindowProc( p_windowHandle, p_message, p_wParam, p_lParam );
// VERBOSE( "message endby default with result : " << l_res);
return l_res;
}
}
// VERBOSE( "message end: " << p_message);
return 0;
}
LRESULT CALLBACK ElypsePluginInstance :: GetMessageProc( int p_code, WPARAM p_wParam, LPARAM p_lParam )
{
LPMSG l_msg = ( LPMSG ) p_lParam;
if ( g_main != NULL
&& g_main->m_focus
&& p_code >= 0
&& p_wParam == PM_REMOVE
&& l_msg->message >= WM_KEYFIRST
&& l_msg->message <= WM_KEYLAST )
{
if ( l_msg->message == WM_KEYDOWN
&& l_msg->wParam != 116
&& l_msg->wParam != 122 )
{
g_main->OnKeyDown( UINT( l_msg->wParam ), HIWORD( l_msg->lParam ), LOWORD( l_msg->lParam ) );
l_msg->message = WM_NULL;
l_msg->lParam = 0L;
l_msg->wParam = 0;
}
if ( l_msg->message == WM_KEYUP
&& l_msg->wParam != 116
&& l_msg->wParam != 122 )
{
g_main->OnKeyUp( UINT( l_msg->wParam ) );
l_msg->message = WM_NULL;
l_msg->lParam = 0L;
l_msg->wParam = 0;
}
if ( l_msg->message == WM_SYSKEYDOWN
&& l_msg->wParam != 116
&& l_msg->wParam != 122 )
{
g_main->OnSysKeyDown( UINT( l_msg->wParam ), HIWORD( l_msg->lParam ), LOWORD( l_msg->lParam ) );
l_msg->message = WM_NULL;
l_msg->lParam = 0L;
l_msg->wParam = 0;
}
if ( l_msg->message == WM_SYSKEYUP )
{
g_main->OnSysKeyUp( UINT( l_msg->wParam ) );
l_msg->message = WM_NULL;
l_msg->lParam = 0L;
l_msg->wParam = 0;
}
}
return ::CallNextHookEx( NULL, p_code, p_wParam, p_lParam );
}
#endif
//TODO : finir �a -> lier vers la fonction ExecuteScript, reorganiser le bidule NPObject de merde pour le multi instance.
extern NPClass Private_Class;
NPObject * ElypsePluginInstance :: Private_ScriptableObject()
{
static NPObject * obj = NULL;
if ( obj == NULL )
{
obj = NPN_CreateObject( m_instance, & Private_Class );
}
if ( obj != NULL )
{
NPN_RetainObject( obj );
}
return obj;
}
void ElypsePluginInstance :: _updatePlayer()
{
if ( FileExists( m_installPath / c_installerName ) )
{
FileDelete( m_installPath / c_updaterName );
FileCopy( m_installPath / c_installerName, m_installPath / c_updaterName );
Execute( c_updaterName, m_installPath + "\\", c_updaterParams, ES_SHELL );
}
}
| 20.320044 | 146 | 0.659872 | [
"object"
] |
1948ac59900e2b31b0fbb8efbf6643b54d5fe096 | 674 | cpp | C++ | c++/leetcode/0969-Pancake_Sorting-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | 1 | 2020-03-02T10:56:22.000Z | 2020-03-02T10:56:22.000Z | c++/leetcode/0969-Pancake_Sorting-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | c++/leetcode/0969-Pancake_Sorting-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | // 969 Pancake Sorting
// https://leetcode.com/problems/pancake-sorting
// version: 1; create time: 2020-02-07 23:16:27;
class Solution {
public:
vector<int> pancakeSort(vector<int>& A) {
vector<int> res;
const int n = A.size();
int i = 0;
for (int i = n - 1; i >= 0; --i) {
if (A[i] != i + 1) {
int idx = std::find(A.begin(), A.end(), i + 1) - A.begin();
res.push_back(idx + 1);
std::reverse(A.begin(), A.begin() + idx + 1);
res.push_back(i + 1);
std::reverse(A.begin(), A.begin() + i + 1);
}
}
return res;
}
};
| 29.304348 | 75 | 0.452522 | [
"vector"
] |
194a747b07b2bcee7af2ef9b402dfa3c7d62d721 | 4,492 | cpp | C++ | src/caffe/syncedmem.cpp | gujunli/OpenCL-CAFFE-Research | e8848f727733e503671e0e6a68aa885973b31197 | [
"BSD-2-Clause"
] | null | null | null | src/caffe/syncedmem.cpp | gujunli/OpenCL-CAFFE-Research | e8848f727733e503671e0e6a68aa885973b31197 | [
"BSD-2-Clause"
] | null | null | null | src/caffe/syncedmem.cpp | gujunli/OpenCL-CAFFE-Research | e8848f727733e503671e0e6a68aa885973b31197 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 2014 BVLC and contributors.
#include <cstring>
#include <stdio.h>
#include "caffe/common.hpp"
#include "caffe/syncedmem.hpp"
#include "caffe/util/ocl_util.hpp"
#define CL_MEM_USE_PERSISTENT_MEM_AMD (1 << 6) // Alloc from GPU's CPU visible heap
namespace caffe {
SyncedMemory::~SyncedMemory() {
if (cpu_ptr_ && own_cpu_data_) {
OCL_CHECK( clEnqueueUnmapMemObject(amdDevice.CommandQueue, (cl_mem)gpu_cache_ptr_, cpu_ptr_, 0, NULL, NULL) );
clFinish(amdDevice.CommandQueue);
}
if(gpu_cache_ptr_ && own_cpu_data_) {
OCL_CHECK( clReleaseMemObject((cl_mem)gpu_cache_ptr_) );
}
if (gpu_ptr_) {
OCL_CHECK( clReleaseMemObject((cl_mem)gpu_ptr_) );
}
clReleaseKernel(oclmem_kernel);
}
void SyncedMemory::ocl_setup() {
cl_int err=0;
oclmem_kernel = clCreateKernel(amdDevice.Program, "OCL_memset2", &err);
OCL_CHECK(err);
}
inline void SyncedMemory::to_cpu() {
switch (head_) {
case UNINITIALIZED:
//allocate pre-pinned memory
//pinned_buffer_ptr_
// if(data_layer_){
// gpu_cache_ptr_ = clCreateBuffer(amdDevice.Context, CL_MEM_USE_PERSISTENT_MEM_AMD, size_, NULL, NULL);
// }
// else{
gpu_cache_ptr_ = clCreateBuffer(amdDevice.Context, CL_MEM_ALLOC_HOST_PTR, size_, NULL, NULL);
//}
cpu_ptr_ = clEnqueueMapBuffer(amdDevice.CommandQueue, (cl_mem)gpu_cache_ptr_, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, size_, 0, NULL, NULL, NULL);
memset(cpu_ptr_, 0, size_);
head_ = HEAD_AT_CPU;
own_cpu_data_ = true;
break;
case HEAD_AT_GPU:{
if (cpu_ptr_ == NULL) {
gpu_cache_ptr_ = clCreateBuffer(amdDevice.Context, CL_MEM_ALLOC_HOST_PTR, size_, NULL, NULL);
cpu_ptr_ = clEnqueueMapBuffer(amdDevice.CommandQueue, (cl_mem)gpu_cache_ptr_, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, size_, 0, NULL, NULL, NULL);
own_cpu_data_ = true;
}
OCL_CHECK(clEnqueueCopyBuffer(amdDevice.CommandQueue, (cl_mem)gpu_ptr_, (cl_mem)gpu_cache_ptr_, 0, 0, size_, 0, NULL, NULL));
clFinish(amdDevice.CommandQueue);
head_ = SYNCED;
#ifdef Track_data_transfer
LOG(WARNING) << "sync: data from GPU to CPU";
#endif
break;
}
case HEAD_AT_CPU:
case SYNCED:
break;
}
}
inline void SyncedMemory::to_gpu() {
switch (head_) {
case UNINITIALIZED:{
//To Do: implement OCL_CHECK_NULL
cl_mem tmpMem = clCreateBuffer(amdDevice.Context, CL_MEM_READ_WRITE, size_, NULL, NULL);
if(NULL == tmpMem){
fprintf(stderr,"Failed to create memory object 58\n");
break;
}
ocl_memset(oclmem_kernel, tmpMem, (int)0, (int)(size_/sizeof(int)));
gpu_ptr_ = (void*)tmpMem;
head_ = HEAD_AT_GPU;
break;
}
case HEAD_AT_CPU:{
if (gpu_ptr_ == NULL) {
cl_mem tmpMem = clCreateBuffer(amdDevice.Context, CL_MEM_READ_WRITE, size_, NULL, NULL);
if(NULL == tmpMem){
fprintf(stderr,"Failed to create memory object\n");
}
gpu_ptr_ = (void*)tmpMem;
}
OCL_CHECK(clEnqueueCopyBuffer(amdDevice.CommandQueue, (cl_mem)gpu_cache_ptr_, (cl_mem)gpu_ptr_, 0, 0, size_, 0, NULL, NULL));
clFinish(amdDevice.CommandQueue);
head_ = SYNCED;
#ifdef Track_data_transfer
LOG(WARNING) << "sync: data from CPU to GPU";
#endif
break;
}
case HEAD_AT_GPU:
case SYNCED:
break;
}
}
const void* SyncedMemory::cpu_data() {
to_cpu();
return (const void*)cpu_ptr_;
}
void SyncedMemory::set_cpu_data(void* data) {
CHECK(data);
if (own_cpu_data_) {
OCL_CHECK( clEnqueueUnmapMemObject(amdDevice.CommandQueue, (cl_mem) gpu_cache_ptr_, cpu_ptr_, 0, NULL, NULL));
OCL_CHECK( clReleaseMemObject((cl_mem) gpu_cache_ptr_));
clFinish(amdDevice.CommandQueue); //is this necessary?
}
gpu_cache_ptr_ = clCreateBuffer(amdDevice.Context, CL_MEM_USE_HOST_PTR, size_, data, NULL);
cpu_ptr_ = clEnqueueMapBuffer(amdDevice.CommandQueue, (cl_mem)gpu_cache_ptr_, CL_TRUE, CL_MAP_READ | CL_MAP_WRITE, 0, size_, 0, NULL, NULL, NULL);
head_ = HEAD_AT_CPU;
own_cpu_data_ = false;
}
//TO_DO Junli: implement set_gpu_data(prefetech_data_ptr)
// {gpu_ptr = prefetch_data_ptr; head_ = HEAD_AT_GPU; }
const void* SyncedMemory::gpu_data() {
to_gpu();
return (const void*)gpu_ptr_;
}
const void* SyncedMemory::gpu_cache_data(){
to_cpu();
return (const void*)gpu_cache_ptr_;
}
void* SyncedMemory::mutable_cpu_data() {
to_cpu();
head_ = HEAD_AT_CPU;
return cpu_ptr_;
}
void* SyncedMemory::mutable_gpu_data() {
to_gpu();
head_ = HEAD_AT_GPU;
return gpu_ptr_;
}
} // namespace caffe
| 28.980645 | 152 | 0.703028 | [
"object"
] |
194bf1f1641e973398b35e1d9cb3543fe09a8a9c | 5,177 | cpp | C++ | src/mongo/db/storage/record_store.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/storage/record_store.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/db/storage/record_store.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2021-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/storage/record_store.h"
#include "mongo/db/storage/storage_options.h"
namespace mongo {
namespace {
void validateWriteAllowed(OperationContext* opCtx) {
uassert(ErrorCodes::IllegalOperation,
"Cannot execute a write operation in read-only mode",
!opCtx->readOnly());
}
} // namespace
void RecordStore::deleteRecord(OperationContext* opCtx, const RecordId& dl) {
validateWriteAllowed(opCtx);
doDeleteRecord(opCtx, dl);
}
Status RecordStore::insertRecords(OperationContext* opCtx,
std::vector<Record>* inOutRecords,
const std::vector<Timestamp>& timestamps) {
validateWriteAllowed(opCtx);
return doInsertRecords(opCtx, inOutRecords, timestamps);
}
Status RecordStore::updateRecord(OperationContext* opCtx,
const RecordId& recordId,
const char* data,
int len) {
validateWriteAllowed(opCtx);
return doUpdateRecord(opCtx, recordId, data, len);
}
StatusWith<RecordData> RecordStore::updateWithDamages(OperationContext* opCtx,
const RecordId& loc,
const RecordData& oldRec,
const char* damageSource,
const mutablebson::DamageVector& damages) {
validateWriteAllowed(opCtx);
return doUpdateWithDamages(opCtx, loc, oldRec, damageSource, damages);
}
Status RecordStore::truncate(OperationContext* opCtx) {
validateWriteAllowed(opCtx);
return doTruncate(opCtx);
}
void RecordStore::cappedTruncateAfter(OperationContext* opCtx, RecordId end, bool inclusive) {
validateWriteAllowed(opCtx);
doCappedTruncateAfter(opCtx, end, inclusive);
}
Status RecordStore::compact(OperationContext* opCtx) {
validateWriteAllowed(opCtx);
return doCompact(opCtx);
}
Status RecordStore::oplogDiskLocRegister(OperationContext* opCtx,
const Timestamp& opTime,
bool orderedCommit) {
// Callers should be updating visibility as part of a write operation. We want to ensure that
// we never get here while holding an uninterruptible, read-ticketed lock. That would indicate
// that we are operating with the wrong global lock semantics, and either hold too weak a lock
// (e.g. IS) or that we upgraded in a way we shouldn't (e.g. IS -> IX).
invariant(opCtx->lockState()->isNoop() || !opCtx->lockState()->hasReadTicket() ||
!opCtx->lockState()->uninterruptibleLocksRequested());
return oplogDiskLocRegisterImpl(opCtx, opTime, orderedCommit);
}
void RecordStore::waitForAllEarlierOplogWritesToBeVisible(OperationContext* opCtx) const {
// Callers are waiting for other operations to finish updating visibility. We want to ensure
// that we never get here while holding an uninterruptible, write-ticketed lock. That could
// indicate we are holding a stronger lock than we need to, and that we could actually
// contribute to ticket-exhaustion. That could prevent the write we are waiting on from
// acquiring the lock it needs to update the oplog visibility.
invariant(opCtx->lockState()->isNoop() || !opCtx->lockState()->hasWriteTicket() ||
!opCtx->lockState()->uninterruptibleLocksRequested());
waitForAllEarlierOplogWritesToBeVisibleImpl(opCtx);
}
} // namespace mongo
| 44.62931 | 98 | 0.674136 | [
"vector"
] |
194e9071e15ee5840cbf7065e48062ef7064e0ee | 31,092 | cpp | C++ | wallet/transactions/swaps/bridges/ethereum/ethereum_side.cpp | tradingsecret/beam_wallet | abfe5dbb6c2fe325839887271150ae8e996e100f | [
"Apache-2.0"
] | 631 | 2018-11-10T05:56:05.000Z | 2022-03-30T13:21:00.000Z | wallet/transactions/swaps/bridges/ethereum/ethereum_side.cpp | tradingsecret/beam_wallet | abfe5dbb6c2fe325839887271150ae8e996e100f | [
"Apache-2.0"
] | 1,824 | 2018-11-08T11:32:58.000Z | 2022-03-28T12:33:03.000Z | wallet/transactions/swaps/bridges/ethereum/ethereum_side.cpp | tradingsecret/beam_wallet | abfe5dbb6c2fe325839887271150ae8e996e100f | [
"Apache-2.0"
] | 216 | 2018-11-12T08:07:21.000Z | 2022-03-08T20:50:19.000Z | // Copyright 2020 The Beam Team
//
// 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 "ethereum_side.h"
#include <bitcoin/bitcoin.hpp>
#include <ethash/keccak.hpp>
#include "common.h"
#include "utility/logger.h"
using namespace ECC;
namespace
{
// TODO: check
constexpr uint32_t kExternalHeightMaxDifference = 10;
const std::string kEthSignPrefix = std::string("\x19") + "Ethereum Signed Message:\n32";
}
namespace beam::wallet
{
EthereumSide::EthereumSide(BaseTransaction& tx, ethereum::IBridge::Ptr ethBridge, ethereum::ISettingsProvider& settingsProvider, bool isBeamSide)
: m_tx(tx)
, m_ethBridge(ethBridge)
, m_settingsProvider(settingsProvider)
, m_isEthOwner(!isBeamSide)
{
m_settingsProvider.AddRef();
}
EthereumSide::~EthereumSide()
{
m_settingsProvider.ReleaseRef();
}
bool EthereumSide::Initialize()
{
if (!m_blockCount)
{
GetBlockCount(true);
return false;
}
if (m_isEthOwner)
{
InitSecret();
}
// InitLocalKeys - ? init publicSwap & secretSwap keys
m_tx.SetParameter(TxParameterID::AtomicSwapPublicKey, ethereum::ConvertEthAddressToStr(m_ethBridge->generateEthAddress()));
return true;
}
bool EthereumSide::InitLockTime()
{
auto height = m_blockCount;
assert(height);
LOG_DEBUG() << "InitLockTime height = " << height;
auto externalLockPeriod = height + GetLockTimeInBlocks();
m_tx.SetParameter(TxParameterID::AtomicSwapExternalLockTime, externalLockPeriod);
return true;
}
bool EthereumSide::ValidateLockTime()
{
auto height = m_blockCount;
assert(height);
auto externalLockTime = m_tx.GetMandatoryParameter<Height>(TxParameterID::AtomicSwapExternalLockTime);
LOG_DEBUG() << "ValidateLockTime height = " << height << " external = " << externalLockTime;
if (externalLockTime <= height)
{
return false;
}
double blocksPerBeamBlock = GetBlocksPerHour() / beam::Rules::get().DA.Target_s;
Height beamCurrentHeight = m_tx.GetWalletDB()->getCurrentHeight();
Height beamHeightDiff = beamCurrentHeight - m_tx.GetMandatoryParameter<Height>(TxParameterID::MinHeight, SubTxIndex::BEAM_LOCK_TX);
Height peerMinHeight = externalLockTime - GetLockTimeInBlocks();
Height peerEstCurrentHeight = peerMinHeight + static_cast<Height>(std::ceil(blocksPerBeamBlock * beamHeightDiff));
return peerEstCurrentHeight >= height - kExternalHeightMaxDifference
&& peerEstCurrentHeight <= height + kExternalHeightMaxDifference;
}
void EthereumSide::AddTxDetails(SetTxParameter& txParameters)
{
auto txID = m_tx.GetMandatoryParameter<std::string>(TxParameterID::AtomicSwapExternalTxID, SubTxIndex::LOCK_TX);
txParameters.AddParameter(TxParameterID::AtomicSwapPeerPublicKey, ethereum::ConvertEthAddressToStr(m_ethBridge->generateEthAddress()));
txParameters.AddParameter(TxParameterID::SubTxIndex, SubTxIndex::LOCK_TX);
txParameters.AddParameter(TxParameterID::AtomicSwapExternalTxID, txID);
}
bool EthereumSide::ConfirmLockTx()
{
if (m_isEthOwner)
{
return true;
}
// wait TxID from peer
std::string txHash;
if (!m_tx.GetParameter(TxParameterID::AtomicSwapExternalTxID, txHash, SubTxIndex::LOCK_TX))
return false;
if (!m_SwapLockTxBlockNumber)
{
// validate contract
m_ethBridge->getTxByHash(txHash, [this, weak = this->weak_from_this()] (const ethereum::IBridge::Error& error, const nlohmann::json& txInfo)
{
if (weak.expired())
{
return;
}
if (error.m_type != ethereum::IBridge::None)
{
LOG_DEBUG() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(SubTxIndex::LOCK_TX) << "]" << " Failed to get transaction: " << error.m_message;
return;
}
try
{
auto contractAddrStr = txInfo["to"].get<std::string>();
auto localContractAddrStr = GetContractAddressStr();
std::transform(localContractAddrStr.begin(),
localContractAddrStr.end(),
localContractAddrStr.begin(),
[](char c) -> char { return static_cast<char>(std::tolower(c)); });
if (contractAddrStr != localContractAddrStr)
{
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::SwapInvalidContract, false, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
return;
}
std::string strValue = ethereum::RemoveHexPrefix(txInfo["value"].get<std::string>());
auto amount = ethereum::ConvertStrToUintBig(strValue);
uintBig swapAmount = IsERC20Token() ? ECC::Zero : GetSwapAmount();
if (amount != swapAmount)
{
LOG_ERROR() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(SubTxIndex::LOCK_TX) << "]"
<< " Unexpected amount, expected: " << swapAmount.str() << ", got: " << amount.str();
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::SwapInvalidAmount, false, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
return;
}
auto txInputStr = ethereum::RemoveHexPrefix(txInfo["input"].get<std::string>());
libbitcoin::data_chunk data = BuildLockTxData();
auto lockTxDataStr = libbitcoin::encode_base16(data);
if (txInputStr != lockTxDataStr)
{
LOG_ERROR() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(SubTxIndex::LOCK_TX) << "]"
<< " Transaction data does not match.";
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::SwapInvalidContract, false, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
return;
}
}
catch (const std::exception& ex)
{
LOG_ERROR() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(SubTxIndex::LOCK_TX) << "]" << " Failed to parse txInfo: " << ex.what();
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::SwapFormatResponseError, false, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
return;
}
});
// get block number of transaction and check status of transaction
m_ethBridge->getTxBlockNumber(txHash, [this, weak = this->weak_from_this()](const ethereum::IBridge::Error& error, uint64_t txBlockNumber)
{
if (weak.expired())
{
return;
}
switch (error.m_type)
{
case ethereum::IBridge::ErrorType::None:
break;
case ethereum::IBridge::ErrorType::InvalidResultFormat:
case ethereum::IBridge::ErrorType::EthError:
{
LOG_ERROR() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(SubTxIndex::LOCK_TX) << "]" << " Transaction is not valid.";
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::InvalidTransaction, false, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
return;
}
default:
{
m_tx.UpdateOnNextTip();
return;
}
}
m_SwapLockTxBlockNumber = txBlockNumber;
});
return false;
}
uint64_t currentBlockNumber = GetBlockCount();
if (m_SwapLockTxBlockNumber < currentBlockNumber)
{
uint32_t confirmations = static_cast<uint32_t>(currentBlockNumber - m_SwapLockTxBlockNumber);
if (confirmations != m_SwapLockTxConfirmations)
{
m_SwapLockTxConfirmations = confirmations;
LOG_DEBUG() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(SubTxIndex::LOCK_TX) << "] " << confirmations << "/"
<< GetTxMinConfirmations(SubTxIndex::LOCK_TX) << " confirmations are received.";
m_tx.SetParameter(TxParameterID::Confirmations, confirmations, true, SubTxIndex::LOCK_TX);
}
}
return m_SwapLockTxConfirmations >= GetTxMinConfirmations(SubTxIndex::LOCK_TX);
}
bool EthereumSide::ConfirmRefundTx()
{
return ConfirmWithdrawTx(SubTxIndex::REFUND_TX);
}
bool EthereumSide::ConfirmRedeemTx()
{
return ConfirmWithdrawTx(SubTxIndex::REDEEM_TX);
}
bool EthereumSide::ConfirmWithdrawTx(SubTxID subTxID)
{
std::string txID;
if (!m_tx.GetParameter(TxParameterID::AtomicSwapExternalTxID, txID, subTxID))
return false;
if (m_WithdrawTxConfirmations < GetTxMinConfirmations(subTxID))
{
GetWithdrawTxConfirmations(subTxID);
return false;
}
return true;
}
void EthereumSide::GetWithdrawTxConfirmations(SubTxID subTxID)
{
if (!m_WithdrawTxBlockNumber)
{
std::string txID = m_tx.GetMandatoryParameter<std::string>(TxParameterID::AtomicSwapExternalTxID, subTxID);
m_ethBridge->getTxBlockNumber(txID, [this, weak = this->weak_from_this()](const ethereum::IBridge::Error& error, uint64_t txBlockNumber)
{
if (weak.expired())
{
return;
}
if (error.m_type != ethereum::IBridge::None)
{
return;
}
m_WithdrawTxBlockNumber = txBlockNumber;
});
return;
}
auto currentBlockCount = GetBlockCount();
if (currentBlockCount >= m_WithdrawTxBlockNumber)
{
uint32_t confirmations = static_cast<uint32_t>(currentBlockCount - m_WithdrawTxBlockNumber);
if (confirmations != m_WithdrawTxConfirmations)
{
m_WithdrawTxConfirmations = confirmations;
LOG_DEBUG() << m_tx.GetTxID() << "[" << subTxID << "] " << confirmations << "/"
<< GetTxMinConfirmations(subTxID) << " confirmations are received.";
m_tx.SetParameter(TxParameterID::Confirmations, confirmations, true, subTxID);
}
}
}
bool EthereumSide::SendLockTx()
{
SwapTxState swapTxState = SwapTxState::Initial;
bool stateExist = m_tx.GetParameter(TxParameterID::State, swapTxState, SubTxIndex::LOCK_TX);
if (swapTxState == SwapTxState::Constructed)
return true;
std::string txID;
if (m_tx.GetParameter(TxParameterID::AtomicSwapExternalTxID, txID, SubTxIndex::LOCK_TX))
{
// check status of transaction
m_ethBridge->getTxBlockNumber(txID, [this, weak = this->weak_from_this()](const ethereum::IBridge::Error& error, uint64_t txBlockNumber)
{
if (weak.expired())
{
return;
}
switch (error.m_type)
{
case ethereum::IBridge::ErrorType::None:
break;
case ethereum::IBridge::ErrorType::InvalidResultFormat:
case ethereum::IBridge::ErrorType::EthError:
{
LOG_ERROR() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(SubTxIndex::LOCK_TX) << "]" << " Transaction is not valid.";
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::InvalidTransaction, false, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
return;
}
default:
{
m_tx.UpdateOnNextTip();
return;
}
}
m_tx.SetState(SwapTxState::Constructed, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
});
return false;
}
if (IsERC20Token())
{
if (!stateExist)
{
// ERC20::approve + swapContractAddress + value
uintBig swapAmount = GetSwapAmount();
libbitcoin::data_chunk data;
data.reserve(ethereum::kEthContractMethodHashSize + 2 * ethereum::kEthContractABIWordSize);
libbitcoin::decode_base16(data, ethereum::ERC20Hashes::kApproveHash);
ethereum::AddContractABIWordToBuffer(GetContractAddress(), data);
ethereum::AddContractABIWordToBuffer({ std::begin(swapAmount.m_pData), std::end(swapAmount.m_pData) }, data);
auto swapCoin = m_tx.GetMandatoryParameter<AtomicSwapCoin>(TxParameterID::AtomicSwapCoin);
const auto tokenContractAddress = ethereum::ConvertStrToEthAddress(m_settingsProvider.GetSettings().GetTokenContractAddress(swapCoin));
m_ethBridge->erc20Approve(tokenContractAddress, GetContractAddress(), swapAmount, GetApproveTxGasLimit(), GetGasPrice(SubTxIndex::LOCK_TX),
[this, weak = this->weak_from_this()](const ethereum::IBridge::Error& error, std::string txHash)
{
if (!weak.expired())
{
if (error.m_type != ethereum::IBridge::None)
{
LOG_DEBUG() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(SubTxIndex::LOCK_TX) << "]" << " Failed to call ERC20::approve!";
if (error.m_type == ethereum::IBridge::EthError ||
error.m_type == ethereum::IBridge::InvalidResultFormat)
{
SetTxError(error, SubTxIndex::LOCK_TX);
}
m_tx.UpdateOnNextTip();
return;
}
m_tx.SetState(SwapTxState::CreatingTx, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
}
});
m_tx.SetState(SwapTxState::Initial, SubTxIndex::LOCK_TX);
return false;
}
// waiting result of ERC20::approve
if (swapTxState == SwapTxState::Initial)
{
return false;
}
}
if (swapTxState != SwapTxState::SigningTx)
{
libbitcoin::data_chunk data = BuildLockTxData();
uintBig swapAmount = IsERC20Token() ? ECC::Zero : GetSwapAmount();
m_ethBridge->send(GetContractAddress(), data, swapAmount, GetGasLimit(SubTxIndex::LOCK_TX), GetGasPrice(SubTxIndex::LOCK_TX),
[this, weak = this->weak_from_this()](const ethereum::IBridge::Error& error, std::string txHash, uint64_t txNonce)
{
if (!weak.expired())
{
if (error.m_type != ethereum::IBridge::None)
{
if (error.m_type == ethereum::IBridge::EthError ||
error.m_type == ethereum::IBridge::InvalidResultFormat)
{
SetTxError(error, SubTxIndex::LOCK_TX);
}
m_tx.UpdateOnNextTip();
return;
}
m_tx.SetParameter(TxParameterID::AtomicSwapExternalTxID, txHash, false, SubTxIndex::LOCK_TX);
m_tx.SetParameter(TxParameterID::NonceSlot, txNonce, false, SubTxIndex::LOCK_TX);
m_tx.UpdateAsync();
}
});
m_tx.SetState(SwapTxState::SigningTx, SubTxIndex::LOCK_TX);
}
return false;
}
bool EthereumSide::SendRefund()
{
return SendWithdrawTx(SubTxIndex::REFUND_TX);
}
bool EthereumSide::SendRedeem()
{
return SendWithdrawTx(SubTxIndex::REDEEM_TX);
}
bool EthereumSide::SendWithdrawTx(SubTxID subTxID)
{
std::string txID;
if (m_tx.GetParameter(TxParameterID::AtomicSwapExternalTxID, txID, subTxID))
return true;
if (!m_isWithdrawTxSent)
{
auto data = BuildWithdrawTxData(subTxID);
m_ethBridge->send(GetContractAddress(), data, ECC::Zero, GetGasLimit(subTxID), GetGasPrice(subTxID),
[this, weak = this->weak_from_this(), subTxID](const ethereum::IBridge::Error& error, std::string txHash, uint64_t txNonce)
{
if (!weak.expired())
{
if (error.m_type != ethereum::IBridge::None)
{
LOG_DEBUG() << m_tx.GetTxID() << "[" << subTxID << "]" << " Failed to send withdraw TX: " << error.m_message;
m_isWithdrawTxSent = false;
// trying to resend
m_tx.UpdateOnNextTip();
return;
}
m_tx.SetParameter(TxParameterID::Confirmations, uint32_t(0), false, subTxID);
m_tx.SetParameter(TxParameterID::AtomicSwapExternalTxID, txHash, false, subTxID);
m_tx.SetParameter(TxParameterID::NonceSlot, txNonce, false, subTxID);
m_tx.UpdateAsync();
}
});
m_isWithdrawTxSent = true;
}
return false;
}
beam::ByteBuffer EthereumSide::BuildWithdrawTxData(SubTxID subTxID)
{
return (subTxID == SubTxIndex::REDEEM_TX) ? BuildRedeemTxData() : BuildRefundTxData();
}
beam::ByteBuffer EthereumSide::BuildRedeemTxData()
{
auto secretHash = GetSecretHash();
auto secret = GetSecret();
libbitcoin::data_chunk data;
if (IsHashLockScheme())
{
// kRedeemMethodHash + secret + secretHash
data.reserve(ethereum::kEthContractMethodHashSize + 2 * ethereum::kEthContractABIWordSize);
libbitcoin::decode_base16(data, ethereum::swap_contract::GetRedeemMethodHash(IsHashLockScheme()));
data.insert(data.end(), std::begin(secret.m_pData), std::end(secret.m_pData));
data.insert(data.end(), std::begin(secretHash), std::end(secretHash));
}
else
{
auto initiatorStr = m_tx.GetMandatoryParameter<std::string>(TxParameterID::AtomicSwapPeerPublicKey);
auto initiator = ethereum::ConvertStrToEthAddress(initiatorStr);
auto participant = m_ethBridge->generateEthAddress();
// keccak256: addressFromSecret + participant + initiator + refundTimeInBlocks
uintBig refundTimeInBlocks = m_tx.GetMandatoryParameter<Height>(TxParameterID::AtomicSwapExternalLockTime);
libbitcoin::data_chunk hashData;
hashData.reserve(3 * libbitcoin::short_hash_size + ethereum::kEthContractABIWordSize);
hashData.insert(hashData.end(), secretHash.cbegin(), secretHash.cend());
hashData.insert(hashData.end(), participant.cbegin(), participant.cend());
hashData.insert(hashData.end(), initiator.cbegin(), initiator.cend());
hashData.insert(hashData.end(), std::cbegin(refundTimeInBlocks.m_pData), std::cend(refundTimeInBlocks.m_pData));
if (IsERC20Token())
{
// add TokenContractAddress
auto swapCoin = m_tx.GetMandatoryParameter<AtomicSwapCoin>(TxParameterID::AtomicSwapCoin);
const auto tokenContractAddress = ethereum::ConvertStrToEthAddress(m_settingsProvider.GetSettings().GetTokenContractAddress(swapCoin));
hashData.insert(hashData.end(), tokenContractAddress.cbegin(), tokenContractAddress.cend());
}
auto msgHash = ethash::keccak256(&hashData[0], hashData.size());
libbitcoin::data_chunk msgWithPrefixData(kEthSignPrefix.begin(), kEthSignPrefix.end());
msgWithPrefixData.insert(std::end(msgWithPrefixData), std::begin(msgHash.bytes), std::end(msgHash.bytes));
auto hash = ethash::keccak256(&msgWithPrefixData[0], msgWithPrefixData.size());
libbitcoin::hash_digest hashDigest;
std::move(std::begin(hash.bytes), std::end(hash.bytes), hashDigest.begin());
libbitcoin::ec_secret secretEC;
std::move(std::begin(secret.m_pData), std::end(secret.m_pData), std::begin(secretEC));
libbitcoin::recoverable_signature signature;
libbitcoin::sign_recoverable(signature, secretEC, hashDigest);
// kRedeemMethodHash + addressFromSecret + signature (r, s, v)
data.reserve(ethereum::kEthContractMethodHashSize + 4 * ethereum::kEthContractABIWordSize);
libbitcoin::decode_base16(data, ethereum::swap_contract::GetRedeemMethodHash(IsHashLockScheme()));
ethereum::AddContractABIWordToBuffer(secretHash, data);
data.insert(data.end(), std::begin(signature.signature), std::end(signature.signature));
data.insert(data.end(), 31u, 0x00);
data.push_back(signature.recovery_id + 27u);
}
return data;
}
beam::ByteBuffer EthereumSide::BuildRefundTxData()
{
// kRefundMethodHash + secretHash/addressFromSecret
auto secretHash = GetSecretHash();
libbitcoin::data_chunk data;
data.reserve(ethereum::kEthContractMethodHashSize + ethereum::kEthContractABIWordSize);
libbitcoin::decode_base16(data, ethereum::swap_contract::GetRefundMethodHash(IsHashLockScheme()));
ethereum::AddContractABIWordToBuffer(secretHash, data);
return data;
}
bool EthereumSide::IsERC20Token() const
{
auto swapCoin = m_tx.GetMandatoryParameter<AtomicSwapCoin>(TxParameterID::AtomicSwapCoin);
switch (swapCoin)
{
case beam::wallet::AtomicSwapCoin::Dai:
case beam::wallet::AtomicSwapCoin::Usdt:
case beam::wallet::AtomicSwapCoin::WBTC:
return true;
case beam::wallet::AtomicSwapCoin::Ethereum:
return false;
default:
{
assert("Unexpected swapCoin type.");
return false;
}
}
}
beam::ByteBuffer EthereumSide::BuildLockTxData()
{
auto participantStr = m_isEthOwner ?
m_tx.GetMandatoryParameter<std::string>(TxParameterID::AtomicSwapPeerPublicKey) :
m_tx.GetMandatoryParameter<std::string>(TxParameterID::AtomicSwapPublicKey);
auto participant = ethereum::ConvertStrToEthAddress(participantStr);
uintBig refundTimeInBlocks = m_tx.GetMandatoryParameter<Height>(TxParameterID::AtomicSwapExternalLockTime);
// LockMethodHash + refundTimeInBlocks + hashedSecret/addressFromSecret + participant
beam::ByteBuffer out;
out.reserve(ethereum::kEthContractMethodHashSize + 3 * ethereum::kEthContractABIWordSize);
libbitcoin::decode_base16(out, ethereum::swap_contract::GetLockMethodHash(IsERC20Token(), IsHashLockScheme()));
ethereum::AddContractABIWordToBuffer({ std::begin(refundTimeInBlocks.m_pData), std::end(refundTimeInBlocks.m_pData) }, out);
ethereum::AddContractABIWordToBuffer(GetSecretHash(), out);
ethereum::AddContractABIWordToBuffer(participant, out);
if (IsERC20Token())
{
// + ERC20 contractAddress, + value
auto swapCoin = m_tx.GetMandatoryParameter<AtomicSwapCoin>(TxParameterID::AtomicSwapCoin);
const auto tokenContractAddress = ethereum::ConvertStrToEthAddress(m_settingsProvider.GetSettings().GetTokenContractAddress(swapCoin));
uintBig swapAmount = GetSwapAmount();
ethereum::AddContractABIWordToBuffer(tokenContractAddress, out);
ethereum::AddContractABIWordToBuffer({ std::begin(swapAmount.m_pData), std::end(swapAmount.m_pData) }, out);
}
return out;
}
bool EthereumSide::IsHashLockScheme() const
{
// TODO: -> settings or mb add as TxParameterID
return false;
}
void EthereumSide::SetTxError(const ethereum::IBridge::Error& error, SubTxID subTxID)
{
TxFailureReason previousReason;
if (m_tx.GetParameter(TxParameterID::InternalFailureReason, previousReason, subTxID))
{
return;
}
LOG_ERROR() << m_tx.GetTxID() << "[" << static_cast<SubTxID>(subTxID) << "]" << " Bridge internal error: type = " << error.m_type << "; message = " << error.m_message;
switch (error.m_type)
{
case ethereum::IBridge::EmptyResult:
case ethereum::IBridge::InvalidResultFormat:
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::SwapFormatResponseError, false, subTxID);
break;
case ethereum::IBridge::IOError:
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::SwapNetworkBridgeError, false, subTxID);
break;
default:
m_tx.SetParameter(TxParameterID::InternalFailureReason, TxFailureReason::SwapSecondSideBridgeError, false, subTxID);
}
m_tx.UpdateAsync();
}
ECC::uintBig EthereumSide::GetSwapAmount() const
{
auto swapCoin = m_tx.GetMandatoryParameter<AtomicSwapCoin>(TxParameterID::AtomicSwapCoin);
uintBig swapAmount = m_tx.GetMandatoryParameter<Amount>(TxParameterID::AtomicSwapAmount);
swapAmount = swapAmount * ECC::uintBig(ethereum::GetCoinUnitsMultiplier(swapCoin));
return swapAmount;
}
bool EthereumSide::IsLockTimeExpired()
{
uint64_t height = GetBlockCount();
uint64_t lockHeight = 0;
m_tx.GetParameter(TxParameterID::AtomicSwapExternalLockTime, lockHeight);
return height >= lockHeight;
}
bool EthereumSide::HasEnoughTimeToProcessLockTx()
{
Height lockTxMaxHeight = MaxHeight;
if (m_tx.GetParameter(TxParameterID::MaxHeight, lockTxMaxHeight, SubTxIndex::BEAM_LOCK_TX))
{
Block::SystemState::Full systemState;
if (m_tx.GetTip(systemState) && systemState.m_Height > lockTxMaxHeight - GetLockTxEstimatedTimeInBeamBlocks())
{
return false;
}
}
return true;
}
bool EthereumSide::IsQuickRefundAvailable()
{
return false;
}
Amount EthereumSide::CalcLockTxFee(Amount priceGas, AtomicSwapCoin swapCoin)
{
Amount result = priceGas * ethereum::kLockTxGasLimit;
if (IsEthToken(swapCoin))
{
result += 2 * priceGas * ethereum::kApproveTxGasLimit; // sometimes need 2 appove
}
return result;
}
Amount EthereumSide::CalcWithdrawTxFee(Amount priceGas, AtomicSwapCoin swapCoin)
{
return priceGas * ethereum::kWithdrawTxGasLimit;
}
uint64_t EthereumSide::GetBlockCount(bool notify)
{
m_ethBridge->getBlockNumber([this, weak = this->weak_from_this(), notify](const ethereum::IBridge::Error& error, uint64_t blockCount)
{
if (!weak.expired())
{
if (error.m_type != ethereum::IBridge::None)
{
m_tx.UpdateOnNextTip();
return;
}
if (blockCount != m_blockCount)
{
m_blockCount = blockCount;
m_tx.SetParameter(TxParameterID::AtomicSwapExternalHeight, m_blockCount, true);
if (notify)
{
m_tx.UpdateAsync();
}
}
}
});
return m_blockCount;
}
void EthereumSide::InitSecret()
{
NoLeak<uintBig> secret;
GenRandom(secret.V);
if (IsHashLockScheme())
{
m_tx.SetParameter(TxParameterID::PreImage, secret.V, false, BEAM_REDEEM_TX);
}
else
{
m_tx.SetParameter(TxParameterID::AtomicSwapSecretPrivateKey, secret.V, false, BEAM_REDEEM_TX);
}
}
uint16_t EthereumSide::GetTxMinConfirmations(SubTxID subTxID) const
{
switch (subTxID)
{
case SubTxIndex::LOCK_TX:
return m_settingsProvider.GetSettings().GetLockTxMinConfirmations();
case SubTxIndex::REDEEM_TX:
case SubTxIndex::REFUND_TX:
return m_settingsProvider.GetSettings().GetWithdrawTxMinConfirmations();
default:
assert(false && "unexpected subTxID");
return 0;
}
}
uint32_t EthereumSide::GetLockTimeInBlocks() const
{
return m_settingsProvider.GetSettings().GetLockTimeInBlocks();
}
double EthereumSide::GetBlocksPerHour() const
{
return m_settingsProvider.GetSettings().GetBlocksPerHour();
}
uint32_t EthereumSide::GetLockTxEstimatedTimeInBeamBlocks() const
{
// TODO: check
return 10;
}
ECC::uintBig EthereumSide::GetSecret() const
{
if (IsHashLockScheme())
{
return m_tx.GetMandatoryParameter<Hash::Value>(TxParameterID::PreImage, SubTxIndex::BEAM_REDEEM_TX);
}
else
{
return m_tx.GetMandatoryParameter<uintBig>(TxParameterID::AtomicSwapSecretPrivateKey, SubTxIndex::BEAM_REDEEM_TX);
}
}
ByteBuffer EthereumSide::GetSecretHash() const
{
if (IsHashLockScheme())
{
Hash::Value lockImage(Zero);
if (NoLeak<uintBig> secret; m_tx.GetParameter(TxParameterID::PreImage, secret.V, SubTxIndex::BEAM_REDEEM_TX))
{
Hash::Processor() << secret.V >> lockImage;
}
else
{
lockImage = m_tx.GetMandatoryParameter<uintBig>(TxParameterID::PeerLockImage, SubTxIndex::BEAM_REDEEM_TX);
}
return libbitcoin::to_chunk(lockImage.m_pData);
}
else
{
libbitcoin::wallet::ec_public secretPublicKey;
if (m_isEthOwner)
{
NoLeak<uintBig> secretPrivateKey;
m_tx.GetParameter(TxParameterID::AtomicSwapSecretPrivateKey, secretPrivateKey.V, SubTxIndex::BEAM_REDEEM_TX);
libbitcoin::ec_secret secret;
std::copy(std::begin(secretPrivateKey.V.m_pData), std::end(secretPrivateKey.V.m_pData), secret.begin());
libbitcoin::wallet::ec_private privateKey(secret, libbitcoin::wallet::ec_private::mainnet, false);
secretPublicKey = privateKey.to_public();
}
else
{
Point publicKeyPoint = m_tx.GetMandatoryParameter<Point>(TxParameterID::AtomicSwapSecretPublicKey, SubTxIndex::BEAM_REDEEM_TX);
auto publicKeyRaw = SerializePubkey(ConvertPointToPubkey(publicKeyPoint));
secretPublicKey = libbitcoin::wallet::ec_public(publicKeyRaw);
}
libbitcoin::short_hash addressFromSecret = ethereum::GetEthAddressFromPubkeyStr(secretPublicKey.encoded());
return ByteBuffer(addressFromSecret.begin(), addressFromSecret.end());
}
}
ECC::uintBig EthereumSide::GetGasLimit(SubTxID subTxID) const
{
if (subTxID == SubTxIndex::LOCK_TX)
{
return m_settingsProvider.GetSettings().m_lockTxGasLimit;
}
return m_settingsProvider.GetSettings().m_withdrawTxGasLimit;
}
ECC::uintBig EthereumSide::GetApproveTxGasLimit() const
{
return m_settingsProvider.GetSettings().m_approveTxGasLimit;
}
ECC::uintBig EthereumSide::GetGasPrice(SubTxID subTxID) const
{
// TODO need change this. maybe overflow
// convert from gwei to wei
return m_tx.GetMandatoryParameter<Amount>(TxParameterID::Fee, subTxID) * 1'000'000'000u;
}
libbitcoin::short_hash EthereumSide::GetContractAddress() const
{
return ethereum::ConvertStrToEthAddress(GetContractAddressStr());
}
std::string EthereumSide::GetContractAddressStr() const
{
if (IsERC20Token())
{
return m_settingsProvider.GetSettings().GetERC20SwapContractAddress(IsHashLockScheme());
}
return m_settingsProvider.GetSettings().GetContractAddress(IsHashLockScheme());
}
} // namespace beam::wallet | 36.621908 | 171 | 0.646372 | [
"transform"
] |
1952f0e69026a834c536f4f5fb6e45304b2e0a14 | 734 | cpp | C++ | issa-engine-sfml/src/InputManager.cpp | zhooda/issa-engine | b64a89735617ec6e45439cef62f7858e7c50a591 | [
"MIT"
] | 1 | 2020-03-23T17:17:07.000Z | 2020-03-23T17:17:07.000Z | issa-engine-sfml/xcode/issa-engine/InputManager.cpp | zhooda/issa-engine | b64a89735617ec6e45439cef62f7858e7c50a591 | [
"MIT"
] | null | null | null | issa-engine-sfml/xcode/issa-engine/InputManager.cpp | zhooda/issa-engine | b64a89735617ec6e45439cef62f7858e7c50a591 | [
"MIT"
] | null | null | null | //
// InputManager.cpp
// issa-engine
//
// Created by Zeeshan Hooda on 3/8/20.
// Copyright © 2020 Deceptive Labs. All rights reserved.
//
#include "InputManager.hpp"
namespace Issa {
bool InputManager::IsSpriteClicked(sf::Sprite object, sf::Mouse::Button button, sf::RenderWindow &window) {
if (sf::Mouse::isButtonPressed(button)) {
sf::IntRect tempRect(object.getPosition().x, object.getPosition().y, object.getGlobalBounds().width, object.getGlobalBounds().height);
if (tempRect.contains(sf::Mouse::getPosition(window))) {
return true;
}
}
return false;
}
sf::Vector2i InputManager::GetMousePosition(sf::RenderWindow &window) {
return sf::Mouse::getPosition(window);
}
}
| 28.230769 | 142 | 0.682561 | [
"object"
] |
19627d7a440366d1cdc85fdfd18a51cdab6e33e4 | 1,469 | cpp | C++ | cpp/leetcode/BinaryTreeFlatten.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/BinaryTreeFlatten.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/BinaryTreeFlatten.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | //Leetcode Problem No 114 Flatten Binary Tree to Linked List
//Solution written by Xuqiang Fang on 23 Oct, 2018
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
using namespace std;
struct TreeNode{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x), left(NULL), right(NULL){}
};
class Solution {
public:
void flatten(TreeNode* root) {
if(!root) return;
helper(root);
return;
}
private:
TreeNode* helper(TreeNode* root){
if(!root || (!root->left && !root->right)){
return root;
}
else{
TreeNode* tmp = helper(root->right);
root->right = helper(root->left);
root->left = NULL;
right(root)->right = tmp;
return root;
}
}
TreeNode* right(TreeNode* root){
while(root->right){
root = root->right;
}
return root;
}
};
int main(){
Solution s;
TreeNode a(1);
TreeNode b(2);
TreeNode c(3);
TreeNode d(4);
TreeNode e(5);
a.left = &b;
b.left = &c;
c.right = &d;
a.right = &e;
s.flatten(&a);
TreeNode* t = &a;
while(t){
cout << t->val << endl;
t = t->right;
}
return 0;
}
| 21.925373 | 60 | 0.501702 | [
"vector"
] |
19646e0e069f5e73fea644196568809383038a7f | 58,570 | cpp | C++ | coreLibrary_200/source/core/dgAABBPolygonSoup.cpp | rastullahs-lockenpracht/newton | 99b82478f3de9ee7c8d17c8ebefe62e46283d857 | [
"Zlib"
] | null | null | null | coreLibrary_200/source/core/dgAABBPolygonSoup.cpp | rastullahs-lockenpracht/newton | 99b82478f3de9ee7c8d17c8ebefe62e46283d857 | [
"Zlib"
] | null | null | null | coreLibrary_200/source/core/dgAABBPolygonSoup.cpp | rastullahs-lockenpracht/newton | 99b82478f3de9ee7c8d17c8ebefe62e46283d857 | [
"Zlib"
] | null | null | null | /* Copyright (c) <2003-2011> <Julio Jerez, Newton Game Dynamics>
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
*
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
*
* 3. This notice may not be removed or altered from any source distribution.
*/
/****************************************************************************
*
* File Name : Bitmap.C
* Visual C++ 4.0 base by Julio Jerez
*
****************************************************************************/
#include "dgStdafx.h"
#include "dgHeap.h"
#include "dgStack.h"
#include "dgList.h"
#include "dgMatrix.h"
#include "dgPolygonSoupBuilder.h"
#include "dgSimd_Instrutions.h"
#include "dgAABBPolygonSoup.h"
#define DG_STACK_DEPTH 63
#ifdef _MSC_VER
#pragma warning (disable: 4201) //nonstandard extension used : nameless struct/union
#endif
class dgAABBTree
{
class TreeNode
{
#define DG_INDEX_COUNT_BITS 6
public:
inline TreeNode()
{
_ASSERTE(0);
}
inline TreeNode(dgUnsigned32 node)
{
m_node = node;
_ASSERTE(!IsLeaf());
}
inline dgUnsigned32 IsLeaf() const
{
return m_node & 0x80000000;
}
inline dgUnsigned32 GetCount() const
{
_ASSERTE(IsLeaf());
return (m_node & (~0x80000000)) >> (32 - DG_INDEX_COUNT_BITS - 1);
}
inline dgUnsigned32 GetIndex() const
{
_ASSERTE(IsLeaf());
return m_node & (~(-(1 << (32 - DG_INDEX_COUNT_BITS - 1))));
}
inline TreeNode(dgUnsigned32 faceIndexCount, dgUnsigned32 faceIndexStart)
{
_ASSERTE(faceIndexCount < (1<<DG_INDEX_COUNT_BITS));
m_node = 0x80000000 | (faceIndexCount << (32 - DG_INDEX_COUNT_BITS - 1))
| faceIndexStart;
}
inline dgAABBTree* GetNode(const void* root) const
{
return ((dgAABBTree*) root) + m_node;
}
union
{
dgUnsigned32 m_node;
};
};
class dgHeapNodePair
{
public:
dgInt32 m_nodeA;
dgInt32 m_nodeB;
};
class dgConstructionTree
{
public:
DG_CLASS_ALLOCATOR(allocator)
dgConstructionTree()
{
}
/*
dgConstructionTree(dgConstructionTree* const back, dgConstructionTree* const front)
{
m_back = back;
m_front = front;
m_parent = NULL;
m_boxIndex = -1;
m_p0.m_x = GetMin (back->m_p0.m_x, front->m_p0.m_x);
m_p0.m_y = GetMin (back->m_p0.m_y, front->m_p0.m_y);
m_p0.m_z = GetMin (back->m_p0.m_z, front->m_p0.m_z);
m_p1.m_x = GetMax (back->m_p1.m_x, front->m_p1.m_x);
m_p1.m_y = GetMax (back->m_p1.m_y, front->m_p1.m_y);
m_p1.m_z = GetMax (back->m_p1.m_z, front->m_p1.m_z);
m_p0.m_w = dgFloat32 (0.0f);
m_p1.m_w = dgFloat32 (0.0f);
dgVector side0(m_p1 - m_p0);
dgVector side1(side0.m_y, side0.m_z, side0.m_x, dgFloat32(0.0f));
m_surfaceArea = side0 % side1;
}
*/
~dgConstructionTree()
{
if (m_back)
{
delete m_back;
}
if (m_front)
{
delete m_front;
}
}
dgVector m_p0;
dgVector m_p1;
dgInt32 m_boxIndex;
dgFloat32 m_surfaceArea;
dgConstructionTree* m_back;
dgConstructionTree* m_front;
dgConstructionTree* m_parent;
};
public:
void CalcExtends(dgTriplex* const vertex, dgInt32 indexCount,
const dgInt32* const indexArray)
{
dgVector minP(dgFloat32(1.0e15f), dgFloat32(1.0e15f), dgFloat32(1.0e15f),
dgFloat32(0.0f));
dgVector maxP(-dgFloat32(1.0e15f), -dgFloat32(1.0e15f), -dgFloat32(1.0e15f),
dgFloat32(0.0f));
for (dgInt32 i = 1; i < indexCount; i++)
{
dgInt32 index;
index = indexArray[i];
dgVector p(&vertex[index].m_x);
minP.m_x = GetMin(p.m_x, minP.m_x);
minP.m_y = GetMin(p.m_y, minP.m_y);
minP.m_z = GetMin(p.m_z, minP.m_z);
maxP.m_x = GetMax(p.m_x, maxP.m_x);
maxP.m_y = GetMax(p.m_y, maxP.m_y);
maxP.m_z = GetMax(p.m_z, maxP.m_z);
}
vertex[m_minIndex].m_x = minP.m_x - dgFloat32(1.0e-3f);
vertex[m_minIndex].m_y = minP.m_y - dgFloat32(1.0e-3f);
vertex[m_minIndex].m_z = minP.m_z - dgFloat32(1.0e-3f);
vertex[m_maxIndex].m_x = maxP.m_x + dgFloat32(1.0e-3f);
vertex[m_maxIndex].m_y = maxP.m_y + dgFloat32(1.0e-3f);
vertex[m_maxIndex].m_z = maxP.m_z + dgFloat32(1.0e-3f);
}
dgInt32 BuildTree(dgConstructionTree* const root, dgAABBTree* const boxArray,
dgAABBTree* const boxCopy, dgTriplex* const vertexArrayOut,
dgInt32 &treeVCount)
{
TreeNode* parent[128];
dgConstructionTree* pool[128];
dgInt32 index = 0;
dgInt32 stack = 1;
parent[0] = NULL;
pool[0] = root;
while (stack)
{
stack--;
dgConstructionTree* const node = pool[stack];
TreeNode* const parentNode = parent[stack];
if (node->m_boxIndex != -1)
{
if (parentNode)
{
*parentNode = boxCopy[node->m_boxIndex].m_back;
}
else
{
//_ASSERTE(boxCount == 1);
dgAABBTree* const newNode = &boxArray[index];
*newNode = boxCopy[node->m_boxIndex];
index++;
}
}
else
{
dgAABBTree* const newNode = &boxArray[index];
newNode->m_minIndex = treeVCount;
vertexArrayOut[treeVCount].m_x = node->m_p0.m_x;
vertexArrayOut[treeVCount].m_y = node->m_p0.m_y;
vertexArrayOut[treeVCount].m_z = node->m_p0.m_z;
newNode->m_maxIndex = treeVCount + 1;
vertexArrayOut[treeVCount + 1].m_x = node->m_p1.m_x;
vertexArrayOut[treeVCount + 1].m_y = node->m_p1.m_y;
vertexArrayOut[treeVCount + 1].m_z = node->m_p1.m_z;
treeVCount += 2;
if (parentNode)
{
*parentNode = TreeNode(dgUnsigned32(index));
}
index++;
pool[stack] = node->m_front;
parent[stack] = &newNode->m_front;
stack++;
pool[stack] = node->m_back;
parent[stack] = &newNode->m_back;
stack++;
}
}
// this object is not to be deleted when using stack allocation
//delete root;
return index;
}
void PushNodes(dgConstructionTree* const root,
dgList<dgConstructionTree*>& list) const
{
if (root->m_back)
{
PushNodes(root->m_back, list);
}
if (root->m_front)
{
PushNodes(root->m_front, list);
}
if (root->m_boxIndex == -1)
{
list.Append(root);
}
}
dgInt32 CalculateMaximunDepth(dgConstructionTree* tree) const
{
dgInt32 depthPool[128];
dgConstructionTree* pool[128];
depthPool[0] = 0;
pool[0] = tree;
dgInt32 stack = 1;
dgInt32 maxDepth = -1;
while (stack)
{
stack--;
dgInt32 depth = depthPool[stack];
dgConstructionTree* const node = pool[stack];
maxDepth = GetMax(maxDepth, depth);
if (node->m_boxIndex == -1)
{
_ASSERTE(node->m_back);
_ASSERTE(node->m_front);
depth++;
depthPool[stack] = depth;
pool[stack] = node->m_back;
stack++;
depthPool[stack] = depth;
pool[stack] = node->m_front;
stack++;
}
}
return maxDepth + 1;
}
dgFloat32 CalculateArea(dgConstructionTree* const node0,
dgConstructionTree* const node1) const
{
dgVector p0(GetMin(node0->m_p0.m_x, node1->m_p0.m_x),
GetMin(node0->m_p0.m_y, node1->m_p0.m_y),
GetMin(node0->m_p0.m_z, node1->m_p0.m_z), dgFloat32(0.0f));
dgVector p1(GetMax(node0->m_p1.m_x, node1->m_p1.m_x),
GetMax(node0->m_p1.m_y, node1->m_p1.m_y),
GetMax(node0->m_p1.m_z, node1->m_p1.m_z), dgFloat32(0.0f));
dgVector side0(p1 - p0);
dgVector side1(side0.m_y, side0.m_z, side0.m_x, dgFloat32(0.0f));
return side0 % side1;
}
void SetBox(dgConstructionTree* const node) const
{
node->m_p0.m_x = GetMin(node->m_back->m_p0.m_x, node->m_front->m_p0.m_x);
node->m_p0.m_y = GetMin(node->m_back->m_p0.m_y, node->m_front->m_p0.m_y);
node->m_p0.m_z = GetMin(node->m_back->m_p0.m_z, node->m_front->m_p0.m_z);
node->m_p1.m_x = GetMax(node->m_back->m_p1.m_x, node->m_front->m_p1.m_x);
node->m_p1.m_y = GetMax(node->m_back->m_p1.m_y, node->m_front->m_p1.m_y);
node->m_p1.m_z = GetMax(node->m_back->m_p1.m_z, node->m_front->m_p1.m_z);
dgVector side0(node->m_p1 - node->m_p0);
dgVector side1(side0.m_y, side0.m_z, side0.m_x, dgFloat32(0.0f));
node->m_surfaceArea = side0 % side1;
}
void ImproveNodeFitness(dgConstructionTree* const node) const
{
_ASSERTE(node->m_back);
_ASSERTE(node->m_front);
if (node->m_parent)
{
if (node->m_parent->m_back == node)
{
dgFloat32 cost0 = node->m_surfaceArea;
dgFloat32 cost1 = CalculateArea(node->m_front, node->m_parent->m_front);
dgFloat32 cost2 = CalculateArea(node->m_back, node->m_parent->m_front);
if ((cost1 <= cost0) && (cost1 <= cost2))
{
dgConstructionTree* const parent = node->m_parent;
node->m_p0 = parent->m_p0;
node->m_p1 = parent->m_p1;
node->m_surfaceArea = parent->m_surfaceArea;
if (parent->m_parent)
{
if (parent->m_parent->m_back == parent)
{
parent->m_parent->m_back = node;
}
else
{
_ASSERTE(parent->m_parent->m_front == parent);
parent->m_parent->m_front = node;
}
}
node->m_parent = parent->m_parent;
parent->m_parent = node;
node->m_front->m_parent = parent;
parent->m_back = node->m_front;
node->m_front = parent;
SetBox(parent);
}
else if ((cost2 <= cost0) && (cost2 <= cost1))
{
dgConstructionTree* const parent = node->m_parent;
node->m_p0 = parent->m_p0;
node->m_p1 = parent->m_p1;
node->m_surfaceArea = parent->m_surfaceArea;
if (parent->m_parent)
{
if (parent->m_parent->m_back == parent)
{
parent->m_parent->m_back = node;
}
else
{
_ASSERTE(parent->m_parent->m_front == parent);
parent->m_parent->m_front = node;
}
}
node->m_parent = parent->m_parent;
parent->m_parent = node;
node->m_back->m_parent = parent;
parent->m_back = node->m_back;
node->m_back = parent;
SetBox(parent);
}
}
else
{
dgFloat32 cost0 = node->m_surfaceArea;
dgFloat32 cost1 = CalculateArea(node->m_back, node->m_parent->m_back);
dgFloat32 cost2 = CalculateArea(node->m_front, node->m_parent->m_back);
if ((cost1 <= cost0) && (cost1 <= cost2))
{
dgConstructionTree* const parent = node->m_parent;
node->m_p0 = parent->m_p0;
node->m_p1 = parent->m_p1;
node->m_surfaceArea = parent->m_surfaceArea;
if (parent->m_parent)
{
if (parent->m_parent->m_back == parent)
{
parent->m_parent->m_back = node;
}
else
{
_ASSERTE(parent->m_parent->m_front == parent);
parent->m_parent->m_front = node;
}
}
node->m_parent = parent->m_parent;
parent->m_parent = node;
node->m_back->m_parent = parent;
parent->m_front = node->m_back;
node->m_back = parent;
SetBox(parent);
}
else if ((cost2 <= cost0) && (cost2 <= cost1))
{
dgConstructionTree* const parent = node->m_parent;
node->m_p0 = parent->m_p0;
node->m_p1 = parent->m_p1;
node->m_surfaceArea = parent->m_surfaceArea;
if (parent->m_parent)
{
if (parent->m_parent->m_back == parent)
{
parent->m_parent->m_back = node;
}
else
{
_ASSERTE(parent->m_parent->m_front == parent);
parent->m_parent->m_front = node;
}
}
node->m_parent = parent->m_parent;
parent->m_parent = node;
node->m_front->m_parent = parent;
parent->m_front = node->m_front;
node->m_front = parent;
SetBox(parent);
}
}
}
}
dgFloat64 TotalFitness(dgList<dgConstructionTree*>& nodeList) const
{
dgFloat64 cost = dgFloat32(0.0f);
for (dgList<dgConstructionTree*>::dgListNode* node = nodeList.GetFirst();
node; node = node->GetNext())
{
dgConstructionTree* const box = node->GetInfo();
cost += box->m_surfaceArea;
}
return cost;
}
dgConstructionTree* ImproveTotalFitness(dgConstructionTree* const root,
dgAABBTree* const boxArray, dgMemoryAllocator* const allocator)
{
dgList<dgConstructionTree*> nodesList(allocator);
dgConstructionTree* newRoot = root;
PushNodes(root, nodesList);
if (nodesList.GetCount())
{
dgInt32 maxPasses = CalculateMaximunDepth(root) * 2;
dgFloat64 newCost = TotalFitness(nodesList);
dgFloat64 prevCost = newCost;
do
{
prevCost = newCost;
for (dgList<dgConstructionTree*>::dgListNode* node =
nodesList.GetFirst(); node; node = node->GetNext())
{
dgConstructionTree* const box = node->GetInfo();
ImproveNodeFitness(box);
}
newCost = TotalFitness(nodesList);
maxPasses--;
} while (maxPasses && (newCost < prevCost));
newRoot = nodesList.GetLast()->GetInfo();
while (newRoot->m_parent)
{
newRoot = newRoot->m_parent;
}
}
return newRoot;
}
/*
dgInt32 BuildBottomUp (dgMemoryAllocator* const allocator, dgInt32 boxCount, dgAABBTree* const boxArray, dgTriplex* const vertexArrayOut, dgInt32 &treeVCount)
{
dgInt32 count;
dgStack <dgAABBTree> boxCopy (boxCount);
dgStack<dgHeapNodePair> heapPool(boxCount / 8 + 32);
dgStack<dgConstructionTree*> tmpTreeArrayPool(2 * boxCount);
dgConstructionTree** const tmpTreeArray = &tmpTreeArrayPool[0];
dgDownHeap<dgHeapNodePair, dgFloat32> heap (&heapPool[0], heapPool.GetSizeInBytes() - 32);
count = boxCount;
memcpy (&boxCopy[0], boxArray, boxCount * sizeof (dgAABBTree));
for (dgInt32 i = 0; i < count; i ++) {
dgConstructionTree* const node = new (allocator) dgConstructionTree();
tmpTreeArray[i] = node;
dgInt32 j = boxArray[i].m_minIndex;
node->m_p0 = dgVector (vertexArrayOut[j].m_x, vertexArrayOut[j].m_y, vertexArrayOut[j].m_z, dgFloat32 (0.0f));
j = boxArray[i].m_maxIndex;
node->m_p1 = dgVector (vertexArrayOut[j].m_x, vertexArrayOut[j].m_y, vertexArrayOut[j].m_z, dgFloat32 (0.0f));
dgVector side0 (node->m_p1 - node->m_p0);
dgVector side1 (side0.m_y, side0.m_z, side0.m_x, dgFloat32 (0.0f));
node->m_surfaceArea = side0 % side1;
node->m_boxIndex = i;
node->m_back = NULL;
node->m_front = NULL;
}
while (count > 1){
dgInt32 axis;
dgInt32 newCount;
axis = GetAxis (&tmpTreeArray[0], count);
dgSortIndirect (&tmpTreeArray[0], count, CompareBox, &axis);
heap.Flush();
for (dgInt32 i = 0; i < count - 1; i ++) {
dgInt32 bestProxi;
dgFloat32 smallestVolume;
dgFloat32 breakValue;
dgConstructionTree* nodeA;
nodeA = tmpTreeArray[i];
bestProxi = -1;
smallestVolume = dgFloat32 (1.0e20f);
breakValue = ((count - i) < 32) ? dgFloat32 (1.0e20f) : nodeA->m_p1[axis] + dgFloat32 (2.0f);
if (breakValue < tmpTreeArray[i + 1]->m_p0[axis]) {
breakValue = tmpTreeArray[i + 1]->m_p0[axis] + dgFloat32 (2.0f);
}
for (dgInt32 j = i + 1; (j < count) && (tmpTreeArray[j]->m_p0[axis] < breakValue); j ++) {
dgFloat32 volume;
dgVector p0;
dgVector p1;
dgConstructionTree* nodeB;
nodeB = tmpTreeArray[j];
p0.m_x = GetMin (nodeA->m_p0.m_x, nodeB->m_p0.m_x);
p0.m_y = GetMin (nodeA->m_p0.m_y, nodeB->m_p0.m_y);
p0.m_z = GetMin (nodeA->m_p0.m_z, nodeB->m_p0.m_z);
p0.m_w = dgFloat32 (0.0f);
p1.m_x = GetMax (nodeA->m_p1.m_x, nodeB->m_p1.m_x);
p1.m_y = GetMax (nodeA->m_p1.m_y, nodeB->m_p1.m_y);
p1.m_z = GetMax (nodeA->m_p1.m_z, nodeB->m_p1.m_z);
p1.m_w = dgFloat32 (0.0f);
dgVector dist (p1 - p0);
volume = dist.m_x * dist.m_y * dist.m_z;
if (volume < smallestVolume) {
bestProxi = j;
smallestVolume = volume;
}
}
_ASSERTE (bestProxi != -1);
dgHeapNodePair pair;
pair.m_nodeA = i;
pair.m_nodeB = bestProxi;
if (heap.GetCount() < heap.GetMaxCount()) {
heap.Push(pair, smallestVolume);
} else {
if (smallestVolume < heap.Value()) {
heap.Pop();
heap.Push(pair, smallestVolume);
}
}
}
heap.Sort ();
for (dgInt32 j = heap.GetCount() - 1; j >= 0; j --) {
dgHeapNodePair pair (heap[j]);
if ((tmpTreeArray[pair.m_nodeA]->m_p0.m_w == dgFloat32 (0.0f)) && (tmpTreeArray[pair.m_nodeB]->m_p0.m_w == dgFloat32 (0.0f))) {
tmpTreeArray[pair.m_nodeA]->m_p0.m_w = dgFloat32 (1.0f);
tmpTreeArray[pair.m_nodeB]->m_p0.m_w = dgFloat32 (1.0f);
dgConstructionTree* const node = new (allocator) dgConstructionTree (tmpTreeArray[pair.m_nodeA], tmpTreeArray[pair.m_nodeB]);
tmpTreeArray[count] = node;
count ++;
}
}
newCount = 0;
for (dgInt32 i = 0; i < count; i ++) {
if (tmpTreeArray[i]->m_p0.m_w == dgFloat32 (0.0f)) {
tmpTreeArray[newCount] = tmpTreeArray[i];
newCount ++;
}
}
_ASSERTE (newCount < count);
count = newCount;
}
count = BuildTree (tmpTreeArray[0], boxArray, &boxCopy[0], vertexArrayOut, treeVCount);
delete tmpTreeArray[0];
return count;
}
*/
dgConstructionTree* BuildTree(dgMemoryAllocator* const allocator,
dgInt32 firstBox, dgInt32 lastBox, dgAABBTree* const boxArray,
const dgTriplex* const vertexArray, dgConstructionTree* parent)
{
dgConstructionTree* const tree = new (allocator) dgConstructionTree();
_ASSERTE(firstBox >= 0);
_ASSERTE(lastBox >= 0);
tree->m_parent = parent;
if (lastBox == firstBox)
{
dgInt32 j0 = boxArray[firstBox].m_minIndex;
dgInt32 j1 = boxArray[firstBox].m_maxIndex;
tree->m_p0 = dgVector(vertexArray[j0].m_x, vertexArray[j0].m_y,
vertexArray[j0].m_z, dgFloat32(0.0f));
tree->m_p1 = dgVector(vertexArray[j1].m_x, vertexArray[j1].m_y,
vertexArray[j1].m_z, dgFloat32(0.0f));
tree->m_boxIndex = firstBox;
tree->m_back = NULL;
tree->m_front = NULL;
}
else
{
struct dgSpliteInfo
{
dgSpliteInfo(dgAABBTree* const boxArray, dgInt32 boxCount,
const dgTriplex* const vertexArray,
const dgConstructionTree* const tree)
{
dgVector minP(dgFloat32(1.0e15f), dgFloat32(1.0e15f),
dgFloat32(1.0e15f), dgFloat32(0.0f));
dgVector maxP(-dgFloat32(1.0e15f), -dgFloat32(1.0e15f),
-dgFloat32(1.0e15f), dgFloat32(0.0f));
if (boxCount == 2)
{
m_axis = 1;
for (dgInt32 i = 0; i < boxCount; i++)
{
dgInt32 j0 = boxArray[i].m_minIndex;
dgInt32 j1 = boxArray[i].m_maxIndex;
dgVector p0(vertexArray[j0].m_x, vertexArray[j0].m_y,
vertexArray[j0].m_z, dgFloat32(0.0f));
dgVector p1(vertexArray[j1].m_x, vertexArray[j1].m_y,
vertexArray[j1].m_z, dgFloat32(0.0f));
minP.m_x = GetMin(p0.m_x, minP.m_x);
minP.m_y = GetMin(p0.m_y, minP.m_y);
minP.m_z = GetMin(p0.m_z, minP.m_z);
maxP.m_x = GetMax(p1.m_x, maxP.m_x);
maxP.m_y = GetMax(p1.m_y, maxP.m_y);
maxP.m_z = GetMax(p1.m_z, maxP.m_z);
}
}
else
{
dgVector median(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector varian(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
for (dgInt32 i = 0; i < boxCount; i++)
{
dgInt32 j0 = boxArray[i].m_minIndex;
dgInt32 j1 = boxArray[i].m_maxIndex;
dgVector p0(vertexArray[j0].m_x, vertexArray[j0].m_y,
vertexArray[j0].m_z, dgFloat32(0.0f));
dgVector p1(vertexArray[j1].m_x, vertexArray[j1].m_y,
vertexArray[j1].m_z, dgFloat32(0.0f));
minP.m_x = GetMin(p0.m_x, minP.m_x);
minP.m_y = GetMin(p0.m_y, minP.m_y);
minP.m_z = GetMin(p0.m_z, minP.m_z);
maxP.m_x = GetMax(p1.m_x, maxP.m_x);
maxP.m_y = GetMax(p1.m_y, maxP.m_y);
maxP.m_z = GetMax(p1.m_z, maxP.m_z);
dgVector p((p0 + p1).Scale(0.5f));
median += p;
varian += p.CompProduct(p);
}
varian = varian.Scale(dgFloat32(boxCount))
- median.CompProduct(median);
dgInt32 index = 0;
dgFloat32 maxVarian = dgFloat32(-1.0e10f);
for (dgInt32 i = 0; i < 3; i++)
{
if (varian[i] > maxVarian)
{
index = i;
maxVarian = varian[i];
}
}
dgVector center = median.Scale(
dgFloat32(1.0f) / dgFloat32(boxCount));
dgFloat32 test = center[index];
dgInt32 i0 = 0;
dgInt32 i1 = boxCount - 1;
dgInt32 step = sizeof(dgTriplex) / sizeof(dgFloat32);
const dgFloat32* const points = &vertexArray[0].m_x;
do
{
for (; i0 <= i1; i0++)
{
dgInt32 j0 = boxArray[i0].m_minIndex;
dgInt32 j1 = boxArray[i0].m_maxIndex;
dgFloat32 val = (points[j0 * step + index]
+ points[j1 * step + index]) * dgFloat32(0.5f);
if (val > test)
{
break;
}
}
for (; i1 >= i0; i1--)
{
dgInt32 j0 = boxArray[i1].m_minIndex;
dgInt32 j1 = boxArray[i1].m_maxIndex;
dgFloat32 val = (points[j0 * step + index]
+ points[j1 * step + index]) * dgFloat32(0.5f);
if (val < test)
{
break;
}
}
if (i0 < i1)
{
Swap(boxArray[i0], boxArray[i1]);
i0++;
i1--;
}
} while (i0 <= i1);
if (i0 > 0)
{
i0--;
}
if ((i0 + 1) >= boxCount)
{
i0 = boxCount - 2;
}
m_axis = i0 + 1;
}
_ASSERTE(maxP.m_x - minP.m_x >= dgFloat32 (0.0f));
_ASSERTE(maxP.m_y - minP.m_y >= dgFloat32 (0.0f));
_ASSERTE(maxP.m_z - minP.m_z >= dgFloat32 (0.0f));
m_p0 = minP;
m_p1 = maxP;
}
dgInt32 m_axis;
dgVector m_p0;
dgVector m_p1;
};
dgSpliteInfo info(&boxArray[firstBox], lastBox - firstBox + 1,
vertexArray, tree);
tree->m_boxIndex = -1;
tree->m_p0 = info.m_p0;
tree->m_p1 = info.m_p1;
tree->m_front = BuildTree(allocator, firstBox + info.m_axis, lastBox,
boxArray, vertexArray, tree);
tree->m_back = BuildTree(allocator, firstBox, firstBox + info.m_axis - 1,
boxArray, vertexArray, tree);
}
dgVector side0(tree->m_p1 - tree->m_p0);
dgVector side1(side0.m_y, side0.m_z, side0.m_x, dgFloat32(0.0f));
tree->m_surfaceArea = side0 % side1;
return tree;
}
dgInt32 BuildTopDown(dgMemoryAllocator* const allocator, dgInt32 boxCount,
dgAABBTree* const boxArray, dgTriplex* const vertexArrayOut,
dgInt32 &treeVCount, bool optimizedBuild)
{
dgStack<dgAABBTree> boxCopy(boxCount);
memcpy(&boxCopy[0], boxArray, boxCount * sizeof(dgAABBTree));
dgConstructionTree* tree = BuildTree(allocator, 0, boxCount - 1,
&boxCopy[0], vertexArrayOut, NULL);
optimizedBuild = true;
if (optimizedBuild)
{
tree = ImproveTotalFitness(tree, &boxCopy[0], allocator);
}
dgInt32 count = BuildTree(tree, boxArray, &boxCopy[0], vertexArrayOut,
treeVCount);
delete tree;
return count;
}
DG_INLINE dgInt32 BoxIntersectSimd(const dgTriplex* const vertexArray,
const dgVector& min, const dgVector& max) const
{
#ifdef DG_BUILD_SIMD_CODE
simd_type minBox = simd_loadu_v(vertexArray[m_minIndex].m_x);
simd_type maxBox = simd_loadu_v(vertexArray[m_maxIndex].m_x);
simd_type test =
simd_or_v (simd_cmpge_v ((simd_type&)minBox, (simd_type&) max), simd_cmple_v ((simd_type&)maxBox, (simd_type&) min));
test =
simd_or_v (test, simd_permut_v (test, test, PURMUT_MASK (3, 2, 2, 0)));
return simd_store_is(simd_or_v (test, simd_permut_v (test, test, PURMUT_MASK (3, 2, 1, 1))));
#else
return 0;
#endif
}
DG_INLINE dgInt32 BoxIntersect(const dgTriplex* const vertexArray,
const dgVector& min, const dgVector& max) const
{
dgFloatSign tmp0_x;
dgFloatSign tmp0_y;
dgFloatSign tmp0_z;
dgFloatSign tmp1_x;
dgFloatSign tmp1_y;
dgFloatSign tmp1_z;
const dgTriplex& minBox = vertexArray[m_minIndex];
const dgTriplex& maxBox = vertexArray[m_maxIndex];
tmp0_x.m_fVal = maxBox.m_x - min.m_x;
tmp0_y.m_fVal = maxBox.m_y - min.m_y;
tmp0_z.m_fVal = maxBox.m_z - min.m_z;
tmp1_x.m_fVal = max.m_x - minBox.m_x;
tmp1_y.m_fVal = max.m_y - minBox.m_y;
tmp1_z.m_fVal = max.m_z - minBox.m_z;
return tmp0_x.m_integer.m_iVal | tmp0_y.m_integer.m_iVal
| tmp0_z.m_integer.m_iVal | tmp1_x.m_integer.m_iVal
| tmp1_y.m_integer.m_iVal | tmp1_z.m_integer.m_iVal;
}
DG_INLINE dgInt32 RayTestSimd(const dgFastRayTest& ray,
const dgTriplex* const vertexArray) const
{
#ifdef DG_BUILD_SIMD_CODE
simd_type minBox = simd_loadu_v (vertexArray[m_minIndex].m_x);
simd_type maxBox = simd_loadu_v (vertexArray[m_maxIndex].m_x);
simd_type paralletTest =
simd_and_v (simd_or_v (simd_cmplt_v((simd_type&)ray.m_p0, (simd_type&)minBox), simd_cmpgt_v((simd_type&)ray.m_p0, (simd_type&)maxBox)), (simd_type&)ray.m_isParallel);
simd_type test =
simd_or_v (paralletTest, simd_move_hl_v (paralletTest, paralletTest));
if (simd_store_is(simd_or_v (test, simd_permut_v (test, test, PURMUT_MASK(3, 2, 1, 1)))))
{
return 0;
}
simd_type tt0 =
simd_mul_v (simd_sub_v ((simd_type&)minBox, (simd_type&)ray.m_p0), (simd_type&)ray.m_dpInv);
simd_type tt1 =
simd_mul_v (simd_sub_v ((simd_type&)maxBox, (simd_type&)ray.m_p0), (simd_type&)ray.m_dpInv);
test = simd_cmple_v (tt0, tt1);
simd_type t0 =
simd_max_v(simd_or_v (simd_and_v(tt0, test), simd_andnot_v (tt1, test)), (simd_type&)ray.m_minT);
t0 = simd_max_v(t0, simd_permut_v (t0, t0, PURMUT_MASK(3, 2, 1, 2)));
t0 = simd_max_s(t0, simd_permut_v (t0, t0, PURMUT_MASK(3, 2, 1, 1)));
simd_type t1 =
simd_min_v(simd_or_v (simd_and_v(tt1, test), simd_andnot_v (tt0, test)), (simd_type&)ray.m_maxT);
t1 = simd_min_v(t1, simd_permut_v (t1, t1, PURMUT_MASK(3, 2, 1, 2)));
t1 = simd_min_s(t1, simd_permut_v (t1, t1, PURMUT_MASK(3, 2, 1, 1)));
return simd_store_is(simd_cmple_s(t0, t1));
#else
return 0;
#endif
}
DG_INLINE dgInt32 RayTest(const dgFastRayTest& ray,
const dgTriplex* const vertexArray) const
{
dgFloat32 tmin = 0.0f;
dgFloat32 tmax = 1.0f;
dgVector minBox(&vertexArray[m_minIndex].m_x);
dgVector maxBox(&vertexArray[m_maxIndex].m_x);
for (dgInt32 i = 0; i < 3; i++)
{
if (ray.m_isParallel[i])
{
if (ray.m_p0[i] < minBox[i] || ray.m_p0[i] > maxBox[i])
{
return 0;
}
}
else
{
dgFloat32 t1 = (minBox[i] - ray.m_p0[i]) * ray.m_dpInv[i];
dgFloat32 t2 = (maxBox[i] - ray.m_p0[i]) * ray.m_dpInv[i];
if (t1 > t2)
{
Swap(t1, t2);
}
if (t1 > tmin)
{
tmin = t1;
}
if (t2 < tmax)
{
tmax = t2;
}
if (tmin > tmax)
{
return 0;
}
}
}
return 0xffffffff;
}
void ForAllSectorsSimd(const dgInt32* const indexArray,
const dgFloat32* const vertexArray, const dgVector& min,
const dgVector& max, dgAABBIntersectCallback callback,
void* const context) const
{
dgInt32 stack;
const dgAABBTree *stackPool[DG_STACK_DEPTH];
stack = 1;
stackPool[0] = this;
// const dgAABBTree* const root = this;
while (stack)
{
stack--;
const dgAABBTree* const me = stackPool[stack];
if (me->BoxIntersectSimd((dgTriplex*) vertexArray, min, max) >= 0)
{
if (me->m_back.IsLeaf())
{
dgInt32 index = dgInt32(me->m_back.GetIndex());
dgInt32 vCount = dgInt32((me->m_back.GetCount() >> 1) - 1);
if ((vCount > 0)
&& callback(context, vertexArray, sizeof(dgTriplex),
&indexArray[index + 1], vCount) == t_StopSearh)
{
return;
}
}
else
{
_ASSERTE(stack < DG_STACK_DEPTH);
stackPool[stack] = me->m_back.GetNode(this);
stack++;
}
if (me->m_front.IsLeaf())
{
dgInt32 index = dgInt32(me->m_front.GetIndex());
dgInt32 vCount = dgInt32((me->m_front.GetCount() >> 1) - 1);
if ((vCount > 0)
&& callback(context, vertexArray, sizeof(dgTriplex),
&indexArray[index + 1], vCount) == t_StopSearh)
{
return;
}
}
else
{
_ASSERTE(stack < DG_STACK_DEPTH);
stackPool[stack] = me->m_front.GetNode(this);
stack++;
}
}
}
}
void ForAllSectors(const dgInt32* const indexArray,
const dgFloat32* const vertexArray, const dgVector& min,
const dgVector& max, dgAABBIntersectCallback callback,
void* const context) const
{
dgInt32 stack;
const dgAABBTree *stackPool[DG_STACK_DEPTH];
stack = 1;
stackPool[0] = this;
// const dgAABBTree* const root = this;
while (stack)
{
stack--;
const dgAABBTree* const me = stackPool[stack];
if (me->BoxIntersect((dgTriplex*) vertexArray, min, max) >= 0)
{
if (me->m_back.IsLeaf())
{
dgInt32 index = dgInt32(me->m_back.GetIndex());
dgInt32 vCount = dgInt32((me->m_back.GetCount() >> 1) - 1);
if ((vCount > 0) && callback(context, vertexArray, sizeof(dgTriplex), &indexArray[index + 1], vCount) == t_StopSearh)
{
return;
}
}
else
{
_ASSERTE(stack < DG_STACK_DEPTH);
stackPool[stack] = me->m_back.GetNode(this);
stack++;
}
if (me->m_front.IsLeaf())
{
dgInt32 index = dgInt32(me->m_front.GetIndex());
dgInt32 vCount = dgInt32((me->m_front.GetCount() >> 1) - 1);
if ((vCount > 0) && callback(context, vertexArray, sizeof(dgTriplex), &indexArray[index + 1], vCount) == t_StopSearh)
{
return;
}
}
else
{
_ASSERTE(stack < DG_STACK_DEPTH);
stackPool[stack] = me->m_front.GetNode(this);
stack++;
}
}
}
}
void ForAllSectorsRayHitSimd(const dgFastRayTest& raySrc,
const dgInt32* indexArray, const dgFloat32* vertexArray,
dgRayIntersectCallback callback, void* const context) const
{
const dgAABBTree *stackPool[DG_STACK_DEPTH];
dgFastRayTest ray(raySrc);
dgInt32 stack = 1;
dgFloat32 maxParam = dgFloat32(1.0f);
stackPool[0] = this;
while (stack)
{
stack--;
const dgAABBTree* const me = stackPool[stack];
if (me->RayTestSimd(ray, (dgTriplex*) vertexArray))
{
if (me->m_back.IsLeaf())
{
dgInt32 vCount = dgInt32((me->m_back.GetCount() >> 1) - 1);
if (vCount > 0)
{
dgInt32 index = dgInt32(me->m_back.GetIndex());
dgFloat32 param = callback(context, vertexArray, sizeof(dgTriplex),
&indexArray[index + 1], vCount);
_ASSERTE(param >= dgFloat32 (0.0f));
if (param < maxParam)
{
maxParam = param;
if (maxParam == dgFloat32 (0.0f)) {
break;
}
ray.Reset(maxParam);
}
}
}
else
{
_ASSERTE(stack < DG_STACK_DEPTH);
stackPool[stack] = me->m_back.GetNode(this);
stack++;
}
if (me->m_front.IsLeaf())
{
dgInt32 vCount = dgInt32((me->m_front.GetCount() >> 1) - 1);
if (vCount > 0)
{
dgInt32 index = dgInt32(me->m_front.GetIndex());
dgFloat32 param = callback(context, vertexArray, sizeof(dgTriplex),
&indexArray[index + 1], vCount);
_ASSERTE(param >= dgFloat32 (0.0f));
if (param < maxParam)
{
maxParam = param;
if (maxParam == dgFloat32 (0.0f)) {
break;
}
ray.Reset(maxParam);
}
}
}
else
{
_ASSERTE(stack < DG_STACK_DEPTH);
stackPool[stack] = me->m_front.GetNode(this);
stack++;
}
}
}
}
void ForAllSectorsRayHit(const dgFastRayTest& raySrc, const dgInt32* indexArray,
const dgFloat32* vertexArray, dgRayIntersectCallback callback,
void* const context) const
{
const dgAABBTree *stackPool[DG_STACK_DEPTH];
dgFastRayTest ray(raySrc);
dgInt32 stack = 1;
dgFloat32 maxParam = dgFloat32(1.0f);
stackPool[0] = this;
while (stack)
{
stack--;
const dgAABBTree * const me = stackPool[stack];
if (me->RayTest(ray, (dgTriplex*) vertexArray))
{
if (me->m_back.IsLeaf())
{
dgInt32 vCount = dgInt32((me->m_back.GetCount() >> 1) - 1);
if (vCount > 0)
{
dgInt32 index = dgInt32(me->m_back.GetIndex());
dgFloat32 param = callback(context, vertexArray, sizeof(dgTriplex),
&indexArray[index + 1], vCount);
_ASSERTE(param >= dgFloat32 (0.0f));
if (param < maxParam)
{
maxParam = param;
if (maxParam == dgFloat32 (0.0f)) {
break;
}
ray.Reset(maxParam);
}
}
}
else
{
_ASSERTE(stack < DG_STACK_DEPTH);
stackPool[stack] = me->m_back.GetNode(this);
stack++;
}
if (me->m_front.IsLeaf())
{
dgInt32 vCount = dgInt32((me->m_front.GetCount() >> 1) - 1);
if (vCount > 0)
{
dgInt32 index = dgInt32(me->m_front.GetIndex());
dgFloat32 param = callback(context, vertexArray, sizeof(dgTriplex),
&indexArray[index + 1], vCount);
_ASSERTE(param >= dgFloat32 (0.0f));
if (param < maxParam)
{
maxParam = param;
if (maxParam == dgFloat32 (0.0f)) {
break;
}
ray.Reset(maxParam);
}
}
}
else
{
_ASSERTE(stack < DG_STACK_DEPTH);
stackPool[stack] = me->m_front.GetNode(this);
stack++;
}
}
}
}
dgVector ForAllSectorsSupportVertex(const dgVector& dir,
const dgInt32* const indexArray, const dgFloat32* const vertexArray) const
{
dgFloat32 aabbProjection[DG_STACK_DEPTH];
const dgAABBTree *stackPool[DG_STACK_DEPTH];
dgInt32 stack = 1;
stackPool[0] = this;
aabbProjection[0] = dgFloat32(1.0e10f);
const dgTriplex* const boxArray = (dgTriplex*) vertexArray;
dgVector supportVertex(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgFloat32 maxProj = dgFloat32(-1.0e20f);
dgInt32 ix = (dir[0] > dgFloat32(0.0f)) ? 1 : 0;
dgInt32 iy = (dir[1] > dgFloat32(0.0f)) ? 1 : 0;
dgInt32 iz = (dir[2] > dgFloat32(0.0f)) ? 1 : 0;
while (stack)
{
dgFloat32 boxSupportValue;
stack--;
boxSupportValue = aabbProjection[stack];
if (boxSupportValue > maxProj)
{
dgFloat32 backSupportDist = dgFloat32(0.0f);
dgFloat32 frontSupportDist = dgFloat32(0.0f);
const dgAABBTree* const me = stackPool[stack];
if (me->m_back.IsLeaf())
{
backSupportDist = dgFloat32(-1.0e20f);
dgInt32 index = dgInt32(me->m_back.GetIndex());
dgInt32 vCount = dgInt32((me->m_back.GetCount() >> 1) - 1);
dgVector vertex(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
for (dgInt32 j = 0; j < vCount; j++)
{
dgInt32 i0 = indexArray[index + j + 1]
* dgInt32(sizeof(dgTriplex) / sizeof(dgFloat32));
dgVector p(&vertexArray[i0]);
dgFloat32 dist = p % dir;
if (dist > backSupportDist)
{
backSupportDist = dist;
vertex = p;
}
}
if (backSupportDist > maxProj)
{
maxProj = backSupportDist;
supportVertex = vertex;
}
}
else
{
dgVector box[2];
const dgAABBTree* const node = me->m_back.GetNode(this);
box[0].m_x = boxArray[node->m_minIndex].m_x;
box[0].m_y = boxArray[node->m_minIndex].m_y;
box[0].m_z = boxArray[node->m_minIndex].m_z;
box[1].m_x = boxArray[node->m_maxIndex].m_x;
box[1].m_y = boxArray[node->m_maxIndex].m_y;
box[1].m_z = boxArray[node->m_maxIndex].m_z;
dgVector supportPoint(box[ix].m_x, box[iy].m_y, box[iz].m_z,
dgFloat32(0.0));
backSupportDist = supportPoint % dir;
}
if (me->m_front.IsLeaf())
{
frontSupportDist = dgFloat32(-1.0e20f);
dgInt32 index = dgInt32(me->m_front.GetIndex());
dgInt32 vCount = dgInt32((me->m_front.GetCount() >> 1) - 1);
dgVector vertex(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
for (dgInt32 j = 0; j < vCount; j++)
{
dgInt32 i0 = indexArray[index + j + 1]
* dgInt32(sizeof(dgTriplex) / sizeof(dgFloat32));
dgVector p(&vertexArray[i0]);
dgFloat32 dist = p % dir;
if (dist > frontSupportDist)
{
frontSupportDist = dist;
vertex = p;
}
}
if (frontSupportDist > maxProj)
{
maxProj = frontSupportDist;
supportVertex = vertex;
}
}
else
{
dgVector box[2];
const dgAABBTree* const node = me->m_front.GetNode(this);
box[0].m_x = boxArray[node->m_minIndex].m_x;
box[0].m_y = boxArray[node->m_minIndex].m_y;
box[0].m_z = boxArray[node->m_minIndex].m_z;
box[1].m_x = boxArray[node->m_maxIndex].m_x;
box[1].m_y = boxArray[node->m_maxIndex].m_y;
box[1].m_z = boxArray[node->m_maxIndex].m_z;
dgVector supportPoint(box[ix].m_x, box[iy].m_y, box[iz].m_z,
dgFloat32(0.0));
frontSupportDist = supportPoint % dir;
}
if (frontSupportDist >= backSupportDist)
{
if (!me->m_back.IsLeaf())
{
aabbProjection[stack] = backSupportDist;
stackPool[stack] = me->m_back.GetNode(this);
stack++;
}
if (!me->m_front.IsLeaf())
{
aabbProjection[stack] = frontSupportDist;
stackPool[stack] = me->m_front.GetNode(this);
stack++;
}
}
else
{
if (!me->m_front.IsLeaf())
{
aabbProjection[stack] = frontSupportDist;
stackPool[stack] = me->m_front.GetNode(this);
stack++;
}
if (!me->m_back.IsLeaf())
{
aabbProjection[stack] = backSupportDist;
stackPool[stack] = me->m_back.GetNode(this);
stack++;
}
}
}
}
return supportVertex;
}
private:
dgInt32 GetAxis(dgConstructionTree** boxArray, dgInt32 boxCount) const
{
dgInt32 axis;
dgFloat32 maxVal;
dgVector median(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
dgVector varian(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
for (dgInt32 i = 0; i < boxCount; i++)
{
median += boxArray[i]->m_p0;
median += boxArray[i]->m_p1;
varian += boxArray[i]->m_p0.CompProduct(boxArray[i]->m_p0);
varian += boxArray[i]->m_p1.CompProduct(boxArray[i]->m_p1);
}
boxCount *= 2;
varian.m_x = boxCount * varian.m_x - median.m_x * median.m_x;
varian.m_y = boxCount * varian.m_y - median.m_y * median.m_y;
varian.m_z = boxCount * varian.m_z - median.m_z * median.m_z;
axis = 0;
maxVal = varian[0];
for (dgInt32 i = 1; i < 3; i++)
{
if (varian[i] > maxVal)
{
axis = i;
maxVal = varian[i];
}
}
return axis;
}
/*
class DG_AABB_CMPBOX
{
public:
dgInt32 m_axis;
const dgTriplex* m_points;
};
static inline dgInt32 CompareBox (const dgAABBTree* const boxA, const dgAABBTree* const boxB, void* const context)
{
DG_AABB_CMPBOX& info = *((DG_AABB_CMPBOX*)context);
dgInt32 axis = info.m_axis;
const dgFloat32* p0 = &info.m_points[boxA->m_minIndex].m_x;
const dgFloat32* p1 = &info.m_points[boxB->m_minIndex].m_x;
if (p0[axis] < p1[axis]) {
return -1;
} else if (p0[axis] > p1[axis]) {
return 1;
}
return 0;
}
*/
static inline dgInt32 CompareBox(const dgConstructionTree* const boxA,
const dgConstructionTree* const boxB, void* const context)
{
dgInt32 axis;
axis = *((dgInt32*) context);
if (boxA->m_p0[axis] < boxB->m_p0[axis])
{
return -1;
}
else if (boxA->m_p0[axis] > boxB->m_p0[axis])
{
return 1;
}
return 0;
}
dgInt32 m_minIndex;
dgInt32 m_maxIndex;
TreeNode m_back;
TreeNode m_front;
friend class dgAABBPolygonSoup;
};
dgAABBPolygonSoup::dgAABBPolygonSoup() :
dgPolygonSoupDatabase()
{
m_aabb = NULL;
m_indices = NULL;
m_indexCount = 0;
m_nodesCount = 0;
}
dgAABBPolygonSoup::~dgAABBPolygonSoup()
{
if (m_aabb)
{
dgFreeStack(m_aabb);
dgFreeStack(m_indices);
}
}
void* dgAABBPolygonSoup::GetRootNode() const
{
return m_aabb;
}
void* dgAABBPolygonSoup::GetBackNode(const void* const root) const
{
dgAABBTree* const node = (dgAABBTree*) root;
return node->m_back.IsLeaf() ? NULL : node->m_back.GetNode(m_aabb);
}
void* dgAABBPolygonSoup::GetFrontNode(const void* const root) const
{
dgAABBTree* const node = (dgAABBTree*) root;
return node->m_front.IsLeaf() ? NULL : node->m_front.GetNode(m_aabb);
}
void dgAABBPolygonSoup::GetNodeAABB(const void* const root, dgVector& p0,
dgVector& p1) const
{
dgAABBTree* const node = (dgAABBTree*) root;
const dgTriplex* const vertex = (dgTriplex*) m_localVertex;
p0 = dgVector(vertex[node->m_minIndex].m_x, vertex[node->m_minIndex].m_y,
vertex[node->m_minIndex].m_z, dgFloat32(0.0f));
p1 = dgVector(vertex[node->m_maxIndex].m_x, vertex[node->m_maxIndex].m_y,
vertex[node->m_maxIndex].m_z, dgFloat32(0.0f));
}
void dgAABBPolygonSoup::ForAllSectorsSimd(const dgVector& min,
const dgVector& max, dgAABBIntersectCallback callback,
void* const context) const
{
dgAABBTree* tree;
if (m_aabb)
{
tree = (dgAABBTree*) m_aabb;
tree->ForAllSectorsSimd(m_indices, m_localVertex, min, max, callback,
context);
}
}
void dgAABBPolygonSoup::ForAllSectors(const dgVector& min, const dgVector& max,
dgAABBIntersectCallback callback, void* const context) const
{
dgAABBTree* tree;
if (m_aabb)
{
tree = (dgAABBTree*) m_aabb;
tree->ForAllSectors(m_indices, m_localVertex, min, max, callback, context);
}
}
dgVector dgAABBPolygonSoup::ForAllSectorsSupportVectex(
const dgVector& dir) const
{
dgAABBTree* tree;
if (m_aabb)
{
tree = (dgAABBTree*) m_aabb;
return tree->ForAllSectorsSupportVertex(dir, m_indices, m_localVertex);
}
else
{
return dgVector(0, 0, 0, 0);
}
}
void dgAABBPolygonSoup::GetAABB(dgVector& p0, dgVector& p1) const
{
if (m_aabb)
{
dgAABBTree* tree;
tree = (dgAABBTree*) m_aabb;
p0 = dgVector(&m_localVertex[tree->m_minIndex * 3]);
p1 = dgVector(&m_localVertex[tree->m_maxIndex * 3]);
}
else
{
p0 = dgVector(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
p1 = dgVector(dgFloat32(0.0f), dgFloat32(0.0f), dgFloat32(0.0f),
dgFloat32(0.0f));
}
}
void dgAABBPolygonSoup::ForAllSectorsRayHit(const dgFastRayTest& ray,
dgRayIntersectCallback callback, void* const context) const
{
dgAABBTree* tree;
if (m_aabb)
{
tree = (dgAABBTree*) m_aabb;
tree->ForAllSectorsRayHit(ray, m_indices, m_localVertex, callback, context);
}
}
void dgAABBPolygonSoup::ForAllSectorsRayHitSimd(const dgFastRayTest& ray,
dgRayIntersectCallback callback, void* const context) const
{
dgAABBTree* tree;
if (m_aabb)
{
tree = (dgAABBTree*) m_aabb;
tree->ForAllSectorsRayHitSimd(ray, m_indices, m_localVertex, callback,
context);
}
}
void dgAABBPolygonSoup::Serialize(dgSerialize callback,
void* const userData) const
{
dgAABBTree* tree;
tree = (dgAABBTree*) m_aabb;
callback(userData, &m_vertexCount, sizeof(dgInt32));
callback(userData, &m_indexCount, sizeof(dgInt32));
callback(userData, &m_nodesCount, sizeof(dgInt32));
callback(userData, &m_nodesCount, sizeof(dgInt32));
if (tree)
{
callback(userData, m_localVertex, sizeof(dgTriplex) * m_vertexCount);
callback(userData, m_indices, sizeof(dgInt32) * m_indexCount);
callback(userData, tree, sizeof(dgAABBTree) * m_nodesCount);
}
}
void dgAABBPolygonSoup::Deserialize(dgDeserialize callback,
void* const userData)
{
dgInt32 nodes;
dgAABBTree* tree;
tree = (dgAABBTree*) m_aabb;
m_strideInBytes = sizeof(dgTriplex);
callback(userData, &m_vertexCount, sizeof(dgInt32));
callback(userData, &m_indexCount, sizeof(dgInt32));
callback(userData, &m_nodesCount, sizeof(dgInt32));
callback(userData, &nodes, sizeof(dgInt32));
if (m_vertexCount)
{
m_localVertex = (dgFloat32*) dgMallocStack(
sizeof(dgTriplex) * m_vertexCount);
m_indices = (dgInt32*) dgMallocStack(sizeof(dgInt32) * m_indexCount);
tree = (dgAABBTree*) dgMallocStack(sizeof(dgAABBTree) * m_nodesCount);
callback(userData, m_localVertex, sizeof(dgTriplex) * m_vertexCount);
callback(userData, m_indices, sizeof(dgInt32) * m_indexCount);
callback(userData, tree, sizeof(dgAABBTree) * nodes);
}
else
{
m_localVertex = NULL;
m_indices = NULL;
tree = NULL;
}
m_aabb = tree;
}
dgIntersectStatus dgAABBPolygonSoup::CalculateThisFaceEdgeNormals(void *context,
const dgFloat32* const polygon, dgInt32 strideInBytes,
const dgInt32* const indexArray, dgInt32 indexCount)
{
AdjacentdFaces& adjacentFaces = *((AdjacentdFaces*) context);
dgInt32 count = adjacentFaces.m_count;
dgInt32 stride = dgInt32(strideInBytes / sizeof(dgFloat32));
dgInt32 j0 = indexArray[indexCount - 1];
for (dgInt32 j = 0; j < indexCount; j++)
{
dgInt32 j1 = indexArray[j];
dgInt64 key = (dgInt64(j0) << 32) + j1;
for (dgInt32 i = 0; i < count; i++)
{
if (adjacentFaces.m_edgeMap[i] == key)
{
dgFloat32 maxDist = dgFloat32(0.0f);
for (dgInt32 k = 0; k < indexCount; k++)
{
dgVector r(&polygon[indexArray[k] * stride]);
dgFloat32 dist = adjacentFaces.m_normal.Evalue(r);
if (dgAbsf(dist) > dgAbsf(maxDist))
{
maxDist = dist;
}
}
if (maxDist < dgFloat32(1.0e-4f))
{
adjacentFaces.m_index[i + count + 1] = indexArray[indexCount];
}
break;
}
}
j0 = j1;
}
return t_ContinueSearh;
}
dgIntersectStatus dgAABBPolygonSoup::CalculateAllFaceEdgeNormals(void *context, const dgFloat32* const polygon, dgInt32 strideInBytes,
const dgInt32* const indexArray, dgInt32 indexCount)
{
dgAABBPolygonSoup* const me = (dgAABBPolygonSoup*) context;
dgInt32 stride = dgInt32(strideInBytes / sizeof(dgFloat32));
AdjacentdFaces adjacentFaces;
adjacentFaces.m_count = indexCount;
adjacentFaces.m_index = (dgInt32*) indexArray;
dgVector n(&polygon[indexArray[indexCount] * stride]);
dgVector p(&polygon[indexArray[0] * stride]);
adjacentFaces.m_normal = dgPlane(n, -(n % p));
_ASSERTE(indexCount < dgInt32 (sizeof (adjacentFaces.m_edgeMap) / sizeof (adjacentFaces.m_edgeMap[0])));
dgInt32 edgeIndex = indexCount - 1;
dgInt32 i0 = indexArray[indexCount - 1];
dgVector p0(dgFloat32(1.0e15f), dgFloat32(1.0e15f), dgFloat32(1.0e15f), dgFloat32(0.0f));
dgVector p1(-dgFloat32(1.0e15f), -dgFloat32(1.0e15f), -dgFloat32(1.0e15f), dgFloat32(0.0f));
for (dgInt32 i = 0; i < indexCount; i++)
{
dgInt32 i1 = indexArray[i];
dgInt32 index = i1 * stride;
dgVector p(&polygon[index]);
p0.m_x = GetMin(p.m_x, p0.m_x);
p0.m_y = GetMin(p.m_y, p0.m_y);
p0.m_z = GetMin(p.m_z, p0.m_z);
p1.m_x = GetMax(p.m_x, p1.m_x);
p1.m_y = GetMax(p.m_y, p1.m_y);
p1.m_z = GetMax(p.m_z, p1.m_z);
adjacentFaces.m_edgeMap[edgeIndex] = (dgInt64(i1) << 32) + i0;
edgeIndex = i;
i0 = i1;
}
p0.m_x -= dgFloat32(0.5f);
p0.m_y -= dgFloat32(0.5f);
p0.m_z -= dgFloat32(0.5f);
p1.m_x += dgFloat32(0.5f);
p1.m_y += dgFloat32(0.5f);
p1.m_z += dgFloat32(0.5f);
me->ForAllSectors(p0, p1, CalculateThisFaceEdgeNormals, &adjacentFaces);
return t_ContinueSearh;
}
dgFloat32 dgAABBPolygonSoup::CalculateFaceMaxSize(dgTriplex* const vertex, dgInt32 indexCount, const dgInt32* const indexArray) const
{
dgFloat32 maxSize = dgFloat32(0.0f);
dgInt32 index = indexArray[indexCount - 1];
dgVector p0(vertex[index].m_x, vertex[index].m_y, vertex[index].m_z, dgFloat32(0.0f));
for (dgInt32 i = 0; i < indexCount; i++)
{
dgInt32 index = indexArray[i];
dgVector p1(vertex[index].m_x, vertex[index].m_y, vertex[index].m_z, dgFloat32(0.0f));
dgVector dir(p1 - p0);
dir = dir.Scale(dgRsqrt (dir % dir));
dgFloat32 maxVal = dgFloat32(-1.0e10f);
dgFloat32 minVal = dgFloat32(1.0e10f);
for (dgInt32 j = 0; j < indexCount; j++)
{
dgInt32 index = indexArray[j];
dgVector q(vertex[index].m_x, vertex[index].m_y, vertex[index].m_z, dgFloat32(0.0f));
dgFloat32 val = dir % q;
minVal = GetMin(minVal, val);
maxVal = GetMax(maxVal, val);
}
dgFloat32 size = maxVal - minVal;
maxSize = GetMax(maxSize, size);
p0 = p1;
}
return maxSize;
}
void dgAABBPolygonSoup::Create(const dgPolygonSoupDatabaseBuilder& builder, bool optimizedBuild)
{
if (builder.m_faceCount == 0)
{
return;
}
m_strideInBytes = sizeof(dgTriplex);
m_indexCount = builder.m_indexCount * 2 + builder.m_faceCount;
m_indices = (dgInt32*) dgMallocStack(sizeof(dgInt32) * m_indexCount);
m_aabb = (dgAABBTree*) dgMallocStack(sizeof(dgAABBTree) * builder.m_faceCount);
m_localVertex = (dgFloat32*) dgMallocStack(sizeof(dgTriplex) * (builder.m_vertexCount + builder.m_normalCount + builder.m_faceCount * 4));
dgAABBTree* const tree = (dgAABBTree*) m_aabb;
dgTriplex* const tmpVertexArray = (dgTriplex*) m_localVertex;
for (dgInt32 i = 0; i < builder.m_vertexCount; i++)
{
tmpVertexArray[i].m_x = dgFloat32(builder.m_vertexPoints[i].m_x);
tmpVertexArray[i].m_y = dgFloat32(builder.m_vertexPoints[i].m_y);
tmpVertexArray[i].m_z = dgFloat32(builder.m_vertexPoints[i].m_z);
}
for (dgInt32 i = 0; i < builder.m_normalCount; i++)
{
tmpVertexArray[i + builder.m_vertexCount].m_x = dgFloat32(builder.m_normalPoints[i].m_x);
tmpVertexArray[i + builder.m_vertexCount].m_y = dgFloat32(builder.m_normalPoints[i].m_y);
tmpVertexArray[i + builder.m_vertexCount].m_z = dgFloat32(builder.m_normalPoints[i].m_z);
}
dgInt32 polygonIndex = 0;
dgInt32* indexMap = m_indices;
const dgInt32* const indices = &builder.m_vertexIndex[0];
for (dgInt32 i = 0; i < builder.m_faceCount; i++)
{
dgInt32 indexCount = builder.m_faceVertexCount[i];
dgAABBTree& box = tree[i];
box.m_minIndex = builder.m_normalCount + builder.m_vertexCount + i * 2;
box.m_maxIndex = builder.m_normalCount + builder.m_vertexCount + i * 2 + 1;
box.m_front = dgAABBTree::TreeNode(0, 0);
box.m_back = dgAABBTree::TreeNode(dgUnsigned32(indexCount * 2), dgUnsigned32(indexMap - m_indices));
box.CalcExtends(&tmpVertexArray[0], indexCount, &indices[polygonIndex]);
for (dgInt32 j = 0; j < indexCount; j++)
{
indexMap[0] = indices[polygonIndex + j];
indexMap++;
}
indexMap[0] = builder.m_vertexCount + builder.m_normalIndex[i];
indexMap++;
for (dgInt32 j = 1; j < indexCount; j++)
{
indexMap[0] = -1;
indexMap++;
}
dgFloat32 faceSize = CalculateFaceMaxSize(&tmpVertexArray[0], indexCount - 1, &indices[polygonIndex + 1]);
indexMap[0] = dgInt32(faceSize);
indexMap++;
polygonIndex += indexCount;
}
dgInt32 extraVertexCount = builder.m_normalCount + builder.m_vertexCount + builder.m_faceCount * 2;
// if (optimizedBuild) {
// m_nodesCount = tree->BuildBottomUp (builder.m_allocator, builder.m_faceCount, tree, &tmpVertexArray[0], extraVertexCount);
// } else {
// m_nodesCount = tree->BuildTopDown (builder.m_allocator, builder.m_faceCount, tree, &tmpVertexArray[0], extraVertexCount);
// }
// m_nodesCount = tree->BuildBottomUp (builder.m_allocator, builder.m_faceCount, tree, &tmpVertexArray[0], extraVertexCount, optimizedBuild);
m_nodesCount = tree->BuildTopDown(builder.m_allocator, builder.m_faceCount, tree, &tmpVertexArray[0], extraVertexCount, optimizedBuild);
m_localVertex[tree->m_minIndex * 3 + 0] -= dgFloat32(0.1f);
m_localVertex[tree->m_minIndex * 3 + 1] -= dgFloat32(0.1f);
m_localVertex[tree->m_minIndex * 3 + 2] -= dgFloat32(0.1f);
m_localVertex[tree->m_maxIndex * 3 + 0] += dgFloat32(0.1f);
m_localVertex[tree->m_maxIndex * 3 + 1] += dgFloat32(0.1f);
m_localVertex[tree->m_maxIndex * 3 + 2] += dgFloat32(0.1f);
extraVertexCount -= (builder.m_normalCount + builder.m_vertexCount);
dgStack<dgInt32> indexArray(extraVertexCount);
extraVertexCount = dgVertexListToIndexList(
&tmpVertexArray[builder.m_normalCount + builder.m_vertexCount].m_x,
sizeof(dgTriplex), sizeof(dgTriplex), 0, extraVertexCount, &indexArray[0],
dgFloat32(1.0e-6f));
for (dgInt32 i = 0; i < m_nodesCount; i++)
{
dgAABBTree& box = tree[i];
dgInt32 j = box.m_minIndex - builder.m_normalCount - builder.m_vertexCount;
box.m_minIndex = indexArray[j] + builder.m_normalCount + builder.m_vertexCount;
j = box.m_maxIndex - builder.m_normalCount - builder.m_vertexCount;
box.m_maxIndex = indexArray[j] + builder.m_normalCount + builder.m_vertexCount;
}
m_vertexCount = extraVertexCount + builder.m_normalCount + builder.m_vertexCount;
dgVector p0;
dgVector p1;
GetAABB(p0, p1);
ForAllSectors(p0, p1, CalculateAllFaceEdgeNormals, this);
}
| 30.600836 | 175 | 0.574543 | [
"object"
] |
1970456c36451171dc62678f7f03258283610c3c | 1,767 | cpp | C++ | src/lib/utils/format_duration.cpp | PeterTsayun/hyrise | 40ed5e570a0ee2cb259f43607aa1d90dc52d77b8 | [
"MIT"
] | null | null | null | src/lib/utils/format_duration.cpp | PeterTsayun/hyrise | 40ed5e570a0ee2cb259f43607aa1d90dc52d77b8 | [
"MIT"
] | null | null | null | src/lib/utils/format_duration.cpp | PeterTsayun/hyrise | 40ed5e570a0ee2cb259f43607aa1d90dc52d77b8 | [
"MIT"
] | null | null | null | #include "format_duration.hpp"
#include <sstream>
#include <boost/hana/for_each.hpp>
#include <boost/hana/tuple.hpp>
#include "utils/assert.hpp"
namespace opossum {
std::string format_duration(const std::chrono::nanoseconds& total_nanoseconds) {
constexpr auto TIME_UNIT_ORDER =
boost::hana::to_tuple(boost::hana::tuple_t<std::chrono::minutes, std::chrono::seconds, std::chrono::milliseconds,
std::chrono::microseconds, std::chrono::nanoseconds>);
const std::vector<std::string> unit_strings = {" min", " s", " ms", " µs", " ns"};
std::chrono::nanoseconds remaining_nanoseconds = total_nanoseconds;
std::vector<uint64_t> floor_durations;
std::vector<uint64_t> round_durations;
boost::hana::for_each(TIME_UNIT_ORDER, [&](const auto duration_t) {
using DurationType = typename decltype(duration_t)::type;
auto floored_duration = std::chrono::floor<DurationType>(total_nanoseconds);
floor_durations.emplace_back(floored_duration.count());
round_durations.emplace_back(std::chrono::round<DurationType>(remaining_nanoseconds).count());
remaining_nanoseconds -= floored_duration;
});
std::stringstream stream;
for (size_t unit_iterator{0}; unit_iterator < unit_strings.size(); ++unit_iterator) {
const auto& floored_duration = floor_durations.at(unit_iterator);
const auto is_last_element = unit_iterator == unit_strings.size() - 1;
if (floored_duration > 0 || is_last_element) {
stream << floored_duration << unit_strings.at(unit_iterator);
if (!is_last_element) {
stream << " " << round_durations.at(unit_iterator + 1) << unit_strings.at(unit_iterator + 1);
}
break;
}
}
return stream.str();
}
} // namespace opossum
| 39.266667 | 119 | 0.699491 | [
"vector"
] |
1973ca134619dc47b5c63a20f2577c9b34a683f8 | 1,464 | cpp | C++ | src/log4qt/helpers/binaryclasslogger.cpp | ztxc/Log4Qt | 41c108535b6a0035e667c5a1a5d696c7adbd81c3 | [
"Apache-2.0"
] | 421 | 2015-12-22T15:13:26.000Z | 2022-03-29T02:26:28.000Z | src/log4qt/helpers/binaryclasslogger.cpp | ztxc/Log4Qt | 41c108535b6a0035e667c5a1a5d696c7adbd81c3 | [
"Apache-2.0"
] | 34 | 2016-05-09T17:32:38.000Z | 2022-03-21T09:56:43.000Z | src/log4qt/helpers/binaryclasslogger.cpp | ztxc/Log4Qt | 41c108535b6a0035e667c5a1a5d696c7adbd81c3 | [
"Apache-2.0"
] | 184 | 2016-01-15T08:43:16.000Z | 2022-03-29T02:26:31.000Z | /******************************************************************************
*
* This file is part of Log4Qt library.
*
* Copyright (C) 2007 - 2020 Log4Qt contributors
*
* 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 "helpers/binaryclasslogger.h"
#include "logmanager.h"
#include "binarylogger.h"
#include <QString>
namespace Log4Qt
{
BinaryClassLogger::BinaryClassLogger()
: mLogger(nullptr)
{
}
BinaryLogger *BinaryClassLogger::logger(const QObject *object)
{
Q_ASSERT_X(object, "BinaryClassLogger::logger()", "object must not be null");
QString loggename(object->metaObject()->className());
loggename += QStringLiteral("@@binary@@");
if (!mLogger.loadAcquire())
mLogger.testAndSetOrdered(nullptr, qobject_cast<BinaryLogger *>(LogManager::logger(loggename)));
return mLogger.loadAcquire();
}
} // namespace Log4Qt
| 31.148936 | 104 | 0.647541 | [
"object"
] |
197931e3a995b87a656217e1cb13011d5763c288 | 1,409 | hpp | C++ | src/core/seat/keyboard.hpp | EdwardBetts/wayfire | 10eb4dbe4ed1c930702bc271e41ed29ff9fa8b7d | [
"MIT"
] | 1,249 | 2018-08-20T02:39:53.000Z | 2022-03-31T08:04:02.000Z | src/core/seat/keyboard.hpp | EdwardBetts/wayfire | 10eb4dbe4ed1c930702bc271e41ed29ff9fa8b7d | [
"MIT"
] | 1,084 | 2018-08-14T19:44:47.000Z | 2022-03-31T14:08:10.000Z | src/core/seat/keyboard.hpp | EdwardBetts/wayfire | 10eb4dbe4ed1c930702bc271e41ed29ff9fa8b7d | [
"MIT"
] | 190 | 2018-09-10T09:52:59.000Z | 2022-03-30T23:53:29.000Z | #pragma once
#include <chrono>
#include "seat.hpp"
#include "wayfire/util.hpp"
#include <wayfire/option-wrapper.hpp>
namespace wf
{
enum locked_mods_t
{
KB_MOD_NUM_LOCK = 1 << 0,
KB_MOD_CAPS_LOCK = 1 << 1,
};
/**
* Represents a logical keyboard.
*/
class keyboard_t
{
public:
keyboard_t(wlr_input_device *keyboard);
~keyboard_t();
wlr_keyboard *handle;
wlr_input_device *device;
/** Get the currently pressed modifiers */
uint32_t get_modifiers();
/* The keycode which triggered the modifier binding */
uint32_t mod_binding_key = 0;
private:
wf::wl_listener_wrapper on_key, on_modifier;
void setup_listeners();
wf::signal_connection_t on_config_reload;
void reload_input_options();
wf::option_wrapper_t<std::string>
model, variant, layout, options, rules;
wf::option_wrapper_t<int> repeat_rate, repeat_delay;
/** Options have changed in the config file */
bool dirty_options = true;
std::chrono::steady_clock::time_point mod_binding_start;
bool handle_keyboard_key(uint32_t key, uint32_t state);
void handle_keyboard_mod(uint32_t key, uint32_t state);
/** Convert a key to a modifier */
uint32_t mod_from_key(uint32_t key);
/** Get the current locked mods */
uint32_t get_locked_mods();
/** Check whether we have only modifiers pressed down */
bool has_only_modifiers();
};
}
| 22.725806 | 60 | 0.699077 | [
"model"
] |
197a0acf4c2f62058b630fa0c3a1fdf457e71f6c | 1,122 | cpp | C++ | cppPrime/overloadoperatorconversion_c15/test_05.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | cppPrime/overloadoperatorconversion_c15/test_05.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | cppPrime/overloadoperatorconversion_c15/test_05.cpp | ilvcr/cpplgproject | d3dc492b37c3754e35669eee2dd96d83de63ead4 | [
"Apache-2.0"
] | null | null | null | /*************************************************************************
> File Name: test_05.cpp
> Author: yoghourt->ilvcr
> Mail: liyaoliu@foxmail.com @@ ilvcr@outlook.com
> Created Time: 2018年07月18日 星期三 12时34分10秒
> Description:
使用了ScreenPtr 类 ScreenPtr 类型的对象用起来就像 Screen*类型的对象
************************************************************************/
#include<iostream>
#include<string>
#include"Screen.h"
using namespace std;
void printScreen( ScreenPtr& ps){
cout << " Screen Object ("
<< ps->height() << ", "
<< ps->width() << " )\n\n";
for(int ix=1; ix <= ps->height(); ++ix){
for(int iy=1; iy <= ps->width(); ++iy){
cout << ps->get(ix, iy);
}
}
}
int main(int argc, char* argv[]){
Screen sobj(2, 5);
string.iint("HelloWorld");
ScreenPtr ps(sobj);
//设置屏幕内容
string::size_ytpe iintpos = 0;
for(int ix=1; ix <= ps->height(); ++ix){
for(int iy=1 iy <= ps->width(); ++iy){
ps->move(ix, iy);
ps->set(iint[iintpos++]);
}
}
//输出屏幕内容
printScreen(ps);
return 0;
}
| 22.44 | 74 | 0.467914 | [
"object"
] |
197c4359a5fbaa9bcd2707fd9b5da29c39f66214 | 8,631 | cpp | C++ | src/solvers/gecode/inspectors/dataflowinspector.cpp | Patstrom/disUnison | 94731ad37cefa9dc3b6472de3adea8a8d5f0a44b | [
"BSD-3-Clause"
] | 6 | 2018-03-01T19:12:07.000Z | 2018-09-10T15:52:14.000Z | src/solvers/gecode/inspectors/dataflowinspector.cpp | Patstrom/disUnison | 94731ad37cefa9dc3b6472de3adea8a8d5f0a44b | [
"BSD-3-Clause"
] | 56 | 2018-02-26T16:44:15.000Z | 2019-02-23T17:07:32.000Z | src/solvers/gecode/inspectors/dataflowinspector.cpp | Patstrom/disUnison | 94731ad37cefa9dc3b6472de3adea8a8d5f0a44b | [
"BSD-3-Clause"
] | null | null | null | /*
* Main authors:
* Roberto Castaneda Lozano <roberto.castaneda@ri.se>
*
* This file is part of Unison, see http://unison-code.github.io
*
* Copyright (c) 2016, RISE SICS AB
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "dataflowinspector.hpp"
std::string DataFlowInspector::name(void) { return "Data flow"; }
DataFlowGraph DataFlowInspector::dataFlowGraph(const Model& m, block b) {
DataFlowGraph dfg;
//cerr << "digraph b" << b << "{\n";
for (operation o : m.input->ops[b]) {
//cerr << "\tnode " << i << "\n";
NodeType type;
if (m.a(o).assigned() && m.a(o).val()) type = ACTIVE;
else if (m.a(o).in(1)) type = UNDECIDEDACTIVENESS;
else type = INACTIVE;
dfg.nodeType[o] = type;
for (instruction i : m.input->instructions[o])
dfg.initialInstructions[o].push_back(show_instruction(i, o, m.input).c_str());
for (IntVarValues o1(m.i(o)); o1(); ++o1) {
instruction i = m.input->instructions[o][o1.val()];
dfg.instructions[o].push_back(show_instruction(i, o, m.input).c_str());
}
QString in = QString::number(o);
dfg.graph->insert(in);
QSize labSize = dfg.nodeLabelSize(o, DPI);
dfg.graph->setNodeSize(in, labSize.width() / DPI, labSize.height() / DPI);
}
// Add fixed getEdges()
int instance = 0;
for (unsigned int e = 0; e < m.input->dep[b].size(); e++) {
operation o1 = m.input->dep[b][e][0],
o2 = m.input->dep[b][e][1];
//cerr << "\t" << i << " -> " << j << "\n";
EdgeId key = edgeId(o1, o2, instance);
dfg.graph->insert(key);
dfg.edgeType[key] = FIXED;
instance++;
}
// Add data getEdges()
for (operation o : m.input->ops[b])
for (operand p : m.input->operands[o])
if (m.input->use[p])
for (unsigned int ti = 0; ti < m.input->temps[p].size(); ti++) {
temporary t = m.input->temps[p][ti];
if (t != NULL_TEMPORARY) {
operation d = m.input->def_opr[t];
QString source = QString::number(d),
target = QString::number(o);
EdgeType type;
if (m.y(p).assigned() && m.y(p).val() == (int)ti) type = ASSIGNED;
else if (m.y(p).in(ti)) type = POSSIBLE;
else type = DISCARDED;
EdgeId key = edgeId(source, target, instance);
if (dfg.edgeType.count(key) && (dfg.edgeType[key] > type))
continue;
QString label = "t" + QString::number(t);
dfg.graph->insert(key);
dfg.graph->setEdgeAttribute(key, "label", label);
dfg.graph->setEdgeAttribute(key, "fontsize", "20");
dfg.edgeLabel[key] = label;
dfg.edgeType[key] = type;
EdgeLabelType labType;
if (m.l(t).assigned() && m.l(t).val()) labType = LIVE;
else if (m.l(t).in(1)) labType = UNDECIDEDLIVENESS;
else labType = DEAD;
dfg.edgeLabelType[key] = labType;
instance++;
}
}
//cerr << "}\n";
// Compute graph layout
dfg.graph->draw();
return dfg;
}
void DataFlowInspector::
draw(const Model& m, DataFlowGraph& dfg, const QPointF& topLeft) {
for (DotEdge edge : dfg.graph->getEdges()) {
operation o = get<0>(edge.key).toInt();
EdgeType edgeType = dfg.edgeType[edge.key];
EdgeLabelType edgeLabelType = dfg.edgeLabelType[edge.key];
if (edgeType == FIXED || edgeType == DISCARDED) continue;
QColor fillcolor = type_color(m.input->type[o]);
if (edgeType == ASSIGNED) fillcolor = fillcolor.darker(110);
QPen pen(fillcolor);
pen.setWidth(edgeType == ASSIGNED ? 6 : 2);
QBrush brush(fillcolor);
QColor labColor = edgeLabelType == LIVE ? Qt::black : Qt::gray;
QGraphicsTextItem *l = scene->addText(dfg.edgeLabel[edge.key]);
QGraphicsPathItem * e = new QGraphicsPathItem(edge.path);
QGraphicsPathItem * a = new QGraphicsPathItem(edge.arrow);
e->translate(topLeft.x(), topLeft.y());
a->translate(topLeft.x(), topLeft.y());
e->setPen(pen);
a->setBrush(brush);
a->setPen(pen);
scene->addItem(e);
scene->addItem(a);
QPointF labelTopLeft = topLeft + edge.topLeftPos;
l->setPos(labelTopLeft);
l->setDefaultTextColor(labColor);
QFont f = l->font();
f.setPointSize(20);
l->setFont(f);
}
for (DotNode node : dfg.graph->getNodes()) {
operation o = node.name.toInt();
NodeType nodeType = dfg.nodeType[o];
if (nodeType == INACTIVE) continue;
QColor textcolor = nodeType == ACTIVE ? Qt::black : Qt::gray;
QColor fillcolor = type_color(m.input->type[o]);
if (!(nodeType == ACTIVE)) fillcolor = fillcolor.lighter(120);
QPen pen(fillcolor.darker(110));
pen.setWidth(nodeType == ACTIVE ? 6 : 2);
QBrush brush(fillcolor);
QPointF nodeTopLeft = topLeft + node.topLeftPos + (QPointF(0, 0) * DPI);
QSize labSize = dfg.nodeLabelSize(o, DPI);
QGraphicsRectItem *r =
scene->addRect(nodeTopLeft.x(), nodeTopLeft.y(),
labSize.width(), labSize.height());
r->setPen(pen);
r->setBrush(brush);
QGraphicsTextItem *l = scene->addText(dfg.nodeLabel(o));
l->setPos(nodeTopLeft);
setFontPointSize(l, FONTSIZE);
l->setDefaultTextColor(textcolor);
}
}
void GlobalDataFlowInspector::inspect(const Space& s) {
const Model& m = static_cast<const Model&>(s);
initialize();
int xoff = 1,
yoff = 1;
Dot cfg;
vector<DataFlowGraph> dfgs;
// Build data-flow graphs
for (block b : m.input->B) dfgs.push_back(dataFlowGraph(m, b));
// Add getNodes() and set their size
for (block b : m.input->B) {
QString bn = QString::number(b);
cfg.insert(bn);
double w = (dfgs[b].graph->box().width() / DPI) + xoff,
h = (dfgs[b].graph->box().height() / DPI) + yoff;
cfg.setNodeSize(bn, w, h);
}
for (vector<block> e : m.input->cfg) cfg.insert(edgeId(e[0], e[1]));
// Compute graph layout
cfg.draw();
QPointF off = QPointF(xoff, yoff) * DPI;
QPen thickPen(Qt::black);
thickPen.setWidth(3);
for (DotNode node : cfg.getNodes()) {
block b = node.name.toInt();
QPointF topLeft = node.topLeftPos + off;
draw(m, dfgs[b], topLeft);
QRectF br = dfgs[b].graph->box();
br.moveTopLeft(topLeft);
QGraphicsRectItem *r = scene->addRect(br);
r->setPen(thickPen);
}
for (DotEdge edge : cfg.getEdges()) {
QGraphicsPathItem * e = new QGraphicsPathItem(edge.path);
QGraphicsPathItem * a = new QGraphicsPathItem(edge.arrow);
e->setPen(thickPen);
QBrush brush(Qt::black);
a->setBrush(brush);
a->setPen(thickPen);
scene->addItem(e);
scene->addItem(a);
}
scene->setSceneRect (cfg.box());
view->fitInView (cfg.box(), Qt::KeepAspectRatio);
mw->show();
}
void LocalDataFlowInspector::inspect(const Space& s) {
const LocalModel& m = static_cast<const LocalModel&>(s);
initialize();
int xoff = 0,
yoff = 0;
QPointF topLeft = QPointF(xoff, yoff) * DPI;
DataFlowGraph dfg = dataFlowGraph(m, m.b);
draw(m, dfg, topLeft);
show_window(dfg.graph->box());
}
| 28.963087 | 84 | 0.627506 | [
"vector",
"model"
] |
197e1c64fa69c0a0591d732ae78664d415b06fd0 | 2,055 | cpp | C++ | Competitive Programing Problem Solutions/Number Theory/olee vai nt/406 - Prime Cuts.cpp | BIJOY-SUST/ACM---ICPC | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | 1 | 2022-02-27T12:07:59.000Z | 2022-02-27T12:07:59.000Z | Competitive Programing Problem Solutions/Number Theory/olee vai nt/406 - Prime Cuts.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | Competitive Programing Problem Solutions/Number Theory/olee vai nt/406 - Prime Cuts.cpp | BIJOY-SUST/Competitive-Programming | b382d80d327ddcab15ab15c0e763ccf8a22e0d43 | [
"Apache-2.0"
] | null | null | null | #include<bits/stdc++.h>
//#define mx 10000001
using namespace std;
vector<int>prime;
void sieve(int mx){
if(mx==1) prime.push_back(1);
else if(mx==2){
prime.push_back(1);
prime.push_back(2);
}
else{
bool mark[mx+1];
memset(mark,true,sizeof(mark));
mark[0]=mark[1]=false;
for(int i=4;i<=mx;i+=2) mark[i]=false;
for(int i=3;i<=(int)sqrt(mx);i+=2){
if(mark[i]){
for(int j=i*i;j<=mx;j+=2*i) mark[j]=false;
}
}
prime.push_back(1);
prime.push_back(2);
for(int i=3;i<=mx;i+=2) if(mark[i]) prime.push_back(i);
}
}
int main(){
// freopen("111.txt","r",stdin);
// freopen("112.txt","w",stdout);
int n,c;
while(scanf("%d %d",&n,&c)==2){
sieve(n);
int s=prime.size();
if(s%2){
int cc=c*2-1;
if(cc>=s){
printf("%d %d:",n,c);
for(int i=0;i<s;i++){
printf(" %d",prime[i]);
}
printf("\n");
}
else{
int L1=s/2-cc/2;
int L2=s/2+cc/2;
printf("%d %d:",n,c);
for(int i=L1;i<=L2;i++){
printf(" %d",prime[i]);
}
printf("\n");
}
}
else{
int cc=c*2;
if(cc>=s){
printf("%d %d:",n,c);
for(int i=0;i<s;i++){
printf(" %d",prime[i]);
}
printf("\n");
}
else{
int L1=s/2-c;
int L2=s/2+c;
printf("%d %d:",n,c);
for(int i=L1;i<L2;i++){
printf(" %d",prime[i]);
}
printf("\n");
}
}
printf("\n");
prime.clear();
}
return 0;
}
// for(int i=0;i<=28;i++){
// cout<<i+1<<" "<<prime[i]<<endl;
// }
| 25.6875 | 60 | 0.346472 | [
"vector"
] |
197f5cc722723244668002f07feeeed26fab734a | 1,446 | cpp | C++ | solutions/LeetCode/C++/942.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 854 | 2018-11-09T08:06:16.000Z | 2022-03-31T06:05:53.000Z | solutions/LeetCode/C++/942.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 29 | 2019-06-02T05:02:25.000Z | 2021-11-15T04:09:37.000Z | solutions/LeetCode/C++/942.cpp | timxor/leetcode-journal | 5f1cb6bcc44a5bc33d88fb5cdb4126dfc6f4232a | [
"MIT"
] | 347 | 2018-12-23T01:57:37.000Z | 2022-03-12T14:51:21.000Z | __________________________________________________________________________________________________
sample 36 ms submission
static int x = []() {
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
vector<int> diStringMatch(string &S) {
int len = S.size()+1;
std::vector<int> res(len);
int small = 0;
int big = len-1;
for(int i=0;i<len-1;i++){
int mask = S[i]-'I';
res[i] = mask ? big:small;
big -= bool(mask);
small += bool(!mask);
}
res[len-1] = small;
return res;
}
};
__________________________________________________________________________________________________
sample 10184 kb submission
class Solution {
public:
vector<int> diStringMatch(string S) {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
int size = S.size();
vector<int> v(size+1);
int front = 0 , back = size;
for(int i=0 ; i<size ; i++){
if(S[i] == 'D'){
v[i] = back;
back--;
}
else{
v[i] = front;
front++;
}
}
if(S[size-1] == 'D') v[size] = front;
else v[size] = back;
return v;
}
};
__________________________________________________________________________________________________
| 26.777778 | 98 | 0.543568 | [
"vector"
] |
1989bd2982a52368a95a953446734e55edf32ca0 | 1,615 | hh | C++ | src/lepton/thread_handoff.hh | suryatmodulus/lepton | 2a08b777579819677e37af133f1565765d08db04 | [
"Apache-2.0"
] | 5,342 | 2016-07-14T04:40:58.000Z | 2022-03-31T07:26:06.000Z | src/lepton/thread_handoff.hh | suryatmodulus/lepton | 2a08b777579819677e37af133f1565765d08db04 | [
"Apache-2.0"
] | 126 | 2016-07-14T18:30:39.000Z | 2022-03-30T00:46:44.000Z | src/lepton/thread_handoff.hh | suryatmodulus/lepton | 2a08b777579819677e37af133f1565765d08db04 | [
"Apache-2.0"
] | 451 | 2016-07-14T14:27:08.000Z | 2022-03-08T22:57:18.000Z | #ifndef THREAD_HANDOFF_HH_
#define THREAD_HANDOFF_HH_
#include <vector>
#include "../vp8/util/options.hh"
#include "../vp8/util/aligned_block.hh"
#include "../vp8/util/nd_array.hh"
class ThreadHandoff {
public:
uint16_t luma_y_start;
uint16_t luma_y_end;
uint32_t segment_size;
uint8_t overhang_byte;
uint8_t num_overhang_bits;
Sirikata::Array1d<int16_t, (uint32_t)ColorChannel::NumBlockTypes> last_dc;
enum {
BYTES_PER_HANDOFF = (16 /* luma end is implicit*/ + 32 + 16 * 4 + 8 * 2) / 8,
// num_overhang_bits is set to this for legacy formats which must be decoded single threaded
LEGACY_OVERHANG_BITS = 0xff
};
static ThreadHandoff zero() {
ThreadHandoff ret;
memset(&ret, 0, sizeof(ret));
return ret;
}
bool is_legacy_mode() const{ // legacy mode doesn't have access to handoff data
return num_overhang_bits == LEGACY_OVERHANG_BITS;
}
static size_t get_remaining_data_size_from_two_bytes(unsigned char input[2]);
static std::vector<ThreadHandoff> deserialize(const unsigned char *data, size_t max_size);
static std::vector<unsigned char> serialize(const ThreadHandoff * data,
unsigned int num_threads);
static std::vector<ThreadHandoff> make_rand(int num_items);
/* combine two ThreadHandoff objects into a range, starting with the initialization
of the thread represented by the first object, and continuing until the end
of the second object */
ThreadHandoff operator-( const ThreadHandoff & other ) const;
};
#endif
| 38.452381 | 100 | 0.69226 | [
"object",
"vector"
] |
198ad43b6b231ad2ac9a9ba1f06693d9a37c778a | 892 | cc | C++ | 2021_0927_1003/879.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | 2021_0927_1003/879.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | 2021_0927_1003/879.cc | guohaoqiang/leetcode | 802447c029c36892e8dd7391c825bcfc7ac0fd0b | [
"MIT"
] | null | null | null | class Solution {
public:
int profitableSchemes(int n, int minProfit, vector<int>& group, vector<int>& profit) {
const int kmod = 1e9+7;
vector<vector<int>> dp(minProfit+1,vector<int>(n+1,0));
dp.at(0).at(0) = 1;
for (int i=0; i<group.size(); ++i){
int p = profit.at(i);
int g = group.at(i);
for (int j=minProfit; j>=0; --j){
int ip = min(minProfit,j+p);
for (int k=n-g; k>=0; --k){
dp.at(ip).at(k+g) = (dp.at(ip).at(k+g) + dp.at(j).at(k))%kmod;
}
}
}
/*
int ans = 0;
for (int c=0; c<=n; ++c){
ans = (ans+dp.at(minProfit).at(c))%kmod;
}
return ans;
*/
return accumulate(dp.at(minProfit).begin(),dp.at(minProfit).end(),0ll)%kmod;
}
};
| 29.733333 | 90 | 0.430493 | [
"vector"
] |
19902d934dfa1166f6f0f865e337e98aeefcf4ee | 1,029 | cpp | C++ | source/503.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | 2 | 2017-02-28T11:39:13.000Z | 2019-12-07T17:23:20.000Z | source/503.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | source/503.cpp | narikbi/LeetCode | 835215c21d1bd6820b20c253026bcb6f889ed3fc | [
"MIT"
] | null | null | null | //
// 503.cpp
// LeetCode
//
// Created by Narikbi on 19.02.17.
// Copyright © 2017 app.leetcode.kz. All rights reserved.
//
#include <stdio.h>
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <deque>
#include <queue>
#include <set>
#include <map>
#include <stack>
#include <cmath>
using namespace std;
vector<int> nextGreaterElements(vector<int>& nums) {
vector<int> res (nums.size(), -1);
stack <int> s;
int n = nums.size();
for (int i = 0; i < n * 2; i++) {
int num = nums[i%n];
while (!s.empty() && nums[s.top()] < num) {
res[s.top()] = num;
s.pop();
}
if (i < n) {
s.push(i);
}
}
return res;
}
//int main(int argc, const char * argv[]) {
//
//
// vector<int> v= {1,2,1};
// // vector<int> v= {1};
// vector<int> r = nextGreaterElements(v);
//
// for (int x : r) {
// cout << x << endl;
// }
//
// return 0;
//}
| 18.052632 | 58 | 0.488824 | [
"vector"
] |
19978e1a8a6bc04140ffbc64eaa49d6755924c76 | 2,522 | hpp | C++ | paradice9/include/paradice9/paradice9.hpp | KazDragon/paradice9 | bb89ce8bff2f99d2526f45b064bfdd3412feb992 | [
"MIT"
] | 9 | 2015-12-16T07:00:39.000Z | 2021-05-05T13:29:28.000Z | paradice9/include/paradice9/paradice9.hpp | KazDragon/paradice9 | bb89ce8bff2f99d2526f45b064bfdd3412feb992 | [
"MIT"
] | 43 | 2015-07-18T11:13:15.000Z | 2017-07-15T13:18:43.000Z | paradice9/include/paradice9/paradice9.hpp | KazDragon/paradice9 | bb89ce8bff2f99d2526f45b064bfdd3412feb992 | [
"MIT"
] | 3 | 2015-10-09T13:33:35.000Z | 2016-07-11T02:23:08.000Z | // ==========================================================================
// Paradice9 Application
//
// Copyright (C) 2009 Matthew Chaplain, All Rights Reserved.
//
// Permission to reproduce, distribute, perform, display, and to prepare
// derivitive works from this file under the following conditions:
//
// 1. Any copy, reproduction or derivitive work of any part of this file
// contains this copyright notice and licence in its entirety.
//
// 2. The rights granted to you under this license automatically terminate
// should you attempt to assert any patent claims against the licensor
// or contributors, which in any way restrict the ability of any party
// from using this software or portions thereof in any form under the
// terms of this license.
//
// Disclaimer: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
// KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
// OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
// OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ==========================================================================
#ifndef PARADICE9_HPP_
#define PARADICE9_HPP_
#include <boost/asio/io_service.hpp>
#include <memory>
//* =========================================================================
/// \brief A class that implements the main engine for the Paradice9 server.
/// \param io_service - The engine will be run within using the dispatch
/// mechanisms of this object.
/// \brief work - A "work" object. While this is not reset, the threads'
/// run() methods will not terminate. Resetting this work object
/// is part of the shutdown protocol.
/// \brief port - The server will be set up on this port number.
//* =========================================================================
class paradice9
{
public :
paradice9(
boost::asio::io_service &io_service
, std::shared_ptr<boost::asio::io_service::work> work
, unsigned int port);
private :
struct impl;
std::shared_ptr<impl> pimpl_;
};
#endif
| 44.245614 | 78 | 0.576923 | [
"object"
] |
1998cfe3b4922777d1acf40aaaa6aea7cddf525d | 1,386 | cpp | C++ | atcoder/abc/abc107/b.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | atcoder/abc/abc107/b.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | atcoder/abc/abc107/b.cpp | yu3mars/proconVSCodeGcc | fcf36165bb14fb6f555664355e05dd08d12e426b | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using pii = pair<int, int>;
#define REP(i,n) for(int i=0, i##_len=(n); i<i##_len; ++i)
#define all(x) (x).begin(),(x).end()
#define m0(x) memset(x,0,sizeof(x))
int dx4[4] = {1,0,-1,0}, dy4[4] = {0,1,0,-1};
int main()
{
int h,w;
cin>>h>>w;
vector<string> a(h);
bool wskip[100],hskip[100];
for(int i = 0; i < 100; i++)
{
wskip[i]=true;
hskip[i]=true;
}
for(int i = 0; i < h; i++)
{
cin>>a[i];
}
for(int hh = 0; hh < h; hh++)
{
for(int ww = 0; ww < w; ww++)
{
if(a[hh][ww]=='#')
{
hskip[hh]=false;
break;
}
}
}
for(int ww = 0; ww < w; ww++)
{
for(int hh = 0; hh < h; hh++)
{
if(a[hh][ww]=='#')
{
wskip[ww]=false;
break;
}
}
}
for(int hh = 0; hh < h; hh++)
{
if(hskip[hh]==false)
{
for(int ww = 0; ww < w; ww++)
{
if(wskip[ww]==false)
{
cout<<a[hh][ww];
}
}
cout<<endl;
}
}
return 0;
} | 17.544304 | 58 | 0.333333 | [
"vector"
] |
19997fe9193c65e00a54037d69b7f92973817920 | 14,415 | cpp | C++ | vendor/matvec/VectorM2DO.cpp | OpenLSTO/OpenLSTO | 170a7f28be880c04d40d5eea3581a385c7d7c4c1 | [
"Apache-2.0"
] | 17 | 2018-08-26T22:47:48.000Z | 2021-08-16T20:58:03.000Z | vendor/matvec/VectorM2DO.cpp | OpenLSTO/OpenLSTO | 170a7f28be880c04d40d5eea3581a385c7d7c4c1 | [
"Apache-2.0"
] | null | null | null | vendor/matvec/VectorM2DO.cpp | OpenLSTO/OpenLSTO | 170a7f28be880c04d40d5eea3581a385c7d7c4c1 | [
"Apache-2.0"
] | 1 | 2021-06-19T12:59:31.000Z | 2021-06-19T12:59:31.000Z | template<typename _Scalar, int _nElem>
void Vector<_Scalar,_nElem>::operator = (const Vector<_Scalar,_nElem> &rhs) { // Vector Assignment; Static-Static
assert(_nElem == rhs.data.size());
for (uint ii = 0; ii < _nElem; ++ii) {
data[ii] = rhs.data[ii];
}
}
template<typename _Scalar, int _nElem>
void Vector<_Scalar,_nElem>::operator = (const Vector<_Scalar,-1> &rhs) { // Vector Assignment; Static-Dynamic
assert(_nElem == rhs.data.size());
for (uint ii = 0; ii < _nElem; ++ii) {
data[ii] = rhs.data[ii];
}
}
template<typename _Scalar, int _nElem>
_Scalar &Vector<_Scalar,_nElem>::operator () (const double indx) { // Value Retrieval
if (indx > _nElem-1 || indx != round(indx) || indx < 0) {
std::cout << "\nERROR: The Vector index should be an Integer from 0 to _nElem, inclusive.\n\n";
assert(false);
}
else {
return data[indx];
}
}
template<typename _Scalar, int _nElem>
void Vector<_Scalar,_nElem>::operator += (const double alpha) { // Constant Addition
uint flag = 0,ii;
for (ii = 0; ii < _nElem; ++ii) {
if (data[ii] == round(data[ii]) && alpha != round(alpha)) {
flag++;
}
data[ii] += alpha;
}
if (flag > 0) {
std::cout << "WARNING: The final vector may have been rounded due to the DOUBLE constant of addition!\n";
}
}
template<typename _Scalar, int _nElem>
void Vector<_Scalar,_nElem>::operator -= (const double alpha) { // Constant Subtraction
uint flag = 0,ii;
for (ii = 0; ii < _nElem; ++ii) {
if (data[ii] == round(data[ii]) && alpha != round(alpha)) {
flag++;
}
data[ii] -= alpha;
}
if (flag > 0) {
std::cout << "WARNING: The final vector may have been rounded due to the DOUBLE constant of subtraction!\n";
}
}
template<typename _Scalar, int _nElem>
void Vector<_Scalar,_nElem>::operator *= (const double alpha) { // Constant Multiplication
uint flag = 0,ii;
for (ii = 0; ii < _nElem; ++ii) {
if (data[ii] == round(data[ii]) && alpha != round(alpha)) {
flag++;
}
data[ii] *= alpha;
}
if (flag > 0) {
std::cout << "WARNING: The final vector may have been rounded due to the DOUBLE constant of multiplication!\n";
}
}
template<typename _Scalar, int _nElem>
void Vector<_Scalar,_nElem>::operator /= (const double alpha) { // Constant Division
if (alpha == 0) {
std::cout << "ERROR: The divisor cannot be zero!\n\n";
assert(false);
}
else {
uint flag = 0,ii;
for (ii = 0; ii < _nElem; ++ii) {
if (data[ii] == round(data[ii]) && alpha != round(alpha)) {
flag++;
}
data[ii] /= alpha;
}
if (flag > 0) {
std::cout << "WARNING: The final vector may have been rounded due to the DOUBLE constant of division!\n";
}
}
}
// binary
template<typename _Scalar, int _nElem>
Vector<_Scalar,_nElem> Vector<_Scalar,_nElem>::operator + (const Vector<_Scalar,_nElem> &rhs) { // Vector Addition; Static-Static
Vector<_Scalar,_nElem> vect;
for (uint ii = 0; ii < _nElem; ++ii) {
vect[ii] = this->data[ii] + rhs.data[ii];
}
return vect;
}
template<typename _Scalar, int _nElem>
Vector<_Scalar,_nElem> Vector<_Scalar,_nElem>::operator - (const Vector<_Scalar,_nElem> &rhs) { // Vector Subtraction; Static-Static
Vector<_Scalar,_nElem> vect;
for (uint ii = 0; ii < _nElem; ++ii) {
vect[ii] = this->data[ii] - rhs.data[ii];
}
return vect;
}
template<typename _Scalar, int _nElem>
Vector<_Scalar,_nElem> Vector<_Scalar,_nElem>::operator * (const Vector<_Scalar,_nElem> &rhs) { // Vector Multiplication; Static-Static
Vector<_Scalar,_nElem> vect;
for (uint ii = 0; ii < _nElem; ++ii) {
vect[ii] = this->data[ii] * rhs.data[ii];
}
return vect;
}
// template<typename _Scalar, int _nElem>
// Vector<_Scalar,_nElem> &Vector<_Scalar,_nElem>::operator /= (const Vector<_Scalar,_nElem> &rhs) { // Vector Division; Static-Static
// uint flag = 0,jj = 0;
// while (flag == 0 && jj < _nElem) {
// if (rhs.data[jj] == 0) {
// flag = 1;
// }
// jj++;
// }
// if (flag == 1) {
// std::cout << "ERROR: The divisor vector contains a zero value element!\n\n";
// assert(false);
// }
// else {
// for (uint ii = 0; ii < _nElem; ++ii) {
// data[ii] /= rhs.data[ii];
// }
// return data;
// }
// }
template<typename _Scalar, int _nElem>
Vector<_Scalar,-1> Vector<_Scalar,_nElem>::operator + (const Vector<_Scalar,-1> &rhs) { // Vector Addition; Static-Dynamic
Vector<_Scalar,-1> vect(_nElem);
for (uint ii = 0; ii < _nElem; ++ii) {
vect[ii] = data[ii] + rhs.data[ii];
}
return vect;
}
template<typename _Scalar, int _nElem>
Vector<_Scalar,-1> Vector<_Scalar,_nElem>::operator - (const Vector<_Scalar,-1> &rhs) { // Vector Subtraction; Static-Dynamic
Vector<_Scalar,-1> vect(_nElem);
for (uint ii = 0; ii < _nElem; ++ii) {
vect[ii] = data[ii] - rhs.data[ii];
}
return vect;
}
template<typename _Scalar, int _nElem>
Vector<_Scalar,-1> Vector<_Scalar,_nElem>::operator * (const Vector<_Scalar,-1> &rhs) { // Vector Multiplication; Static-Dynamic
Vector<_Scalar,-1> vect(_nElem);
for (uint ii = 0; ii < _nElem; ++ii) {
vect[ii] = data[ii] * rhs.data[ii];
}
return vect;
}
// template<typename _Scalar, int _nElem>
// Vector<_Scalar,_nElem> &Vector<_Scalar,_nElem>::operator / (const Vector<_Scalar,-1> &rhs) { // Vector Division; Static-Dynamic
// uint flag = 0,jj = 0;
// while (flag == 0 && jj < _nElem) {
// if (rhs.data[jj] == 0) {
// flag = 1;
// }
// jj++;
// }
// if (flag == 1) {
// std::cout << "ERROR: The divisor vector contains a zero value element!\n\n";
// assert(false);
// }
// else {
// for (uint ii = 0; ii < _nElem; ++ii) {
// data[ii] /= rhs.data[ii];
// }
// return data;
// }
// }
template<typename _Scalar, int _nElem>
bool Vector<_Scalar,_nElem>::operator == (const Vector<_Scalar,_nElem> &rhs) { // Equality Check; Static-Static
if (_nElem != rhs.data.size()) {
return false;
}
else {
uint ii = 0;
bool equality = true;
while (ii < _nElem) {
if (data[ii] != rhs.data[ii]) {
ii = _nElem;
equality = false;
}
ii++;
}
return equality;
}
}
template<typename _Scalar, int _nElem>
bool Vector<_Scalar,_nElem>::operator == (const Vector<_Scalar,-1> &rhs) { // Equality Check; Static-Dynamic
if (_nElem != rhs.data.size()) {
return false;
}
else {
uint ii = 0;
bool equality = true;
while (ii < _nElem) {
if (data[ii] != rhs.data[ii]) {
ii = _nElem;
equality = false;
}
ii++;
}
return equality;
}
}
template<typename _Scalar, int _nElem>
uint Vector<_Scalar,_nElem>::size() const{
return _nElem;
}
template<typename _Scalar, int _nElem>
void Vector<_Scalar,_nElem>::fill(_Scalar _value) {
for (uint ii = 0; ii < _nElem; ++ii) {
data[ii] = _value;
}
}
template<typename _Scalar, int _nElem>
double Vector<_Scalar,_nElem>::norm() const {
double length_ = 0.0;
for (uint ii = 0; ii < _nElem; ++ii) {
length_ += data[ii]*data[ii];
}
length_ = std::sqrt(length_);
return length_;
}
template<typename _Scalar, int _nElem>
void Vector<_Scalar,_nElem>::print() const{
std::cout << "\n [ ";
for (uint ii = 0; ii < _nElem-1; ++ii) {
std::cout << data[ii] << " , ";
}
std::cout << data[_nElem-1] << " ]\n";
}
template<typename _Scalar, int _nElem>
double Vector<_Scalar,_nElem>::dot(Vector<_Scalar,_nElem> &rhs) { // Static-Static
double dot_ = 0.0;
for (uint ii = 0; ii < _nElem; ++ii) {
dot_ += data[ii]*rhs(ii);
}
return dot_;
}
template<typename _Scalar, int _nElem>
double Vector<_Scalar,_nElem>::dot(Vector<_Scalar,-1> &rhs) { // Static-Dynamic
double dot_ = 0.0;
for (uint ii = 0; ii < _nElem; ++ii) {
dot_ += data[ii]*rhs(ii);
}
return dot_;
}
template<typename _Scalar>
uint Vector<_Scalar,-1>::size() const{
return data.size();
}
template<typename _Scalar>
void Vector<_Scalar,-1>::fill(_Scalar _value) {
for (uint ii = 0; ii < this->size(); ++ii) {
data[ii] = _value;
}
}
template<typename _Scalar>
double Vector<_Scalar,-1>::norm() const {
double length_ = 0.0;
for (uint ii = 0; ii < data.size(); ++ii) {
length_ += data[ii]*data[ii];
}
length_ = std::sqrt(length_);
return length_;
}
template<typename _Scalar>
void Vector<_Scalar,-1>::resize(int nx) {
data.clear();
data.resize(nx);
}
template<typename _Scalar>
void Vector<_Scalar,-1>::print() const {
std::cout << "\n [ ";
for (uint ii = 0; ii < data.size()-1; ++ii) {
std::cout << data[ii] << " , ";
}
std::cout << data[size()-1] << " ]\n";
}
template<typename _Scalar>
template<typename _OtherScalar, int _OtherElem>
double Vector<_Scalar,-1>::dot(Vector<_OtherScalar,_OtherElem> rhs) {
double dot_ = 0.0;
for (uint ii = 0; ii < data.size(); ++ii) {
dot_ += data[ii]*rhs.data[ii];
}
return dot_;
}
template<typename _Scalar>
template<typename _OtherScalar, int _OtherElem>
void Vector<_Scalar,-1>::operator = (Vector<_OtherScalar,_OtherElem> rhs) {
data.resize(_OtherElem);
for (uint ii = 0; ii < _OtherElem; ++ii) {
data[ii] = rhs.data[ii];
}
}
template<typename _Scalar>
template<typename _OtherScalar>
void Vector<_Scalar,-1>::operator = (Vector<_OtherScalar,-1> rhs) {
data.resize(rhs.size());
for (uint ii = 0; ii < rhs.size(); ++ii) {
data[ii] = rhs.data[ii];
}
}
template<typename _Scalar>
_Scalar &Vector<_Scalar,-1>::operator () (const double indx) { // Value Retrieval
if (indx > data.size()-1 || indx != round(indx) || indx < 0) {
std::cout << "\nERROR: The Vector index should be an Integer from 0 to _nElem, inclusive.\n\n";
assert(false);
}
else {
return data[indx];
}
}
template<typename _Scalar>
void Vector<_Scalar,-1>::operator += (const double alpha) { // Constant Addition
uint flag = 0,ii;
for (ii = 0; ii < data.size(); ++ii) {
if (data[ii] == round(data[ii]) && alpha != round(alpha)) {
flag++;
}
data[ii] += alpha;
}
if (flag > 0) {
std::cout << "WARNING: The final vector may have been rounded due to the DOUBLE constant of addition!\n";
}
}
template<typename _Scalar>
void Vector<_Scalar,-1>::operator -= (const double alpha) { // Constant Subtraction
uint flag = 0,ii;
for (ii = 0; ii < data.size(); ++ii) {
if (data[ii] == round(data[ii]) && alpha != round(alpha)) {
flag++;
}
data[ii] -= alpha;
}
if (flag > 0) {
std::cout << "WARNING: The final vector may have been rounded due to the DOUBLE constant of subtraction!\n";
}
}
template<typename _Scalar>
void Vector<_Scalar,-1>::operator *= (const double alpha) { // Constant Multiplication
uint flag = 0,ii;
for (ii = 0; ii < data.size(); ++ii) {
if (data[ii] == round(data[ii]) && alpha != round(alpha)) {
flag++;
}
data[ii] *= alpha;
}
if (flag > 0) {
std::cout << "WARNING: The final vector may have been rounded due to the DOUBLE constant of multiplication!\n";
}
}
template<typename _Scalar>
void Vector<_Scalar,-1>::operator /= (const double alpha) { // Constant Division
if (alpha == 0) {
std::cout << "ERROR: The divisor cannot be zero!\n\n";
assert(false);
}
else {
uint flag = 0,ii;
for (ii = 0; ii < data.size(); ++ii) {
if (data[ii] == round(data[ii]) && alpha != round(alpha)) {
flag++;
}
data[ii] /= alpha;
}
if (flag > 0) {
std::cout << "WARNING: The final vector may have been rounded due to the DOUBLE constant of division!\n";
}
}
}
template<typename _Scalar>
template<typename _OtherScalar, int _OtherElem>
Vector<_Scalar,-1> Vector<_Scalar,-1>::operator + (const Vector<_OtherScalar,_OtherElem> &rhs) { // Vector Addition
Vector<_Scalar,-1> vect(this->size());
for (uint ii = 0; ii < data.size(); ++ii) {
vect[ii] = this->data[ii] + rhs.data[ii];
}
return vect;
}
template<typename _Scalar>
template<typename _OtherScalar, int _OtherElem>
Vector<_Scalar,-1> Vector<_Scalar,-1>::operator - (const Vector<_OtherScalar,_OtherElem> &rhs) { // Vector Subtraction
Vector<_Scalar,-1> vect(this->size());
for (uint ii = 0; ii < data.size(); ++ii) {
vect[ii] = this->data[ii] - rhs.data[ii];
}
return vect;
}
template<typename _Scalar>
template<typename _OtherScalar, int _OtherElem>
Vector<_Scalar,-1> Vector<_Scalar,-1>::operator * (const Vector<_OtherScalar,_OtherElem> &rhs) { // Vector Multiplication
Vector<_Scalar,-1> vect(this->size());
for (uint ii = 0; ii < data.size(); ++ii) {
vect[ii] = this->data[ii] * rhs.data[ii];
}
return vect;
}
// template<typename _Scalar>
// template<typename _OtherScalar, int _OtherElem>
// Vector<_Scalar,-1> &Vector<_Scalar,-1>::operator /= (const Vector<_OtherScalar,_OtherElem> &rhs) { // Vector Division
// uint flag = 0,jj = 0;
// while (flag == 0 && jj < data.size()) {
// if (rhs.data[jj] == 0) {
// flag = 1;
// }
// jj++;
// }
// if (flag == 1) {
// std::cout << "ERROR: The divisor vector contains a zero value element!\n\n";
// assert(false);
// }
// else {
// for (uint ii = 0; ii < data.size(); ++ii) {
// data[ii] /= rhs.data[ii];
// }
// return data;
// }
// }
template<typename _Scalar>
template<typename _OtherScalar, int _OtherElem>
bool Vector<_Scalar,-1>::operator == (const Vector<_OtherScalar,_OtherElem> &rhs) { // Equality Check
if (data.size() != rhs.data.size()) {
return false;
}
else {
uint ii = 0;
bool equality = true;
while (ii < data.size()) {
if (data[ii] != rhs.data[ii]) {
ii = data.size();
equality = false;
}
ii++;
}
return equality;
}
}
| 29.84472 | 135 | 0.576899 | [
"vector"
] |
199c3fd554187dfbe0fd46bedb5198fb56e9d7af | 3,293 | cpp | C++ | Viewer/ViewerUtils.cpp | mkahra14/libOpenDRIVE | a787635e39f58c844b435ade5a557d94321f485d | [
"Apache-2.0"
] | null | null | null | Viewer/ViewerUtils.cpp | mkahra14/libOpenDRIVE | a787635e39f58c844b435ade5a557d94321f485d | [
"Apache-2.0"
] | null | null | null | Viewer/ViewerUtils.cpp | mkahra14/libOpenDRIVE | a787635e39f58c844b435ade5a557d94321f485d | [
"Apache-2.0"
] | null | null | null | #include "ViewerUtils.h"
#include "Math.hpp"
#include "RefLine.h"
#include "Road.h"
#include <memory>
#include <vector>
namespace odr
{
Mesh3D get_refline_segments(const OpenDriveMap& odr_map, double eps)
{
/* indices are pairs of vertices representing line segments */
Mesh3D reflines;
for (std::shared_ptr<const Road> road : odr_map.get_roads())
{
const size_t idx_offset = reflines.vertices.size();
std::set<double> s_vals = road->ref_line->approximate_linear(eps, 0.0, road->length);
for (const double& s : s_vals)
{
reflines.vertices.push_back(road->ref_line->get_xyz(s));
reflines.normals.push_back(normalize(road->ref_line->get_grad(s)));
}
for (size_t idx = idx_offset; idx < (idx_offset + s_vals.size() - 1); idx++)
{
reflines.indices.push_back(idx);
reflines.indices.push_back(idx + 1);
}
}
return reflines;
}
RoadNetworkMesh get_road_network_mesh(const OpenDriveMap& odr_map, double eps)
{
RoadNetworkMesh out_mesh;
LanesMesh& lanes_mesh = out_mesh.lanes_mesh;
RoadmarksMesh& roadmarks_mesh = out_mesh.roadmarks_mesh;
RoadObjectsMesh& road_objects_mesh = out_mesh.road_objects_mesh;
for (std::shared_ptr<const Road> road : odr_map.get_roads())
{
lanes_mesh.road_start_indices[lanes_mesh.vertices.size()] = road->id;
roadmarks_mesh.road_start_indices[roadmarks_mesh.vertices.size()] = road->id;
road_objects_mesh.road_start_indices[road_objects_mesh.vertices.size()] = road->id;
for (std::shared_ptr<const LaneSection> lanesec : road->get_lanesections())
{
lanes_mesh.lanesec_start_indices[lanes_mesh.vertices.size()] = lanesec->s0;
roadmarks_mesh.lanesec_start_indices[roadmarks_mesh.vertices.size()] = lanesec->s0;
for (std::shared_ptr<const Lane> lane : lanesec->get_lanes())
{
const size_t lanes_idx_offset = lanes_mesh.vertices.size();
lanes_mesh.lane_start_indices[lanes_idx_offset] = lane->id;
lanes_mesh.add_mesh(lane->get_mesh(lanesec->s0, lanesec->get_end(), eps));
size_t roadmarks_idx_offset = roadmarks_mesh.vertices.size();
roadmarks_mesh.lane_start_indices[roadmarks_idx_offset] = lane->id;
const std::vector<std::shared_ptr<RoadMark>> roadmarks = lane->get_roadmarks(lanesec->s0, lanesec->get_end());
for (std::shared_ptr<const RoadMark> roadmark : roadmarks)
{
roadmarks_idx_offset = roadmarks_mesh.vertices.size();
roadmarks_mesh.roadmark_type_start_indices[roadmarks_idx_offset] = roadmark->type;
roadmarks_mesh.add_mesh(lane->get_roadmark_mesh(roadmark, eps));
}
}
}
for (std::shared_ptr<const RoadObject> road_object : road->get_road_objects())
{
const size_t road_objs_idx_offset = road_objects_mesh.vertices.size();
road_objects_mesh.road_object_start_indices[road_objs_idx_offset] = road_object->id;
road_objects_mesh.add_mesh(road_object->get_mesh(eps));
}
}
return out_mesh;
}
} // namespace odr | 39.674699 | 126 | 0.653204 | [
"vector"
] |
199dbf80dda6d61279a828d61b685daf7b3b29d7 | 3,042 | cpp | C++ | hackerearth/hacker_earth/dhurva/building.cpp | bristy/codemania | ceaacce07cb1b66202e17ad313a3467bd591bdc1 | [
"MIT"
] | null | null | null | hackerearth/hacker_earth/dhurva/building.cpp | bristy/codemania | ceaacce07cb1b66202e17ad313a3467bd591bdc1 | [
"MIT"
] | null | null | null | hackerearth/hacker_earth/dhurva/building.cpp | bristy/codemania | ceaacce07cb1b66202e17ad313a3467bd591bdc1 | [
"MIT"
] | null | null | null | //Data Structure includes
#include<vector>
#include<stack>
#include<set>
#include<bitset>
#include<map>
#include<queue>
#include<deque>
#include<string>
//Other Includes
#include<iostream>
#include<fstream>
#include<algorithm>
#include<cstring>
#include<cassert>
#include<cstdlib>
#include<cstdio>
#include<cmath>
using namespace std;
#define FOR(i,a,b) for(int i=a;i<b;i++)
#define REP(i,n) FOR(i,0,n)
#define pb push_back
#define mp make_pair
#define s(n) scanf("%d",&n)
#define sl(n) scanf("%lld",&n)
#define sf(n) scanf("%lf",&n)
#define ss(n) scanf("%s",n)
#define fill(a,v) memset(a, v, sizeof a)
#define sz(a) int((a).size())
#define INF (int)1e9
#define EPS 1e-9
#define bitcount __builtin_popcount
#define all(c) (c).begin(), (c).end()
#define gcd __gcd
#define maX(a,b) (a>b?a:b)
#define miN(a,b) (a<b?a:b)
#define DREP(a) sort(all(a)); a.erase(unique(all(a)),a.end())
#define INDEX(arr,ind) lower_bound(all(arr),ind)-arr.begin())
#define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
typedef vector<int> VI;
typedef vector<vector<int> > VVI;
typedef long long LL;
typedef vector<long long > VLL;
typedef pair<int, int > PII;
#define MAX 100010
#define MOD 1000000007
struct node{
int idx;
int mx;
};
node T[4 * MAX];
int A[MAX];
int sqrtMax[MAX];
int sqrtMaxIdx[MAX];
int n;
int len;
node combine(node l, node r){
node ret = l;
if(ret.mx <= r.mx){
ret = r;
}
return ret;
}
void init(int k, int lo, int hi){
if(lo == hi){
T[k].idx = lo;
T[k].mx = A[lo];
return;
}
int mid = (lo + hi) / 2;
int next = k << 1;
init(next, lo, mid);
init(next + 1, mid + 1, hi);
T[k] = combine(T[next], T[next + 1]);
return;
}
node query(int k, int lo, int hi, int qlo, int qhi){
if(lo==qlo && hi==qhi){
return T[k];
}
int mid=(lo+hi)>>1;
int next=k<<1;
if(mid>=qhi){
return query(next, lo, mid, qlo, qhi);
}
if(mid<qlo){
return query(next+1, mid+1, hi, qlo, qhi);
}
return combine(
query(next, lo, mid, qlo, mid),
query(next+1, mid+1, hi, mid+1, qhi)
);
}
int getMax(int l, int r){
node ret = query(1, 0, n - 1, l, r);
return ret.idx;
}
void deb(){
s(n);
len = sqrt(n) + 1;
REP(i, n){
s(A[i]);
}
init(1, 0, n - 1);
}
void solve(){
deb();
if(n <= 2){
printf("0\n");
return;
}
int l = 0;
int r;
while(l < n-1 && A[l] < A[l + 1]){
l++;
}
LL ret = 0;
while(l + 1 < n){
r = getMax(l + 1, n - 1);
//printf("%d %d\n", l, r);
int base = miN(A[l], A[r]);
while(l < r){
if(A[l] < base){
ret += base - A[l];
}
l++;
}
ret %= MOD;
}
printf("%lld\n", ret % MOD);
}
int main(){
int t;
s(t);
while(t--){
solve();
}
}
| 17.382857 | 77 | 0.521039 | [
"vector"
] |
19a1780ea719088b6baf518f51504832e807ea12 | 1,873 | cc | C++ | src/lycon/io/base.cc | peter0749/lycon | 0e7b3e51f56140d68e0466d00be45d79b4de682b | [
"BSD-3-Clause"
] | 278 | 2017-01-17T22:54:24.000Z | 2022-03-16T07:33:31.000Z | src/lycon/io/base.cc | peter0749/lycon | 0e7b3e51f56140d68e0466d00be45d79b4de682b | [
"BSD-3-Clause"
] | 22 | 2017-01-31T02:18:55.000Z | 2021-12-07T17:52:49.000Z | src/lycon/io/base.cc | peter0749/lycon | 0e7b3e51f56140d68e0466d00be45d79b4de682b | [
"BSD-3-Clause"
] | 25 | 2017-08-29T17:19:52.000Z | 2022-01-12T12:14:34.000Z | #include "lycon/io/base.h"
#include "lycon/io/bitstream.h"
namespace lycon
{
BaseImageDecoder::BaseImageDecoder()
{
m_width = m_height = 0;
m_type = -1;
m_buf_supported = false;
m_scale_denom = 1;
}
bool BaseImageDecoder::setSource(const String& filename)
{
m_filename = filename;
m_buf.release();
return true;
}
bool BaseImageDecoder::setSource(const Mat& buf)
{
if (!m_buf_supported)
return false;
m_filename = String();
m_buf = buf;
return true;
}
size_t BaseImageDecoder::signatureLength() const
{
return m_signature.size();
}
bool BaseImageDecoder::checkSignature(const String& signature) const
{
size_t len = signatureLength();
return signature.size() >= len && memcmp(signature.c_str(), m_signature.c_str(), len) == 0;
}
int BaseImageDecoder::setScale(const int& scale_denom)
{
int temp = m_scale_denom;
m_scale_denom = scale_denom;
return temp;
}
ImageDecoder BaseImageDecoder::newDecoder() const
{
return ImageDecoder();
}
BaseImageEncoder::BaseImageEncoder()
{
m_buf_supported = false;
}
bool BaseImageEncoder::isFormatSupported(int depth) const
{
return depth == LYCON_8U;
}
String BaseImageEncoder::getDescription() const
{
return m_description;
}
bool BaseImageEncoder::setDestination(const String& filename)
{
m_filename = filename;
m_buf = 0;
return true;
}
bool BaseImageEncoder::setDestination(std::vector<uchar>& buf)
{
if (!m_buf_supported)
return false;
m_buf = &buf;
m_buf->clear();
m_filename = String();
return true;
}
ImageEncoder BaseImageEncoder::newEncoder() const
{
return ImageEncoder();
}
void BaseImageEncoder::throwOnEror() const
{
if (!m_last_error.empty())
{
String msg = "Raw image encoder error: " + m_last_error;
throw std::runtime_error(msg.c_str());
}
}
}
| 18.919192 | 95 | 0.684463 | [
"vector"
] |
19a46223c0d5b3d23c13d22fd3d5eca5d6370f33 | 3,503 | hpp | C++ | include/reactive_planners/dynamic_graph/stepper_head.hpp | Lhumd/reactive_planners-1 | 5d8bd04da3d06fb2f968aa23a0c6713dcd773f44 | [
"BSD-3-Clause"
] | 6 | 2021-09-13T10:25:50.000Z | 2022-02-27T21:55:25.000Z | include/reactive_planners/dynamic_graph/stepper_head.hpp | Lhumd/reactive_planners-1 | 5d8bd04da3d06fb2f968aa23a0c6713dcd773f44 | [
"BSD-3-Clause"
] | 1 | 2021-11-28T04:02:31.000Z | 2022-01-18T16:33:43.000Z | include/reactive_planners/dynamic_graph/stepper_head.hpp | Lhumd/reactive_planners-1 | 5d8bd04da3d06fb2f968aa23a0c6713dcd773f44 | [
"BSD-3-Clause"
] | 2 | 2021-09-15T09:07:01.000Z | 2022-02-16T21:28:10.000Z | /**
* @file
* @license BSD 3-clause
* @copyright Copyright (c) 2020, New York University and Max Planck
* Gesellschaft
*
* @brief Implements an entity to coordinate the stepping for the
* dcm_vrp_planner.
*/
#pragma once
#include "reactive_planners/dcm_vrp_planner.hpp"
#include <dynamic-graph/all-commands.h>
#include <dynamic-graph/all-signals.h>
#include <dynamic-graph/entity.h>
namespace reactive_planners
{
namespace dynamic_graph
{
/**
* @brief Main entity controlling the stepping phase and keeps track of
* previously computed variables.
*/
class StepperHead : public dynamicgraph::Entity
{
DYNAMIC_GRAPH_ENTITY_DECL();
public:
/**
* @brief Construct a new StepperHead object using its Dynamic Graph name.
*
* @param name
*/
StepperHead(const std::string& name);
/*
* Input Signals.
*/
/** @brief The u as computed by the dcm_vrp_planner. */
dynamicgraph::SignalPtr<dynamicgraph::Vector, int> next_step_location_sin_;
/** @brief The t_end as computed by the dcm_vrp_planner. */
dynamicgraph::SignalPtr<double, int> duration_before_step_landing_sin_;
/*
* Output Signals.
*/
/** @brief The time [s] of the current stepping phase. */
dynamicgraph::SignalTimeDependent<double, int>
time_from_last_step_touchdown_sout_;
/** @brief The stepping phase. */
dynamicgraph::SignalTimeDependent<int, int> is_left_leg_in_contact_sout_;
/** @brief The old u. */
dynamicgraph::SignalTimeDependent<dynamicgraph::Vector, int>
old_step_location_sout_;
/** @brief The current u. */
dynamicgraph::SignalTimeDependent<dynamicgraph::Vector, int>
current_step_location_sout_;
/**
* @brief Helper to define the name of the signals.
*
* @param isInputSignal
* @param signalType
* @param signalName
* @return std::string
*/
std::string make_signal_string(const bool& is_input_signal,
const std::string& signal_type,
const std::string& signal_name);
protected:
// Use these variables to determine the current outputs.
int dg_time_phase_switch_;
double last_duration_before_step_landing_;
bool is_left_leg_in_contact_;
Eigen::Vector3d last_next_step_location_;
Eigen::Vector3d old_step_location_;
Eigen::Vector3d current_step_location_;
/**
* @brief Callback for time_from_last_step_touchdown_sout_ signal.
*
* @param time_last_step
* @param t
* @return double&
*/
double& time_from_last_step_touchdown(double& time_last_step, int time);
/**
* @brief Callback for is_left_leg_in_contact_sout_ signal.
*
* @param left_leg_in_contact
* @param t
* @return double&
*/
int& is_left_leg_in_contact(int& left_leg_in_contact, int time);
/**
* @brief Callback for old_step_location_sout_ signal.
*
* @param step_location
* @param t
* @return double&
*/
dynamicgraph::Vector& old_step_location(dynamicgraph::Vector& step_location,
int time);
/**
* @brief Callback for current_step_location_sout_ signal.
*
* @param step_location
* @param t
* @return double&
*/
dynamicgraph::Vector& current_step_location(
dynamicgraph::Vector& step_location, int time);
};
} // namespace dynamic_graph
} // namespace reactive_planners
| 26.946154 | 80 | 0.663146 | [
"object",
"vector"
] |
30b74c6517cbd1f48b22cd08d9fdbd7473e2f248 | 26,377 | cpp | C++ | code/Graphics/OpenGL/OpenGLRenderer.cpp | jpike/Renderer3D | 71374bf0a45945593147250e136ab67305324dae | [
"Unlicense"
] | null | null | null | code/Graphics/OpenGL/OpenGLRenderer.cpp | jpike/Renderer3D | 71374bf0a45945593147250e136ab67305324dae | [
"Unlicense"
] | null | null | null | code/Graphics/OpenGL/OpenGLRenderer.cpp | jpike/Renderer3D | 71374bf0a45945593147250e136ab67305324dae | [
"Unlicense"
] | null | null | null | #include <algorithm>
#include <gl/GL.h>
#include <gl/GLU.h>
#include <GL/gl3w.h>
#include "Graphics/OpenGL/OpenGLRenderer.h"
namespace GRAPHICS::OPEN_GL
{
/// Renders an entire 3D scene.
/// @param[in] scene - The scene to render.
/// @param[in] camera - The camera to use to view the scene.
void OpenGLRenderer::Render(const Scene& scene, const Camera& camera) const
{
glEnable(GL_DEPTH_TEST);
ViewingTransformations viewing_transformations(camera);
ClearScreen(scene.BackgroundColor);
for (const auto& object_3D : scene.Objects)
{
Render(object_3D, scene.PointLights, viewing_transformations);
}
#if OLD_OPEN_GL
// SET LIGHTING IF APPROPRIATE.
/// @todo Better way to control lighting than presence/absence of light?
bool lighting_enabled = bool(scene.PointLights);
if (lighting_enabled)
{
// ENABLE LIGHTING.
glEnable(GL_LIGHTING);
// SET EACH LIGHT.
// While lights only up to GL_LIGHT7 are explicitly defined,
// more lights are actually supported, and the greater lights
// can be specified by simple addition (http://docs.gl/gl2/glLight).
GLenum light_count = static_cast<GLenum>(scene.PointLights->size());
GLenum max_light_index = std::min<GLenum>(light_count, GL_MAX_LIGHTS);
for (GLenum light_index = 0; light_index < max_light_index; ++light_index)
{
// ENABLE THE CURRENT LIGHT.
GLenum light_id = GL_LIGHT0 + light_index;
glEnable(light_id);
const float LIGHT_ATTENUATION = 2.0f;
glLightfv(light_id, GL_QUADRATIC_ATTENUATION, &LIGHT_ATTENUATION);
// SET PROPERTIES RELATED TO THE CURRENT TYPE OF LIGHT.
const Light& current_light = (*scene.PointLights)[light_index];
float light_color[] = { current_light.Color.Red, current_light.Color.Green, current_light.Color.Blue, current_light.Color.Alpha };
const float NO_LIGHT_COLOR[] = { 0.0f, 0.0f, 0.0f, 1.0f };
switch (current_light.Type)
{
case LightType::AMBIENT:
{
glLightfv(light_id, GL_AMBIENT, light_color);
break;
}
case LightType::DIRECTIONAL:
{
glLightfv(light_id, GL_DIFFUSE, light_color);
glLightfv(light_id, GL_SPECULAR, light_color);
float light_direction[] = { current_light.DirectionalLightDirection.X, current_light.DirectionalLightDirection.Y, current_light.DirectionalLightDirection.Z };
glLightfv(light_id, GL_SPOT_DIRECTION, light_direction);
break;
}
case LightType::POINT:
{
glLightfv(light_id, GL_DIFFUSE, light_color);
glLightfv(light_id, GL_SPECULAR, light_color);
float light_position[] = { current_light.PointLightWorldPosition.X, current_light.PointLightWorldPosition.Y, current_light.PointLightWorldPosition.Z, 1.0f };
glLightfv(light_id, GL_POSITION, light_position);
break;
}
}
}
}
else
{
glDisable(GL_LIGHTING);
}
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
if (ProjectionType::ORTHOGRAPHIC == camera.Projection)
{
/// @todo Centralize screen dimensions!
glOrtho(
camera.WorldPosition.X - 200.0f,
camera.WorldPosition.X + 200.0f,
camera.WorldPosition.Y - 200.0f,
camera.WorldPosition.Y + 200.0f,
-1.0f,
1.0f);
}
else if (ProjectionType::PERSPECTIVE == camera.Projection)
{
const float NEAR_Z_WORLD_BOUNDARY = 1.0f;
const float FAR_Z_WORLD_BOUNDARY = 500.0f;
#define GLU 1
#if GLU
const MATH::Angle<float>::Degrees VERTICAL_FIELD_OF_VIEW_IN_DEGREES(90.0f);
const float ASPECT_RATIO_WIDTH_OVER_HEIGHT = 1.0f;
gluPerspective(VERTICAL_FIELD_OF_VIEW_IN_DEGREES.Value, ASPECT_RATIO_WIDTH_OVER_HEIGHT, NEAR_Z_WORLD_BOUNDARY, FAR_Z_WORLD_BOUNDARY);
#else
glFrustum(
camera.WorldPosition.X - 200.0f,
camera.WorldPosition.X + 200.0f,
camera.WorldPosition.Y - 200.0f,
camera.WorldPosition.Y + 200.0f,
NEAR_Z_WORLD_BOUNDARY,
FAR_Z_WORLD_BOUNDARY);
#endif
}
/// @todo Perspective!
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
MATH::Matrix4x4f view_matrix = camera.ViewTransform();
glLoadMatrixf(view_matrix.Elements.ValuesInColumnMajorOrder().data());
// RENDER EACH OBJECT IN THE SCENE.
for (const auto& object_3D : scene.Objects)
{
glPushMatrix();
//glLoadIdentity();
MATH::Matrix4x4f world_matrix = object_3D.WorldTransform();
//glLoadMatrixf(world_matrix.Elements.ValuesInColumnMajorOrder().data());
glMultMatrixf(world_matrix.Elements.ValuesInColumnMajorOrder().data());
Render(object_3D);
glPopMatrix();
}
#endif
}
/// Clears the screen to the specified color.
/// @param[in] color - The color to clear to.
void OpenGLRenderer::ClearScreen(const Color& color) const
{
GLfloat background_color[] = { color.Red, color.Green, color.Blue, color.Alpha };
const GLint NO_SPECIFIC_DRAW_BUFFER = 0;
glClearBufferfv(GL_COLOR, NO_SPECIFIC_DRAW_BUFFER, background_color);
/// @todo Not sure if this is fully correct.
GLfloat max_depth[] = { 1.0f, 1.0f, 1.0f, 1.0f };
glClearBufferfv(GL_DEPTH, NO_SPECIFIC_DRAW_BUFFER, max_depth);
}
/// Renders the specified object.
/// @param[in] object_3D - The 3D object to render.
/// @param[in] lights - Any lights in the scene.
/// @param[in] viewing_transformations - The viewing transformations.
void OpenGLRenderer::Render(
const Object3D& object_3D,
const std::optional<std::vector<Light>>& lights,
const ViewingTransformations& viewing_transformations) const
{
// USE THE OBJECT'S SHADER PROGRAM.
glUseProgram(object_3D.ShaderProgram->Id);
// SET UNIFORMS.
GLint world_matrix_variable = glGetUniformLocation(object_3D.ShaderProgram->Id, "world_transform");
MATH::Matrix4x4f world_transform = object_3D.WorldTransform();
const float* world_matrix_elements_in_row_major_order = world_transform.ElementsInRowMajorOrder();
const GLsizei ONE_MATRIX = 1;
const GLboolean ROW_MAJOR_ORDER = GL_TRUE;
glUniformMatrix4fv(world_matrix_variable, ONE_MATRIX, ROW_MAJOR_ORDER, world_matrix_elements_in_row_major_order);
GLint view_matrix_variable = glGetUniformLocation(object_3D.ShaderProgram->Id, "view_transform");
const float* view_matrix_elements_in_row_major_order = viewing_transformations.CameraViewTransform.ElementsInRowMajorOrder();
glUniformMatrix4fv(view_matrix_variable, ONE_MATRIX, ROW_MAJOR_ORDER, view_matrix_elements_in_row_major_order);
GLint projection_matrix_variable = glGetUniformLocation(object_3D.ShaderProgram->Id, "projection_transform");
const float* projection_matrix_elements_in_row_major_order = viewing_transformations.CameraProjectionTransform.ElementsInRowMajorOrder();
glUniformMatrix4fv(projection_matrix_variable, ONE_MATRIX, ROW_MAJOR_ORDER, projection_matrix_elements_in_row_major_order);
GLint texture_sampler_variable = glGetUniformLocation(object_3D.ShaderProgram->Id, "texture_sampler");
glUniform1i(texture_sampler_variable, 0);
bool is_lit = lights.has_value();
GLint is_lit_variable = glGetUniformLocation(object_3D.ShaderProgram->Id, "is_lit");
glUniform1i(is_lit_variable, is_lit);
if (is_lit)
{
// Single arbitrary light for now.
const Light& first_light = lights->at(0);
GLint light_position_variable = glGetUniformLocation(object_3D.ShaderProgram->Id, "light_position");
glUniform4f(
light_position_variable,
first_light.PointLightWorldPosition.X,
first_light.PointLightWorldPosition.Y,
first_light.PointLightWorldPosition.Z,
1.0f);
GLint light_color_variable = glGetUniformLocation(object_3D.ShaderProgram->Id, "input_light_color");
glUniform4f(
light_color_variable,
first_light.Color.Red,
first_light.Color.Green,
first_light.Color.Blue,
first_light.Color.Alpha);
}
/// @todo Pass vertices for entire object at once!
/// @todo Look at https://github.com/jpike/OpenGLEngine/ for possible better handling of some stuff?
for (const auto& triangle : object_3D.Triangles)
{
// ALLOCATE A TEXTURE IF APPLICABLE.
// Must be done outside of glBegin()/glEnd() (http://docs.gl/gl2/glGenTextures).
GLuint texture = 0;
bool is_textured = (ShadingType::TEXTURED == triangle.Material->Shading);
if (is_textured)
{
glGenTextures(1, &texture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(
GL_TEXTURE_2D,
0, // level of detail
GL_RGBA, // this is the only thing we currently support
triangle.Material->Texture->GetWidthInPixels(),
triangle.Material->Texture->GetHeightInPixels(),
0, // no border
GL_RGBA,
GL_UNSIGNED_BYTE, // one byte per color component
triangle.Material->Texture->GetRawData());
}
GLint is_textured_variable = glGetUniformLocation(object_3D.ShaderProgram->Id, "is_textured");
glUniform1i(is_textured_variable, is_textured);
// ALLOCATE A VERTEX ARRAY/BUFFER.
const GLsizei ONE_VERTEX_ARRAY = 1;
GLuint vertex_array_id = 0;
glGenVertexArrays(ONE_VERTEX_ARRAY, &vertex_array_id);
glBindVertexArray(vertex_array_id);
const GLsizei ONE_VERTEX_BUFFER = 1;
GLuint vertex_buffer_id = 0;
glGenBuffers(ONE_VERTEX_BUFFER, &vertex_buffer_id);
// FILL THE BUFFER WITH THE VERTEX DATA.
constexpr std::size_t POSITION_COORDINATE_COUNT_PER_VERTEX = 4;
constexpr std::size_t VERTEX_POSITION_COORDINATE_TOTAL_COUNT = POSITION_COORDINATE_COUNT_PER_VERTEX * Triangle::VERTEX_COUNT;
constexpr std::size_t COLOR_COMPONENT_COUNT_PER_VERTEX = 4;
constexpr std::size_t VERTEX_COLOR_COMPONENT_TOTAL_COUNT = COLOR_COMPONENT_COUNT_PER_VERTEX * Triangle::VERTEX_COUNT;
constexpr std::size_t TEXTURE_COORDINATE_COMPONENT_COUNT_PER_VERTEX = 2;
constexpr std::size_t TEXTURE_COORDINATE_COMPONENT_TOTAL_COUNT = TEXTURE_COORDINATE_COMPONENT_COUNT_PER_VERTEX * Triangle::VERTEX_COUNT;
constexpr std::size_t NORMAL_COORDINATE_COUNT_PER_VERTEX = 4;
constexpr std::size_t NORMAL_COORDINATE_COMPONENT_TOTAL_COUNT = NORMAL_COORDINATE_COUNT_PER_VERTEX * Triangle::VERTEX_COUNT;
constexpr std::size_t VERTEX_ATTRIBUTE_TOTAL_VALUE_COUNT = (
VERTEX_POSITION_COORDINATE_TOTAL_COUNT +
VERTEX_COLOR_COMPONENT_TOTAL_COUNT +
TEXTURE_COORDINATE_COMPONENT_TOTAL_COUNT +
NORMAL_COORDINATE_COMPONENT_TOTAL_COUNT);
std::vector<float> vertex_attribute_values;
vertex_attribute_values.reserve(VERTEX_ATTRIBUTE_TOTAL_VALUE_COUNT);
MATH::Vector3f surface_normal = triangle.SurfaceNormal();
for (std::size_t vertex_index = 0; vertex_index < Triangle::VERTEX_COUNT; ++vertex_index)
{
const MATH::Vector3f& vertex = triangle.Vertices[vertex_index];
vertex_attribute_values.emplace_back(vertex.X);
vertex_attribute_values.emplace_back(vertex.Y);
vertex_attribute_values.emplace_back(vertex.Z);
constexpr float HOMOGENEOUS_VERTEX_W = 1.0f;
vertex_attribute_values.emplace_back(HOMOGENEOUS_VERTEX_W);
const GRAPHICS::Color& vertex_color = triangle.Material->VertexColors[vertex_index];
vertex_attribute_values.emplace_back(vertex_color.Red);
vertex_attribute_values.emplace_back(vertex_color.Green);
vertex_attribute_values.emplace_back(vertex_color.Blue);
vertex_attribute_values.emplace_back(vertex_color.Alpha);
if (!triangle.Material->VertexTextureCoordinates.empty())
{
const MATH::Vector2f& current_vertex_texture_coordinates = triangle.Material->VertexTextureCoordinates[vertex_index];
vertex_attribute_values.emplace_back(current_vertex_texture_coordinates.X);
vertex_attribute_values.emplace_back(current_vertex_texture_coordinates.Y);
}
else
{
vertex_attribute_values.emplace_back(0.0f);
vertex_attribute_values.emplace_back(0.0f);
}
vertex_attribute_values.emplace_back(surface_normal.X);
vertex_attribute_values.emplace_back(surface_normal.Y);
vertex_attribute_values.emplace_back(surface_normal.Z);
vertex_attribute_values.emplace_back(1.0f);
}
GLsizeiptr vertex_data_size_in_bytes = sizeof(float) * VERTEX_ATTRIBUTE_TOTAL_VALUE_COUNT;
glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer_id);
glBufferData(GL_ARRAY_BUFFER, vertex_data_size_in_bytes, vertex_attribute_values.data(), GL_STATIC_DRAW);
// SPECIFY HOW VERTEX BUFFER DATA MAPS TO SHADER INPUTS.
constexpr GLboolean NO_NORMALIZATION = GL_FALSE;
constexpr GLsizei SINGLE_VERTEX_ATTRIBUTE_VALUE_COUNT = (
POSITION_COORDINATE_COUNT_PER_VERTEX +
COLOR_COMPONENT_COUNT_PER_VERTEX +
TEXTURE_COORDINATE_COMPONENT_COUNT_PER_VERTEX +
NORMAL_COORDINATE_COUNT_PER_VERTEX);
constexpr GLsizei SINGLE_VERTEX_ENTIRE_DATA_SIZE_IN_BYTES = sizeof(float) * SINGLE_VERTEX_ATTRIBUTE_VALUE_COUNT;
constexpr uint64_t VERTEX_POSITION_STARTING_OFFSET_IN_BYTES = 0;
GLint local_vertex_position_variable_id = glGetAttribLocation(object_3D.ShaderProgram->Id, "local_vertex");
glVertexAttribPointer(
local_vertex_position_variable_id,
POSITION_COORDINATE_COUNT_PER_VERTEX,
GL_FLOAT,
NO_NORMALIZATION,
SINGLE_VERTEX_ENTIRE_DATA_SIZE_IN_BYTES,
(void*)VERTEX_POSITION_STARTING_OFFSET_IN_BYTES);
glEnableVertexAttribArray(local_vertex_position_variable_id);
const uint64_t VERTEX_COLOR_STARTING_OFFSET_IN_BYTES = sizeof(float) * POSITION_COORDINATE_COUNT_PER_VERTEX;
GLint vertex_color_variable_id = glGetAttribLocation(object_3D.ShaderProgram->Id, "input_vertex_color");
glVertexAttribPointer(
vertex_color_variable_id,
COLOR_COMPONENT_COUNT_PER_VERTEX,
GL_FLOAT,
NO_NORMALIZATION,
SINGLE_VERTEX_ENTIRE_DATA_SIZE_IN_BYTES,
(void*)VERTEX_COLOR_STARTING_OFFSET_IN_BYTES);
glEnableVertexAttribArray(vertex_color_variable_id);
constexpr std::size_t VERTEX_COLOR_SIZE_IN_BYTES = sizeof(float) * COLOR_COMPONENT_COUNT_PER_VERTEX;
const uint64_t TEXTURE_COORDINATE_STARTING_OFFSET_IN_BYTES = VERTEX_COLOR_STARTING_OFFSET_IN_BYTES + VERTEX_COLOR_SIZE_IN_BYTES;
GLint texture_coordinates_variable_id = glGetAttribLocation(object_3D.ShaderProgram->Id, "input_texture_coordinates");
glVertexAttribPointer(
texture_coordinates_variable_id,
TEXTURE_COORDINATE_COMPONENT_COUNT_PER_VERTEX,
GL_FLOAT,
NO_NORMALIZATION,
SINGLE_VERTEX_ENTIRE_DATA_SIZE_IN_BYTES,
(void*)TEXTURE_COORDINATE_STARTING_OFFSET_IN_BYTES);
glEnableVertexAttribArray(texture_coordinates_variable_id);
constexpr std::size_t TEXTURE_COORDINATE_SIZE_IN_BYTES = sizeof(float) * TEXTURE_COORDINATE_COMPONENT_COUNT_PER_VERTEX;
const uint64_t NORMAL_STARTING_OFFSET_IN_BYTES = TEXTURE_COORDINATE_STARTING_OFFSET_IN_BYTES + TEXTURE_COORDINATE_SIZE_IN_BYTES;
GLint normal_variable_id = glGetAttribLocation(object_3D.ShaderProgram->Id, "vertex_normal");
glVertexAttribPointer(
normal_variable_id,
NORMAL_COORDINATE_COUNT_PER_VERTEX,
GL_FLOAT,
NO_NORMALIZATION,
SINGLE_VERTEX_ENTIRE_DATA_SIZE_IN_BYTES,
(void*)NORMAL_STARTING_OFFSET_IN_BYTES);
glEnableVertexAttribArray(normal_variable_id);
// DRAW THE TRIANGLE.
const unsigned int FIRST_VERTEX = 0;
GLsizei vertex_count = static_cast<GLsizei>(Triangle::VERTEX_COUNT);
glDrawArrays(GL_TRIANGLES, FIRST_VERTEX, vertex_count);
/// @todo Encapsulate this vertex array stuff with object?
glDeleteBuffers(ONE_VERTEX_BUFFER, &vertex_buffer_id);
glDeleteVertexArrays(ONE_VERTEX_ARRAY, &vertex_array_id);
if (is_textured)
{
glDeleteTextures(1, &texture);
}
}
#if OLD_OPEN_GL
for (const auto& triangle : object_3D.Triangles)
{
// ALLOCATE A TEXTURE IF APPLICABLE.
// Must be done outside of glBegin()/glEnd() (http://docs.gl/gl2/glGenTextures).
GLuint texture = 0;
bool is_textured = (ShadingType::TEXTURED == triangle.Material->Shading);
if (is_textured)
{
glEnable(GL_TEXTURE_2D);
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexImage2D(
GL_TEXTURE_2D,
0, // level of detail
GL_RGBA, // this is the only thing we currently support
triangle.Material->Texture->GetWidthInPixels(),
triangle.Material->Texture->GetHeightInPixels(),
0, // no border
GL_RGBA,
GL_UNSIGNED_BYTE, // one byte per color component
triangle.Material->Texture->GetRawData());
}
// START RENDERING THE APPROPRIATE TYPE OF PRIMITIVE.
bool is_wireframe = (ShadingType::WIREFRAME == triangle.Material->Shading);
if (is_wireframe)
{
// RENDER LINES BETWEEN EACH VERTEX.
glBegin(GL_LINE_LOOP);
}
else
{
// RENDER NORMAL TRIANGLES.
glBegin(GL_TRIANGLES);
}
// SET THE APPROPRIATE TYPE OF SHADING.
bool is_flat = (
ShadingType::WIREFRAME == triangle.Material->Shading ||
ShadingType::FLAT == triangle.Material->Shading);
if (is_flat)
{
glShadeModel(GL_FLAT);
}
else
{
glShadeModel(GL_SMOOTH);
}
// SET THE SURFACE NORMAL.
MATH::Vector3f surface_normal = triangle.SurfaceNormal();
glNormal3f(surface_normal.X, surface_normal.Y, surface_normal.Z);
// RENDER EACH VERTEX.
for (std::size_t vertex_index = 0; vertex_index < triangle.Vertices.size(); ++vertex_index)
{
#if TODO_THIS_CAUSES_TOO_MUCH_INTERFERENCE_HARD_TO_MANAGE_STATE
// CLEAR ANY PREVIOUSLY SET MATERIAL PROPERTIES TO AVOID INTERFERENCE.
// They're reset to defaults (http://docs.gl/gl2/glMaterial) to allow other lighting to continue.
const float NO_MATERIAL_COLOR[] = { 0.0f, 0.0f, 0.0f, 1.0f };
const float DEFAULT_AMBIENT_MATERIAL_COLOR[] = { 0.2f, 0.2f, 0.2f, 1.0f };
const float DEFAULT_DIFFUSE_MATERIAL_COLOR[] = { 0.8f, 0.8f, 0.8f, 1.0f };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, DEFAULT_AMBIENT_MATERIAL_COLOR);
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, DEFAULT_DIFFUSE_MATERIAL_COLOR);
/// @todo Clear shininess too?
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, NO_MATERIAL_COLOR);
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, NO_MATERIAL_COLOR);
#endif
// SPECIFY THE VERTEX COLOR.
switch (triangle.Material->Shading)
{
case ShadingType::WIREFRAME:
{
glColor3f(
triangle.Material->VertexColors[vertex_index].Red,
triangle.Material->VertexColors[vertex_index].Green,
triangle.Material->VertexColors[vertex_index].Blue);
break;
}
case ShadingType::FLAT:
{
glColor3f(
triangle.Material->VertexColors[vertex_index].Red,
triangle.Material->VertexColors[vertex_index].Green,
triangle.Material->VertexColors[vertex_index].Blue);
break;
}
case ShadingType::FACE_VERTEX_COLOR_INTERPOLATION:
{
const Color& vertex_color = triangle.Material->VertexColors[vertex_index];
glColor3f(
vertex_color.Red,
vertex_color.Green,
vertex_color.Blue);
break;
}
case ShadingType::GOURAUD:
{
const Color& vertex_color = triangle.Material->VertexColors[vertex_index];
glColor3f(
vertex_color.Red,
vertex_color.Green,
vertex_color.Blue);
break;
}
case ShadingType::TEXTURED:
{
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL);
const MATH::Vector2f& current_vertex_texture_coordinates = triangle.Material->VertexTextureCoordinates[vertex_index];
glTexCoord2f(current_vertex_texture_coordinates.X, current_vertex_texture_coordinates.Y);
break;
}
case ShadingType::MATERIAL:
{
#if TODO_THIS_CAUSES_TOO_MUCH_INTERFERENCE_HARD_TO_MANAGE_STATE
float ambient_color[] = { triangle.Material->AmbientColor.Red, triangle.Material->AmbientColor.Green, triangle.Material->AmbientColor.Blue, triangle.Material->AmbientColor.Alpha };
glMaterialfv(GL_FRONT_AND_BACK, GL_AMBIENT, ambient_color);
float diffuse_color[] = { triangle.Material->DiffuseColor.Red, triangle.Material->DiffuseColor.Green, triangle.Material->DiffuseColor.Blue, triangle.Material->DiffuseColor.Alpha };
glMaterialfv(GL_FRONT_AND_BACK, GL_DIFFUSE, diffuse_color);
float specular_color[] = { triangle.Material->SpecularColor.Red, triangle.Material->SpecularColor.Green, triangle.Material->SpecularColor.Blue, triangle.Material->SpecularColor.Alpha };
glMaterialfv(GL_FRONT_AND_BACK, GL_SPECULAR, specular_color);
glMaterialfv(GL_FRONT_AND_BACK, GL_SHININESS, &triangle.Material->SpecularPower);
float emissive_color[] = { triangle.Material->EmissiveColor.Red, triangle.Material->EmissiveColor.Green, triangle.Material->EmissiveColor.Blue, triangle.Material->EmissiveColor.Alpha };
glMaterialfv(GL_FRONT_AND_BACK, GL_EMISSION, emissive_color);
#else
glColor3f(0.5f, 0.5f, 0.5f);
#endif
break;
}
}
// SPECIFY THE VERTEX POSITION.
const auto& vertex = triangle.Vertices[vertex_index];
glVertex3f(vertex.X, vertex.Y, vertex.Z);
}
// FINISH RENDERING THE TRIANGLE.
glEnd();
if (is_textured)
{
glDeleteTextures(1, &texture);
glDisable(GL_TEXTURE_2D);
}
}
#endif
}
}
| 49.027881 | 209 | 0.613413 | [
"render",
"object",
"vector",
"3d"
] |
30bec88003e4de0ff6ce8616001afc2d625d4bb3 | 2,345 | cpp | C++ | src/Common/JSONBuilder.cpp | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 15,577 | 2019-09-23T11:57:53.000Z | 2022-03-31T18:21:48.000Z | src/Common/JSONBuilder.cpp | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 16,476 | 2019-09-23T11:47:00.000Z | 2022-03-31T23:06:01.000Z | src/Common/JSONBuilder.cpp | pdv-ru/ClickHouse | 0ff975bcf3008fa6c6373cbdfed16328e3863ec5 | [
"Apache-2.0"
] | 3,633 | 2019-09-23T12:18:28.000Z | 2022-03-31T15:55:48.000Z | #include <Common/JSONBuilder.h>
#include <IO/WriteHelpers.h>
#include <Common/typeid_cast.h>
namespace DB::JSONBuilder
{
static bool isArrayOrMap(const IItem & item)
{
return typeid_cast<const JSONArray *>(&item) || typeid_cast<const JSONMap *>(&item);
}
static bool isSimpleArray(const std::vector<ItemPtr> & values)
{
for (const auto & value : values)
if (isArrayOrMap(*value))
return false;
return true;
}
void JSONString::format(const FormatSettings & settings, FormatContext & context)
{
writeJSONString(value, context.out, settings.settings);
}
void JSONBool::format(const FormatSettings &, FormatContext & context)
{
writeString(value ? "true" : "false", context.out);
}
void JSONArray::format(const FormatSettings & settings, FormatContext & context)
{
writeChar('[', context.out);
context.offset += settings.indent;
bool single_row = settings.print_simple_arrays_in_single_row && isSimpleArray(values);
bool first = true;
for (const auto & value : values)
{
if (!first)
writeChar(',', context.out);
if (!single_row)
{
writeChar('\n', context.out);
writeChar(' ', context.offset, context.out);
}
else if (!first)
writeChar(' ', context.out);
first = false;
value->format(settings, context);
}
context.offset -= settings.indent;
if (!single_row)
{
writeChar('\n', context.out);
writeChar(' ', context.offset, context.out);
}
writeChar(']', context.out);
}
void JSONMap::format(const FormatSettings & settings, FormatContext & context)
{
writeChar('{', context.out);
context.offset += settings.indent;
bool first = true;
for (const auto & value : values)
{
if (!first)
writeChar(',', context.out);
first = false;
writeChar('\n', context.out);
writeChar(' ', context.offset, context.out);
writeJSONString(value.key, context.out, settings.settings);
writeChar(':', context.out);
writeChar(' ', context.out);
value.value->format(settings, context);
}
context.offset -= settings.indent;
writeChar('\n', context.out);
writeChar(' ', context.offset, context.out);
writeChar('}', context.out);
}
}
| 23.45 | 90 | 0.617484 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.