hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ae38f72c78ef42f31273498ba0aa14853c32c46e
| 8,622
|
cpp
|
C++
|
Cpp/Docker/OBJ.cpp
|
Gabidal/GAC
|
f36b76bceb6a39a87b50c393eb3540f4085bd879
|
[
"MIT"
] | 5
|
2019-08-19T18:18:08.000Z
|
2019-12-13T19:26:03.000Z
|
Cpp/Docker/OBJ.cpp
|
Gabidal/GAC
|
f36b76bceb6a39a87b50c393eb3540f4085bd879
|
[
"MIT"
] | 3
|
2019-04-15T19:24:36.000Z
|
2020-02-29T13:09:07.000Z
|
Cpp/Docker/OBJ.cpp
|
Gabidal/GAC
|
f36b76bceb6a39a87b50c393eb3540f4085bd879
|
[
"MIT"
] | 2
|
2019-10-08T23:16:05.000Z
|
2019-12-18T22:58:04.000Z
|
#include "../../H/Docker/OBJ.h"
#include "../../H/BackEnd/Selector.h"
#include "../../H/Nodes/Node.h"
#include "../../H/Assembler/Assembler_Types.h"
#include "../../H/UI/Usr.h"
#include "../../H/UI/Safe.h"
#include "../../H/Assembler/Assembler.h"
#include "../../H/Docker/Docker.h"
extern Selector* selector;
extern Node* Global_Scope;
extern Usr* sys;
extern Assembler* assembler;
vector<OBJ::Section> OBJ::Gather_All_Sections(vector<char> buffer, int Section_Count)
{
vector<Section> Result;
for (int i = sizeof(Header); i < Section_Count; i += sizeof(Section)) {
Result.push_back(*(Section*)&(buffer[i]));
}
return Result;
}
vector<string> OBJ::Get_Symbol_Table_Content(Header h, vector<char> buffer)
{
vector<string> Result;
vector<Symbol> Symbols;
for (int i = *(int*)h.Pointer_To_Symbol_Table; i < buffer.size(); i++) {
Symbols.push_back(*(Symbol*)&(buffer[i]));
}
for (auto& S : Symbols) {
if (S.Name.Header == 0) {
string Name = "";
for (int i = *(int*)S.Name.Offset; i < buffer.size(); i++) {
if (buffer[i] == '\0')
break;
Name += buffer[i];
}
Result.push_back(Name);
}
else
Result.push_back(string(S.Full_Name, 8));
}
return Result;
}
void OBJ::OBJ_Analyser(vector<string>& Output) {
//get the header and then start up the section suckup syste 2000 :D
//read the file
vector<uint8_t> tmp = DOCKER::Get_Char_Buffer_From_File(DOCKER::Working_Dir.back().second + DOCKER::FileName.back(), "");
vector<char> Buffer = vector<char>(*(char*)tmp.data(), tmp.size());
//read the header of this obj file
Header header = *(Header*)&Buffer;
DOCKER::Append(Output, Get_Symbol_Table_Content(header, Buffer));
}
vector<unsigned char> OBJ::Create_Obj(vector<Byte_Map_Section*> Input){
OBJ::Header header;
header.Machine = selector->OBJ_Machine_ID;
header.Number_OF_Sections = Input.size();
header.Date_Time = time_t(time(NULL));
header.Pointer_To_Symbol_Table = offsetof(OBJ::Header, Characteristics) + sizeof(Header::Characteristics) + sizeof(OBJ::Section) * Input.size();
//calculate the exports and import functions from global scope
for (auto s : Global_Scope->Defined){
if (s->Has(vector<string>{"export", "import"}) > 0){
header.Number_Of_Symbols++;
}
}
header.Size_Of_Optional_Header = 0;
header.Characteristics = _IMAGE_FILE_LARGE_ADDRESS_AWARE;
// header.Magic = _MAGIC_PE32_PlUS;
// header.Linker_Version = 0x0000;
// for (auto i : Input){
// header.Size_Of_Code += i->Calculated_Size;
// }
// for (auto i : Input){
// if (i->Is_Data_Section)
// header.Size_Of_Initialized_Data += i->Calculated_Size;
// }
// header.Size_Of_Uninitialized_Data = 0;
// if (sys->Info.Format == "lib"){
// header.Address_Of_Entry_Point = 0;
// }
// else{
// string Unmangled_Starting_Function_Name = sys->Info.Start_Function_Name;
// Node* Function = Global_Scope->Find(Unmangled_Starting_Function_Name, Global_Scope, FUNCTION_NODE);
// if (Function == nullptr){
// Report(Observation(ERROR, "Function " + Unmangled_Starting_Function_Name + " not found in the global scope", LINKER_MISSING_STARTING_FUNCTION));
// return vector<unsigned char>();
// }
// string Mangled_Starting_Function_Name = Function->Mangled_Name;
// header.Address_Of_Entry_Point = assembler->Symbol_Table.at(Mangled_Starting_Function_Name);
// }
// header.Base_Of_Code = Input.size() * sizeof(Section) + header.Number_Of_Symbols * sizeof(Symbol) + sizeof(Header);
// header.Base_Of_Data = header.Base_Of_Code + header.Size_Of_Code;
// if (sys->Info.OS == "win"){
// if (sys->Info.Format == "exe"){
// header.Image_Base = _WINDOWS_PE_EXE_BASE_IMAGE;
// }
// else if (sys->Info.Format == "dll"){
// header.Image_Base = _WINDOWS_PE_DLL_BASE_IMAGE;
// }
// }
// header.Section_Alignment = _FILE_ALIGNMENT;
// header.File_Alignment = _FILE_ALIGNMENT;
// header.Operating_System_Version = 0x0006;
// header.Image_Version = 0;
// header.Subsystem_Version = 0;
// header.Win32_Version_Value = 0;
// header.Size_Of_Image = header.Size_Of_Code + header.Size_Of_Initialized_Data + header.Size_Of_Uninitialized_Data + sizeof(Section) * Input.size() + header.Number_Of_Symbols * sizeof(Symbol) + sizeof(Header);
// header.Size_Of_Headers = sizeof(Header) + sizeof(Section) * Input.size() + header.Number_Of_Symbols * sizeof(Symbol);
// header.Check_Sum = 0;
// header.Subsystem = 0;
// header.Dll_Characteristics = 0;
// header.Size_Of_Stack_Reserve = 0x100000;
// header.Size_Of_Stack_Commit = 0x1000;
// //Allocate for one bucket + bucket buffer for the Evie allocator.
// header.Size_Of_Heap_Reserve = _BUCKET_SIZE;
// header.Size_Of_Heap_Commit = _ALLOCATOR_BUCKET_COUNT + _BUCKET_SIZE;
// header.Loader_Flags = 0;
// header.Number_Of_Rva_And_Sizes = 0;
vector<OBJ::Symbol> Symbols = Generate_Symbol_Table();
vector<string> Symbol_Names = Generate_Name_Section_For_Symbol_Table();
unsigned long long Symbol_Name_Size = 0;
for (auto i : Symbol_Names){
//add the null terminator
Symbol_Name_Size += i.size() + 1;
}
vector<OBJ::Section> Sections = Generate_Section_Table(Input, header.Pointer_To_Symbol_Table + sizeof(header.Pointer_To_Symbol_Table) + sizeof(OBJ::Symbol) * Symbols.size() + Symbol_Name_Size);
//Now inline all the data into one humongus buffer
vector<unsigned char> Buffer;
//Remove the optional headers from the buffer
unsigned char* Header_Start_Address = (unsigned char*)&header;
unsigned char* Header_End_Address = (unsigned char*)&header.Characteristics + sizeof(header.Characteristics);
Buffer.insert(Buffer.end(), (unsigned char*)&header, Header_End_Address);
Buffer.insert(Buffer.end(), (unsigned char*)Sections.data(), (unsigned char*)Sections.data() + sizeof(OBJ::Section) * Input.size());
Buffer.insert(Buffer.end(), (unsigned char*)Symbols.data(), (unsigned char*)Symbols.data() + sizeof(OBJ::Symbol) * Symbols.size());
int s = sizeof(OBJ::Symbol);
unsigned int String_Table_Size = 0;
vector<unsigned char> String_Table_Buffer;
for (auto i : Symbol_Names){
String_Table_Buffer.insert(String_Table_Buffer.end(), i.begin(), i.end());
String_Table_Buffer.push_back(0);
}
String_Table_Size = String_Table_Buffer.size() + sizeof(String_Table_Size);
Buffer.insert(Buffer.end(), (unsigned char*)&String_Table_Size, (unsigned char*)&String_Table_Size + sizeof(String_Table_Size));
Buffer.insert(Buffer.end(), String_Table_Buffer.begin(), String_Table_Buffer.end());
for (auto i : Input){
for (auto& j : i->Byte_Maps){
vector<unsigned char> Data = selector->Assemble(j);
Buffer.insert(Buffer.end(), Data.begin(), Data.end());
}
}
//transform the
return Buffer;
}
vector<OBJ::Section> OBJ::Generate_Section_Table(vector<Byte_Map_Section*> Input, unsigned long long Origo){
vector<OBJ::Section> Result;
for (auto i : Input){
Section tmp;
memcpy(&tmp.Name, i->Name.data(), i->Name.size());
tmp.Virtual_Size = i->Calculated_Size;
tmp.Virtual_Address = i->Calculated_Address;
tmp.Size_Of_Raw_Data = i->Calculated_Size;
tmp.Pointer_To_Raw_Data = i->Calculated_Address + Origo;
tmp.Pointer_To_Relocations = 0;
tmp.Pointer_To_Line_Numbers = 0;
tmp.Number_Of_Relocations = 0;
tmp.Number_Of_Line_Numbers = 0;
if (i->Is_Data_Section){
tmp.Characteristics = _IMAGE_SCN_CNT_INITIALIZED_DATA | _IMAGE_SCN_MEM_READ | _IMAGE_SCN_MEM_WRITE;
}
else{
tmp.Characteristics = _IMAGE_SCN_CNT_CODE | _IMAGE_SCN_MEM_EXECUTE | _IMAGE_SCN_MEM_READ;
}
Result.push_back(tmp);
}
return Result;
}
vector<OBJ::Symbol> OBJ::Generate_Symbol_Table(){
vector<OBJ::Symbol> Result;
//Skip the String_Table_Size identifier
long long Current_Symbol_Offset = sizeof(unsigned int);
for (auto i : assembler->Symbol_Table){
OBJ::Symbol Current;
//Generate the offset for the name redies in, transform it to text
Current.Full_Name = Current_Symbol_Offset << 32;
Current.Value = i.second;
Current.Section_Number = 0;
Current.Type = 0;
Current.Storage_Class = _IMAGE_SYM_CLASS_LABEL;
Current.Number_Of_Aux_Symbols = 0;
Result.push_back(Current);
Current_Symbol_Offset += i.first.size() + 1;
}
return Result;
}
vector<string> OBJ::Generate_Name_Section_For_Symbol_Table(){
vector<string> Result;
for (auto symbol : assembler->Symbol_Table){
Result.push_back(symbol.first);
}
return Result;
}
| 31.933333
| 212
| 0.694734
|
Gabidal
|
ae3ab6bc4f88c37f0fa5090dce0cf138c035c01c
| 308
|
hpp
|
C++
|
pythran/pythonic/include/cmath/log.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/include/cmath/log.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
pythran/pythonic/include/cmath/log.hpp
|
artas360/pythran
|
66dad52d52be71693043e9a7d7578cfb9cb3d1da
|
[
"BSD-3-Clause"
] | null | null | null |
#ifndef PYTHONIC_INCLUDE_CMATH_LOG_HPP
#define PYTHONIC_INCLUDE_CMATH_LOG_HPP
#include "pythonic/include/utils/proxy.hpp"
#include <cmath>
namespace pythonic
{
namespace cmath
{
ALIAS_DECL(log, std::log);
double log(double x, double base);
PROXY_DECL(pythonic::cmath, log);
}
}
#endif
| 15.4
| 43
| 0.733766
|
artas360
|
ae3ca7324c166c72a93c09bd7aa727976348a3cf
| 9,203
|
hpp
|
C++
|
stm32-jl/include/common/uart.hpp
|
serjzimmerman/mipt-rt-stm32-f0-labs
|
561f363ec5c4dece92b2a14c36343aaa9d713785
|
[
"MIT"
] | null | null | null |
stm32-jl/include/common/uart.hpp
|
serjzimmerman/mipt-rt-stm32-f0-labs
|
561f363ec5c4dece92b2a14c36343aaa9d713785
|
[
"MIT"
] | null | null | null |
stm32-jl/include/common/uart.hpp
|
serjzimmerman/mipt-rt-stm32-f0-labs
|
561f363ec5c4dece92b2a14c36343aaa9d713785
|
[
"MIT"
] | null | null | null |
#pragma once
#include <cstdarg>
#include <cstring>
#include "gpio.hpp"
#include "stm32f051/rcc.hpp"
namespace JL {
enum StopBits {
stopBit1 = 0b00,
stopBit05 = 0b01,
stopBit2 = 0b10,
stopBit15 = 0b11,
};
enum WordLength {
wordLength8 = 0b00,
wordLength9 = 0b01,
wordLength7 = 0b10,
};
template <uint32_t addr, typename tx, typename rx, PinAlternateFunction txaf, PinAlternateFunction rxaf, typename clock>
struct UartBase {
static constexpr uint32_t addr_ = addr;
using Tx = tx;
using Rx = rx;
struct CR1 : RegisterBase<addr_ + 0x00, RegisterReadWriteMode> {
using UE = RegisterField<UartBase::CR1, 0, 1, RegisterReadWriteMode>;
using UESM = RegisterField<UartBase::CR1, 1, 1, RegisterReadWriteMode>;
using RE = RegisterField<UartBase::CR1, 2, 1, RegisterReadWriteMode>;
using TE = RegisterField<UartBase::CR1, 3, 1, RegisterReadWriteMode>;
using IDLEIE = RegisterField<UartBase::CR1, 4, 1, RegisterReadWriteMode>;
using EXNEIE = RegisterField<UartBase::CR1, 5, 1, RegisterReadWriteMode>;
using TCIE = RegisterField<UartBase::CR1, 6, 1, RegisterReadWriteMode>;
using TXEIE = RegisterField<UartBase::CR1, 7, 1, RegisterReadWriteMode>;
using PEIE = RegisterField<UartBase::CR1, 8, 1, RegisterReadWriteMode>;
using PS = RegisterField<UartBase::CR1, 9, 1, RegisterReadWriteMode>;
using PCE = RegisterField<UartBase::CR1, 10, 1, RegisterReadWriteMode>;
using WAKE = RegisterField<UartBase::CR1, 11, 1, RegisterReadWriteMode>;
using M0 = RegisterField<UartBase::CR1, 12, 1, RegisterReadWriteMode>;
using MME = RegisterField<UartBase::CR1, 13, 1, RegisterReadWriteMode>;
using CMIE = RegisterField<UartBase::CR1, 14, 1, RegisterReadWriteMode>;
using OVER8 = RegisterField<UartBase::CR1, 15, 1, RegisterReadWriteMode>;
using DEDT = RegisterField<UartBase::CR1, 16, 4, RegisterReadWriteMode>;
using DEAT = RegisterField<UartBase::CR1, 21, 4, RegisterReadWriteMode>;
using RTOIE = RegisterField<UartBase::CR1, 26, 1, RegisterReadWriteMode>;
using EOBIE = RegisterField<UartBase::CR1, 27, 1, RegisterReadWriteMode>;
using M1 = RegisterField<UartBase::CR1, 28, 1, RegisterReadWriteMode>;
};
struct CR2 : RegisterBase<addr_ + 0x04, RegisterReadWriteMode> {
using ADDM7 = RegisterField<UartBase::CR2, 4, 1, RegisterReadWriteMode>;
using LBDL = RegisterField<UartBase::CR2, 5, 1, RegisterReadWriteMode>;
using LBDIE = RegisterField<UartBase::CR2, 6, 1, RegisterReadWriteMode>;
using LBCL = RegisterField<UartBase::CR2, 8, 1, RegisterReadWriteMode>;
using CPHA = RegisterField<UartBase::CR2, 9, 1, RegisterReadWriteMode>;
using CPOL = RegisterField<UartBase::CR2, 10, 1, RegisterReadWriteMode>;
using CLKEN = RegisterField<UartBase::CR2, 11, 1, RegisterReadWriteMode>;
using STOP = RegisterField<UartBase::CR2, 12, 2, RegisterReadWriteMode>;
using LINEN = RegisterField<UartBase::CR2, 14, 1, RegisterReadWriteMode>;
using SWAP = RegisterField<UartBase::CR2, 15, 1, RegisterReadWriteMode>;
using RXINV = RegisterField<UartBase::CR2, 16, 1, RegisterReadWriteMode>;
using TXINV = RegisterField<UartBase::CR2, 17, 1, RegisterReadWriteMode>;
using DATAINV = RegisterField<UartBase::CR2, 18, 1, RegisterReadWriteMode>;
using MSBFIRST = RegisterField<UartBase::CR2, 19, 1, RegisterReadWriteMode>;
using ABREN = RegisterField<UartBase::CR2, 20, 1, RegisterReadWriteMode>;
using ABRMOD = RegisterField<UartBase::CR2, 21, 2, RegisterReadWriteMode>;
using RTOEN = RegisterField<UartBase::CR2, 23, 1, RegisterReadWriteMode>;
using ADD = RegisterField<UartBase::CR2, 24, 8, RegisterReadWriteMode>;
};
struct CR3 : RegisterBase<addr_ + 0x08, RegisterReadWriteMode> {
using EIE = RegisterField<UartBase::CR3, 0, 1, RegisterReadWriteMode>;
using IREN = RegisterField<UartBase::CR3, 1, 1, RegisterReadWriteMode>;
using IRLP = RegisterField<UartBase::CR3, 2, 1, RegisterReadWriteMode>;
using HDSEL = RegisterField<UartBase::CR3, 3, 1, RegisterReadWriteMode>;
using NACK = RegisterField<UartBase::CR3, 4, 1, RegisterReadWriteMode>;
using SCEN = RegisterField<UartBase::CR3, 5, 1, RegisterReadWriteMode>;
using DMAR = RegisterField<UartBase::CR3, 6, 1, RegisterReadWriteMode>;
using DMAT = RegisterField<UartBase::CR3, 7, 2, RegisterReadWriteMode>;
using RTSE = RegisterField<UartBase::CR3, 8, 1, RegisterReadWriteMode>;
using CTSE = RegisterField<UartBase::CR3, 9, 1, RegisterReadWriteMode>;
using CTSIE = RegisterField<UartBase::CR3, 10, 1, RegisterReadWriteMode>;
using ONEBIT = RegisterField<UartBase::CR3, 11, 1, RegisterReadWriteMode>;
using OVRDIS = RegisterField<UartBase::CR3, 12, 1, RegisterReadWriteMode>;
using DDRE = RegisterField<UartBase::CR3, 13, 1, RegisterReadWriteMode>;
using DEM = RegisterField<UartBase::CR3, 14, 1, RegisterReadWriteMode>;
using DEP = RegisterField<UartBase::CR3, 15, 1, RegisterReadWriteMode>;
using SCARCNT = RegisterField<UartBase::CR3, 17, 3, RegisterReadWriteMode>;
using WUS = RegisterField<UartBase::CR3, 20, 2, RegisterReadWriteMode>;
using WUFIE = RegisterField<UartBase::CR3, 22, 1, RegisterReadWriteMode>;
};
struct BRR : RegisterBase<addr_ + 0x0c, RegisterReadWriteMode> {
using BRR16 = RegisterField<UartBase::BRR, 0, 16, RegisterReadWriteMode>;
using FRAC8 = RegisterField<UartBase::BRR, 0, 3, RegisterReadWriteMode>;
using BRR8 = RegisterField<UartBase::BRR, 4, 12, RegisterReadWriteMode>;
};
struct RDRREG : RegisterBase<addr_ + 0x24, RegisterReadMode> {
using RDR = RegisterField<UartBase::RDRREG, 0, 9, RegisterReadMode>;
};
struct TDRREG : RegisterBase<addr_ + 0x28, RegisterReadWriteMode> {
using TDR = RegisterField<UartBase::TDRREG, 0, 9, RegisterReadWriteMode>;
};
struct ISR : RegisterBase<addr_ + 0x1c, RegisterReadMode> {
using PE = RegisterField<UartBase::ISR, 0, 1, RegisterReadMode>;
using FE = RegisterField<UartBase::ISR, 1, 1, RegisterReadMode>;
using NF = RegisterField<UartBase::ISR, 2, 1, RegisterReadMode>;
using ORE = RegisterField<UartBase::ISR, 3, 1, RegisterReadMode>;
using IDLE = RegisterField<UartBase::ISR, 4, 1, RegisterReadMode>;
using RXNE = RegisterField<UartBase::ISR, 5, 1, RegisterReadMode>;
using TC = RegisterField<UartBase::ISR, 6, 1, RegisterReadMode>;
using TXE = RegisterField<UartBase::ISR, 7, 1, RegisterReadMode>;
using LBDF = RegisterField<UartBase::ISR, 8, 1, RegisterReadMode>;
using CTSIF = RegisterField<UartBase::ISR, 9, 1, RegisterReadMode>;
using CTS = RegisterField<UartBase::ISR, 10, 1, RegisterReadMode>;
using RTOF = RegisterField<UartBase::ISR, 11, 1, RegisterReadMode>;
using EOBF = RegisterField<UartBase::ISR, 12, 1, RegisterReadMode>;
using ABRE = RegisterField<UartBase::ISR, 14, 1, RegisterReadMode>;
using ABRF = RegisterField<UartBase::ISR, 15, 1, RegisterReadMode>;
using BUSY = RegisterField<UartBase::ISR, 16, 1, RegisterReadMode>;
using CMF = RegisterField<UartBase::ISR, 17, 1, RegisterReadMode>;
using SBKF = RegisterField<UartBase::ISR, 18, 1, RegisterReadMode>;
using RWU = RegisterField<UartBase::ISR, 19, 1, RegisterReadMode>;
using WUF = RegisterField<UartBase::ISR, 20, 1, RegisterReadMode>;
using TEACK = RegisterField<UartBase::ISR, 21, 1, RegisterReadMode>;
using REACK = RegisterField<UartBase::ISR, 22, 1, RegisterReadMode>;
};
/* Only for oversampling 16 */
static inline void SetFrequency(uint32_t baudrate) {
BRR::BRR16::Set(APBClock / baudrate);
}
static inline void Config(uint32_t baudrate, StopBits stop, WordLength length, PinType type) {
/* Enable clock for USART and tx and rx PORT */
ClockPack<typename rx::PinPort::Clock, typename tx::PinPort::Clock>::Enable();
ClockPack<clock>::Enable();
PinPack<rx, tx>::Config(modeAlternate, speedMid);
rx::SetAlternateFunction(rxaf);
tx::SetAlternateFunction(txaf);
CR1::Set(0);
CR2::Set(0);
CR3::Set(0);
PinPack<rx, tx>::SetOutputType(type);
/* If type and open-drain, then USART is configured in half-duplex mode */
if (type == typeOpdr) {
CR3::HDSEL::Set(1);
}
SetFrequency(baudrate);
CR1::UE::Set(1);
/* Configure word length and number of stop bits */
RegisterFieldPack<typename CR1::M0, typename CR1::M1>::Set(CR1::M0::GetIndividualValue(length & 1) |
CR1::M1::GetIndividualValue((length >> 1) & 1));
RegisterFieldPack<typename CR2::STOP>::Set(CR2::STOP::GetIndividualValue(stop));
/* Enable USART, transmitter and receiver */
}
static void PutChar(char tosend) {
TDRREG::TDR::Set(tosend);
/* Todo: implement timeout */
while (ISR::TC::Get() != 1)
;
}
static char GetChar() {
while (ISR::RXNE::Get() != 1)
;
return RDRREG::RDR::Get();
}
static void Print(const char *s) {
while (*s) {
PutChar(*s++);
}
}
};
} // namespace JL
| 48.183246
| 120
| 0.693144
|
serjzimmerman
|
ae3cec7f20f8fdb8d588ff4460e5e882697b33d1
| 9,676
|
cpp
|
C++
|
src/modules/hip/kernel/median_filter.cpp
|
shobana-mcw/rpp
|
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
|
[
"MIT"
] | 26
|
2019-09-04T17:48:41.000Z
|
2022-02-23T17:04:24.000Z
|
src/modules/hip/kernel/median_filter.cpp
|
shobana-mcw/rpp
|
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
|
[
"MIT"
] | 57
|
2019-09-06T21:37:34.000Z
|
2022-03-09T02:13:46.000Z
|
src/modules/hip/kernel/median_filter.cpp
|
shobana-mcw/rpp
|
e4a5eb622b9abd0a5a936bf7174a84a5e2470b59
|
[
"MIT"
] | 24
|
2019-09-04T23:12:07.000Z
|
2022-03-30T02:06:22.000Z
|
#include <hip/hip_runtime.h>
#include "rpp_hip_host_decls.hpp"
#define saturate_8u(value) ((value) > 255 ? 255 : ((value) < 0 ? 0 : (value)))
#define SIZE 7*7
extern "C" __global__ void median_filter_pkd(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned int kernelSize)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
if (id_x >= width || id_y >= height || id_z >= channel)
{
return;
}
int c[SIZE];
int counter = 0;
int pixIdx = id_y * channel * width + id_x * channel + id_z;
int bound = (kernelSize - 1) / 2;
for(int i = -bound ; i <= bound; i++)
{
for(int j = -bound; j <= bound; j++)
{
if(id_x + j >= 0 && id_x + j <= width - 1 && id_y + i >= 0 && id_y + i <= height - 1)
{
unsigned int index = pixIdx + (j * channel) + (i * width * channel);
c[counter] = input[index];
}
else
{
c[counter] = 0;
counter++;
}
}
}
int pos;
int max = 0;
for (int i = 0; i < counter; i++)
{
for (int j = i; j < counter; j++)
{
if (max < c[j])
{
max = c[j];
pos = j;
}
}
max = 0;
int temp = c[pos];
c[pos] = c[i];
c[i] = temp;
}
counter = kernelSize * bound + bound + 1;
output[pixIdx] = c[counter];
}
extern "C" __global__ void median_filter_pln(unsigned char *input,
unsigned char *output,
const unsigned int height,
const unsigned int width,
const unsigned int channel,
const unsigned int kernelSize)
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
if (id_x >= width || id_y >= height || id_z >= channel)
{
return;
}
int c[SIZE];
int counter = 0;
int pixIdx = id_y * width + id_x + id_z * width * height;
int bound = (kernelSize - 1) / 2;
unsigned char pixel = input[pixIdx];
for(int i = -bound; i <= bound; i++)
{
for(int j = -bound; j <= bound; j++)
{
if(id_x + j >= 0 && id_x + j <= width - 1 && id_y + i >= 0 && id_y + i <= height - 1)
{
unsigned int index = pixIdx + j + (i * width);
c[counter] = input[index];
}
else
{
c[counter] = 0;
counter++;
}
}
}
int pos;
int max = 0;
for (int i = 0; i < counter; i++)
{
for (int j = i; j < counter; j++)
{
if (max < c[j])
{
max = c[j];
pos = j;
}
}
max = 0;
int temp = c[pos];
c[pos] = c[i];
c[i] = temp;
}
counter = kernelSize * bound + bound + 1;
output[pixIdx] = c[counter];
}
extern "C" __global__ void median_filter_batch(unsigned char *input,
unsigned char *output,
unsigned int *kernelSize,
unsigned int *xroi_begin,
unsigned int *xroi_end,
unsigned int *yroi_begin,
unsigned int *yroi_end,
unsigned int *height,
unsigned int *width,
unsigned int *max_width,
unsigned long long *batch_index,
const unsigned int channel,
unsigned int *inc, // use width * height for pln and 1 for pkd
const int plnpkdindex) // use 1 pln 3 for pkd
{
int id_x = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
int id_y = hipBlockIdx_y * hipBlockDim_y + hipThreadIdx_y;
int id_z = hipBlockIdx_z * hipBlockDim_z + hipThreadIdx_z;
unsigned char valuer, valuer1, valueg, valueg1, valueb, valueb1;
int kernelSizeTemp = kernelSize[id_z];
int indextmp = 0;
long pixIdx = 0;
int temp;
// printf("%d", id_x);
int value = 0;
int value1 = 0;
int counter = 0;
int r[SIZE], g[SIZE], b[SIZE], maxR = 0, maxG = 0, maxB = 0, posR, posG, posB;
int bound = (kernelSizeTemp - 1) / 2;
pixIdx = batch_index[id_z] + (id_x + id_y * max_width[id_z]) * plnpkdindex;
if((id_y >= yroi_begin[id_z]) && (id_y <= yroi_end[id_z]) && (id_x >= xroi_begin[id_z]) && (id_x <= xroi_end[id_z]))
{
for(int i = -bound; i <= bound; i++)
{
for(int j = -bound; j <= bound; j++)
{
if(id_x + j >= 0 && id_x + j <= width[id_z] - 1 && id_y + i >= 0 && id_y + i <= height[id_z] - 1)
{
unsigned int index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex;
r[counter] = input[index];
if(channel == 3)
{
index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex + inc[id_z];
g[counter] = input[index];
index = pixIdx + (j + (i * max_width[id_z])) * plnpkdindex + inc[id_z] * 2;
b[counter] = input[index];
}
}
else
{
r[counter] = 0;
if(channel == 3)
{
g[counter] = 0;
b[counter] = 0;
}
}
counter++;
}
}
for (int i = 0; i < counter; i++)
{
posB = i;
posG = i;
posR = i;
for (int j = i; j < counter; j++)
{
if (maxR < r[j])
{
maxR = r[j];
posR = j;
}
if (maxG < g[j])
{
maxG = g[j];
posG = j;
}
if (maxB < b[j])
{
maxB = b[j];
posB = j;
}
}
maxR = 0;
maxG = 0;
maxB = 0;
int temp;
temp = r[posR];
r[posR] = r[i];
r[i] = temp;
temp = g[posG];
g[posG] = g[i];
g[i] = temp;
temp = b[posB];
b[posB] = b[i];
b[i] = temp;
}
counter = kernelSizeTemp * bound + bound + 1;
output[pixIdx] = r[counter];
if(channel == 3)
{
output[pixIdx + inc[id_z]] = g[counter];
output[pixIdx + inc[id_z] * 2] = b[counter];
}
}
else if((id_x < width[id_z]) && (id_y < height[id_z]))
{
for(indextmp = 0; indextmp < channel; indextmp++)
{
output[pixIdx] = input[pixIdx];
pixIdx += inc[id_z];
}
}
}
RppStatus hip_exec_median_filter_batch(Rpp8u *srcPtr, Rpp8u *dstPtr, rpp::Handle& handle, RppiChnFormat chnFormat, Rpp32u channel, Rpp32s plnpkdind, Rpp32u max_height, Rpp32u max_width)
{
int localThreads_x = 32;
int localThreads_y = 32;
int localThreads_z = 1;
int globalThreads_x = (max_width + 31) & ~31;
int globalThreads_y = (max_height + 31) & ~31;
int globalThreads_z = handle.GetBatchSize();
hipLaunchKernelGGL(median_filter_batch,
dim3(ceil((float)globalThreads_x/localThreads_x), ceil((float)globalThreads_y/localThreads_y), ceil((float)globalThreads_z/localThreads_z)),
dim3(localThreads_x, localThreads_y, localThreads_z),
0,
handle.GetStream(),
srcPtr,
dstPtr,
handle.GetInitHandle()->mem.mgpu.uintArr[0].uintmem,
handle.GetInitHandle()->mem.mgpu.roiPoints.x,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiWidth,
handle.GetInitHandle()->mem.mgpu.roiPoints.y,
handle.GetInitHandle()->mem.mgpu.roiPoints.roiHeight,
handle.GetInitHandle()->mem.mgpu.srcSize.height,
handle.GetInitHandle()->mem.mgpu.srcSize.width,
handle.GetInitHandle()->mem.mgpu.maxSrcSize.width,
handle.GetInitHandle()->mem.mgpu.srcBatchIndex,
channel,
handle.GetInitHandle()->mem.mgpu.inc,
plnpkdind);
return RPP_SUCCESS;
}
| 35.185455
| 185
| 0.423625
|
shobana-mcw
|
ae4e5b3ae84f0a27adcc7442fc4f8cd1a6f576eb
| 3,660
|
cpp
|
C++
|
Haru/hpdf/hpdf_image.cpp
|
miyako/4d-plugin-haru
|
749599d7ec9f21a2071ebef3859eb3fce8c59754
|
[
"MIT"
] | null | null | null |
Haru/hpdf/hpdf_image.cpp
|
miyako/4d-plugin-haru
|
749599d7ec9f21a2071ebef3859eb3fce8c59754
|
[
"MIT"
] | 1
|
2020-02-13T03:34:38.000Z
|
2020-06-01T21:08:11.000Z
|
Haru/hpdf/hpdf_image.cpp
|
miyako/4d-plugin-haru
|
749599d7ec9f21a2071ebef3859eb3fce8c59754
|
[
"MIT"
] | 2
|
2016-06-07T08:28:17.000Z
|
2016-08-03T10:53:05.000Z
|
#include "hpdf_image.h"
// ------------------------------------- Image ------------------------------------
void PDF_Image_AddSMask(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_TEXT Param2;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
Param2.fromParamAtIndex(pParams, 2);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
HPDF_Image smask = (HPDF_Image)_fromHex(Param2);
returnValue.setIntValue(HPDF_Image_AddSMask(image, smask));
returnValue.setReturn(pResult);
}
void PDF_Image_GetSize(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_REAL Param2;
C_REAL Param3;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
HPDF_Point size;
returnValue.setIntValue(HPDF_Image_GetSize2(image, &size));
Param2.setDoubleValue(size.x);
Param3.setDoubleValue(size.y);
Param2.toParamAtIndex(pParams, 2);
Param3.toParamAtIndex(pParams, 3);
returnValue.setReturn(pResult);
}
void PDF_Image_GetWidth(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
returnValue.setIntValue(HPDF_Image_GetWidth(image));
returnValue.setReturn(pResult);
}
void PDF_Image_GetHeight(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
returnValue.setIntValue(HPDF_Image_GetHeight(image));
returnValue.setReturn(pResult);
}
void PDF_Image_GetBitsPerComponent(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
returnValue.setIntValue(HPDF_Image_GetBitsPerComponent(image));
returnValue.setReturn(pResult);
}
void PDF_Image_GetColorSpace(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_TEXT returnValue;
Param1.fromParamAtIndex(pParams, 1);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
CUTF8String u = CUTF8String((const uint8_t *)HPDF_Image_GetColorSpace(image));
returnValue.setUTF8String(&u);
returnValue.setReturn(pResult);
}
void PDF_Image_SetColorMask(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_LONGINT Param2;
C_LONGINT Param3;
C_LONGINT Param4;
C_LONGINT Param5;
C_LONGINT Param6;
C_LONGINT Param7;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
Param2.fromParamAtIndex(pParams, 2);
Param3.fromParamAtIndex(pParams, 3);
Param4.fromParamAtIndex(pParams, 4);
Param5.fromParamAtIndex(pParams, 5);
Param6.fromParamAtIndex(pParams, 6);
Param7.fromParamAtIndex(pParams, 7);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
HPDF_UINT rmin = (HPDF_UINT)Param2.getIntValue();
HPDF_UINT rmax = (HPDF_UINT)Param3.getIntValue();
HPDF_UINT gmin = (HPDF_UINT)Param4.getIntValue();
HPDF_UINT gmax = (HPDF_UINT)Param5.getIntValue();
HPDF_UINT bmin = (HPDF_UINT)Param6.getIntValue();
HPDF_UINT bmax = (HPDF_UINT)Param7.getIntValue();
returnValue.setIntValue(HPDF_Image_SetColorMask(image, rmin, rmax, gmin, gmax, bmin, bmax));
returnValue.setReturn(pResult);
}
void PDF_Image_SetMaskImage(sLONG_PTR *pResult, PackagePtr pParams)
{
C_TEXT Param1;
C_TEXT Param2;
C_LONGINT returnValue;
Param1.fromParamAtIndex(pParams, 1);
Param2.fromParamAtIndex(pParams, 2);
HPDF_Image image = (HPDF_Image)_fromHex(Param1);
HPDF_Image mask_image = (HPDF_Image)_fromHex(Param2);
returnValue.setIntValue(HPDF_Image_SetMaskImage(image, mask_image));
returnValue.setReturn(pResult);
}
| 24.4
| 93
| 0.764208
|
miyako
|
ae5289e95ee89e9358178fefeafc955aca22fb10
| 11,663
|
cpp
|
C++
|
Computer Graphics/src/scene_texture.cpp
|
sergio5405/Computer-Graphics-Project
|
829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc
|
[
"MIT"
] | null | null | null |
Computer Graphics/src/scene_texture.cpp
|
sergio5405/Computer-Graphics-Project
|
829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc
|
[
"MIT"
] | null | null | null |
Computer Graphics/src/scene_texture.cpp
|
sergio5405/Computer-Graphics-Project
|
829cd1f25caaa88070a0aeccd2b7cdcb5007fbcc
|
[
"MIT"
] | null | null | null |
#include "scene_texture.h"
#include "ifile.h"
#include "time.h"
#include "cgmath.h"
#include "vec2.h"
#include "vec3.h"
#include "mat3.h"
#include "mat4.h"
#include <string>
#include <vector>
scene_texture::~scene_texture() {
glDeleteProgram(shader_program);
}
void scene_texture::init() {
std::vector<cgmath::vec3> positions;
//Front
positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f));
//Top
positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f));
//Right
positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, 3.0f));
//Left
positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f));
//Down
positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, -3.0f, 3.0f));
positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(-3.0f, -3.0f, 3.0f));
//Back
positions.push_back(cgmath::vec3(-3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(-3.0f, 3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, -3.0f, -3.0f));
positions.push_back(cgmath::vec3(3.0f, 3.0f, -3.0f));
std::vector<unsigned int> indices{ 0, 1, 2, //front
1, 3, 2,
4, 5, 6, //top
5, 7, 6,
8, 9, 10, //right
9, 11, 10,
12, 13, 14, //left
13, 15, 14,
16, 17, 18, //down
17, 19, 18,
20, 21, 22, //back
21, 23, 22
};
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glGenBuffers(1, &positionsVBO);
glBindBuffer(GL_ARRAY_BUFFER, positionsVBO);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cgmath::vec3) * positions.size(),
positions.data(),
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glGenBuffers(1, &positionsIndicesBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, positionsIndicesBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(unsigned int) * indices.size(),
indices.data(),
GL_STATIC_DRAW);
std::vector<cgmath::vec3> colors;
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(1.0f, 0.0f, 0.0f));//red
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(0.0f, 1.0f, 0.0f));//green
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(0.0f, 0.0f, 1.0f));//blue
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(1.0f, 0.0f, 1.0f));//pink
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(1.0f, 1.0f, 0.0f));//yellow
for (int i = 0; i < 4; i++)
colors.push_back(cgmath::vec3(0.0f, 1.0f, 1.0f));//cyan
//std::vector<unsigned int> indicesColors{ 0, 0, 0, 0, 0, 0, //front
// 1, 1, 1, 1, 1, 1, //top
// 2, 2, 2, 2, 2, 2, //right
// 3, 3, 3, 3, 3, 3, //left
// 4, 4, 4, 4, 4, 4, //down
// 5, 5, 5, 5, 5, 5, //back
//};
glGenBuffers(1, &colorBuffer);
glBindBuffer(GL_ARRAY_BUFFER, colorBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cgmath::vec3) * colors.size(),
colors.data(),
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
/*glGenBuffers(1, &indicesColorBuffer);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indicesColorBuffer);
glBufferData(GL_ELEMENT_ARRAY_BUFFER,
sizeof(unsigned int) * indicesColors.size(),
indicesColors.data(),
GL_STATIC_DRAW);
glBindVertexArray(0);*/
std::vector<cgmath::vec3> normals;
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(0.0f, 0.0f, 1.0f));//front
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(0.0f, 1.0f, 0.0f));//top
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(1.0f, 0.0f, 0.0f));//right
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(-1.0f, 0.0f, 0.0f));//left
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(0.0f, -1.0f, 0.0f));//down
for (int i = 0; i < 4; i++)
normals.push_back(cgmath::vec3(0.0f, 0.0f, -1.0f));//back
glGenBuffers(1, &normalBuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cgmath::vec3) * normals.size(),
normals.data(),
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
std::vector<cgmath::vec2> texCoords;
for (int i = 0; i < 6; i++) {
texCoords.push_back(cgmath::vec2(1.0f, 0.0f));
texCoords.push_back(cgmath::vec2(1.0f, 1.0f));
texCoords.push_back(cgmath::vec2(0.0f, 0.0f));
texCoords.push_back(cgmath::vec2(0.0f, 1.0f));
}
glGenBuffers(1, &texCoordsBuffer);
glBindBuffer(GL_ARRAY_BUFFER, texCoordsBuffer);
glBufferData(GL_ARRAY_BUFFER,
sizeof(cgmath::vec2) * texCoords.size(),
texCoords.data(),
GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
ilGenImages(1, &pigImageId);
ilBindImage(pigImageId);
ilLoadImage("images/pig.png");
glGenTextures(2, textureId);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId[0]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,
0,
ilGetInteger(IL_IMAGE_FORMAT),
ilGetInteger(IL_IMAGE_WIDTH),
ilGetInteger(IL_IMAGE_HEIGHT),
0,
ilGetInteger(IL_IMAGE_FORMAT),
ilGetInteger(IL_IMAGE_TYPE),
ilGetData());
glGenerateMipmap(GL_TEXTURE_2D);
ilDeleteImages(1, &pigImageId);
ILenum Error;
while ((Error = ilGetError()) != IL_NO_ERROR) {
printf("%d: /n", Error);
}
ilGenImages(1, &crateImageId);
ilBindImage(crateImageId);
ilLoadImage("images/crate.png");
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureId[1]);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D,
0,
ilGetInteger(IL_IMAGE_FORMAT),
ilGetInteger(IL_IMAGE_WIDTH),
ilGetInteger(IL_IMAGE_HEIGHT),
0,
ilGetInteger(IL_IMAGE_FORMAT),
ilGetInteger(IL_IMAGE_TYPE),
ilGetData());
glGenerateMipmap(GL_TEXTURE_2D);
ilDeleteImages(1, &crateImageId);
while ((Error = ilGetError()) != IL_NO_ERROR) {
printf("%d: /n", Error);
}
glBindTexture(GL_TEXTURE_2D, 0);
ifile shader_file;
shader_file.read("shaders/cubeTex.vert");
std::string vertex_source = shader_file.get_contents();
const GLchar* vertex_source_c = (const GLchar*)vertex_source.c_str();
GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_source_c, nullptr);
glCompileShader(vertex_shader);
GLint Result = GL_FALSE;
int InfoLogLength;
// Check Vertex Shader
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &Result);
glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0) {
std::vector<char> VertexShaderErrorMessage(InfoLogLength + 1);
glGetShaderInfoLog(vertex_shader, InfoLogLength, NULL, &VertexShaderErrorMessage[0]);
printf("%s\n", &VertexShaderErrorMessage[0]);
}
shader_file.read("shaders/cubeColorsTex.frag");
std::string fragment_source = shader_file.get_contents();
const GLchar* fragment_source_c = (const GLchar*)fragment_source.c_str();
GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &fragment_source_c, nullptr);
glCompileShader(fragment_shader);
Result = GL_FALSE;
InfoLogLength;
// Check Frag Shader
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &Result);
glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &InfoLogLength);
if (InfoLogLength > 0) {
std::vector<char> FragShaderErrorMessage(InfoLogLength + 1);
glGetShaderInfoLog(fragment_shader, InfoLogLength, NULL, &FragShaderErrorMessage[0]);
printf("%s\n", &FragShaderErrorMessage[0]);
}
shader_program = glCreateProgram();
glAttachShader(shader_program, vertex_shader);
glAttachShader(shader_program, fragment_shader);
glBindAttribLocation(shader_program, 0, "VertexPosition");
glBindAttribLocation(shader_program, 1, "Color");
glBindAttribLocation(shader_program, 2, "VertexNormal");
glBindAttribLocation(shader_program, 3, "TexC");
glLinkProgram(shader_program);
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
glUseProgram(0);
}
void scene_texture::awake() {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glEnable(GL_PROGRAM_POINT_SIZE);
}
void scene_texture::sleep() {
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glDisable(GL_PROGRAM_POINT_SIZE);
}
void scene_texture::mainLoop() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shader_program);
float t = time::elapsed_time().count();
////Vmath library from http://www.openglsuperbible.com/example-code/
//Model matrix
cgmath::mat4 rotationMatrix = cgmath::mat4::rotateMatrix(t*30.0f, t*60.0f, t*30.0f);
cgmath::mat4 modelMatrix = rotationMatrix;
// View Matrix
cgmath::mat4 viewMatrix(1.0f);
viewMatrix[3][2] = 20.0f;
viewMatrix = cgmath::mat4::inverse(viewMatrix);
// Projection Matrix
float far = 1000.0f;
float near = 1.0f;
float half_fov = cgmath::radians(30.0f);
cgmath::mat4 projectionMatrix;
projectionMatrix[0][0] = 1.0f / (1.0f * tan(half_fov));
projectionMatrix[1][1] = 1.0f / tan(half_fov);
projectionMatrix[2][2] = -((far + near) / (far - near));
projectionMatrix[2][3] = -1.0f;
projectionMatrix[3][2] = -((2 * far * near) / (far - near));
cgmath::mat4 mvpMatrix = projectionMatrix * viewMatrix * modelMatrix;
cgmath::mat3 esqSupIzq = cgmath::mat3();
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
esqSupIzq[i][j] = modelMatrix[i][j];
cgmath::mat3 normalMatrix = cgmath::mat3::transpose(cgmath::mat3::inverse(esqSupIzq));
GLuint mvp_location = glGetUniformLocation(shader_program, "MVPMatrix");
glUniformMatrix4fv(mvp_location, 1, GL_FALSE, &mvpMatrix[0][0]);
GLuint normal_location = glGetUniformLocation(shader_program, "NormalMatrix");
glUniformMatrix3fv(normal_location, 1, GL_FALSE, &normalMatrix[0][0]);
GLuint model_location = glGetUniformLocation(shader_program, "ModelMatrix");
glUniformMatrix4fv(model_location, 1, GL_FALSE, &modelMatrix[0][0]);
cgmath::vec3 lightVector = cgmath::vec3(-3, 6, 10);
GLuint light_location = glGetUniformLocation(shader_program, "LightPosition");
glUniform3fv(light_location, 1, &lightVector[0]);
cgmath::vec3 cameraPos = cgmath::vec3(0, 0, 10);
GLuint camera_loc = glGetUniformLocation(shader_program, "CameraPosition");
glUniform3fv(camera_loc, 1, &cameraPos[0]);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, textureId[0]);
GLint pig_tex_location = glGetUniformLocation(shader_program, "PigTex");
glUniform1i(pig_tex_location, 0);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, textureId[1]);
GLint crate_tex_location = glGetUniformLocation(shader_program, "CrateTex");
glUniform1i(crate_tex_location, 1);
glBindVertexArray(vao);
glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, nullptr);
glBindVertexArray(0);
glUseProgram(0);
}
void scene_texture::resize(int width, int height) {
glViewport(0, 0, width, height);
}
| 32.307479
| 87
| 0.717311
|
sergio5405
|
ae5b4d125742c200e4661b8418e7cdd46ff338a4
| 958
|
hpp
|
C++
|
fsc/include/fsx/sim_event.hpp
|
gbucknell/fsc-sdk
|
11b7cda4eea35ec53effbe37382f4b28020cd59d
|
[
"MIT"
] | null | null | null |
fsc/include/fsx/sim_event.hpp
|
gbucknell/fsc-sdk
|
11b7cda4eea35ec53effbe37382f4b28020cd59d
|
[
"MIT"
] | null | null | null |
fsc/include/fsx/sim_event.hpp
|
gbucknell/fsc-sdk
|
11b7cda4eea35ec53effbe37382f4b28020cd59d
|
[
"MIT"
] | null | null | null |
// (c) Copyright 2008 Samuel Debionne.
//
// Distributed under the MIT Software License. (See accompanying file
// license.txt) or copy at http://www.opensource.org/licenses/mit-license.php)
//
// See http://code.google.com/p/fsc-sdk/ for the library home page.
//
// $Revision: $
// $History: $
/// \file sim_event.hpp
/// Events of the Sim Connect API
#if !defined(__FSX_SIM_EVENT_HPP__)
#define __FSX_SIM_EVENT_HPP__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <cassert>
#include <windows.h>
#include <SimConnect.h>
namespace fsx {
/// Sim connect event.
class sim_event
{
public:
sim_event(SIMCONNECT_CLIENT_EVENT_ID _id, const DWORD& _data) : id_(_id), data_(_data) {}
private:
SIMCONNECT_CLIENT_EVENT_ID id_;
DWORD data_;
};
//template <class T>
//struct sim_data_traits
//{
// int
//};
} //namespace fsx
#endif //__FSX_SIM_EVENT_HPP__
| 17.418182
| 94
| 0.656576
|
gbucknell
|
ae609a38d49a1719bae957c603e67db286fac184
| 20,403
|
cpp
|
C++
|
hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp
|
MoritzNegwer/vaa3d_tools
|
bdb2dc95bc13e9a31e1d416cc341c00d97153968
|
[
"MIT"
] | null | null | null |
hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp
|
MoritzNegwer/vaa3d_tools
|
bdb2dc95bc13e9a31e1d416cc341c00d97153968
|
[
"MIT"
] | null | null | null |
hackathon/XuanZhao/TraceNeuronBasedLine/branchtree.cpp
|
MoritzNegwer/vaa3d_tools
|
bdb2dc95bc13e9a31e1d416cc341c00d97153968
|
[
"MIT"
] | null | null | null |
#include "branchtree.h"
#include <queue>
void adjustRalationForSplitBranches(Branch *origin, vector<Branch *> target) {
target.front()->parent = origin->parent;
if (origin->parent) {
auto it = origin->parent->children.begin();
for (; it != origin->parent->children.end(); ++it) {
if (*it == origin) {
origin->parent->children.erase(it);
break;
}
}
origin->parent->children.push_back(target.front());
}
for (int k = 1; k < target.size(); ++k) {
target[k]->parent = target[k - 1];
target[k - 1]->children.push_back(target[k]);
}
target.back()->children = origin->children;
for (Branch* child : origin->children) {
child->parent = target.back();
}
}
void adjustRalationForRemoveBranch(Branch *origin) {
if (origin->parent) {
auto it = origin->parent->children.begin();
for (; it != origin->parent->children.end(); ++it) {
if (*it == origin) {
origin->parent->children.erase(it);
break;
}
}
}
for (Branch* child : origin->children) {
if (origin->parent) {
origin->parent->children.push_back(child);
}
child->parent = origin->parent;
}
}
void PointFeature::getFeature(unsigned char *pdata, long long *sz, float x, float y, float z) {
this->x = x;
this->y = y;
this->z = z;
double *vec1 = new double[3];
double *vec2 = new double[3];
double *vec3 = new double[3];
double pc1, pc2, pc3;
int xx = x + 0.5, yy = y + 0.5, zz = z + 0.5;
xx = xx >= sz[0] ? sz[0] - 1 : xx;
xx = xx < 0 ? 0 : xx;
yy = yy >= sz[1] ? sz[1] - 1 : yy;
yy = yy < 0 ? 0 : yy;
zz = zz >= sz[2] ? sz[2] - 1 : zz;
zz = zz < 0 ? 0 : zz;
this->intensity = pdata[zz * sz[0]* sz[1] + yy * sz[0] + xx];
computeCubePcaEigVec(pdata, sz, xx, yy, zz, 3, 3, 3, pc1, pc2, pc3, vec1, vec2, vec3);
this->linearity_3 = pc2 == 0 ? 0 : pc1 / pc2;
computeCubePcaEigVec(pdata, sz, xx, yy, zz, 5, 5, 5, pc1, pc2, pc3, vec1, vec2, vec3);
this->linearity_5 = pc2 == 0 ? 0 : pc1 / pc2;
computeCubePcaEigVec(pdata, sz, xx, yy, zz, 8, 8, 8, pc1, pc2, pc3, vec1, vec2, vec3);
this->linearity_8 = pc2 == 0 ? 0 : pc1 / pc2;
if (x < 5 || x > sz[0] -5 ||
y < 5 || y > sz[1] - 5 ||
z < 5 || z > sz[2] - 5) {
this->nearEdge = 1;
} else {
this->nearEdge = 0;
}
if(vec1){
delete[] vec1; vec1 = 0;
}
if(vec2){
delete[] vec2; vec2 = 0;
}
if(vec3){
delete[] vec3; vec3 = 0;
}
}
void LineFeature::intial() {
this->pointsFeature.clear();
this->pointsFeature = vector<PointFeature>(5);
this->directions.clear();
this->directions = vector<XYZ>(5, XYZ());
this->intensity_mean = this->intensity_std = 0;
this->intensity_mean_r5 = this->intensity_std_r5 = 0;
this->linearity_3_mean = this->linearity_5_mean = this->linearity_8_mean = 0;
}
vector<Branch*> Branch::splitByInflectionPoint(float d, float cosAngleThres) {
vector<Branch*> results;
int pointSize = this->points.size();
float* path = new float[pointSize];
memset(path, 0, sizeof(float) * pointSize);
if (pointSize < 2) {
results.push_back(this);
return results;
}
for (int i = 1; i < pointSize; ++i) {
float tmpD = zx_dist(this->points[i], this->points[i - 1]);
path[i] = path[i-1] + tmpD;
}
XYZ v1,v2;
XYZ p1,p2;
p1 = XYZ(this->points[0].x, this->points[0].y, this->points[0].z);
float cosAngle;
int startPoint = 0;
int i,j,k;
int ppIndex,ccIndex,curIndex;
XYZ pp1,pp2;
float inflectionPointCosAngle;
int inflectionPointIndex = -1;
for (i = 0; i < pointSize;) {
for (j = i+1; j < pointSize; ++j) {
if (path[j] - path[i] > d) {
p2 = XYZ(this->points[j].x, this->points[j].y, this->points[j].z);
if (i == startPoint) {
v1 = p2 - p1;
} else {
v2 = p2 - p1;
cosAngle = dot(normalize(v1), normalize(v2));
if (cosAngle < cosAngleThres) {
inflectionPointCosAngle = 1;
inflectionPointIndex = -1;
for (k = startPoint + 1; k < j; ++k) {
if ((path[k] - path[startPoint]) < d || (path[j] - path[k]) < d) {
continue;
}
curIndex = k;
ppIndex = startPoint;
ccIndex = j;
for (int ki = k - 1; ki >= startPoint; --ki) {
if (path[k] - path[ki] > d) {
ppIndex = ki;
break;
}
}
for (int ki = k + 1; ki <= j; ++ki) {
if (path[ki] - path[k] > d) {
ccIndex = ki;
break;
}
}
pp1 = XYZ(this->points[ppIndex].x, this->points[ppIndex].y, this->points[ppIndex].z);
pp2 = XYZ(this->points[ccIndex].x, this->points[ccIndex].y, this->points[ccIndex].z);
double tmpCosAngle = dot(normalize(pp1), normalize(pp2));
if (tmpCosAngle < inflectionPointCosAngle) {
inflectionPointCosAngle = tmpCosAngle;
inflectionPointIndex = k;
}
}
if(cosAngle > (sqrt(2.0)/2) || inflectionPointIndex == -1){
inflectionPointIndex = (j + startPoint) / 2;
}
Branch* line = new Branch();
for (k = startPoint; k <= inflectionPointIndex; ++k) {
line->points.push_back(this->points[k]);
}
results.push_back(line);
startPoint = j;
}
}
p1 = p2;
break;
}
}
i = j;
}
if (startPoint == 0) {
results.push_back(this);
return results;
} else {
Branch* line = new Branch();
for (k = inflectionPointIndex; k < pointSize; ++k) {
line->points.push_back(this->points[k]);
}
results.push_back(line);
}
adjustRalationForSplitBranches(this, results);
return results;
}
vector<Branch*> Branch::splitByLength(float l_thres) {
vector<Branch*> results;
this->calLength();
if (this->length < l_thres) {
results.push_back(this);
return results;
}
int length_mean = this->length / ceil(this->length / l_thres);
int count_i = 1;
float path_length = 0;
int start_index = 0;
for (int i = 1; i<this->points.size() - 1; ++i) {
path_length += zx_dist(this->points[i], this->points[i - 1]);
if (path_length > length_mean * count_i) {
Branch* branch = new Branch();
branch->points.insert(branch->points.end(), this->points.begin() + start_index, this->points.begin() + i + 1);
results.push_back(branch);
start_index = i;
count_i++;
}
}
Branch* branch = new Branch();
branch->points.insert(branch->points.end(), this->points.begin() + start_index, this->points.end());
results.push_back(branch);
adjustRalationForSplitBranches(this, results);
return results;
}
void Branch::removePointsNearSoma(const NeuronSWC &soma, float ratio) {
if (this->level > 2) {
return;
}
auto it = this->points.begin();
for (; it != this->points.end(); ) {
if (zx_dist(*it, soma) < soma.r * ratio) {
this->points.erase(it);
} else {
break;
}
}
}
void Branch::removeTerminalPoints(float d) {
auto it = this->points.begin();
float length = 0;
for (; it != this->points.end() - 1; ) {
if (length < d) {
length += zx_dist(*it, *(it + 1));
this->points.erase(it);
} else {
break;
}
}
it = this->points.end() - 1;
length = 0;
for (; it != this->points.begin(); ) {
if (length < d) {
length += zx_dist(*it, *(it - 1));
this->points.erase(it);
--it;
} else {
break;
}
}
}
float Branch::calLength() {
this->length = 0;
auto it = this->points.begin();
for(; it != this->points.end() - 1; ++it) {
this->length += zx_dist(*it, *(it + 1));
}
return this->length;
}
float Branch::calDistance() {
this->distance = this->points.size() ? zx_dist(this->points.front(), this->points.back()) : 0;
return this->distance;
}
void Branch::getFeature(unsigned char *pdata, long long *sz) {
this->line_feature.intial();
this->calLength();
this->calDistance();
int pointSize = this->points.size();
double *vec1 = new double[3];
double *vec2 = new double[3];
double *vec3 = new double[3];
int x,y,z;
double pc1,pc2,pc3;
vector<unsigned char> intensities;
this->line_feature.pointsFeature[0].getFeature(pdata, sz, this->points.front().x, this->points.front().y, this->points.front().z);
this->line_feature.intensity_mean += this->line_feature.pointsFeature.front().intensity;
intensities.push_back(this->line_feature.pointsFeature.front().intensity);
this->line_feature.linearity_3_mean += this->line_feature.pointsFeature.front().linearity_3;
this->line_feature.linearity_5_mean += this->line_feature.pointsFeature.front().linearity_5;
this->line_feature.linearity_8_mean += this->line_feature.pointsFeature.front().linearity_8;
int point_i = 1;
float cur_length = 0;
for (int i = 1; i < pointSize - 1; ++i) {
cur_length += zx_dist(this->points[i], this->points[i - 1]);
if (cur_length > this->length / 5 * point_i) {
this->line_feature.pointsFeature[point_i].getFeature(pdata, sz, this->points[i].x, this->points[i].y, this->points[i].z);
this->line_feature.intensity_mean += this->line_feature.pointsFeature[point_i].intensity;
intensities.push_back(this->line_feature.pointsFeature[point_i].intensity);
this->line_feature.linearity_3_mean += this->line_feature.pointsFeature[point_i].linearity_3;
this->line_feature.linearity_5_mean += this->line_feature.pointsFeature[point_i].linearity_5;
this->line_feature.linearity_8_mean += this->line_feature.pointsFeature[point_i].linearity_8;
point_i++;
} else {
x = this->points[i].x + 0.5;
y = this->points[i].y + 0.5;
z = this->points[i].z + 0.5;
x = x >= sz[0] ? sz[0] - 1 : x;
x = x < 0 ? 0 : x;
y = y >= sz[1] ? sz[1] - 1 : y;
y = y < 0 ? 0 : y;
z = z >= sz[2] ? sz[2] - 1 : z;
z = z < 0 ? 0 : z;
this->line_feature.intensity_mean += pdata[z * sz[0] * sz[1] + y * sz[0] + x];
intensities.push_back(pdata[z * sz[0] * sz[1] + y * sz[0] + x]);
computeCubePcaEigVec(pdata, sz, x, y, z, 3, 3, 3, pc1, pc2, pc3, vec1, vec2, vec3);
this->line_feature.linearity_3_mean += (pc2 == 0 ? 0 : pc1 / pc2);
computeCubePcaEigVec(pdata, sz, x, y, z, 5, 5, 5, pc1, pc2, pc3, vec1, vec2, vec3);
this->line_feature.linearity_5_mean += (pc2 == 0 ? 0 : pc1 / pc2);
computeCubePcaEigVec(pdata, sz, x, y, z, 8, 8, 8, pc1, pc2, pc3, vec1, vec2, vec3);
this->line_feature.linearity_8_mean += (pc2 == 0 ? 0 : pc1 / pc2);
}
}
this->line_feature.pointsFeature[4].getFeature(pdata, sz, this->points.back().x, this->points.back().y, this->points.back().z);
this->line_feature.intensity_mean += this->line_feature.pointsFeature.back().intensity;
intensities.push_back(this->line_feature.pointsFeature.front().intensity);
this->line_feature.linearity_3_mean += this->line_feature.pointsFeature.back().linearity_3;
this->line_feature.linearity_5_mean += this->line_feature.pointsFeature.back().linearity_5;
this->line_feature.linearity_8_mean += this->line_feature.pointsFeature.back().linearity_8;
this->line_feature.intensity_mean /= pointSize;
this->line_feature.linearity_3_mean /= pointSize;
this->line_feature.linearity_5_mean /= pointSize;
this->line_feature.linearity_8_mean /= pointSize;
for (auto intensity : intensities) {
this->line_feature.intensity_std += pow((intensity - this->line_feature.intensity_mean), 2);
}
this->line_feature.intensity_std = sqrt(this->line_feature.intensity_std / pointSize);
NeuronTree nt_r5;
for (NeuronSWC s : this->points) {
s.radius = 5;
nt_r5.listNeuron.push_back(s);
}
setNeuronTreeHash(nt_r5);
vector<MyMarker*> markers_r5 = swc_convert(nt_r5);
unsigned char* mask_r5 = 0;
swcTomask(mask_r5, markers_r5, sz[0], sz[1], sz[2]);
V3DLONG total_sz = sz[0] * sz[1] * sz[2];
intensities.clear();
// qDebug()<<"origin: "<<"r5_mean: "<<this->line_feature.intensity_mean_r5<<" r5_std: "<<this->line_feature.intensity_std_r5;
// qDebug()<<"intensity size: "<<intensities.size();
for (int i = 0; i < total_sz; ++i) {
if (mask_r5[i] > 0) {
this->line_feature.intensity_mean_r5 += pdata[i];
intensities.push_back(pdata[i]);
}
}
// qDebug()<<"after intensity size: "<<intensities.size();
if (intensities.size() > 0) {
this->line_feature.intensity_mean_r5 /= intensities.size();
}
for (auto intensity : intensities) {
this->line_feature.intensity_std_r5 += pow((intensity - this->line_feature.intensity_mean_r5), 2);
}
if (intensities.size() > 0) {
this->line_feature.intensity_std_r5 = sqrt(this->line_feature.intensity_std_r5 / intensities.size());
}
// qDebug()<<"r5_mean: "<<this->line_feature.intensity_mean_r5<<" r5_std: "<<this->line_feature.intensity_std_r5;
if (this->line_feature.pointsFeature.front().x > this->line_feature.pointsFeature.back().x) {
reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end());
} else if (this->line_feature.pointsFeature.front().x == this->line_feature.pointsFeature.back().x) {
if (this->line_feature.pointsFeature.front().y > this->line_feature.pointsFeature.back().y) {
reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end());
} else if (this->line_feature.pointsFeature.front().y == this->line_feature.pointsFeature.back().y){
if (this->line_feature.pointsFeature.front().z > this->line_feature.pointsFeature.back().z) {
reverse(this->line_feature.pointsFeature.begin(), this->line_feature.pointsFeature.end());
}
}
}
this->line_feature.directions[0] = XYZ(this->line_feature.pointsFeature.back().x - this->line_feature.pointsFeature.front().x,
this->line_feature.pointsFeature.back().y - this->line_feature.pointsFeature.front().y,
this->line_feature.pointsFeature.back().z - this->line_feature.pointsFeature.front().z);
for (int i = 1; i < this->line_feature.pointsFeature.size(); ++i) {
this->line_feature.directions[i] = XYZ(this->line_feature.pointsFeature[i].x - this->line_feature.pointsFeature[i - 1].x,
this->line_feature.pointsFeature[i].y - this->line_feature.pointsFeature[i - 1].y,
this->line_feature.pointsFeature[i].z - this->line_feature.pointsFeature[i - 1].z);
}
for (int i = 0; i < 5; ++i) {
normalize(this->line_feature.directions[i]);
}
}
bool BranchTree::initialize(NeuronTree &nt) {
this->branches.clear();
vector<V3DLONG> rootIndex = vector<V3DLONG>();
V3DLONG size = nt.listNeuron.size();
vector<vector<V3DLONG> > children = vector<vector<V3DLONG> >(size,vector<V3DLONG>());
for (V3DLONG i = 0; i < size; ++i) {
V3DLONG prt = nt.listNeuron[i].parent;
if (nt.hashNeuron.contains(prt)) {
V3DLONG prtIndex = nt.hashNeuron.value(prt);
children[prtIndex].push_back(i);
} else {
rootIndex.push_back(i);
}
}
queue<V3DLONG> q;
if (rootIndex.size() != 1) {
return false;
} else {
this->soma = nt.listNeuron[rootIndex.front()];
q.push(rootIndex.front());
if (soma.parent == -1) {
this->hasSoma = true;
} else {
this->hasSoma = false;
}
}
while (!q.empty()) {
V3DLONG tmp = q.front();
q.pop();
vector<V3DLONG>& child = children[tmp];
for(int i = 0; i < child.size(); ++i)
{
Branch* branch = new Branch();
int cIndex = child[i];
branch->points.push_back(nt.listNeuron[tmp]);
while(children[cIndex].size() == 1)
{
branch->points.push_back(nt.listNeuron[cIndex]);
cIndex = children[cIndex][0];
}
if(children.at(cIndex).size() >= 1)
{
q.push(cIndex);
}
branch->points.push_back(nt.listNeuron[cIndex]);
this->branches.push_back(branch);
}
}
//initial parent
for(int i = 0; i < this->branches.size(); ++i)
{
if(this->branches[i]->points.front().parent == this->soma.parent)
{
this->branches[i]->parent = nullptr;
}
else
{
for(int j = 0; j < this->branches.size(); ++j)
{
if(this->branches[i]->points.front().n == this->branches[j]->points.back().n)
{
this->branches[i]->parent = this->branches[j];
break;
}
}
}
}
//initial level
for(int i = 0; i < this->branches.size(); ++i)
{
Branch* branch = this->branches[i];
int level=0;
while(branch->parent != nullptr)
{
level++;
branch = branch->parent;
}
this->branches[i]->level = level;
}
//initial children
for(int i = 0; i < this->branches.size(); ++i){
if (this->branches[i]->parent) {
this->branches[i]->parent->children.push_back(this->branches[i]);
}
}
}
void BranchTree::preProcess(float inflection_d, float cosAngleThres,
float l_thres_max, float l_thres_min,
float t_length, float soma_ratio) {
vector<Branch*> tmp_results;
for (Branch* branch : this->branches) {
vector<Branch*> s_results = branch->splitByInflectionPoint(inflection_d, cosAngleThres);
tmp_results.insert(tmp_results.end(), s_results.begin(), s_results.end());
}
this->branches.clear();
for (Branch* branch : tmp_results) {
vector<Branch*> s_results = branch->splitByLength(l_thres_max);
this->branches.insert(this->branches.end(), s_results.begin(), s_results.end());
}
if (this->hasSoma) {
for (Branch* branch : this->branches) {
branch->removePointsNearSoma(this->soma, soma_ratio);
}
}
for (Branch* branch : this->branches) {
branch->removeTerminalPoints(t_length);
}
auto it = this->branches.begin();
for (; it != this->branches.end();) {
if ((*it)->calLength() < l_thres_min) {
adjustRalationForRemoveBranch(*it);
this->branches.erase(it);
} else {
++it;
}
}
}
void BranchTree::getFeature(unsigned char *pdata, long long *sz) {
for (Branch* branch : this->branches) {
branch->getFeature(pdata, sz);
}
}
| 36.82852
| 134
| 0.538646
|
MoritzNegwer
|
ae62f1acdcbd3b242c2ab531e9039846d26c5ebe
| 2,994
|
cpp
|
C++
|
src/Eos/SurfaceGroup/eossurfacegroupclient.cpp
|
sparkleholic/qml-webos-framework
|
dbf1f8608ae88b189dedd358acc97d9504425996
|
[
"Apache-2.0"
] | 12
|
2018-03-17T12:35:32.000Z
|
2021-10-15T09:04:56.000Z
|
src/Eos/SurfaceGroup/eossurfacegroupclient.cpp
|
sparkleholic/qml-webos-framework
|
dbf1f8608ae88b189dedd358acc97d9504425996
|
[
"Apache-2.0"
] | 2
|
2020-05-28T14:58:01.000Z
|
2022-02-04T04:03:07.000Z
|
src/Eos/SurfaceGroup/eossurfacegroupclient.cpp
|
sparkleholic/qml-webos-framework
|
dbf1f8608ae88b189dedd358acc97d9504425996
|
[
"Apache-2.0"
] | 5
|
2018-03-22T18:54:18.000Z
|
2020-03-04T19:20:01.000Z
|
// Copyright (c) 2015-2018 LG Electronics, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0
#include "eossurfacegroupclient.h"
EosSurfaceGroupClient::EosSurfaceGroupClient(QObject *parent)
: QObject (parent)
, m_webOSWindow (0)
, m_SurfaceGroup (0)
{
}
EosSurfaceGroupClient::~EosSurfaceGroupClient()
{
if (m_SurfaceGroup) {
delete m_SurfaceGroup;
m_SurfaceGroup = 0;
}
}
void EosSurfaceGroupClient::classBegin()
{
}
void EosSurfaceGroupClient::componentComplete()
{
if (!m_webOSWindow) {
qCritical("Need valid value for \"webOSWindow\" ");
return;
}
if (m_groupName.isEmpty()) {
qCritical("Need valid value for \"groupName\" ");
return;
}
handleWindowVisibility();
}
void EosSurfaceGroupClient::handleWindowVisibility()
{
if (m_SurfaceGroup) {
return;
}
if (m_webOSWindow && m_webOSWindow->isVisible()) {
WebOSSurfaceGroupCompositor* compositor = WebOSPlatform::instance()->surfaceGroupCompositor();
if (compositor) {
if (!m_groupName.isEmpty()) {
m_SurfaceGroup = compositor->getGroup(m_groupName);
if (m_SurfaceGroup) {
if (m_layerName.isEmpty()) {
m_SurfaceGroup->attachAnonymousSurface(m_webOSWindow);
} else {
m_SurfaceGroup->attachSurface(m_webOSWindow, m_layerName);
}
}
}
}
}
}
void EosSurfaceGroupClient::setGroupName(const QString& groupName)
{
if (m_groupName.isEmpty() && !groupName.isEmpty()) {
m_groupName = groupName;
}
}
void EosSurfaceGroupClient::setWebOSWindow(WebOSQuickWindow* webOSWindow)
{
if (!m_webOSWindow && webOSWindow) {
m_webOSWindow = webOSWindow;
QObject::connect(m_webOSWindow, SIGNAL(visibleChanged(bool)),
this, SLOT(handleWindowVisibility()));
}
}
void EosSurfaceGroupClient::setLayerName(const QString& layerName)
{
if (m_layerName.isEmpty() && !layerName.isEmpty()) {
m_layerName = layerName;
}
}
void EosSurfaceGroupClient::focusOwner()
{
if (m_SurfaceGroup) {
m_SurfaceGroup->focusOwner();
}
}
void EosSurfaceGroupClient::focusLayer()
{
if (m_SurfaceGroup) {
if (!m_layerName.isEmpty()) {
m_SurfaceGroup->focusLayer(m_layerName);
}
}
}
| 25.810345
| 102
| 0.642285
|
sparkleholic
|
ae6907210038d0f445acfc2d470f884aadd55ec4
| 802
|
hpp
|
C++
|
ql/experimental/templatemodels/hybrid/hybridmodels.hpp
|
sschlenkrich/quantlib
|
ff39ad2cd03d06d185044976b2e26ce34dca470c
|
[
"BSD-3-Clause"
] | null | null | null |
ql/experimental/templatemodels/hybrid/hybridmodels.hpp
|
sschlenkrich/quantlib
|
ff39ad2cd03d06d185044976b2e26ce34dca470c
|
[
"BSD-3-Clause"
] | null | null | null |
ql/experimental/templatemodels/hybrid/hybridmodels.hpp
|
sschlenkrich/quantlib
|
ff39ad2cd03d06d185044976b2e26ce34dca470c
|
[
"BSD-3-Clause"
] | null | null | null |
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2019 Sebastian Schlenkrich
*/
/*! \file hybridmodels.hpp
\brief bind template types to double
*/
#ifndef quantlib_hybridmodels_hpp
#define quantlib_hybridmodels_hpp
#include <ql/experimental/templatemodels/hybrid/assetmodelT.hpp>
#include <ql/experimental/templatemodels/hybrid/hybridmodelT.hpp>
#include <ql/experimental/templatemodels/hybrid/spreadmodelT.hpp>
namespace QuantLib {
typedef AssetModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> AssetModel;
typedef HybridModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> HybridModel;
typedef SpreadModelT<QuantLib::Time, QuantLib::Real, QuantLib::Real> SpreadModel;
}
#endif /* ifndef quantlib_hybridmodelshpp */
| 25.0625
| 85
| 0.753117
|
sschlenkrich
|
ae6a31d9655395ef70277c4e533cd2fd26227972
| 671
|
cpp
|
C++
|
src/ProjectileGraphicsComponent.cpp
|
filipecaixeta/NeonEdgeGame
|
7dbc825507d731d60a96b4a82975a70e6aa68d7e
|
[
"MIT"
] | 6
|
2017-05-10T19:25:23.000Z
|
2021-04-08T23:55:17.000Z
|
src/ProjectileGraphicsComponent.cpp
|
filipecaixeta/NeonEdgeGame
|
7dbc825507d731d60a96b4a82975a70e6aa68d7e
|
[
"MIT"
] | 1
|
2017-11-10T12:17:26.000Z
|
2017-11-10T12:17:26.000Z
|
src/ProjectileGraphicsComponent.cpp
|
filipecaixeta/NeonEdgeGame
|
7dbc825507d731d60a96b4a82975a70e6aa68d7e
|
[
"MIT"
] | 5
|
2017-05-30T01:07:46.000Z
|
2021-04-08T23:55:19.000Z
|
// Copyright (c) 2017 Neon Edge Game.
#include "ProjectileGraphicsComponent.h"
#include "Projectile.h"
#include "Rect.h"
ProjectileGraphicsComponent::ProjectileGraphicsComponent(std::string baseNameParam):
GraphicsComponent(baseNameParam) {
AddSprite(baseName, "Projectile", 4, 80);
sprite = sprites["Projectile"];
surface = surfaces["Projectile"];
}
ProjectileGraphicsComponent::~ProjectileGraphicsComponent() {
}
void ProjectileGraphicsComponent::Update(GameObject *gameObject, float deltaTime) {
characterLeftDirection = (gameObject->facing == GameObject::LEFT);
sprite->Mirror(characterLeftDirection);
sprite->Update(deltaTime);
}
| 29.173913
| 84
| 0.755589
|
filipecaixeta
|
ae6b36b615553c52c30538243fca26525e741ce4
| 323
|
hxx
|
C++
|
inc/html5xx.d/Article.hxx
|
astrorigin/html5xx
|
cbaaeb232597a713630df7425752051036cf0cb2
|
[
"MIT"
] | null | null | null |
inc/html5xx.d/Article.hxx
|
astrorigin/html5xx
|
cbaaeb232597a713630df7425752051036cf0cb2
|
[
"MIT"
] | null | null | null |
inc/html5xx.d/Article.hxx
|
astrorigin/html5xx
|
cbaaeb232597a713630df7425752051036cf0cb2
|
[
"MIT"
] | null | null | null |
/*
*
*/
#ifndef _HTML5XX_ARTICLE_HXX_
#define _HTML5XX_ARTICLE_HXX_
#include "Element.hxx"
using namespace std;
namespace html
{
class Article: public Element
{
public:
Article():
Element(Block, "article")
{}
};
} // end namespace html
#endif // _HTML5XX_ARTICLE_HXX_
// vi: set ai et sw=2 sts=2 ts=2 :
| 10.766667
| 34
| 0.678019
|
astrorigin
|
ae6e79bfa2356803e033cc0b24673eaff495daca
| 4,352
|
cpp
|
C++
|
conui/examples/Test5ValEdit.cpp
|
amalk/GUI-CLI
|
a08f3eed8d65c1cfef259397990f9e218a77d594
|
[
"MIT"
] | 3
|
2016-08-17T09:35:16.000Z
|
2019-02-07T21:27:58.000Z
|
conui/examples/Test5ValEdit.cpp
|
amalk/GUI-CLI
|
a08f3eed8d65c1cfef259397990f9e218a77d594
|
[
"MIT"
] | null | null | null |
conui/examples/Test5ValEdit.cpp
|
amalk/GUI-CLI
|
a08f3eed8d65c1cfef259397990f9e218a77d594
|
[
"MIT"
] | 3
|
2016-08-17T09:35:21.000Z
|
2018-02-14T08:14:35.000Z
|
// Console Input Output Library Tester program for CValEdit
// Test5ValEdit.cpp
//
// Fardad Soleimanloo, Chris Szalwinski
// Oct 10 2012
// Version 0.9
#include "cuigh.h"
#include "console.h"
#include "cframe.h"
#include "cdialog.h"
#include "clabel.h"
#include "cveditline.h"
#include "cbutton.h"
#include <cstring>
#include <cctype>
using namespace std;
using namespace cui;
bool Yes(const char* message, CDialog* owner);
void Help(CDialog* owner, CDialog* helping);
void PhoneHelp(MessageStatus st, CDialog& owner);
void LastNameHelp(MessageStatus st, CDialog& owner);
bool ValidPhone(const char* ph , CDialog& owner);
int main()
{
int key = 0;
int i = 1;
bool done = false;
bool insert = true;
char str[81] = "I want to edit this thing!";
for(int k = 0; k < console.getRows(); k += 2)
{
for(int m = 0; m < console.getCols() - 10; m += 10)
{
console.strdsp((i = !i) ? "Hello" : "Hi", k, m);
}
}
CDialog Screen;
CDialog FD(&Screen, 5, 5, 70, 15, true);
CLabel PhHelp(8, 34, 30);
CLabel LnHelp(5, 37, 30);
CLabel ErrMes(10, 2, 67);
Screen << new CLabel("F1: HELP ", 0, 0);
FD << new CLabel("Name:", 2, 2)
<< new CLineEdit(1, 10, 20, 40, &insert, true)
<< new CLabel("Lastname:", 5, 2)
<< new CValEdit(4, 13, 20, 40, &insert, NO_VALDFUNC, LastNameHelp, true)
<< new CLabel("Phone Number", 8, 2)
<< new CValEdit(7, 16, 15, 12, &insert, ValidPhone, PhoneHelp, true)
<< PhHelp
<< LnHelp
<< ErrMes
<< new CLabel("F1: help, ESCAPE: exit", 11, 2);
FD.draw();
while(!done)
{
key = FD.edit();
switch(key)
{
case F(1):
Help(&Screen, &FD);
break;
case ESCAPE:
if(Yes("Do you really want to quit?", &Screen))
{
done = true;
}
break;
case F(6):
FD.move();
break;
}
}
return 0;
}
bool Yes(const char* message, CDialog* owner)
{
int key;
bool res = false;
bool done = false;
CButton bt_yes("Yes", 4, 4 , true, " _ ");
CButton bt_no("No", 4, 15 , true, " _ ");
CDialog YesNo(owner, (console.getRows() - 10) / 2, (console.getCols() - 40) / 2, 40, 10, true);
YesNo << new CLabel(2, 2, 36) << bt_yes << bt_no;
YesNo[0].set(message);
YesNo.draw(C_FULL_FRAME);
while(!done)
{
key = YesNo.edit();
if(key == C_BUTTON_HIT)
{
res = &YesNo.curField() == &bt_yes;
done = true;
}
else if(key == F(6))
{
YesNo.move();
}
}
YesNo.hide();
return res;
}
void Help(CDialog* owner, CDialog* helping)
{
CDialog help(owner, (console.getRows() - 10) / 2, (console.getCols() - 40) / 2, 40, 10, true);
help << new CLabel(2, 3, 36)
<< new CLabel("Escape Key: Exit the test program.", 4, 3)
<< new CLabel("F1 Key: Open this window.", 6, 3);
switch(helping->curIndex())
{
case 1:
help[0].set("Enter the name here!");
break;
case 3:
help[0].set("Enter the Last name here!");
break;
case 5:
help[0].set("Enter Phone number: 999-999-9999");
}
while(help.edit(C_FULL_FRAME) == F(6))
{
help.move();
}
help.hide();
}
void PhoneHelp(MessageStatus st, CDialog& owner)
{
if(st == ClearMessage)
{
owner[6].set("");
}
else
{
owner[6].set("Phone Format: 999-999-9999");
}
owner.draw(7);
}
void LastNameHelp(MessageStatus st, CDialog& owner)
{
if(st == ClearMessage)
{
owner[7].set("");
}
else
{
owner[7].set("i.e. Middle name and Surname");
}
owner.draw(8);
}
bool ValidPhone(const char* ph , CDialog& owner)
{
bool ok = true;
int i;
for(i = 0; ok && i < 3; ok = (bool)isdigit(ph[i]), i++);
ok = ph[i++] == '-';
for(; ok && i < 7; ok = (bool)isdigit(ph[i]), i++);
ok = ph[i++] == '-';
for(; ok && i < 12; ok = (bool)isdigit(ph[i]), i++);
if(ok)
{
owner[8].set("");
}
else
{
owner[8].set("Invlid phone number, please use the specified phone number format!");
}
owner.draw(9);
return ok;
}
| 21.544554
| 99
| 0.516774
|
amalk
|
ae6e8aa318c8889f6cca7de9f3eeb46bc5c3eb03
| 2,182
|
cpp
|
C++
|
test/libwebsocket-mock/mock_lws_minimal.cpp
|
costanic/mbed-edge
|
4900e950ff67f8974b7aeef955289ef56606c964
|
[
"Apache-2.0"
] | 24
|
2018-03-27T16:44:18.000Z
|
2020-04-28T15:28:34.000Z
|
test/libwebsocket-mock/mock_lws_minimal.cpp
|
costanic/mbed-edge
|
4900e950ff67f8974b7aeef955289ef56606c964
|
[
"Apache-2.0"
] | 19
|
2021-01-28T20:14:45.000Z
|
2021-11-23T13:08:59.000Z
|
test/libwebsocket-mock/mock_lws_minimal.cpp
|
costanic/mbed-edge
|
4900e950ff67f8974b7aeef955289ef56606c964
|
[
"Apache-2.0"
] | 28
|
2018-04-02T02:36:48.000Z
|
2020-10-13T05:37:16.000Z
|
#include "CppUTestExt/MockSupport.h"
#include "cpputest-custom-types/value_pointer.h"
extern "C" {
#include "libwebsockets.h"
}
int lws_callback_on_writable(struct lws *wsi)
{
return mock().actualCall("lws_callback_on_writable")
.returnIntValueOrDefault(0);
}
size_t lws_remaining_packet_payload(struct lws *wsi)
{
return mock().actualCall("lws_remaining_packet_payload").returnUnsignedLongIntValue();
}
int lws_is_final_fragment(struct lws *wsi)
{
return mock().actualCall("lws_is_final_fragment").returnIntValue();
}
int lws_is_first_fragment(struct lws *wsi)
{
return mock().actualCall("lws_is_first_fragment").returnIntValue();
}
void lws_close_reason(struct lws *wsi, enum lws_close_status status, unsigned char *buf, size_t len)
{
mock().actualCall("lws_close_reason");
}
int lws_write(struct lws *wsi, unsigned char *buf, size_t len, enum lws_write_protocol protocol)
{
ValuePointer msg_param = ValuePointer(buf, len);
return mock().actualCall("lws_write")
.withParameterOfType("ValuePointer", "buf", &msg_param)
.returnIntValue();
}
struct lws_context *lws_create_context(const struct lws_context_creation_info *info)
{
return (struct lws_context*) mock().actualCall("lws_create_context").returnPointerValue();
}
void lws_context_destroy(struct lws_context *ctx)
{
mock().actualCall("lws_context_destroy");
free(ctx);
}
LWS_VISIBLE LWS_EXTERN struct lws *lws_client_connect_via_info(const struct lws_client_connect_info *ccinfo)
{
return (struct lws*) mock().actualCall("lws_client_connect_via_info")
.withStringParameter("path", ccinfo->path)
.returnPointerValue();
}
int lws_extension_callback_pm_deflate(struct lws_context *context,
const struct lws_extension *ext,
struct lws *wsi,
enum lws_extension_callback_reasons reason,
void *user,
void *in,
size_t len)
{
return mock().actualCall("lws_extension_callback_pm_deflate").returnIntValue();
}
| 31.623188
| 108
| 0.681027
|
costanic
|
ae71a4ef975ed4a1f28cc8068cf32da4b32e4d2b
| 3,722
|
hpp
|
C++
|
src/mge/core/GameObject.hpp
|
mtesseracttech/CustomEngine
|
1a9ed564408ae29fe49681a810b851403d71f486
|
[
"Apache-2.0"
] | null | null | null |
src/mge/core/GameObject.hpp
|
mtesseracttech/CustomEngine
|
1a9ed564408ae29fe49681a810b851403d71f486
|
[
"Apache-2.0"
] | null | null | null |
src/mge/core/GameObject.hpp
|
mtesseracttech/CustomEngine
|
1a9ed564408ae29fe49681a810b851403d71f486
|
[
"Apache-2.0"
] | null | null | null |
#ifndef GAMEOBJECT_H
#define GAMEOBJECT_H
#include <vector>
#include <string>
#include <iostream>
#include <glm/glm.hpp>
#include "LinearMath/btDefaultMotionState.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "BulletDynamics/Vehicle/btRaycastVehicle.h"
class RigidBody;
class AbstractBehaviour;
class AbstractMaterial;
class World;
class Mesh;
/**
* A GameObject wraps all data required to display an (interactive / dynamic) object, but knows nothing about OpenGL or rendering.
* You will need to alter this class to add colliders etc.
*/
class GameObject
{
public:
GameObject(std::string pName = NULL, glm::vec3 pPosition = glm::vec3(0.0f, 0.0f, 0.0f));
virtual ~GameObject();
void setName(std::string pName);
std::string getName() const;
//contains local rotation, scale, position
const glm::mat4& getTransform() const;
void setTransform(const glm::mat4& pTransform);
//access just the local position
glm::vec3 getLocalPosition() const;
glm::quat getLocalRotation() const;
glm::quat getLocalRotationSlow() const;
void setLocalPosition(const glm::vec3 pPosition);
void setLocalRotation(const glm::quat rotation);
glm::vec3 getTransformRight() const;
glm::vec3 getTransformUp() const;
glm::vec3 getTransformForward() const;
void setTransformForward(glm::vec3 fwd);
//get the objects world position by combining transforms
//expensive operations!! Improvement would be to cache these transforms!
glm::vec3 getWorldPosition() const;
glm::quat getWorldRotation() const;
glm::mat4 getWorldTransform() const;
glm::vec3 getWorldTransformRight() const;
glm::vec3 getWorldTransformUp() const;
glm::vec3 getWorldTransformForward() const;
//change local position, rotation, scaling
void translate(glm::vec3 pTranslation);
void rotate(float pAngle, glm::vec3 pAxis);
//DO NOT USE IN FINAL GAME, ROTATION FUNCTIONS MAKE GAMEOBJECT LOSE SCALE!
void scale(glm::vec3 pScale);
//mesh and material should be shared as much as possible
void setMesh(Mesh* pMesh);
Mesh* getMesh() const;
void setMaterial(AbstractMaterial* pMaterial);
AbstractMaterial* getMaterial() const;
btDefaultMotionState* getDefaultMotionState() const;
void setRigidBody(btCollisionShape* shape, float mass, btDynamicsWorld* world);
void setMeshRigidBody(btDynamicsWorld* world);
RigidBody* getRigidBody() const;
void removeRigidBody() const;
virtual void update(float pStep);
void AddBehaviour(AbstractBehaviour* behaviour);
void RemoveBehaviour(AbstractBehaviour* behaviour);
void ClearBehaviours();
void DeleteBehaviours();
//child management
//shortcut to set the parent of pChild to ourselves
void add(GameObject* pChild);
//shortcut to set the parent of pChild to NULL
void remove(GameObject* pChild);
virtual void setParent(GameObject* pGameObject);
GameObject* getParent();
int getChildCount();
GameObject* getChildAt(int pIndex);
void enableDebugging();
void printDebug();
void deleteObject(const GameObject* pObject);
//light
void AdjustPosition();
virtual void OnCollision(const btCollisionObject* other);
protected:
std::string _name;
glm::mat4 _transform;
GameObject* _parent;
std::vector<GameObject*> _children;
Mesh* _mesh;
AbstractMaterial* _material;
RigidBody* _rigidBody;
btDefaultMotionState* _defaultMotionState;
std::vector<AbstractBehaviour*> _behaviours;
//update children list administration
void _innerAdd(GameObject* pChild);
void _innerRemove(GameObject* pChild);
private:
GameObject(const GameObject&);
GameObject& operator=(const GameObject&);
bool _debug;
glm::mat4 floatToMat4(float* Pmatrix);
};
#endif // GAMEOBJECT_H
| 29.776
| 129
| 0.754164
|
mtesseracttech
|
ae81c922341310210d05bf5ccbe9a368b12e9ce0
| 1,086
|
hpp
|
C++
|
function/codeFunction.hpp
|
TaylorP/TML
|
e4c0c7ce69645a1cf30df005af786a15f85b54a2
|
[
"MIT"
] | 4
|
2015-12-17T21:58:27.000Z
|
2019-10-31T16:50:41.000Z
|
function/codeFunction.hpp
|
TaylorP/TML
|
e4c0c7ce69645a1cf30df005af786a15f85b54a2
|
[
"MIT"
] | null | null | null |
function/codeFunction.hpp
|
TaylorP/TML
|
e4c0c7ce69645a1cf30df005af786a15f85b54a2
|
[
"MIT"
] | 1
|
2019-05-07T18:51:00.000Z
|
2019-05-07T18:51:00.000Z
|
#ifndef CODE_FUNCTION_HPP
#define CODE_FUNCTION_HPP
#include "function/function.hpp"
#include "exception/functionException.hpp"
/// Function for full width code blocks
class CodeFunction : public Function
{
public:
/// Constructs a new code function
CodeFunction(const bool pFilter)
: Function(pFilter)
{
}
/// Emits a full width code block to the stream
virtual void emit(std::ostream& pStream,
const std::vector<std::string>& pInput) const
{
// Validate parameter count
if (pInput.size() != 2)
{
throw(FunctionException("@code",
"Function expects exactly 2 parameters"));
}
// Print the pre tag, including the linenums and language class
pStream << "<pre class='prettyprint linenums " << pInput[0] << "'>";
newline(pStream);
// Print the code
pStream << pInput[1];
newline(pStream);
// Close the pre tag
pStream << "</pre>";
newline(pStream);
}
};
#endif
| 25.255814
| 78
| 0.577348
|
TaylorP
|
ae857cf2e59e794dc8dcefaa309ac2c647a69b70
| 840
|
cpp
|
C++
|
Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp
|
MrWpGg/Durna
|
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
|
[
"Apache-2.0"
] | null | null | null |
Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp
|
MrWpGg/Durna
|
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
|
[
"Apache-2.0"
] | null | null | null |
Durna/Source/Runtime/Platform/OpenGL/OpenGLContext.cpp
|
MrWpGg/Durna
|
62c8ca2d69623e70e2dac49a5560cd3ac2c304ed
|
[
"Apache-2.0"
] | null | null | null |
#include "DurnaPCH.h"
#include "OpenGLContext.h"
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <gl/GL.h>
namespace Durna
{
OpenGLContext::OpenGLContext(GLFWwindow* InWindowHandle)
: WindowHandle(InWindowHandle)
{
DRN_ASSERT(WindowHandle, "WindowHandle is null!")
}
void OpenGLContext::Init()
{
DRN_PROFILE_FUNCTION();
glfwMakeContextCurrent(WindowHandle);
int Status = gladLoadGLLoader((GLADloadproc)glfwGetProcAddress);
DRN_ASSERT(Status, "Failed to init glad!");
LOG_TRACE(LOGCAT_GL, "initialized");
LOG_TRACE(LOGCAT_GL, "Vendor: {0}", glGetString(GL_VENDOR));
LOG_TRACE(LOGCAT_GL, "Renderer: {0}", glGetString(GL_RENDERER));
LOG_TRACE(LOGCAT_GL, "Version: {0}", glGetString(GL_VERSION));
}
void OpenGLContext::SwapBuffers()
{
DRN_PROFILE_FUNCTION();
glfwSwapBuffers(WindowHandle);
}
}
| 21.538462
| 66
| 0.736905
|
MrWpGg
|
ae8d9be81b36679f7935111b3f8dac0d2e28a798
| 7,590
|
cpp
|
C++
|
source/AI/deeplearning/Normalization.cpp
|
TrojanVulgar/AI-framework
|
46779b44ebb542ff88b8b9e91fb9a0889191f928
|
[
"MIT",
"Unlicense"
] | 57
|
2018-02-21T13:28:23.000Z
|
2022-03-05T05:48:41.000Z
|
src/AI/deeplearning/Normalization.cpp
|
Flowx08/artificial_intelligence
|
ab4fec14e6af3e3fca271b76fdb67f05d7e588ed
|
[
"MIT"
] | null | null | null |
src/AI/deeplearning/Normalization.cpp
|
Flowx08/artificial_intelligence
|
ab4fec14e6af3e3fca271b76fdb67f05d7e588ed
|
[
"MIT"
] | 25
|
2018-08-27T01:54:03.000Z
|
2022-03-04T02:58:18.000Z
|
////////////////////////////////////////////////////////////
/// INCLUDES
////////////////////////////////////////////////////////////
#include "Normalization.hpp"
#include <cmath>
#include "../util/ensure.hpp"
#ifdef CUDA_BACKEND
#include "CUDA_backend.hpp"
#endif
////////////////////////////////////////////////////////////
/// NAMESPACE AI
////////////////////////////////////////////////////////////
namespace ai
{
////////////////////////////////////////////////////////////
std::shared_ptr<Operation> Normalization::make(float momentum)
{
return std::shared_ptr<Operation>(new Normalization(momentum));
}
////////////////////////////////////////////////////////////
Normalization::Normalization(float momentum)
{
ensure(momentum >= 0 && momentum < 1);
_gamma = 1.f;
_beta = 0.f;
_epsilon = 1e-4;
_momentum = momentum;
_d_beta = 0;
_d_gamma = 0;
}
////////////////////////////////////////////////////////////
Normalization::Normalization(ai::IOData& data)
{
ai::IOData* size = data.findNode("size");
ensure(size != NULL);
ai::IOData* width = data.findNode("width");
ensure(width != NULL);
ai::IOData* height = data.findNode("height");
ensure(height != NULL);
ai::IOData* depth = data.findNode("depth");
ensure(depth != NULL);
ai::IOData* gamma = data.findNode("gamma");
ensure(gamma != NULL);
ai::IOData* beta = data.findNode("beta");
ensure(beta != NULL);
ai::IOData* epsilon = data.findNode("epsilon");
ensure(epsilon != NULL);
ai::IOData* momentum = data.findNode("momentum");
ensure(momentum != NULL);
size->get(_size);
width->get(_width);
height->get(_height);
depth->get(_depth);
gamma->get(_gamma);
beta->get(_beta);
epsilon->get(_epsilon);
momentum->get(_momentum);
_outputs.setshape(_width, _height, _depth);
_outputs.fill(0);
_errors.setshape(_size);
_errors.fill(0);
_deviation.setshape(_size);
_deviation.fill(0);
_normalized.setshape(_size);
_normalized.fill(0);
_d_beta = 0;
_d_gamma = 0;
#ifdef CUDA_BACKEND
float* tmp = new float[5];
tmp[0] = 0; //variance
tmp[1] = _gamma; //gamma
tmp[2] = _beta; //beta
tmp[3] = 0; //gamma delta
tmp[4] = 0; //beta delta
_params.setshape(5);
_params.copyToDevice(tmp, 5);
delete[] tmp;
#endif
}
////////////////////////////////////////////////////////////
void Normalization::initialize(std::vector<Operation*> &inputs)
{
//Check for errors
ensure(inputs.size() == 1);
//Calculate size
_size = inputs[0]->_outputs.size();
_width = inputs[0]->_outputs.width();
_height = inputs[0]->_outputs.height();
_depth = inputs[0]->_outputs.depth();
//Initialize vectors
_outputs.setshape(_width, _height, _depth);
_outputs.fill(0);
_errors.setshape(_size);
_errors.fill(0);
_deviation.setshape(_size);
_deviation.fill(0);
_normalized.setshape(_size);
_normalized.fill(0);
_d_beta = 0;
_d_gamma = 0;
#ifdef CUDA_BACKEND
float* tmp = new float[5];
tmp[0] = 0; //variance
tmp[1] = _gamma; //gamma
tmp[2] = _beta; //beta
tmp[3] = 0; //gamma delta
tmp[4] = 0; //beta delta
_params.setshape(5);
_params.copyToDevice(tmp, 5);
delete[] tmp;
#endif
}
////////////////////////////////////////////////////////////
void Normalization::save(ai::IOData& data)
{
data.pushNode("size", _size);
data.pushNode("width", _width);
data.pushNode("height", _height);
data.pushNode("depth", _depth);
data.pushNode("gamma", _gamma);
data.pushNode("beta", _beta);
data.pushNode("epsilon", _epsilon);
data.pushNode("momentum", _momentum);
}
////////////////////////////////////////////////////////////
void Normalization::run(std::vector<Operation*> &inputs, const bool training)
{
//Check for correct input size
ensure(inputs.size() == 1);
ensure(inputs[0]->_outputs.size() == _outputs.size());
#ifdef CUDA_BACKEND
ai::cuda::normalization_foreward(inputs[0]->_outputs.pointer(), _deviation.pointer(), _normalized.pointer(),
_outputs.pointer(), &_params.pointer()[0], &_params.pointer()[1], &_params.pointer()[2], _epsilon, _size);
//===== TESTING NORMALIZATION ======
/*
Tensor_float t_out(_outputs.size());
_outputs.copyToHost(t_out.pointer(), t_out.size());
printf("%s\n", t_out.tostring().c_str());
*/
#else
//Shortcuts
Tensor_float& in = inputs[0]->_outputs;
//Calculate mean
_mean = 0;
for (int i = 0; i < in.size(); i++)
_mean += in[i];
_mean /= (double)in.size();
//Subtract mean vector to all inputs and calculate variance
_variance = 0;
for (int i = 0; i < in.size(); i++) {
_deviation[i] = in[i] - _mean;
_variance += _deviation[i] * _deviation[i];
}
_variance /= (double)in.size();
//Calculate normalized vector
for (int i = 0; i < in.size(); i++) {
_normalized[i] = _deviation[i] / std::sqrt(_variance + _epsilon);
_outputs[i] = _normalized[i] * _gamma + _beta;
}
//===== TESTING NORMALIZATION ======
//printf("%s\n", _outputs.tostring().c_str());
#endif
}
////////////////////////////////////////////////////////////
void Normalization::backprop(std::vector<Operation*> &inputs)
{
//Check for correct input size
ensure(inputs.size() == 1);
#ifdef CUDA_BACKEND
ai::cuda::normalization_backward(_errors.pointer(), inputs[0]->_errors.pointer(), _deviation.pointer(),
&_params.pointer()[0], &_params.pointer()[1], &_params.pointer()[2], _epsilon, _size);
#else
//Shortcuts
Tensor_float &out_errors = inputs[0]->_errors;
//Pre compute some expressions
float sum_errors = 0.f;
float sum_errors_dev = 0.f;
for (int i = 0; i < _errors.size(); i++) {
sum_errors += _errors[i];
sum_errors_dev += _errors[i] * _deviation[i];
}
//Calculate output errors
for (int i = 0; i < out_errors.size(); i++) {
out_errors[i] = 1.0 / (float)_size * _gamma / sqrt(_variance + _epsilon) * ((float)_size *
_errors[i] - sum_errors - _deviation[i] / (_variance + _epsilon) * sum_errors_dev);
}
/*
dh = (1. / N) * gamma * (var + eps)**(-1. / 2.) * (N * dy - np.sum(dy, axis=0)
- (h - mu) * (var + eps)**(-1.0) * np.sum(dy * (h - mu), axis=0))
*/
#endif
}
////////////////////////////////////////////////////////////
void Normalization::accumulate_deltas(std::vector<Operation*> &inputs)
{
#ifdef CUDA_BACKEND
ai::cuda::normalization_accumulate_deltas(_errors.pointer(), _deviation.pointer(), &_params.pointer()[0],
&_params.pointer()[3], &_params.pointer()[4], _epsilon, _size);
#else
//calculate beta delta
for (int i = 0; i < _errors.size(); i++)
_d_beta += _errors[i];
//calculate gamma delta
for (int i = 0; i < _errors.size(); i++)
_d_gamma += _deviation[i] * sqrt(_variance + _epsilon) * _errors[i];
#endif
}
////////////////////////////////////////////////////////////
void Normalization::update_parameters(const float learningrate)
{
#ifdef CUDA_BACKEND
ai::cuda::normalization_update_parameters(&_params.pointer()[1], &_params.pointer()[2], &_params.pointer()[3],
&_params.pointer()[4], _momentum, _size, learningrate);
#else
_beta += ((double)_d_beta / (double)_size) * learningrate;
_gamma += ((double)_d_gamma / (double)_size) * learningrate;
_d_beta *= _momentum;
_d_gamma *= _momentum;
#endif
}
////////////////////////////////////////////////////////////
const Operation::Type Normalization::get_type() const
{
return Operation::Normalization;
}
////////////////////////////////////////////////////////////
void Normalization::print()
{
printf("Type: Normalization, Size: %d, Momentum: %f", _size, _momentum);
}
} /* namespace ai */
| 28.00738
| 112
| 0.570224
|
TrojanVulgar
|
ae8e94744ca6aae111967b6d1661e80f23646a74
| 1,150
|
cpp
|
C++
|
codeforces/C - Cycle/Time limit exceeded on test 11 (3).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | 1
|
2022-02-11T16:55:36.000Z
|
2022-02-11T16:55:36.000Z
|
codeforces/C - Cycle/Time limit exceeded on test 11 (3).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
codeforces/C - Cycle/Time limit exceeded on test 11 (3).cpp
|
kzvd4729/Problem-Solving
|
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
|
[
"MIT"
] | null | null | null |
/****************************************************************************************
* @author: kzvd4729 created: Oct/25/2019 15:28
* solution_verdict: Time limit exceeded on test 11 language: GNU C++14
* run_time: 2500 ms memory_used: 6200 KB
* problem: https://codeforces.com/contest/117/problem/C
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=5e3;
bitset<N+2>ot[N+2],in[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n;cin>>n;
for(int i=0;i<n;i++)
{
string s;cin>>s;
for(int j=0;j<n;j++)
if(s[j]=='1')ot[i][j]=1,in[j][i]=1;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(ot[i][j]&&(in[i]&ot[j]).count())
{
cout<<i+1<<" "<<j+1<<" ";
in[i]&=ot[j];
cout<<in[i]._Find_first()+1<<endl;
exit(0);
}
}
}
cout<<-1<<endl;
return 0;
}
| 31.081081
| 111
| 0.376522
|
kzvd4729
|
ae92cacf2969dd5c33f9045e79d00e2a0f097cd7
| 6,807
|
cpp
|
C++
|
samples/tuple-builder/main.cpp
|
tim42/alphyn
|
af0c32df6813bbfded1df271283f9dd5378d0190
|
[
"MIT"
] | 5
|
2016-03-05T00:39:13.000Z
|
2020-01-03T09:49:21.000Z
|
samples/tuple-builder/main.cpp
|
tim42/alphyn
|
af0c32df6813bbfded1df271283f9dd5378d0190
|
[
"MIT"
] | null | null | null |
samples/tuple-builder/main.cpp
|
tim42/alphyn
|
af0c32df6813bbfded1df271283f9dd5378d0190
|
[
"MIT"
] | null | null | null |
#include <tools/ct_string.hpp>
#include <tools/demangle.hpp>
#include <alphyn.hpp>
#include <default_token.hpp>
#include <iostream>
#include <tuple>
// #include <iomanip>
template<const char *TypeName, typename Type>
struct db_type_entry
{
using type = Type;
// a small comparison function
static constexpr bool strcmp(const char *s, size_t start, size_t end)
{
size_t i = start;
size_t j = 0;
for (; i < end && TypeName[j] != '\0' && TypeName[j] == s[i]; ++i, ++j);
if (i != end || TypeName[j] != '\0')
return false;
return true;
}
};
template<typename... Entries>
using type_db = neam::ct::type_list<Entries...>;
/// \brief a very simple tuple builder
/// \param TypeDB should be a type_db< db_type_entry< string, type >... >
template<typename TypeDB, template<typename...> class TupleType = std::tuple>
struct tuple_builder
{
// token relative things (type and invalid)
using token_type = neam::ct::alphyn::token<size_t>;
using type_t = typename token_type::type_t;
/// \brief possible "types" for a token
enum e_token_type : type_t
{
invalid = neam::ct::alphyn::invalid_token_type,
// tokens (terminals)
tok_end = 0,
tok_id = 1,
tok_comma = 2,
tok_br_open = 3,
tok_br_close = 4,
// non-terminals
start = 100,
expr = 101,
val = 104,
};
// THE LEXER THINGS //
// token builders
template<typename... Entries>
struct _id_token_builder
{
// search the type in the Type DB
static constexpr token_type e_id(const char *s, size_t index, size_t end)
{
size_t type_index = TypeDB::size; // invalid
size_t i = 0;
NEAM_EXECUTE_PACK(
(++i) && (type_index == TypeDB::size) && Entries::strcmp(s, index, end) && (type_index = i - 1)
);
if (type_index < TypeDB::size)
return token_type {e_token_type::tok_id, type_index, s, index, end};
else
return token_type::generate_invalid_token(s, index);
}
};
template<typename List>
using id_token_builder = typename neam::ct::extract_types<_id_token_builder, List>::type;
// regular expressions
constexpr static neam::string_t re_id = "[a-zA-Z0-9_-]+";
constexpr static neam::string_t re_end = "$";
/// \brief The lexical syntax that will be used to tokenize a string (tokens are easier to parse)
using lexical_syntax = neam::ct::alphyn::lexical_syntax
<
neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::letter<','>, token_type, token_type::generate_token_with_type<e_token_type::tok_comma>>,
neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::letter<'<'>, token_type, token_type::generate_token_with_type<e_token_type::tok_br_open >>,
neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::letter<'>'>, token_type, token_type::generate_token_with_type<e_token_type::tok_br_close >>,
neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::regexp<re_id>, token_type, id_token_builder<TypeDB>::e_id>,
neam::ct::alphyn::syntactic_unit<neam::ct::alphyn::regexp<re_end>, token_type, token_type::generate_token_with_type<e_token_type::tok_end>>
>;
/// \brief We simply want to skip white spaces
using skipper = neam::ct::alphyn::white_space_skipper;
/// \brief Finally, the lexer
using lexer = neam::ct::alphyn::lexer<tuple_builder>;
// THE PARSER THINGS //
// synthesizers:
template<typename TokID>
struct token_to_type // it transforms a token to a type
{
using type = typename TypeDB::template get_type<TokID::token.value>::type;
};
template<typename Type>
struct type_to_tuple // it transforms a single type to a tuple
{
using type = TupleType<Type>;
};
template<typename Tuple, typename TokComma, typename Type>
struct append_type_to_tuple {};
template<typename... TupleEntries, typename TokComma, typename Type>
struct append_type_to_tuple<TupleType<TupleEntries...>, TokComma, Type> // it appends a type to a tuple
{
using type = TupleType<TupleEntries..., Type>;
};
/// \brief Shortcuts for production_rule
template<typename Attribute, type_t... TokensOrRules>
using production_rule = neam::ct::alphyn::production_rule<tuple_builder, Attribute, TokensOrRules...>;
/// \brief Shortcut for production_rule_set
template<type_t Name, typename... Rules>
using production_rule_set = neam::ct::alphyn::production_rule_set<tuple_builder, Name, Rules...>;
/// \brief The parser grammar
using grammar = neam::ct::alphyn::grammar<tuple_builder, start,
production_rule_set<start,
production_rule<neam::ct::alphyn::forward_attribute<1>, tok_br_open, expr, tok_br_close, tok_end> // start -> < expr > $
>,
production_rule_set<expr,
production_rule<neam::ct::alphyn::synthesizer_attribute<type_to_tuple>, val>, // expr -> val
production_rule<neam::ct::alphyn::synthesizer_attribute<append_type_to_tuple>, expr, tok_comma, val> // expr -> expr, val
>,
production_rule_set<val,
production_rule<neam::ct::alphyn::synthesizer_attribute<token_to_type>, tok_id>, // val -> id
production_rule<neam::ct::alphyn::forward_attribute<1>, tok_br_open, expr, tok_br_close> // val -> < expr >
>
>;
/// \brief The parser. It parses things.
using parser = neam::ct::alphyn::parser<tuple_builder>;
};
// create a simple type DB
constexpr neam::string_t int_str = "int";
constexpr neam::string_t uint_str = "uint";
constexpr neam::string_t long_str = "long";
constexpr neam::string_t ulong_str = "ulong";
constexpr neam::string_t float_str = "float";
constexpr neam::string_t double_str = "double";
using simple_type_db = type_db
<
db_type_entry<int_str, int>,
db_type_entry<uint_str, unsigned int>,
db_type_entry<long_str, long>,
db_type_entry<ulong_str, unsigned long>,
db_type_entry<float_str, float>,
db_type_entry<double_str, double>
>;
// a test string:
constexpr neam::string_t tuple_str = "<int, float, uint, int, <long, <long>, double>>";
using res_tuple = tuple_builder<simple_type_db>::parser::ct_parse_string<tuple_str>; // create a std::tuple from the string
using res_type_list = tuple_builder<simple_type_db, neam::ct::type_list>::parser::ct_parse_string<tuple_str>; // create a neam::ct::type_list from the same string
// check that the tuple is correct:
static_assert(std::is_same<res_tuple, std::tuple<int, float, unsigned int, int, std::tuple<long, std::tuple<long>, double>>>::value, "invalid tuple type (did you change the string ?)");
int main(int /*argc*/, char **/*argv*/)
{
std::cout << "result tuple: " << neam::demangle<res_tuple>() << std::endl;
std::cout << "result type list: " << neam::demangle<res_type_list>() << std::endl;
return 0;
}
| 36.207447
| 185
| 0.680917
|
tim42
|
ae94e27df10cc6338e95e909a79090597b203348
| 12,220
|
cpp
|
C++
|
engine/private/abstracts/pool-protected.cpp
|
cppcooper/Cheryl-Engine
|
9a0b08da46539f756c6fe7d70212e9ca91c6fbe7
|
[
"MIT"
] | null | null | null |
engine/private/abstracts/pool-protected.cpp
|
cppcooper/Cheryl-Engine
|
9a0b08da46539f756c6fe7d70212e9ca91c6fbe7
|
[
"MIT"
] | 1
|
2019-01-22T22:07:27.000Z
|
2019-01-22T22:07:27.000Z
|
engine/private/abstracts/pool-protected.cpp
|
cppcooper/cheryl-engine
|
9a0b08da46539f756c6fe7d70212e9ca91c6fbe7
|
[
"MIT"
] | null | null | null |
#include "abstracts/pool.h"
inline bool inRange(const size_t ts, const ce_uintptr p, const ce_uintptr r, const size_t s){
return (r <= p && p < r+(ts*s));
}
inline bool inRange(const size_t &ts, const ce_uintptr &p, const size_t &ps, const ce_uintptr &r, const size_t &rs){
return (r <= p && p+(ts*ps) <= r+(ts*rs));
}
inline bool isAligned(const size_t &ts, const ce_uintptr &a, const ce_uintptr &b, const size_t &bs){
return a == b+(ts*bs);
}
inline bool update(std::multimap<size_t,openalloc_iter> &OpenList, openlist_iter &iter, const alloc &a){
if(iter != OpenList.end()){
iter->first = a.head_size;
iter->second->first = a.head;
iter->second->second = a;
return true;
}
return false;
}
inline bool update(std::map<ce_uintptr,alloc> &ClosedList, closed_iter &iter, const alloc &a){
if(iter != ClosedList.end()){
iter->first = a.head;
iter->second = a;
return true;
}
return false;
}
bool AbstractPool::isClosed(const ce_uintptr &p){
return find_closed(p) != ClosedList.end();
}
bool AbstractPool::isOpen(const ce_uintptr &p){
return find_open(p) != OpenAllocations.end();
}
bool AbstractPool::merge(openlist_iter &iter, const alloc &a){
if(iter != OpenList.end()){
alloc &b = iter->second->second;
if(isAligned(type_size, a.head, b.head, b.head_size)) {
//merging in on the right
b.head_size += a.head_size;
return update(OpenList,iter,b);
}
if(isAligned(type_size, b.head, a.head, a.head_size)){
//merging in on the left
b.head = a.head;
b.head_size += a.head_size;
return update(OpenList,iter,b);
}
return false;
}
throw invalid_args(__CEFUNCTION__, __LINE__, "Invalid iterator.");
}
int8_t AbstractPool::grow(closed_iter &p_iter, const size_t &N){
if(p_iter != ClosedList.end()){
alloc &a = p_iter->second;
assert(N > a.head_size && "Allocation is not less than the grow parameter N");
auto neighbours = find_neighbours(p_alloc.head);
size_t bytes_needed = bytes-a.head_size;
alloc left,right;
if(neighbours.second != OpenAllocations.end()){
right = neighbours.second->second;
}
if(neighbours.first != OpenAllocations.end()){
left = neighbours.first->second;
}
//Check available space (right, then left)
if(right.head_size >= bytes_needed){
a.head_size = N;
update(ClosedList,p_iter,a);
alloc &b = neighbours.second->second;
b.head_size -= bytes_needed;
if(b.head_size==0){
erase_open(neighbours.second->second);
} else {
b.head = a.head+a.head_size;
if(!update(OpenList,find_open(b),b)){
throw failed_operation(__CEFUNCTION__, __LINE__, "Failed to find OpenList iterator.");
}
}
return 1;
}
if(left.head_size >= bytes_needed){
a.head -= bytes_needed;
a.head_size = N;
update(ClosedList,p_iter,a);
alloc &b = neighbours.first->second;
b.head_size -= bytes_needed;
if(b.head_size==0){
erase_open(neighbours.second->second);
} else {
b_ol_iter->first = b.head_size;
if(!update(OpenList,find_open(b),b)){
throw failed_operation(__CEFUNCTION__, __LINE__, "Failed to find OpenList iterator.");
}
}
return -1;
}
}
return 0;
}
bool AbstractPool::shrink(closed_iter &p_iter, const size_t &N){
if(p_iter != ClosedList.end()){
alloc &a = p_iter->second;
assert(N < a.head_size && "Allocation is not greater than the shrink parameter N");
size_t remainder = a.head_size - N;
a.head_size = N;
if(remainder!=0){
alloc b{a.master, a.head+a.head_size, a.master_size, remainder};
auto right_al_iter = find_neighbours(b.head).second;
if(right_al_iter != OpenAllocations.end()){
alloc &right = right_al_iter->second;
if(isAligned(type_size, right.head, b.head, b.head_size)){
right.head = b.head;
right.head_size += b.head_size;
if(!update(OpenList,find_open(right),right)){
throw failed_operation(__CEFUNCTION__, __LINE__, "Failed to find OpenList iterator.");
}
} else {
add_open(right);
}
}
}
return true;
}
return false;
}
/*
*/
void AbstractPool::add_open(const alloc &a){
auto result = OpenAllocations.emplace(a.head,a);
if(!result.second){
throw bad_request(__CEFUNCTION__,__LINE__,"Allocation already exists in OpenAllocations");
}
if(!OpenList.emplace(a.head_size,result.first).second){
throw bad_request(__CEFUNCTION__,__LINE__,"Allocation already exists in OpenList");
}
}
/*
*/
void AbstractPool::erase_open(openlist_iter &iter){
if(iter==OpenList.end()){
throw invalid_args(__CEFUNCTION__,__LINE__);
}
OpenAllocations.erase(iter->second);
OpenList.erase(iter);
}
/*
*/
void AbstractPool::erase_open(openalloc_iter &iter){
if(iter==OpenList.end()){
throw invalid_args(__CEFUNCTION__,__LINE__);
}
alloc a = iter->second;
auto iter2 = find_open(a);
if(iter2==OpenList.end()){
throw bad_request(__CEFUNCTION__,__LINE__,"Cannot find the OpenList iterator");
}
OpenAllocations.erase(iter);
OpenList.erase(iter2);
}
/* protected method
moves an allocation from the ClosedList to the OpenList
*/
void AbstractPool::moveto_open(closed_iter &iter){
//todo: perform merging
if(iter==ClosedList.end()){
throw invalid_args(__CEFUNCTION__, __LINE__, "Iterator is invalid.");
}
alloc &p_alloc = iter->second;
m_free += p_alloc.head_size;
m_used -= p_alloc.head_size;
auto neighbours = find_neighbours(p_alloc.head);
alloc left,right;
if(neighbours.second != OpenAllocations.end()){
right = neighbours.second->second;
}
if(neighbours.first != OpenAllocations.end()){
left = neighbours.first->second;
}
//todo: remember we might need to merge with both left and right
bool merged = false;
if(isAligned(type_size, right.head, p_alloc.head, p_alloc.head_size)){
auto iter = find_open(right);
merged = merge(iter, p_alloc);
p_alloc = iter->second->second;
if(!merged){
throw failed_operation(__CEFUNCTION__, __LINE__, "Failed attempt of merging allocations.");
}
}
if(isAligned(type_size, p_alloc.head, left.head, left.head_size)){
auto left_ol_iter = find_open(left);
if(merged){
auto right_ol_iter = find_open(right);
merged = merge(left_ol_iter, p_alloc);
erase_open(right_ol_iter);
} else {
merged = merge(left_ol_iter, p_alloc);
}
if(!merged){
throw failed_operation(__CEFUNCTION__, __LINE__, "Failed attempt of merging allocations.");
}
}
if(!merged){
add_open(p_alloc);
}
ClosedList.erase(iter);
}
/* protected method
moves an allocation from the ClosedList to the OpenList
*/
void AbstractPool::moveto_open(closed_iter &iter, const ce_uintptr &p, const size_t &N){
//todo: perform merging
if(iter==ClosedList.end()){
throw invalid_args(__CEFUNCTION__, __LINE__, "Iterator is invalid.");
}
alloc &a = iter->second;
if(a.head == p && a.head_size == N){
moveto_open(iter);
} else if(inRange(type_size, p, N, a.head, a.head_size)) {
auto neighbours = find_neighbours(p_alloc.head);
alloc left,right;
if(neighbours.second != OpenAllocations.end()){
right = neighbours.second->second;
}
if(neighbours.first != OpenAllocations.end()){
left = neighbours.first->second;
}
alloc b{a.head, p, a.master_size, N};
m_free += b.head_size;
m_used -= b.head_size;
if(isAligned(type_size, right.head, b.head, b.head_size)){
if(!merge(find_open(right),b)){
throw failed_operation(__CEFUNCTION__, __LINE__, "Failed attempt of merging allocations.");
}
a.head_size -= N;
} else if(isAligned(type_size, b.head, left.head, left.head_size)) {
if(!merge(find_open(left),b)){
throw failed_operation(__CEFUNCTION__, __LINE__, "Failed attempt of merging allocations.");
}
a.head += N;
a.head_size -= N;
} else {
//update front closed, add back closed, add middle to open
size_t front = b.head - a.head;
alloc c{b.master, b.head+b.head_size, b.master_size, a.head_size-(b.head_size+front)}
a.head_size = front;
add_open(b);
ClosedList.emplace(c.head,c);
}
update(ClosedList,iter,a);
} else {
throw bad_request(__CEFUNCTION__, __LINE__, "Range [p,p+N] is not in the range of the iterator sub-allocation passed.");
}
}
/*
*/
neighbours AbstractPool::find_neighbours(const ce_uintptr &p){
//assert(isClosed(p) && "p isn't managed, what did you do!"); //maybe an exception should be thrown :-/
auto end = OpenAllocations.end();
if(isOpen(p)){
// p would have been merged with its neighbours when joining the Open list
return std::make_pair(end,end); //throwing an exception is probably preferable
}
openalloc_iter left,right;
left = right = OpenAllocations.lower_bound(p);
if(left != OpenAllocations.begin()){
--left;
} else {
left = end;
}
auto iter = find_closed(p);
alloc &a = iter->second;
if(left != end){
if(!isAligned(type_size, a.head, left.head, left.head_size)){
left = end;
}
}
if(right != end){
if(!isAligned(type_size, right.head, a.head, a.head_size)){
right = end;
}
}
return std::make_pair(left,right);
}
/* todo: revise?
*/
closed_iter AbstractPool::find_closed(const ce_uintptr &p){
auto iter = ClosedList.lower_bound(p);
if(iter != ClosedList.end()){
if(iter->second.head != p){
if(iter != ClosedList.begin()){
--iter;
if(!inRange(p, iter->second.head, iter->second.head_size)){
iter = ClosedList.end()
}
} else {
iter = ClosedList.end();
}
}
}
return iter;
}
/*
*/
openlist_iter AbstractPool::find_open(const alloc &a){
auto iter = OpenList.lower_bound(a.head_size);
for(; iter != OpenList.end(); ++iter){
alloc &v = iter->second->second;
if(v.head_size != a.head_size){
return OpenList.end();
} else if(v.head == a.head){
return iter;
}
}
return OpenList.end();
}
openalloc_iter AbstractPool::find_open(const ce_uintptr &p){
auto iter = OpenAllocations.lower_bound(p);
if(iter != OpenAllocations.end()){
if(iter->second.head != p){
if(iter != OpenAllocations.begin()){
--iter;
if(!inRange(p, iter->second.head, iter->second.head_size)){
iter = OpenAllocations.end()
}
} else {
iter = OpenAllocations.end();
}
}
}
return iter;
}
| 33.850416
| 129
| 0.562193
|
cppcooper
|
ae9bf247d58776908d027655c5c3c795a38d297a
| 1,067
|
cpp
|
C++
|
examples/io/scoped_rdbuf.cpp
|
freundlich/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 13
|
2015-02-21T18:35:14.000Z
|
2019-12-29T14:08:29.000Z
|
examples/io/scoped_rdbuf.cpp
|
cpreh/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 5
|
2016-08-27T07:35:47.000Z
|
2019-04-21T10:55:34.000Z
|
examples/io/scoped_rdbuf.cpp
|
freundlich/fcppt
|
17df1b1ad08bf2435f6902d5465e3bc3fe5e3022
|
[
"BSL-1.0"
] | 8
|
2015-01-10T09:22:37.000Z
|
2019-12-01T08:31:12.000Z
|
// Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/char_type.hpp>
#include <fcppt/make_ref.hpp>
#include <fcppt/reference_to_base.hpp>
#include <fcppt/text.hpp>
#include <fcppt/io/cout.hpp>
#include <fcppt/io/ostringstream.hpp>
#include <fcppt/io/scoped_rdbuf.hpp>
#include <fcppt/config/external_begin.hpp>
#include <ios>
#include <streambuf>
#include <fcppt/config/external_end.hpp>
int main()
{
// NOLINTNEXTLINE(fuchsia-default-arguments-calls)
fcppt::io::ostringstream ostream{};
{
fcppt::io::scoped_rdbuf const scoped(
fcppt::reference_to_base<std::basic_ios<fcppt::char_type>>(
fcppt::make_ref(fcppt::io::cout())),
fcppt::reference_to_base<std::basic_streambuf<fcppt::char_type>>(
fcppt::make_ref(*ostream.rdbuf())));
fcppt::io::cout() << FCPPT_TEXT("This is a test!\n");
}
fcppt::io::cout() << ostream.str();
}
| 30.485714
| 73
| 0.686036
|
freundlich
|
ae9db79c5cbab6496f178a5eba9ee3de03974881
| 3,196
|
hpp
|
C++
|
include/AcmeExplorer.hpp
|
akaguha/acme_explorer
|
7c9aad2c7d9d4871b572e0a9e194ce484c77af87
|
[
"BSD-3-Clause"
] | null | null | null |
include/AcmeExplorer.hpp
|
akaguha/acme_explorer
|
7c9aad2c7d9d4871b572e0a9e194ce484c77af87
|
[
"BSD-3-Clause"
] | null | null | null |
include/AcmeExplorer.hpp
|
akaguha/acme_explorer
|
7c9aad2c7d9d4871b572e0a9e194ce484c77af87
|
[
"BSD-3-Clause"
] | null | null | null |
/**********************************************************************************
* BSD 3-Clause License
*
* Copyright (c) 2018, Akash Guha
* 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.
*
***********************************************************************************
*
* @file AcmeExplorer.hpp
* @author Akash Guha(akaguha@terpmail.umd.edu)
* @version 1.0
*
* @brief ENPM808X, Final Project - Localization, mapping and navigation using turtlebot
*
* @section DESCRIPTION
*
* This program is the header implementation of the AcmeExplorer class
*
*/
#ifndef INCLUDE_ACMEEXPLORER_HPP_
#define INCLUDE_ACMEEXPLORER_HPP_
#include <ros/ros.h>
#include <std_msgs/String.h>
#include <string>
#include "Navigate.hpp"
/**
* @brief Class for AcmeExplorer
*/
class AcmeExplorer {
private:
bool botCheckFlag = false; // Flag to check the robot status
ros::NodeHandle nH; // Create a node handle
public:
/**
* @brief Constructor for AcmeExplorer class for testing purpose
*
* @param str as string
* @return nothing
*/
explicit AcmeExplorer(std::string str);
/**
* @brief Default constructor for AcmeExplorer class
*
* @param nothing
* @return nothing
*/
AcmeExplorer();
/**
* @brief Default destructor for AcmeExplorer class
*
* @param nothing
* @return nothing
*/
~AcmeExplorer();
/**
* @brief Function to get the robot's status
*
* @param nothing
* @return true or flase based on the bot's status
*/
bool getbotCheckFlag();
/**
* @brief Function to set the status flag
*
* @param nothing
* @return nothing
*/
void setbotCheckFlag();
};
#endif // INCLUDE_ACMEEXPLORER_HPP_
| 31.96
| 88
| 0.68179
|
akaguha
|
aea40bc3c4a8c9636c15681045a396cdde4d2f1f
| 1,178
|
cpp
|
C++
|
src/Overlay/Widget/GameModeSelectWidget.cpp
|
GrimFlash/BBCF-Improvement-Mod-GGPO
|
9482ead2edd70714f427d3a5683d17b19ab8ac2e
|
[
"MIT"
] | 48
|
2020-06-09T22:53:52.000Z
|
2022-01-02T12:44:33.000Z
|
src/Overlay/Widget/GameModeSelectWidget.cpp
|
GrimFlash/BBCF-Improvement-Mod-GGPO
|
9482ead2edd70714f427d3a5683d17b19ab8ac2e
|
[
"MIT"
] | 2
|
2020-05-27T21:25:49.000Z
|
2020-05-27T23:56:56.000Z
|
src/Overlay/Widget/GameModeSelectWidget.cpp
|
GrimFlash/BBCF-Improvement-Mod-GGPO
|
9482ead2edd70714f427d3a5683d17b19ab8ac2e
|
[
"MIT"
] | 12
|
2020-06-17T20:44:17.000Z
|
2022-01-04T18:15:27.000Z
|
#include "GameModeSelectWidget.h"
#include "Core/interfaces.h"
#include <imgui.h>
void GameModeSelectWidget()
{
ImGui::BeginGroup();
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
ImGui::BeginChild("GameModeSelection", ImVec2(200, 210), true);
ImGui::TextUnformatted("Select game mode:");
for (int i = 0; i < g_interfaces.pGameModeManager->GetGameModesCount(); i++)
{
std::string gameModeName = g_interfaces.pGameModeManager->GetGameModeName((CustomGameMode)i);
std::string gameModeDesc = g_interfaces.pGameModeManager->GetGameModeDesc((CustomGameMode)i);
if (ImGui::RadioButton(gameModeName.c_str(), (int*)&g_interfaces.pGameModeManager->GetActiveGameModeRef(), i))
{
if (g_interfaces.pRoomManager->IsRoomFunctional())
{
g_interfaces.pOnlineGameModeManager->SetThisPlayerGameMode(g_interfaces.pGameModeManager->GetActiveGameMode());
g_interfaces.pOnlineGameModeManager->SendGameModePacket();
}
}
if (ImGui::IsItemHovered() && !gameModeDesc.empty())
{
ImGui::BeginTooltip();
ImGui::TextUnformatted(gameModeDesc.c_str());
ImGui::EndTooltip();
}
}
ImGui::EndChild();
ImGui::PopStyleVar();
ImGui::EndGroup();
}
| 28.047619
| 115
| 0.741087
|
GrimFlash
|
aea4259ff064193e7efb0d9ca8df92be5eb99481
| 4,086
|
cpp
|
C++
|
src/dialog/TableDialog/TableDialog.cpp
|
BlasterAlex/Uni-Correlation-Coefficient
|
709b6318d0c28a8704cfb3b1157a70fd95758e39
|
[
"Apache-2.0"
] | null | null | null |
src/dialog/TableDialog/TableDialog.cpp
|
BlasterAlex/Uni-Correlation-Coefficient
|
709b6318d0c28a8704cfb3b1157a70fd95758e39
|
[
"Apache-2.0"
] | null | null | null |
src/dialog/TableDialog/TableDialog.cpp
|
BlasterAlex/Uni-Correlation-Coefficient
|
709b6318d0c28a8704cfb3b1157a70fd95758e39
|
[
"Apache-2.0"
] | 2
|
2019-09-04T14:34:08.000Z
|
2019-09-17T05:46:36.000Z
|
/***
* Copyright 2019 Alexander Pishchulev (https://github.com/BlasterAlex)
*
* 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 <QCloseEvent>
#include <QDialog>
#include <QHeaderView>
#include <QIcon>
#include <QLabel>
#include <QString>
#include <QTableWidget>
#include <QTableWidgetItem>
#include <QVBoxLayout>
#include <QVariant>
#include <QVector>
#include <QWidget>
#include "../../Table/Table.hpp"
#include "FloatItem/FloatItem.hpp"
#include "TableDialog.hpp"
TableDialog::TableDialog(int n, Table t, QWidget *parent) : QDialog(parent) {
num = n;
setMinimumWidth(550);
setMinimumHeight(450);
setStyleSheet("QHeaderView::section {"
" background-color: #bdbdbd;"
" padding: 4px;"
" font-size: 14pt;"
" border-style: none;"
" border-bottom: 1px solid #fffff8;"
" border-right: 1px solid #fffff8;"
"}"
""
"QHeaderView::section:horizontal {"
" border-top: 1px solid #fffff8;"
"}"
"QHeaderView::section:horizontal:hover {"
" background-color: #a8a8a8;"
" text-decoration: underline;"
" font-weight: bold;"
"}"
""
"QHeaderView::down-arrow {"
" image: url(data/images/sort-down-solid.svg);"
" width: 12px;"
" margin: 0 10px 0 0;"
"}"
""
"QHeaderView::up-arrow {"
" image: url(data/images/sort-up-solid.svg);"
" width: 12px;"
" margin: 0 10px 0 0;"
"}"
""
"QHeaderView::up-arrow,"
"QHeaderView::down-arrow:hover {"
" width: 13px;"
"}"
""
"QLabel {"
" margin: 0 0 5px 0;"
"}");
QVBoxLayout *mainLayout = new QVBoxLayout(this);
mainLayout->setMargin(0);
mainLayout->setContentsMargins(0, 0, 0, 0);
mainLayout->setSpacing(0);
// Название
setWindowTitle(t.name.split(".")[0]);
// Заголовок
QLabel *textLabel = new QLabel(this);
textLabel->setText(t.name.split(".")[0]);
QFont font = textLabel->font();
font.setPointSize(14);
font.setBold(true);
textLabel->setFont(font);
textLabel->setAlignment(Qt::AlignTop | Qt::AlignCenter);
mainLayout->addWidget(textLabel);
// Таблица
table = new QTableWidget(this);
// Запрет редактирования таблицы
table->setEditTriggers(QAbstractItemView::NoEditTriggers);
// Отключение фокуса на таблице
table->setFocusPolicy(Qt::NoFocus);
table->setSelectionMode(QAbstractItemView::NoSelection);
// Включение сортировки столбцов
table->setSortingEnabled(true);
table->horizontalHeader()->setSortIndicatorShown(true);
// Размеры
table->horizontalHeader()->setStretchLastSection(true);
table->verticalHeader()->hide();
// Шапка таблицы
table->setRowCount(t.getSize());
table->setColumnCount(2);
table->setHorizontalHeaderLabels(QStringList() << "rank"
<< "name");
// Данные
int count = 0;
foreach (QVector<QString> rows, t.data) {
table->setItem(count, 0, new FloatItem(rows[0]));
table->setItem(count++, 1, new QTableWidgetItem(rows[1]));
}
mainLayout->addWidget(table);
}
// Событие закрытия окна
void TableDialog::closeEvent(QCloseEvent *event) {
emit shutdown();
event->accept();
}
| 30.721805
| 77
| 0.589574
|
BlasterAlex
|
aea4ab3795001276666987946d5919524daafc4c
| 1,084
|
hxx
|
C++
|
src/identicals.hxx
|
puzzlef/pagerank-nvgraph
|
bbc0ddb2c898c75ad93a4087ab7a57222666d1f4
|
[
"MIT"
] | null | null | null |
src/identicals.hxx
|
puzzlef/pagerank-nvgraph
|
bbc0ddb2c898c75ad93a4087ab7a57222666d1f4
|
[
"MIT"
] | null | null | null |
src/identicals.hxx
|
puzzlef/pagerank-nvgraph
|
bbc0ddb2c898c75ad93a4087ab7a57222666d1f4
|
[
"MIT"
] | null | null | null |
#pragma once
#include <map>
#include <vector>
#include <utility>
#include <algorithm>
#include "_main.hxx"
#include "vertices.hxx"
using std::map;
using std::vector;
using std::move;
using std::sort;
template <class G, class J>
auto edgeIdenticalsFromSize(const G& x, const J& ks, size_t n) {
using K = typename G::key_type;
using vec = vector<K>;
map<vec, vec> m; vec es;
// Find groups of identicals.
for (auto u : ks) {
copyWrite(x.edgeKeys(u), es);
sortValues(es);
m[es].push_back(u);
}
// Copy identicals from given size in sorted order.
vector2d<K> a;
for (auto& p : m) {
auto& is = p.second;
if (is.size()<n) continue;
sortValues(is);
a.push_back(move(is));
}
return a;
}
template <class G>
auto edgeIdenticalsFromSize(const G& x, size_t n) {
return edgeIdenticalsFromSize(x, x.vertexKeys(), n);
}
template <class G, class J>
auto edgeIdenticals(const G& x, const J& ks) {
return edgeIdenticalsFromSize(x, ks, 2);
}
template <class G>
auto edgeIdenticals(const G& x) {
return edgeIdenticals(x, x.vertexKeys());
}
| 20.45283
| 64
| 0.663284
|
puzzlef
|
000d264537608ffb9769272cd044e08410cec520
| 6,507
|
cpp
|
C++
|
Source.cpp
|
kenjinote/GetTwitterBearerToken
|
1c1ec7276cde25b7209c6dfc73bac1ec3dbbbbe6
|
[
"MIT"
] | null | null | null |
Source.cpp
|
kenjinote/GetTwitterBearerToken
|
1c1ec7276cde25b7209c6dfc73bac1ec3dbbbbe6
|
[
"MIT"
] | null | null | null |
Source.cpp
|
kenjinote/GetTwitterBearerToken
|
1c1ec7276cde25b7209c6dfc73bac1ec3dbbbbe6
|
[
"MIT"
] | null | null | null |
#pragma comment(linker,"\"/manifestdependency:type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
#pragma comment(lib, "wininet")
#pragma comment(lib, "crypt32")
#include <windows.h>
#include <commctrl.h>
#include <wininet.h>
#include "json11.hpp"
TCHAR szClassName[] = TEXT("Window");
BOOL GetStringFromJSON(LPCSTR lpszJson, LPCSTR lpszKey, LPSTR lpszValue, int nSizeValue)
{
std::string src(lpszJson);
std::string err;
json11::Json v = json11::Json::parse(src, err);
if (err.size()) return FALSE;
lpszValue[0] = 0;
strcpy_s(lpszValue, nSizeValue, v[lpszKey].string_value().c_str());
return strlen(lpszValue) > 0;
}
BOOL String2Base64(LPWSTR lpszBase64String, DWORD dwSize)
{
BOOL bReturn = FALSE;
DWORD dwLength = WideCharToMultiByte(CP_ACP, 0, lpszBase64String, -1, 0, 0, 0, 0);
LPSTR lpszStringA = (LPSTR)GlobalAlloc(GPTR, dwLength * sizeof(char));
WideCharToMultiByte(CP_ACP, 0, lpszBase64String, -1, lpszStringA, dwLength, 0, 0);
DWORD dwResult = 0;
if (CryptBinaryToStringW((LPBYTE)lpszStringA, dwLength - 1, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, 0, &dwResult))
{
if (dwResult <= dwSize && CryptBinaryToStringW((LPBYTE)lpszStringA, dwLength - 1, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, lpszBase64String, &dwResult))
{
bReturn = TRUE;
}
}
GlobalFree(lpszStringA);
return bReturn;
}
BOOL GetTwitterBearerToken(IN LPCWSTR lpszConsumerKey, IN LPCWSTR lpszConsumerSecret, OUT LPWSTR lpszBearerToken, IN DWORD dwSize)
{
HINTERNET hInternet = InternetOpen(NULL, INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0);
if (hInternet == NULL)
{
return FALSE;
}
HINTERNET hSession = InternetConnectW(hInternet, L"api.twitter.com", INTERNET_DEFAULT_HTTPS_PORT, NULL, NULL, INTERNET_SERVICE_HTTP, 0, 0);
if (hSession == NULL)
{
InternetCloseHandle(hInternet);
return FALSE;
}
HINTERNET hRequest = HttpOpenRequestW(hSession, L"POST", L"/oauth2/token", NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_SECURE, 0);
if (hRequest == NULL)
{
InternetCloseHandle(hSession);
InternetCloseHandle(hInternet);
return FALSE;
}
WCHAR credential[1024];
wsprintfW(credential, L"%s:%s", lpszConsumerKey, lpszConsumerSecret);
String2Base64(credential, sizeof(credential));
WCHAR header[1024];
wsprintfW(header, L"Authorization: Basic %s\r\nContent-Type: application/x-www-form-urlencoded;charset=UTF-8", credential);
CHAR param[] = "grant_type=client_credentials";
if (!HttpSendRequestW(hRequest, header, (DWORD)wcslen(header), param, (DWORD)strlen(param)))
{
InternetCloseHandle(hRequest);
InternetCloseHandle(hSession);
InternetCloseHandle(hInternet);
return FALSE;
}
BOOL bResult = FALSE;
WCHAR szBuffer[256] = { 0 };
DWORD dwBufferSize = _countof(szBuffer);
HttpQueryInfoW(hRequest, HTTP_QUERY_CONTENT_LENGTH, szBuffer, &dwBufferSize, NULL);
DWORD dwContentLength = _wtol(szBuffer);
LPBYTE lpByte = (LPBYTE)GlobalAlloc(0, dwContentLength + 1);
DWORD dwReadSize;
InternetReadFile(hRequest, lpByte, dwContentLength, &dwReadSize);
lpByte[dwReadSize] = 0;
CHAR szAccessToken[256];
if (GetStringFromJSON((LPCSTR)lpByte, "access_token", szAccessToken, _countof(szAccessToken)))
{
DWORD nLength = MultiByteToWideChar(CP_THREAD_ACP, 0, szAccessToken, -1, 0, 0);
if (nLength <= dwSize)
{
MultiByteToWideChar(CP_THREAD_ACP, 0, szAccessToken, -1, lpszBearerToken, nLength);
bResult = TRUE;
}
}
GlobalFree(lpByte);
InternetCloseHandle(hRequest);
InternetCloseHandle(hSession);
InternetCloseHandle(hInternet);
return bResult;
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
static HWND hButton;
static HWND hEdit1;
static HWND hEdit2;
static HWND hEdit3;
switch (msg)
{
case WM_CREATE:
hEdit1 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
SendMessage(hEdit1, EM_SETCUEBANNER, TRUE, (LPARAM)TEXT("Consumer key"));
hEdit2 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), TEXT(""), WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
SendMessage(hEdit2, EM_SETCUEBANNER, TRUE, (LPARAM)TEXT("Consumer secret"));
hButton = CreateWindow(TEXT("BUTTON"), TEXT("取得"), WS_VISIBLE | WS_CHILD | WS_TABSTOP, 0, 0, 0, 0, hWnd, (HMENU)IDOK, ((LPCREATESTRUCT)lParam)->hInstance, 0);
hEdit3 = CreateWindowEx(WS_EX_CLIENTEDGE, TEXT("EDIT"), 0, WS_VISIBLE | WS_CHILD | WS_TABSTOP | ES_AUTOHSCROLL | ES_READONLY, 0, 0, 0, 0, hWnd, 0, ((LPCREATESTRUCT)lParam)->hInstance, 0);
break;
case WM_SIZE:
MoveWindow(hEdit1, 10, 10, LOWORD(lParam) - 20, 32, TRUE);
MoveWindow(hEdit2, 10, 50, LOWORD(lParam) - 20, 32, TRUE);
MoveWindow(hButton, 10, 90, 256, 32, TRUE);
MoveWindow(hEdit3, 10, 130, LOWORD(lParam) - 20, 32, TRUE);
break;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK)
{
WCHAR szConsumerKey[128];
WCHAR szConsumerSecret[128];
WCHAR szBearerToken[128];
GetWindowTextW(hEdit1, szConsumerKey, _countof(szConsumerKey));
GetWindowTextW(hEdit2, szConsumerSecret, _countof(szConsumerSecret));
if (GetTwitterBearerToken(szConsumerKey, szConsumerSecret, szBearerToken, _countof(szBearerToken)))
{
SetWindowTextW(hEdit3, szBearerToken);
SendMessage(hEdit3, EM_SETSEL, 0, -1);
SetFocus(hEdit3);
}
}
break;
case WM_CLOSE:
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefDlgProc(hWnd, msg, wParam, lParam);
}
return 0;
}
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPreInst, LPSTR pCmdLine, int nCmdShow)
{
MSG msg;
WNDCLASS wndclass = {
CS_HREDRAW | CS_VREDRAW,
WndProc,
0,
DLGWINDOWEXTRA,
hInstance,
0,
LoadCursor(0,IDC_ARROW),
0,
0,
szClassName
};
RegisterClass(&wndclass);
HWND hWnd = CreateWindow(
szClassName,
TEXT("Get Twitter Bearer Token"),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
0,
CW_USEDEFAULT,
0,
0,
0,
hInstance,
0
);
ShowWindow(hWnd, SW_SHOWDEFAULT);
UpdateWindow(hWnd);
while (GetMessage(&msg, 0, 0, 0))
{
if (!IsDialogMessage(hWnd, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int)msg.wParam;
}
| 33.890625
| 196
| 0.709851
|
kenjinote
|
000f36e0dff70ffa9eea1662beb5752d0582927c
| 4,060
|
hh
|
C++
|
include/hdf5/helper_functions_test_client_hdf5.hh
|
mlawsonca/empress
|
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
|
[
"MIT"
] | 5
|
2018-11-28T19:38:23.000Z
|
2021-03-15T20:44:07.000Z
|
include/hdf5/helper_functions_test_client_hdf5.hh
|
mlawsonca/empress
|
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
|
[
"MIT"
] | null | null | null |
include/hdf5/helper_functions_test_client_hdf5.hh
|
mlawsonca/empress
|
aa3eb8544f2e01fcbd77749f7dce1b95fbfa11e9
|
[
"MIT"
] | 1
|
2018-07-18T15:22:36.000Z
|
2018-07-18T15:22:36.000Z
|
/*
* Copyright 2018 National Technology & Engineering Solutions of
* Sandia, LLC (NTESS). Under the terms of Contract DE-NA0003525 with NTESS,
* the U.S. Government retains certain rights in this software.
*
* The MIT License (MIT)
*
* Copyright (c) 2018 Sandia Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef HELPERFUNCTIONSTESTCLIENTHDF5_HH
#define HELPERFUNCTIONSTESTCLIENTHDF5_HH
#include <my_metadata_client_hdf5.hh>
#include <hdf5.h>
#include <hdf5_hl.h>
#include <vector>
void create_timestep(std::string run_name, std::string job_id, uint64_t timestep_id, hid_t run_file_id,
std::string TYPENAME_0, std::string TYPENAME_1,
std::string VARNAME_0, std::string VARNAME_1);
void catalog_all_var_attributes ( hid_t var_attr_table_id, uint64_t timestep_id, md_dim_bounds query_dims );
void catalog_all_var_attributes_with_type ( hid_t var_attr_table_id, uint64_t timestep_id, std::string type_name, md_dim_bounds query_dims );
void catalog_all_var_attributes_with_var ( hid_t var_attr_table_id, uint64_t timestep_id, std::string var_name, md_dim_bounds query_dims );
void catalog_all_var_attributes_with_type_var ( hid_t var_attr_table_id, uint64_t timestep_id, std::string type_name, std::string var_name,
md_dim_bounds query_dims );
void catalog_all_var_attributes_with_var_substr ( hid_t file_id, hid_t var_attr_table_id, uint64_t timestep_id,
md_dim_bounds query_dims );
void catalog_all_var_attributes_with_type_var_substr ( hid_t var_attr_table_id, uint64_t timestep_id,
std::string type_name, md_dim_bounds query_dims );
void catalog_all_types_substr ( hid_t var_attr_table_id, uint64_t timestep_id, md_dim_bounds query_dims );
// int delete_var_substr (hid_t file_id, hid_t var_attr_table_id, uint64_t timestep_id);
void create_timestep_attrs(hid_t timestep_attr_table0, hid_t timestep_attr_table1,
std::string type0_name, std::string type1_name );
void catalog_all_timestep_attributes ( hid_t timestep_attr_table_id, uint64_t timestep_id, std::string type_name);
void catalog_all_timesteps_substr ( hid_t run_file_id, std::string type_name, md_dim_bounds query_dims );
void create_new_timesteps(std::string run_name, std::string job_id, uint64_t timestep_id, hid_t run_file_id, std::string type0_name,
std::string type1_name, std::string var0_name, std::string var1_name, hid_t timestep20_var_attr_table_id);
void catalog_all_timesteps ( hid_t run_file_id, std::string type_name, std::string var_name, md_dim_bounds query_dims );
void create_run_attrs(hid_t run_attr_table_id, std::string type0_name, std::string type1_name );
void catalog_all_run_attributes ( hid_t run_attr_table_id, std::string type_name );
void catalog_all_types ( hid_t var_attr_table_id, uint64_t timestep_id, std::string var_name, md_dim_bounds query_dims );
void create_new_types(md_timestep_entry timestep0, md_timestep_entry timestep1, std::string var0_name, std::string var1_name);
#endif //HELPERFUNCTIONSTESTCLIENTHDF5_HH
| 48.333333
| 141
| 0.796552
|
mlawsonca
|
00121787f81db3a3224e3c7c8b80fd7ff1bbb873
| 2,207
|
hpp
|
C++
|
include/ight/common/pointer.hpp
|
alessandro40/libight
|
de434be18791844076603b50167c436a768e830e
|
[
"BSD-2-Clause"
] | null | null | null |
include/ight/common/pointer.hpp
|
alessandro40/libight
|
de434be18791844076603b50167c436a768e830e
|
[
"BSD-2-Clause"
] | null | null | null |
include/ight/common/pointer.hpp
|
alessandro40/libight
|
de434be18791844076603b50167c436a768e830e
|
[
"BSD-2-Clause"
] | null | null | null |
/*-
* This file is part of Libight <https://libight.github.io/>.
*
* Libight is free software. See AUTHORS and LICENSE for more
* information on the copying conditions.
*/
#ifndef IGHT_COMMON_POINTER_HPP
# define IGHT_COMMON_POINTER_HPP
#include <memory>
#include <stdexcept>
namespace ight {
namespace common {
namespace pointer {
/*!
* \brief Improved std::shared_ptr<T> with null pointer checks.
*
* This template class is a drop-in replacemente for the standard library's
* shared_ptr<>. It extends shared_ptr<>'s ->() and *() operators to check
* whether the pointee is a nullptr. In such case, unlike shared_ptr<>, the
* pointee is not accessed and a runtime exception is raised.
*
* Use this class as follows:
*
* using namespace ight::common::pointer;
* ...
* SharedPointer<Foo> ptr;
* ...
* ptr = std::make_shared<Foo>(...);
*
* That is, declare ptr as SharedPointer<Foo> and the behave like ptr was
* a shared_ptr<> variable instead.
*
* It is safe to assign the return value of std::make_shared<Foo> to
* SharedPointer<Foo> because SharedPointer have exactly the same fields
* as std::shared_pointer and because it inherits the copy and move
* constructors from std::shared_pointer.
*/
template<typename T> class SharedPointer : public std::shared_ptr<T> {
using std::shared_ptr<T>::shared_ptr;
public:
/*!
* \brief Access the pointee to get one of its fields.
* \returns A pointer to the pointee that allows one to access
* the requested pointee field.
* \throws std::runtime_error if the pointee is nullptr.
*/
T *operator->() const {
if (this->get() == nullptr) {
throw std::runtime_error("null pointer");
}
return std::shared_ptr<T>::operator->();
}
/*!
* \brief Get the value of the pointee.
* \returns The value of the pointee.
* \throws std::runtime_error if the pointee is nullptr.
*/
typename std::add_lvalue_reference<T>::type operator*() const {
if (this->get() == nullptr) {
throw std::runtime_error("null pointer");
}
return std::shared_ptr<T>::operator*();
}
};
}}}
#endif
| 29.824324
| 75
| 0.656547
|
alessandro40
|
001766550d49a60f20f6c9bb98be1cf0e5e86d3e
| 1,004
|
cpp
|
C++
|
engine/Engine.UI/src/ui/Color.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | null | null | null |
engine/Engine.UI/src/ui/Color.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | 10
|
2018-03-20T21:32:16.000Z
|
2018-04-23T19:42:59.000Z
|
engine/Engine.UI/src/ui/Color.cpp
|
Kartikeyapan598/Ghurund
|
bcdc5e1805bf82b3f9a0543a3bbe22681c5605ea
|
[
"MIT"
] | null | null | null |
#include "ghuipch.h"
#include "Color.h"
#include <regex>
namespace Ghurund::UI {
Color Ghurund::UI::Color::parse(const AString& color) {
uint32_t value = 0;
AString str = color.toLowerCase();
std::regex regex(" *\\#((?:[a-f0-9]{2})?[a-f0-9]{6}) *");
std::smatch m;
std::string s = str.Data;
if (std::regex_match(s, m, regex)) {
for (char c : m[0].str()) {
if (c >= '0' && c <= '9') {
value = value * 16 + (c - '0');
} else if (c >= 'a' && c <= 'f') {
value = value * 16 + (c - 'a' + 10);
}
}
} else {
throw std::invalid_argument("invalid color string");
}
return Color(value);
}
}
namespace Ghurund::Core {
template<>
const Type& getType<Ghurund::UI::Color>() {
static Type TYPE = Type(Ghurund::UI::NAMESPACE_NAME, "Color", sizeof(Ghurund::UI::Color));
return TYPE;
}
}
| 29.529412
| 98
| 0.465139
|
Kartikeyapan598
|
0021a96bced212c6e0f9187e795de7923b722581
| 653
|
hpp
|
C++
|
gibson/core/channels/common/MTLplyloader.hpp
|
rainprob/GibsonEnv
|
e0d0bc614713c676cb303bf9f11ca6a98713e0e0
|
[
"MIT"
] | 731
|
2018-02-26T18:35:05.000Z
|
2022-03-23T04:00:09.000Z
|
gibson/core/channels/common/MTLplyloader.hpp
|
Shubodh/GibsonEnv
|
38274874d7c2c2a87efdb6ee529f2b366c5219de
|
[
"MIT"
] | 111
|
2018-04-19T01:00:22.000Z
|
2022-03-18T17:43:50.000Z
|
gibson/core/channels/common/MTLplyloader.hpp
|
Shubodh/GibsonEnv
|
38274874d7c2c2a87efdb6ee529f2b366c5219de
|
[
"MIT"
] | 153
|
2018-02-27T04:38:40.000Z
|
2022-03-28T08:10:39.000Z
|
#ifndef MTLPLYLOADER_H
#define MTLPLYLOADER_H
#include "MTLtexture.hpp"
bool loadPLY_MTL(
const char * path,
std::vector<std::vector<glm::vec3>> & out_vertices,
std::vector<std::vector<glm::vec2>> & out_uvs,
std::vector<std::vector<glm::vec3>> & out_normals,
std::vector<glm::vec3> & out_centers,
//std::vector<int> & out_material_name,
std::vector<int> & out_material_id,
std::string & out_mtllib,
int & num_vertices
);
bool loadJSONtextures (
std::string jsonpath,
std::vector<int> & out_label_id,
std::vector<int> & out_segment_id,
std::vector<std::vector<int>> & out_face_indices
);
#endif
| 24.185185
| 55
| 0.672282
|
rainprob
|
002bf6c50769fe81aa30eabdf4222b6d9a59c003
| 1,118
|
cpp
|
C++
|
CPP/szuOJ/W12PC-creditCard.cpp
|
ParrySMS/Exp
|
78459e141308827b3e9a4ceb227808517d476a53
|
[
"Apache-2.0"
] | 2
|
2019-05-09T16:35:21.000Z
|
2019-08-19T11:57:53.000Z
|
CPP/szuOJ/W12PC-creditCard.cpp
|
ParrySMS/Exp
|
78459e141308827b3e9a4ceb227808517d476a53
|
[
"Apache-2.0"
] | null | null | null |
CPP/szuOJ/W12PC-creditCard.cpp
|
ParrySMS/Exp
|
78459e141308827b3e9a4ceb227808517d476a53
|
[
"Apache-2.0"
] | 2
|
2019-03-29T05:31:55.000Z
|
2019-12-03T07:35:42.000Z
|
#include <iostream>
#include <math.h>
#include <cstring>
#include <iomanip>
using namespace std;
class CVIP {
protected:
int card_id;
int point;
public:
CCard() {}
CCard(int c,int p) {
card_id = c;
point = p;
}
void init(int c,int p) {
card_id = c;
point = p;
}
};
class CCredit {
protected:
int credit_id;
string name;
int max;
double bill;
int cpoint;
public:
CCredit() { }
CCredit(int cid,string _name,int _max,double _bill,int _cpoint) {
credit_id = cid;
name = _name;
max = _max;
bill = _bill;
cpoint = _cpoint;
}
};
class CCreditVIP: public CCredit,public CVIP {
public:
CCreditVIP() {}
CCreditVIP(int n) {
seat_num = n;
}
};
int main() {
int card_id;
int point;
int credit_id;
string name;
int max;
double bill;
int cpoint;
cin>>max_speed>>speed>>weight;
CVehicle cv(max_speed,speed,weight);
cv.display();
cin>>height;
CBicycle cb(cv,height);
cb.showBYC();
cin>>seat_num;
CMotocar cm(cv,seat_num);
cm.showMOT();
CMotocycle cmoc(max_speed,speed,weight,height,seat_num);
cmoc.showMC();
return 0 ;
}
| 12.704545
| 67
| 0.635957
|
ParrySMS
|
002d927385e6b8518269dd5cb130c407f293b87a
| 316
|
cc
|
C++
|
Ejercicio1/primes.cc
|
Jdorta62/Jdorta62-IB-2020-2021-Practica8-Funciones
|
08ad27b3b1b6eb8d5ad2da177c0fa1dea8469039
|
[
"MIT"
] | null | null | null |
Ejercicio1/primes.cc
|
Jdorta62/Jdorta62-IB-2020-2021-Practica8-Funciones
|
08ad27b3b1b6eb8d5ad2da177c0fa1dea8469039
|
[
"MIT"
] | null | null | null |
Ejercicio1/primes.cc
|
Jdorta62/Jdorta62-IB-2020-2021-Practica8-Funciones
|
08ad27b3b1b6eb8d5ad2da177c0fa1dea8469039
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <cstdlib>
#include <string>
#include "primefunciones.h"
int main (int argc, char * argv[]) {
std::string convert = argv[1];
int primeposition = stoi(convert);
std::cout << "El primo #" << primeposition << " es: " << PrimePosition(primeposition)
<< std::endl;
return 0;
}
| 17.555556
| 87
| 0.642405
|
Jdorta62
|
002edff6b151af92ca0b0f991610936b6470f751
| 674
|
cpp
|
C++
|
Game/messageboxlogger.cpp
|
sethballantyne/Plexis
|
49b98918d9184321ba0dd449aded46b68eedb752
|
[
"MIT"
] | 1
|
2021-04-14T15:06:55.000Z
|
2021-04-14T15:06:55.000Z
|
Game/messageboxlogger.cpp
|
sethballantyne/Plexis
|
49b98918d9184321ba0dd449aded46b68eedb752
|
[
"MIT"
] | 7
|
2020-05-14T02:14:26.000Z
|
2020-05-22T04:57:47.000Z
|
Game/messageboxlogger.cpp
|
sethballantyne/Plexis
|
49b98918d9184321ba0dd449aded46b68eedb752
|
[
"MIT"
] | null | null | null |
#include <vcclr.h>
#include "messageboxlogger.h"
MessageBoxLogger::MessageBoxLogger(HWND hWnd)
{
{
if(!hWnd)
{
throw gcnew ArgumentNullException("hWnd is NULL.");
}
else
{
this->hWnd = hWnd;
}
}
}
void MessageBoxLogger::Write(String ^message)
{
pin_ptr<const wchar_t> unmanagedString = PtrToStringChars(message);
MessageBox(this->hWnd, unmanagedString, L"Unholy Error", MB_OK | MB_ICONEXCLAMATION | MB_TOPMOST);
}
// no idea why you'd use this function but it's here for completeness.
void MessageBoxLogger::WriteLine(String ^message)
{
Write(message += Environment::NewLine);
}
| 23.241379
| 102
| 0.649852
|
sethballantyne
|
002fd3ab99e86c06a4f8bdeab7a989ef10073872
| 43,933
|
cpp
|
C++
|
src/plugProjectHikinoU/PSSe.cpp
|
projectPiki/pikmin2
|
a431d992acde856d092889a515ecca0e07a3ea7c
|
[
"Unlicense"
] | 33
|
2021-12-08T11:10:59.000Z
|
2022-03-26T19:59:37.000Z
|
src/plugProjectHikinoU/PSSe.cpp
|
projectPiki/pikmin2
|
a431d992acde856d092889a515ecca0e07a3ea7c
|
[
"Unlicense"
] | 6
|
2021-12-22T17:54:31.000Z
|
2022-01-07T21:43:18.000Z
|
src/plugProjectHikinoU/PSSe.cpp
|
projectPiki/pikmin2
|
a431d992acde856d092889a515ecca0e07a3ea7c
|
[
"Unlicense"
] | 2
|
2022-01-04T06:00:49.000Z
|
2022-01-26T07:27:28.000Z
|
#include "types.h"
/*
Generated from dpostproc
.section .rodata # 0x804732E0 - 0x8049E220
.global lbl_80490038
lbl_80490038:
.4byte 0x8373834C
.4byte 0x53458AD4
.4byte 0x88F882AB
.4byte 0x90DD92E8
.4byte 0x00000000
.4byte 0x8373834C
.4byte 0x95A8895E
.4byte 0x82D189B9
.4byte 0x00000000
.4byte 0x8373834C
.4byte 0x8E648E96
.4byte 0x924082AB
.4byte 0x89B90000
.4byte 0x8373834C
.4byte 0x93DB82DD
.4byte 0x8D9E82DC
.4byte 0x82EA82E0
.4byte 0x82AA82AB
.4byte 0x90BA0000
.4byte 0x83608383
.4byte 0x838C8393
.4byte 0x83578382
.4byte 0x815B8368
.4byte 0x82CC8367
.4byte 0x83628376
.4byte 0x89E696CA
.4byte 0x97700000
.4byte 0x8373834C
.4byte 0x92859085
.4byte 0x89B99770
.4byte 0x00000000
.4byte 0x8373834C
.4byte 0x8370836A
.4byte 0x8362834E
.4byte 0x83898393
.4byte 0x97700000
.global lbl_804900C8
lbl_804900C8:
.4byte 0x50535365
.4byte 0x2E637070
.4byte 0x00000000
.global lbl_804900D4
lbl_804900D4:
.asciz "P2Assert"
.skip 3
.4byte 0x5053436F
.4byte 0x6D6D6F6E
.4byte 0x2E680000
.4byte 0x838A8393
.4byte 0x834E82AA
.4byte 0x82A082E8
.4byte 0x82DC82B9
.4byte 0x82F10000
.section .data, "wa" # 0x8049E220 - 0x804EFC20
.global __vt__Q26PSGame25Builder_EvnSe_Perspective
__vt__Q26PSGame25Builder_EvnSe_Perspective:
.4byte 0
.4byte 0
.4byte __dt__Q26PSGame25Builder_EvnSe_PerspectiveFv
.4byte
onBuild__Q26PSGame25Builder_EvnSe_PerspectiveFPQ28PSSystem9EnvSeBase .4byte
newSeObj__Q26PSGame25Builder_EvnSe_PerspectiveFUlf3Vec .global
__vt__Q26PSGame13EnvSe_AutoPan
__vt__Q26PSGame13EnvSe_AutoPan:
.4byte 0
.4byte 0
.4byte exec__Q28PSSystem9EnvSeBaseFv
.4byte play__Q28PSSystem9EnvSeBaseFv
.4byte getCastType__Q28PSSystem9EnvSeBaseFv
.4byte setPanAndDolby__Q26PSGame13EnvSe_AutoPanFP8JAISound
.global __vt__Q26PSGame17EnvSe_Perspective
__vt__Q26PSGame17EnvSe_Perspective:
.4byte 0
.4byte 0
.4byte exec__Q28PSSystem9EnvSeBaseFv
.4byte play__Q26PSGame17EnvSe_PerspectiveFv
.4byte getCastType__Q28PSSystem9EnvSeBaseFv
.4byte setPanAndDolby__Q28PSSystem9EnvSeBaseFP8JAISound
.global __vt__Q26PSGame9EnvSe_Pan
__vt__Q26PSGame9EnvSe_Pan:
.4byte 0
.4byte 0
.4byte exec__Q28PSSystem9EnvSeBaseFv
.4byte play__Q28PSSystem9EnvSeBaseFv
.4byte getCastType__Q28PSSystem9EnvSeBaseFv
.4byte setPanAndDolby__Q26PSGame9EnvSe_PanFP8JAISound
.global __vt__Q26PSGame5Rappa
__vt__Q26PSGame5Rappa:
.4byte 0
.4byte 0
.4byte __dt__Q26PSGame5RappaFv
.global __vt__Q26PSGame5SeMgr
__vt__Q26PSGame5SeMgr:
.4byte 0
.4byte 0
.4byte __dt__Q26PSGame5SeMgrFv
.global "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"
"__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>":
.4byte 0
.4byte 0
.4byte "__dt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>Fv"
.section .sdata, "wa" # 0x80514680 - 0x80514D80
.global cRatio__Q26PSGame5Rappa
cRatio__Q26PSGame5Rappa:
.float 15.0
.global cBaseWaitTime__Q26PSGame5Rappa
cBaseWaitTime__Q26PSGame5Rappa:
.4byte 0x00030000
.global sRappa__Q26PSGame5Rappa
sRappa__Q26PSGame5Rappa:
.4byte 0x00000000
.4byte 0x00000000
.global cNotUsingMasterIdRatio__Q26PSGame6RandId
cNotUsingMasterIdRatio__Q26PSGame6RandId:
.float -1.0
.section .sdata2, "a" # 0x80516360 - 0x80520E40
.global lbl_8051E188
lbl_8051E188:
.4byte 0x934794C4
.4byte 0x97700000
.global lbl_8051E190
lbl_8051E190:
.float 1.0
.global lbl_8051E194
lbl_8051E194:
.float 0.5
.global lbl_8051E198
lbl_8051E198:
.4byte 0x00000000
.global lbl_8051E19C
lbl_8051E19C:
.float 0.1
.global lbl_8051E1A0
lbl_8051E1A0:
.4byte 0xBF800000
.4byte 0x00000000
.global lbl_8051E1A8
lbl_8051E1A8:
.4byte 0x43300000
.4byte 0x80000000
.global lbl_8051E1B0
lbl_8051E1B0:
.4byte 0x43300000
.4byte 0x00000000
.global lbl_8051E1B8
lbl_8051E1B8:
.4byte 0x40000000
.global lbl_8051E1BC
lbl_8051E1BC:
.4byte 0x447A0000
*/
namespace PSGame {
/*
* --INFO--
* Address: 8033F158
* Size: 000210
*/
SeMgr::SeMgr()
{
/*
stwu r1, -0x20(r1)
mflr r0
lis r4, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@ha
stw r0, 0x24(r1)
addi r0, r4, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@l
lis r4, lbl_80490038@ha
stw r31, 0x1c(r1)
addi r31, r4, lbl_80490038@l
stw r30, 0x18(r1)
mr r30, r3
lis r3, __vt__Q26PSGame5SeMgr@ha
stw r29, 0x14(r1)
stw r0, 0(r30)
addi r0, r3, __vt__Q26PSGame5SeMgr@l
addi r3, r30, 0x24
stw r30,
"sInstance__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@sda21(r13) stw r0,
0(r30) bl __ct__Q26PSGame6RandIdFv li r0, 0 li r3, 0x18 stw
r0, 0x2c(r30) stw r0, 4(r30) stw r0, 8(r30) stw r0, 0xc(r30) stw
r0, 0x10(r30) stw r0, 0x14(r30) stw r0, 0x18(r30) stw r0,
0x1c(r30) stw r0, 0x20(r30) bl __nw__FUl or. r0, r3, r3 beq
lbl_8033F1EC addi r4, r31, 0 li r5, 0 li r6, 3 bl
__ct__Q26PSGame5SetSeFPCcss mr r0, r3
lbl_8033F1EC:
stw r0, 4(r30)
li r3, 0x18
bl __nw__FUl
or. r0, r3, r3
beq lbl_8033F214
addi r4, r31, 0x14
li r5, 9
li r6, 9
bl __ct__Q26PSGame5SetSeFPCcss
mr r0, r3
lbl_8033F214:
stw r0, 8(r30)
li r3, 0x18
bl __nw__FUl
or. r0, r3, r3
beq lbl_8033F23C
addi r4, r31, 0x24
li r5, 0
li r6, 5
bl __ct__Q26PSGame5SetSeFPCcss
mr r0, r3
lbl_8033F23C:
stw r0, 0xc(r30)
li r3, 0x18
bl __nw__FUl
or. r0, r3, r3
beq lbl_8033F264
addi r4, r31, 0x34
li r5, 0x14
li r6, 0x14
bl __ct__Q26PSGame5SetSeFPCcss
mr r0, r3
lbl_8033F264:
stw r0, 0x14(r30)
li r3, 0x18
bl __nw__FUl
or. r0, r3, r3
beq lbl_8033F28C
addi r4, r31, 0x4c
li r5, 0
li r6, 2
bl __ct__Q26PSGame5SetSeFPCcss
mr r0, r3
lbl_8033F28C:
stw r0, 0x18(r30)
li r3, 0x18
bl __nw__FUl
or. r0, r3, r3
beq lbl_8033F2B4
addi r4, r31, 0x6c
li r5, 2
li r6, 5
bl __ct__Q26PSGame5SetSeFPCcss
mr r0, r3
lbl_8033F2B4:
stw r0, 0x1c(r30)
li r3, 0x18
bl __nw__FUl
or. r0, r3, r3
beq lbl_8033F2DC
addi r4, r31, 0x7c
li r5, 4
li r6, 0xa
bl __ct__Q26PSGame5SetSeFPCcss
mr r0, r3
lbl_8033F2DC:
stw r0, 0x20(r30)
li r3, 0x18
bl __nw__FUl
or. r0, r3, r3
beq lbl_8033F304
addi r4, r2, lbl_8051E188@sda21
li r5, 0x14
li r6, 9
bl __ct__Q26PSGame5SetSeFPCcss
mr r0, r3
lbl_8033F304:
stw r0, 0x10(r30)
li r29, 0
b lbl_8033F33C
lbl_8033F310:
rlwinm r3, r29, 2, 0x16, 0x1d
addi r0, r3, 4
lwzx r0, r30, r0
cmplwi r0, 0
bne lbl_8033F338
addi r3, r31, 0x90
addi r5, r31, 0x9c
li r4, 0x2c
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_8033F338:
addi r29, r29, 1
lbl_8033F33C:
clrlwi r0, r29, 0x18
cmplwi r0, 8
blt lbl_8033F310
lwz r0, 0x24(r1)
mr r3, r30
lwz r31, 0x1c(r1)
lwz r30, 0x18(r1)
lwz r29, 0x14(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
/*
* --INFO--
* Address: 8033F368
* Size: 000120
*/
void SeMgr::playMessageVoice(unsigned long, bool)
{
/*
stwu r1, -0x40(r1)
mflr r0
stw r0, 0x44(r1)
stfd f31, 0x30(r1)
psq_st f31, 56(r1), 0, qr0
stfd f30, 0x20(r1)
psq_st f30, 40(r1), 0, qr0
stw r31, 0x1c(r1)
stw r30, 0x18(r1)
stw r29, 0x14(r1)
mr r30, r4
lfs f31, lbl_8051E190@sda21(r2)
cmpwi r30, 0x1850
lfs f30, cNotUsingMasterIdRatio__Q26PSGame6RandId@sda21(r13)
mr r29, r3
beq lbl_8033F3CC
bge lbl_8033F3B8
cmpwi r30, 0x1846
beq lbl_8033F3C4
b lbl_8033F45C
lbl_8033F3B8:
cmpwi r30, 0x185f
beq lbl_8033F3E4
b lbl_8033F45C
lbl_8033F3C4:
li r31, 0xa
b lbl_8033F3F0
lbl_8033F3CC:
clrlwi. r0, r5, 0x18
bne lbl_8033F3D8
lfs f31, lbl_8051E194@sda21(r2)
lbl_8033F3D8:
lfs f30, lbl_8051E198@sda21(r2)
li r31, 0xf
b lbl_8033F3F0
lbl_8033F3E4:
li r31, 0xf
b lbl_8033F3F0
b lbl_8033F45C
lbl_8033F3F0:
addis r0, r31, 1
cmplwi r0, 0xffff
bne lbl_8033F418
lis r3, lbl_804900C8@ha
lis r5, lbl_804900D4@ha
addi r3, r3, lbl_804900C8@l
li r4, 0x5a
addi r5, r5, lbl_804900D4@l
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_8033F418:
bl getRandom_0_1__7JALCalcFv
fcmpo cr0, f1, f31
bge lbl_8033F42C
li r0, 1
b lbl_8033F430
lbl_8033F42C:
li r0, 0
lbl_8033F430:
clrlwi. r0, r0, 0x18
beq lbl_8033F45C
stfs f30, 0x24(r29)
mr r4, r30
mr r6, r31
addi r3, r29, 0x24
addi r5, r29, 0x2c
li r7, 0
bl playSystemSe__Q26PSGame6RandIdFUlPP8JAISoundUlUl
lfs f0, cNotUsingMasterIdRatio__Q26PSGame6RandId@sda21(r13)
stfs f0, 0x24(r29)
lbl_8033F45C:
psq_l f31, 56(r1), 0, qr0
lfd f31, 0x30(r1)
psq_l f30, 40(r1), 0, qr0
lfd f30, 0x20(r1)
lwz r31, 0x1c(r1)
lwz r30, 0x18(r1)
lwz r0, 0x44(r1)
lwz r29, 0x14(r1)
mtlr r0
addi r1, r1, 0x40
blr
*/
}
/*
* --INFO--
* Address: 8033F488
* Size: 00003C
*/
void SeMgr::stopMessageVoice()
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
lwz r3, 0x2c(r3)
cmplwi r3, 0
beq lbl_8033F4B4
lwz r12, 0x10(r3)
li r4, 0
lwz r12, 0x14(r12)
mtctr r12
bctrl
lbl_8033F4B4:
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033F4C4
* Size: 000050
*/
Rappa::Rappa()
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r3
bl __ct__11JKRDisposerFv
lis r3, __vt__Q26PSGame5Rappa@ha
li r4, -1
addi r3, r3, __vt__Q26PSGame5Rappa@l
li r0, 0
stw r3, 0(r31)
mr r3, r31
stw r4, 0x18(r31)
sth r0, 0x1c(r31)
sth r0, 0x1e(r31)
lwz r31, 0xc(r1)
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033F514
* Size: 0000A0
*/
void Rappa::init(unsigned short)
{
/*
stwu r1, -0x10(r1)
mflr r0
li r5, 1
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r3
stw r30, 8(r1)
mr r30, r4
clrlwi r4, r4, 0x10
subfic r0, r4, 1
orc r3, r5, r4
srwi r0, r0, 1
subf r0, r0, r3
rlwinm. r0, r0, 1, 0x1f, 0x1f
bne lbl_8033F554
li r5, 0
lbl_8033F554:
clrlwi. r0, r5, 0x18
bne lbl_8033F578
lis r3, lbl_804900C8@ha
lis r5, lbl_804900D4@ha
addi r3, r3, lbl_804900C8@l
li r4, 0xb4
addi r5, r5, lbl_804900D4@l
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_8033F578:
clrlwi r3, r30, 0x10
rlwinm r0, r30, 2, 0xe, 0x1d
cntlzw r4, r3
addi r3, r13, sRappa__Q26PSGame5Rappa@sda21
rlwinm r4, r4, 0x1b, 0x1f, 0x1f
neg r4, r4
addi r4, r4, 0xe
stw r4, 0x18(r31)
stwx r31, r3, r0
lwz r31, 0xc(r1)
lwz r30, 8(r1)
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033F5B4
* Size: 000008
*/
void Rappa::setId(unsigned long a1)
{
// Generated from stw r4, 0x18(r3)
_18 = a1;
}
/*
* --INFO--
* Address: 8033F5BC
* Size: 000098
*/
Rappa::~Rappa()
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r4
stw r30, 8(r1)
or. r30, r3, r3
beq lbl_8033F638
lis r3, __vt__Q26PSGame5Rappa@ha
li r6, 0
addi r0, r3, __vt__Q26PSGame5Rappa@l
addi r5, r13, sRappa__Q26PSGame5Rappa@sda21
stw r0, 0(r30)
li r3, 0
b lbl_8033F610
lbl_8033F5F8:
rlwinm r4, r6, 2, 0x16, 0x1d
lwzx r0, r5, r4
cmplw r0, r30
bne lbl_8033F60C
stwx r3, r5, r4
lbl_8033F60C:
addi r6, r6, 1
lbl_8033F610:
clrlwi r0, r6, 0x18
cmplwi r0, 2
blt lbl_8033F5F8
mr r3, r30
li r4, 0
bl __dt__11JKRDisposerFv
extsh. r0, r31
ble lbl_8033F638
mr r3, r30
bl __dl__FPv
lbl_8033F638:
lwz r0, 0x14(r1)
mr r3, r30
lwz r31, 0xc(r1)
lwz r30, 8(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033F654
* Size: 000170
*/
void Rappa::playRappa(bool, float, float, JAInter::Object*)
{
/*
stwu r1, -0x40(r1)
mflr r0
stw r0, 0x44(r1)
stfd f31, 0x30(r1)
psq_st f31, 56(r1), 0, qr0
stfd f30, 0x20(r1)
psq_st f30, 40(r1), 0, qr0
stw r31, 0x1c(r1)
stw r30, 0x18(r1)
stw r29, 0x14(r1)
mr r29, r3
fmr f30, f1
lwz r3, 0x18(r3)
fmr f31, f2
mr r30, r4
mr r31, r5
addis r0, r3, 1
cmplwi r0, 0xffff
bne lbl_8033F6BC
lis r3, lbl_804900C8@ha
lis r5, lbl_804900D4@ha
addi r3, r3, lbl_804900C8@l
li r4, 0xcc
addi r5, r5, lbl_804900D4@l
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_8033F6BC:
clrlwi r0, r30, 0x18
li r3, 0
cmplwi r0, 1
bne lbl_8033F798
lfs f0, lbl_8051E198@sda21(r2)
fcmpo cr0, f31, f0
cror 2, 1, 2
bne lbl_8033F6E4
fmr f1, f31
b lbl_8033F6E8
lbl_8033F6E4:
fneg f1, f31
lbl_8033F6E8:
lfs f0, lbl_8051E198@sda21(r2)
fcmpo cr0, f30, f0
cror 2, 1, 2
bne lbl_8033F700
fmr f31, f30
b lbl_8033F704
lbl_8033F700:
fneg f31, f30
lbl_8033F704:
fcmpo cr0, f31, f1
ble lbl_8033F710
b lbl_8033F714
lbl_8033F710:
fmr f31, f1
lbl_8033F714:
lfs f0, lbl_8051E19C@sda21(r2)
fcmpo cr0, f31, f0
bge lbl_8033F728
li r3, 0
b lbl_8033F798
lbl_8033F728:
mr r3, r31
lwz r4, 0x18(r29)
lwz r12, 0(r31)
li r5, 0
lwz r12, 0xc(r12)
mtctr r12
bctrl
lfs f1, lbl_8051E190@sda21(r2)
lfs f0, lbl_8051E1A0@sda21(r2)
fsubs f3, f31, f1
lfs f2, lbl_8051E198@sda21(r2)
fmuls f3, f3, f0
fcmpo cr0, f3, f2
bge lbl_8033F764
b lbl_8033F778
lbl_8033F764:
fcmpo cr0, f3, f1
ble lbl_8033F774
fmr f2, f1
b lbl_8033F778
lbl_8033F774:
fmr f2, f3
lbl_8033F778:
lfs f0, cRatio__Q26PSGame5Rappa@sda21(r13)
lhz r0, cBaseWaitTime__Q26PSGame5Rappa@sda21(r13)
fmuls f2, f2, f0
fctiwz f0, f2
stfd f0, 8(r1)
lwz r4, 0xc(r1)
add r0, r4, r0
sth r0, 0x1c(r29)
lbl_8033F798:
psq_l f31, 56(r1), 0, qr0
lfd f31, 0x30(r1)
psq_l f30, 40(r1), 0, qr0
lfd f30, 0x20(r1)
lwz r31, 0x1c(r1)
lwz r30, 0x18(r1)
lwz r0, 0x44(r1)
lwz r29, 0x14(r1)
mtlr r0
addi r1, r1, 0x40
blr
*/
}
/*
* --INFO--
* Address: 8033F7C4
* Size: 00003C
*/
void Rappa::syncCpu_WaitChk(JASTrack*)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r3
mr r3, r4
li r4, 0xb
addi r5, r31, 0x1e
bl readPortAppDirect__8JASTrackFUlPUs
lwz r0, 0x14(r1)
lhz r3, 0x1c(r31)
lwz r31, 0xc(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033F800
* Size: 000008
*/
void Rappa::syncCpu_TblNo(JASTrack*)
{
/*
lhz r3, 0x1e(r3)
blr
*/
}
/*
* --INFO--
* Address: 8033F808
* Size: 000078
*/
SetSe::SetSe(const char*, short, short)
{
/*
stwu r1, -0x10(r1)
mflr r0
li r4, 0
stw r0, 0x14(r1)
extsh. r0, r6
stw r31, 0xc(r1)
mr r31, r3
sth r4, 0(r3)
li r3, -1
sth r5, 2(r31)
sth r6, 4(r31)
sth r5, 6(r31)
stw r3, 8(r31)
stb r4, 0x14(r31)
stw r4, 0xc(r31)
stw r4, 0x10(r31)
bge lbl_8033F868
lis r3, lbl_804900C8@ha
lis r5, lbl_804900D4@ha
addi r3, r3, lbl_804900C8@l
li r4, 0x13f
addi r5, r5, lbl_804900D4@l
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_8033F868:
lwz r0, 0x14(r1)
mr r3, r31
lwz r31, 0xc(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033F880
* Size: 000038
*/
void SetSe::exec()
{
/*
lhz r4, 0(r3)
lha r0, 6(r3)
cmpw r4, r0
ble lbl_8033F898
li r0, -1
stw r0, 8(r3)
lbl_8033F898:
lwz r4, 8(r3)
addis r0, r4, 1
cmplwi r0, 0xffff
beqlr
lhz r4, 0(r3)
addi r0, r4, 1
sth r0, 0(r3)
blr
*/
}
/*
* --INFO--
* Address: 8033F8B8
* Size: 0000B8
*/
void SetSe::startSound(JAInter::Object*, unsigned long, unsigned long)
{
/*
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
stw r31, 0x1c(r1)
mr r31, r6
stw r30, 0x18(r1)
mr r30, r5
stw r29, 0x14(r1)
or. r29, r4, r4
stw r28, 0x10(r1)
mr r28, r3
bne lbl_8033F904
lis r3, lbl_804900C8@ha
lis r5, lbl_804900D4@ha
addi r3, r3, lbl_804900C8@l
li r4, 0x150
addi r5, r5, lbl_804900D4@l
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_8033F904:
lwz r3, 8(r28)
addis r0, r3, 1
cmplwi r0, 0xffff
bne lbl_8033F94C
mr r3, r29
mr r4, r30
lwz r12, 0(r29)
mr r5, r31
lwz r12, 0xc(r12)
mtctr r12
bctrl
mr r0, r3
mr r3, r28
mr r31, r0
mr r4, r30
bl startCounter__Q26PSGame5SetSeFUl
mr r3, r31
b lbl_8033F950
lbl_8033F94C:
li r3, 0
lbl_8033F950:
lwz r0, 0x24(r1)
lwz r31, 0x1c(r1)
lwz r30, 0x18(r1)
lwz r29, 0x14(r1)
lwz r28, 0x10(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
/*
* --INFO--
* Address: 8033F970
* Size: 0000A0
*/
void SetSe::playSystemSe(unsigned long, unsigned long)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r4
stw r30, 8(r1)
mr r30, r3
lwz r3, 8(r3)
addis r0, r3, 1
cmplwi r0, 0xffff
bne lbl_8033F9F4
lbz r0, 0x14(r30)
mr r6, r5
lwz r3, spSysIF__8PSSystem@sda21(r13)
slwi r5, r0, 2
addi r5, r5, 0xc
add r5, r30, r5
bl playSystemSe__Q28PSSystem5SysIFFUlPP8JAISoundUl
mr r3, r30
mr r4, r31
bl startCounter__Q26PSGame5SetSeFUl
lbz r4, 0x14(r30)
slwi r3, r4, 2
addi r0, r4, 1
add r3, r30, r3
lwz r3, 0xc(r3)
stb r0, 0x14(r30)
lbz r0, 0x14(r30)
cmplwi r0, 2
bne lbl_8033F9F8
li r0, 0
stb r0, 0x14(r30)
b lbl_8033F9F8
lbl_8033F9F4:
li r3, 0
lbl_8033F9F8:
lwz r0, 0x14(r1)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033FA10
* Size: 000084
*/
void SetSe::startCounter(unsigned long)
{
/*
stwu r1, -0x30(r1)
mflr r0
stw r0, 0x34(r1)
li r0, 0
stw r31, 0x2c(r1)
mr r31, r3
sth r0, 0(r3)
stw r4, 8(r3)
bl getRandom_0_1__7JALCalcFv
lha r4, 4(r31)
lis r3, 0x43300000@ha
lha r0, 2(r31)
xoris r4, r4, 0x8000
stw r3, 8(r1)
xoris r0, r0, 0x8000
lfd f3, lbl_8051E1A8@sda21(r2)
stw r4, 0xc(r1)
lfd f0, 8(r1)
stw r0, 0x14(r1)
fsubs f2, f0, f3
stw r3, 0x10(r1)
lfd f0, 0x10(r1)
fsubs f0, f0, f3
fmadds f0, f2, f1, f0
fctiwz f0, f0
stfd f0, 0x18(r1)
lwz r0, 0x1c(r1)
sth r0, 6(r31)
lwz r31, 0x2c(r1)
lwz r0, 0x34(r1)
mtlr r0
addi r1, r1, 0x30
blr
*/
}
/*
* --INFO--
* Address: 8033FA94
* Size: 00000C
*/
RandId::RandId()
{
/*
lfs f0, cNotUsingMasterIdRatio__Q26PSGame6RandId@sda21(r13)
stfs f0, 0x43300000@l(r3)
blr
*/
}
/*
* --INFO--
* Address: 8033FAA0
* Size: 0001E8
*/
void RandId::startSound(JAInter::Object*, unsigned long, unsigned long, unsigned long)
{
/*
.loc_0x0:
stwu r1, -0x30(r1)
mflr r0
lfs f0, -0x1C0(r2)
stw r0, 0x34(r1)
stmw r27, 0x1C(r1)
mr r27, r3
mr r28, r4
mr r29, r5
mr r30, r6
mr r31, r7
lfs f1, 0x0(r3)
fcmpu cr0, f0, f1
bne- .loc_0xAC
cmplwi r30, 0x1
bgt- .loc_0x58
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1AA
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x3154B4
.loc_0x58:
bl -0x285604
lis r0, 0x4330
stw r30, 0xC(r1)
lfd f2, -0x1B0(r2)
stw r0, 0x8(r1)
lfd f0, 0x8(r1)
fsubs f0, f0, f2
fmuls f1, f0, f1
bl -0x27DFCC
mr r27, r3
cmplw r27, r30
blt- .loc_0xA4
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1AD
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x315500
.loc_0xA4:
add r27, r29, r27
b .loc_0x194
.loc_0xAC:
lfs f0, -0x1C8(r2)
fcmpo cr0, f1, f0
cror 2, 0x1, 0x2
beq- .loc_0xD8
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1B0
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x315534
.loc_0xD8:
cmplwi r30, 0x1
bgt- .loc_0xFC
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1B1
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x315558
.loc_0xFC:
bl -0x2856A8
lfs f0, 0x0(r27)
lfs f4, -0x1C8(r2)
fsubs f5, f1, f0
fcmpo cr0, f5, f4
bge- .loc_0x11C
mr r27, r29
b .loc_0x194
.loc_0x11C:
lis r3, 0x4330
lfs f3, -0x1D0(r2)
stw r30, 0xC(r1)
subi r0, r30, 0x1
lfd f1, -0x1B0(r2)
fsubs f2, f3, f0
stw r3, 0x8(r1)
li r3, 0x1
lfd f0, 0x8(r1)
fsubs f0, f0, f1
fsubs f0, f0, f3
fdivs f0, f2, f0
mtctr r0
cmplwi r30, 0x1
ble- .loc_0x174
.loc_0x158:
fsubs f5, f5, f0
fcmpo cr0, f5, f4
bge- .loc_0x16C
add r27, r29, r3
b .loc_0x194
.loc_0x16C:
addi r3, r3, 0x1
bdnz+ .loc_0x158
.loc_0x174:
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1C3
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x3155EC
mr r27, r29
.loc_0x194:
cmplwi r28, 0
bne- .loc_0x1B8
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1CC
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x315614
.loc_0x1B8:
mr r3, r28
mr r4, r27
lwz r12, 0x0(r28)
mr r5, r31
lwz r12, 0xC(r12)
mtctr r12
bctrl
lmw r27, 0x1C(r1)
lwz r0, 0x34(r1)
mtlr r0
addi r1, r1, 0x30
blr
*/
}
/*
* --INFO--
* Address: 8033FC88
* Size: 0001B8
*/
void RandId::playSystemSe(unsigned long, JAISound**, unsigned long, unsigned long)
{
/*
.loc_0x0:
stwu r1, -0x30(r1)
mflr r0
lfs f0, -0x1C0(r2)
stw r0, 0x34(r1)
stmw r27, 0x1C(r1)
mr r27, r3
mr r28, r4
mr r29, r5
mr r30, r6
mr r31, r7
lfs f1, 0x0(r3)
fcmpu cr0, f0, f1
bne- .loc_0xAC
cmplwi r30, 0x1
bgt- .loc_0x58
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1AA
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x31569C
.loc_0x58:
bl -0x2857EC
lis r0, 0x4330
stw r30, 0xC(r1)
lfd f2, -0x1B0(r2)
stw r0, 0x8(r1)
lfd f0, 0x8(r1)
fsubs f0, f0, f2
fmuls f1, f0, f1
bl -0x27E1B4
mr r27, r3
cmplw r27, r30
blt- .loc_0xA4
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1AD
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x3156E8
.loc_0xA4:
add r4, r28, r27
b .loc_0x194
.loc_0xAC:
lfs f0, -0x1C8(r2)
fcmpo cr0, f1, f0
cror 2, 0x1, 0x2
beq- .loc_0xD8
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1B0
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x31571C
.loc_0xD8:
cmplwi r30, 0x1
bgt- .loc_0xFC
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1B1
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x315740
.loc_0xFC:
bl -0x285890
lfs f0, 0x0(r27)
lfs f4, -0x1C8(r2)
fsubs f5, f1, f0
fcmpo cr0, f5, f4
bge- .loc_0x11C
mr r4, r28
b .loc_0x194
.loc_0x11C:
lis r3, 0x4330
lfs f3, -0x1D0(r2)
stw r30, 0xC(r1)
subi r0, r30, 0x1
lfd f1, -0x1B0(r2)
fsubs f2, f3, f0
stw r3, 0x8(r1)
li r3, 0x1
lfd f0, 0x8(r1)
fsubs f0, f0, f1
fsubs f0, f0, f3
fdivs f0, f2, f0
mtctr r0
cmplwi r30, 0x1
ble- .loc_0x174
.loc_0x158:
fsubs f5, f5, f0
fcmpo cr0, f5, f4
bge- .loc_0x16C
add r4, r28, r3
b .loc_0x194
.loc_0x16C:
addi r3, r3, 0x1
bdnz+ .loc_0x158
.loc_0x174:
lis r3, 0x8049
lis r5, 0x8049
addi r3, r3, 0xC8
li r4, 0x1C3
addi r5, r5, 0xD4
crclr 6, 0x6
bl -0x3157D4
mr r4, r28
.loc_0x194:
lwz r3, -0x67A8(r13)
mr r5, r29
mr r6, r31
bl -0x77B8
lmw r27, 0x1C(r1)
lwz r0, 0x34(r1)
mtlr r0
addi r1, r1, 0x30
blr
*/
}
/*
* --INFO--
* Address: 8033FE40
* Size: 000074
*/
void EnvSe_Pan::setPanAndDolby(JAISound*)
{
/*
stwu r1, -0x10(r1)
mflr r0
li r5, 0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r4
li r4, 0
stw r30, 8(r1)
mr r30, r3
mr r3, r31
lwz r12, 0x10(r31)
lfs f1, 0x3c(r30)
lwz r12, 0x24(r12)
mtctr r12
bctrl
mr r3, r31
lfs f1, 0x40(r30)
lwz r12, 0x10(r31)
li r4, 0
li r5, 0
lwz r12, 0x3c(r12)
mtctr r12
bctrl
lwz r0, 0x14(r1)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033FEB4
* Size: 000060
*/
EnvSe_Perspective::EnvSe_Perspective(unsigned long, float, Vec)
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r5
stw r30, 8(r1)
mr r30, r3
bl __ct__Q28PSSystem9EnvSeBaseFUlf
lis r3, __vt__Q26PSGame17EnvSe_Perspective@ha
lfs f2, 0(r31)
addi r0, r3, __vt__Q26PSGame17EnvSe_Perspective@l
lfs f1, 4(r31)
stw r0, 0x10(r30)
mr r3, r30
lfs f0, 8(r31)
stfs f2, 0x3c(r30)
stfs f1, 0x40(r30)
stfs f0, 0x44(r30)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
lwz r0, 0x14(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033FF14
* Size: 00004C
*/
void EnvSe_Perspective::play()
{
/*
stwu r1, -0x10(r1)
mflr r0
li r7, 0
li r8, 0
stw r0, 0x14(r1)
li r9, 4
stw r31, 0xc(r1)
mr r31, r3
addi r5, r31, 0x34
lwz r3, spSysIF__8PSSystem@sda21(r13)
addi r6, r31, 0x3c
lwz r4, 0x24(r31)
bl "startSoundVecT<8JAISound>__8JAIBasicFUlPP8JAISoundP3VecUlUlUc"
lwz r0, 0x14(r1)
lwz r3, 0x34(r31)
lwz r31, 0xc(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 8033FF60
* Size: 000088
*/
EnvSe_AutoPan::EnvSe_AutoPan(unsigned long, float, float, float, float, float)
{
/*
stwu r1, -0x30(r1)
mflr r0
stw r0, 0x34(r1)
addi r11, r1, 0x30
bl _savefpr_28
stw r31, 0xc(r1)
fmr f28, f1
mr r31, r3
fmr f29, f2
fmr f30, f4
fmr f31, f5
fmr f1, f3
bl __ct__Q28PSSystem9EnvSeBaseFUlf
lis r4, __vt__Q26PSGame9EnvSe_Pan@ha
lis r3, __vt__Q26PSGame13EnvSe_AutoPan@ha
addi r4, r4, __vt__Q26PSGame9EnvSe_Pan@l
li r0, 1
stw r4, 0x10(r31)
addi r4, r3, __vt__Q26PSGame13EnvSe_AutoPan@l
mr r3, r31
stfs f28, 0x3c(r31)
stfs f29, 0x40(r31)
stw r4, 0x10(r31)
stfs f30, 0x44(r31)
stfs f31, 0x48(r31)
stb r0, 0x4c(r31)
stb r0, 0x4d(r31)
addi r11, r1, 0x30
bl _restfpr_28
lwz r0, 0x34(r1)
lwz r31, 0xc(r1)
mtlr r0
addi r1, r1, 0x30
blr
*/
}
/*
* --INFO--
* Address: 8033FFE8
* Size: 00000C
*/
void EnvSe_AutoPan::setDirection(bool, bool)
{
/*
stb r4, 0x4c(r3)
stb r5, 0x4d(r3)
blr
*/
}
/*
* --INFO--
* Address: 8033FFF4
* Size: 00011C
*/
void EnvSe_AutoPan::setPanAndDolby(JAISound*)
{
/*
stwu r1, -0x10(r1)
mflr r0
li r5, 0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
mr r31, r4
stw r30, 8(r1)
mr r30, r3
b lbl_803400AC
lbl_80340018:
clrlwi r3, r5, 0x18
addi r4, r3, 0x4c
lbzx r0, r30, r4
cmplwi r0, 0
beq lbl_8034006C
slwi r0, r3, 2
lfs f0, lbl_8051E190@sda21(r2)
add r3, r30, r0
lfs f2, 0x3c(r3)
lfs f1, 0x44(r3)
fadds f1, f2, f1
stfs f1, 0x3c(r3)
lfs f1, 0x3c(r3)
fcmpo cr0, f1, f0
ble lbl_803400A8
lfs f0, lbl_8051E1B8@sda21(r2)
li r0, 0
fsubs f0, f0, f1
stfs f0, 0x3c(r3)
stbx r0, r30, r4
b lbl_803400A8
lbl_8034006C:
slwi r0, r3, 2
lfs f0, lbl_8051E198@sda21(r2)
add r3, r30, r0
lfs f2, 0x3c(r3)
lfs f1, 0x44(r3)
fsubs f1, f2, f1
stfs f1, 0x3c(r3)
lfs f1, 0x3c(r3)
fcmpo cr0, f1, f0
bge lbl_803400A8
lfs f0, lbl_8051E1A0@sda21(r2)
li r0, 1
fmuls f0, f1, f0
stfs f0, 0x3c(r3)
stbx r0, r30, r4
lbl_803400A8:
addi r5, r5, 1
lbl_803400AC:
clrlwi r0, r5, 0x18
cmplwi r0, 2
blt lbl_80340018
mr r3, r31
lfs f1, 0x3c(r30)
lwz r12, 0x10(r31)
li r4, 0
li r5, 0
lwz r12, 0x24(r12)
mtctr r12
bctrl
mr r3, r31
lfs f1, 0x40(r30)
lwz r12, 0x10(r31)
li r4, 0
li r5, 0
lwz r12, 0x3c(r12)
mtctr r12
bctrl
lwz r0, 0x14(r1)
lwz r31, 0xc(r1)
lwz r30, 8(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
/*
* --INFO--
* Address: 80340110
* Size: 00021C
*/
Builder_EvnSe_Perspective::Builder_EvnSe_Perspective(JGeometry::TBox3<float>)
{
/*
stwu r1, -0x30(r1)
mflr r0
stw r0, 0x34(r1)
stw r31, 0x2c(r1)
mr r31, r4
stw r30, 0x28(r1)
mr r30, r3
bl __ct__11JKRDisposerFv
lis r3, __vt__Q26PSGame25Builder_EvnSe_Perspective@ha
li r0, 0
addi r3, r3, __vt__Q26PSGame25Builder_EvnSe_Perspective@l
lfs f1, 0(r31)
stw r3, 0(r30)
addi r3, r30, 0x40
lfs f0, 4(r31)
stb r0, 0x18(r30)
lfs f4, 8(r31)
stw r0, 0x1c(r30)
lfs f3, 0xc(r31)
stw r0, 0x20(r30)
lfs f2, 0x10(r31)
stfs f1, 0x24(r30)
lfs f1, 0x14(r31)
stfs f0, 0x28(r30)
lfs f0, lbl_8051E198@sda21(r2)
stfs f4, 0x2c(r30)
stfs f3, 0x30(r30)
stfs f2, 0x34(r30)
stfs f1, 0x38(r30)
stfs f0, 0x3c(r30)
bl initiate__10JSUPtrListFv
lfs f0, 0x30(r30)
li r0, 0
lfs f2, 0x24(r30)
fcmpo cr0, f0, f2
cror 2, 1, 2
bne lbl_803401D0
lfs f1, 0x34(r30)
lfs f0, 0x28(r30)
fcmpo cr0, f1, f0
cror 2, 1, 2
bne lbl_803401D0
lfs f1, 0x38(r30)
lfs f0, 0x2c(r30)
fcmpo cr0, f1, f0
cror 2, 1, 2
bne lbl_803401D0
li r0, 1
lbl_803401D0:
clrlwi. r0, r0, 0x18
bne lbl_80340310
lwz r0, 0x24(r30)
lwz r6, 0x28(r30)
stw r0, 8(r1)
lwz r5, 0x2c(r30)
lfs f0, 8(r1)
lwz r4, 0x30(r30)
lwz r3, 0x34(r30)
fcmpo cr0, f2, f0
lwz r0, 0x38(r30)
stw r6, 0xc(r1)
stw r5, 0x10(r1)
stw r4, 0x14(r1)
stw r3, 0x18(r1)
stw r0, 0x1c(r1)
cror 2, 1, 2
bne lbl_8034021C
stfs f0, 0x24(r30)
lbl_8034021C:
lfs f0, 0x28(r30)
lfs f1, 0xc(r1)
fcmpo cr0, f0, f1
cror 2, 1, 2
bne lbl_80340234
stfs f1, 0x28(r30)
lbl_80340234:
lfs f0, 0x2c(r30)
lfs f2, 0x10(r1)
fcmpo cr0, f0, f2
cror 2, 1, 2
bne lbl_8034024C
stfs f2, 0x2c(r30)
lbl_8034024C:
lfs f0, 0x24(r30)
lfs f3, 0x14(r1)
fcmpo cr0, f0, f3
cror 2, 1, 2
bne lbl_80340264
stfs f3, 0x24(r30)
lbl_80340264:
lfs f0, 0x28(r30)
lfs f4, 0x18(r1)
fcmpo cr0, f0, f4
cror 2, 1, 2
bne lbl_8034027C
stfs f4, 0x28(r30)
lbl_8034027C:
lfs f0, 0x2c(r30)
lfs f5, 0x1c(r1)
fcmpo cr0, f0, f5
cror 2, 1, 2
bne lbl_80340294
stfs f5, 0x2c(r30)
lbl_80340294:
lfs f0, 0x30(r30)
lfs f6, 8(r1)
fcmpo cr0, f0, f6
cror 2, 0, 2
bne lbl_803402AC
stfs f6, 0x30(r30)
lbl_803402AC:
lfs f0, 0x34(r30)
fcmpo cr0, f0, f1
cror 2, 0, 2
bne lbl_803402C0
stfs f1, 0x34(r30)
lbl_803402C0:
lfs f0, 0x38(r30)
fcmpo cr0, f0, f2
cror 2, 0, 2
bne lbl_803402D4
stfs f2, 0x38(r30)
lbl_803402D4:
lfs f0, 0x30(r30)
fcmpo cr0, f0, f3
cror 2, 0, 2
bne lbl_803402E8
stfs f3, 0x30(r30)
lbl_803402E8:
lfs f0, 0x34(r30)
fcmpo cr0, f0, f4
cror 2, 0, 2
bne lbl_803402FC
stfs f4, 0x34(r30)
lbl_803402FC:
lfs f0, 0x38(r30)
fcmpo cr0, f0, f5
cror 2, 0, 2
bne lbl_80340310
stfs f5, 0x38(r30)
lbl_80340310:
lwz r0, 0x34(r1)
mr r3, r30
lwz r31, 0x2c(r1)
lwz r30, 0x28(r1)
mtlr r0
addi r1, r1, 0x30
blr
*/
}
/*
* --INFO--
* Address: 8034032C
* Size: 0002D0
*/
void Builder_EvnSe_Perspective::build(float, PSSystem::EnvSeMgr*)
{
/*
stwu r1, -0xc0(r1)
mflr r0
stw r0, 0xc4(r1)
stfd f31, 0xb0(r1)
psq_st f31, 184(r1), 0, qr0
stfd f30, 0xa0(r1)
psq_st f30, 168(r1), 0, qr0
stfd f29, 0x90(r1)
psq_st f29, 152(r1), 0, qr0
stfd f28, 0x80(r1)
psq_st f28, 136(r1), 0, qr0
stfd f27, 0x70(r1)
psq_st f27, 120(r1), 0, qr0
stfd f26, 0x60(r1)
psq_st f26, 104(r1), 0, qr0
stmw r25, 0x44(r1)
or. r27, r4, r4
fmr f31, f1
lis r4, lbl_80490038@ha
mr r26, r3
addi r30, r4, lbl_80490038@l
bne lbl_80340398
addi r3, r30, 0x90
addi r5, r30, 0x9c
li r4, 0x254
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_80340398:
lfs f3, 0x30(r26)
lfs f2, 0x24(r26)
lfs f1, 0x38(r26)
lfs f0, 0x2c(r26)
fsubs f29, f3, f2
fsubs f28, f1, f0
stfs f29, 0xc(r1)
stfs f28, 8(r1)
lbz r0, 0x18(r26)
cmplwi r0, 0
bne lbl_80340400
lfs f1, lbl_8051E1BC@sda21(r2)
addi r4, r26, 0x1c
addi r3, r1, 0xc
addi r0, r26, 0x20
lbl_803403D4:
lfs f0, 0(r3)
cmplw r4, r0
fdivs f0, f0, f1
fctiwz f0, f0
stfd f0, 0x28(r1)
lwz r3, 0x2c(r1)
stw r3, 0(r4)
beq lbl_8034043C
mr r4, r0
addi r3, r1, 8
b lbl_803403D4
lbl_80340400:
lwz r0, 0x1c(r26)
li r3, 0
cmpwi r0, 0
ble lbl_80340420
lwz r0, 0x20(r26)
cmpwi r0, 0
ble lbl_80340420
li r3, 1
lbl_80340420:
clrlwi. r0, r3, 0x18
bne lbl_8034043C
addi r3, r30, 0x90
addi r5, r30, 0x9c
li r4, 0x27f
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_8034043C:
lwz r3, 0x1c(r26)
lis r31, 0x4330
lwz r0, 0x20(r26)
li r29, 0
xoris r3, r3, 0x8000
lfs f5, 0x3c(r26)
xoris r0, r0, 0x8000
stw r3, 0x2c(r1)
lfd f30, lbl_8051E1A8@sda21(r2)
stw r31, 0x28(r1)
lfs f2, lbl_8051E194@sda21(r2)
lfd f0, 0x28(r1)
stw r0, 0x34(r1)
fsubs f4, f0, f30
lfs f1, 0x24(r26)
stw r31, 0x30(r1)
lfs f0, 0x2c(r26)
lfd f3, 0x30(r1)
fdivs f29, f29, f4
stfs f5, 0x20(r1)
fsubs f3, f3, f30
fmadds f27, f29, f2, f1
fdivs f28, f28, f3
fmadds f26, f28, f2, f0
b lbl_803405AC
lbl_803404A0:
xoris r0, r29, 0x8000
stw r31, 0x30(r1)
li r28, 0
stw r0, 0x34(r1)
lfd f0, 0x30(r1)
fsubs f0, f0, f30
fmadds f0, f29, f0, f27
stfs f0, 0x1c(r1)
b lbl_8034059C
lbl_803404C4:
xoris r3, r28, 0x8000
lwz r0, 0x4c(r26)
stw r3, 0x34(r1)
cmplwi r0, 0
stw r31, 0x30(r1)
lfd f0, 0x30(r1)
fsubs f0, f0, f30
fmadds f0, f28, f0, f26
stfs f0, 0x24(r1)
bne lbl_80340500
addi r3, r30, 0xa8
addi r5, r30, 0xb4
li r4, 0xd2
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_80340500:
lwz r3, 0x4c(r26)
lwz r0, 0xc(r3)
stw r0, 0x4c(r26)
lwz r0, 0x4c(r26)
cmplwi r0, 0
bne lbl_80340520
lwz r0, 0x40(r26)
stw r0, 0x4c(r26)
lbl_80340520:
lwz r4, 0x10(r3)
fmr f1, f31
lwz r7, 0x1c(r1)
mr r3, r26
lwz r6, 0x20(r1)
addi r5, r1, 0x10
lwz r0, 0x24(r1)
stw r7, 0x10(r1)
stw r6, 0x14(r1)
stw r0, 0x18(r1)
lwz r12, 0(r26)
lwz r12, 0x10(r12)
mtctr r12
bctrl
or. r25, r3, r3
bne lbl_80340574
addi r3, r30, 0x90
addi r5, r30, 0x9c
li r4, 0x296
crclr 6
bl panic_f__12JUTExceptionFPCciPCce
lbl_80340574:
mr r3, r26
mr r4, r25
lwz r12, 0(r26)
lwz r12, 0xc(r12)
mtctr r12
bctrl
mr r3, r27
mr r4, r25
bl append__10JSUPtrListFP10JSUPtrLink
addi r28, r28, 1
lbl_8034059C:
lwz r0, 0x20(r26)
cmpw r28, r0
blt lbl_803404C4
addi r29, r29, 1
lbl_803405AC:
lwz r0, 0x1c(r26)
cmpw r29, r0
blt lbl_803404A0
psq_l f31, 184(r1), 0, qr0
lfd f31, 0xb0(r1)
psq_l f30, 168(r1), 0, qr0
lfd f30, 0xa0(r1)
psq_l f29, 152(r1), 0, qr0
lfd f29, 0x90(r1)
psq_l f28, 136(r1), 0, qr0
lfd f28, 0x80(r1)
psq_l f27, 120(r1), 0, qr0
lfd f27, 0x70(r1)
psq_l f26, 104(r1), 0, qr0
lfd f26, 0x60(r1)
lmw r25, 0x44(r1)
lwz r0, 0xc4(r1)
mtlr r0
addi r1, r1, 0xc0
blr
*/
}
/*
* --INFO--
* Address: 803405FC
* Size: 0000AC
*/
void Builder_EvnSe_Perspective::newSeObj(unsigned long, float, Vec)
{
/*
stwu r1, -0x40(r1)
mflr r0
stw r0, 0x44(r1)
stfd f31, 0x30(r1)
psq_st f31, 56(r1), 0, qr0
stw r31, 0x2c(r1)
stw r30, 0x28(r1)
stw r29, 0x24(r1)
fmr f31, f1
mr r29, r4
mr r30, r5
li r3, 0x48
bl __nw__FUl
or. r31, r3, r3
beq lbl_80340680
lwz r6, 0(r30)
fmr f1, f31
lwz r5, 4(r30)
mr r4, r29
lwz r0, 8(r30)
stw r6, 8(r1)
stw r5, 0xc(r1)
stw r0, 0x10(r1)
bl __ct__Q28PSSystem9EnvSeBaseFUlf
lis r3, __vt__Q26PSGame17EnvSe_Perspective@ha
lfs f2, 8(r1)
addi r0, r3, __vt__Q26PSGame17EnvSe_Perspective@l
lfs f1, 0xc(r1)
stw r0, 0x10(r31)
lfs f0, 0x10(r1)
stfs f2, 0x3c(r31)
stfs f1, 0x40(r31)
stfs f0, 0x44(r31)
lbl_80340680:
mr r3, r31
psq_l f31, 56(r1), 0, qr0
lwz r0, 0x44(r1)
lfd f31, 0x30(r1)
lwz r31, 0x2c(r1)
lwz r30, 0x28(r1)
lwz r29, 0x24(r1)
mtlr r0
addi r1, r1, 0x40
blr
*/
}
/*
* --INFO--
* Address: 803406A8
* Size: 0000C8
*/
Builder_EvnSe_Perspective::~Builder_EvnSe_Perspective()
{
/*
stwu r1, -0x20(r1)
mflr r0
stw r0, 0x24(r1)
stw r31, 0x1c(r1)
stw r30, 0x18(r1)
mr r30, r4
stw r29, 0x14(r1)
or. r29, r3, r3
beq lbl_80340750
lis r3, __vt__Q26PSGame25Builder_EvnSe_Perspective@ha
addic. r0, r29, 0x40
addi r0, r3, __vt__Q26PSGame25Builder_EvnSe_Perspective@l
stw r0, 0(r29)
beq lbl_80340734
b lbl_80340714
lbl_803406E4:
mr r4, r31
addi r3, r29, 0x40
bl remove__10JSUPtrListFP10JSUPtrLink
lwz r31, 0(r31)
cmplwi r31, 0
beq lbl_80340714
beq lbl_8034070C
mr r3, r31
li r4, 0
bl __dt__10JSUPtrLinkFv
lbl_8034070C:
mr r3, r31
bl __dl__FPv
lbl_80340714:
lwz r31, 0x40(r29)
cmplwi r31, 0
bne lbl_803406E4
addic. r0, r29, 0x40
beq lbl_80340734
addi r3, r29, 0x40
li r4, 0
bl __dt__10JSUPtrListFv
lbl_80340734:
mr r3, r29
li r4, 0
bl __dt__11JKRDisposerFv
extsh. r0, r30
ble lbl_80340750
mr r3, r29
bl __dl__FPv
lbl_80340750:
lwz r0, 0x24(r1)
mr r3, r29
lwz r31, 0x1c(r1)
lwz r30, 0x18(r1)
lwz r29, 0x14(r1)
mtlr r0
addi r1, r1, 0x20
blr
*/
}
} // namespace PSGame
namespace PSSystem {
/*
* --INFO--
* Address: 80340770
* Size: 000050
*/
void SingletonBase<PSGame::SeMgr>::~SingletonBase()
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
or. r31, r3, r3
beq lbl_803407A8
lis r5, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@ha
extsh. r0, r4
addi r4, r5, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@l
li r0, 0
stw r4, 0(r31)
stw r0,
"sInstance__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@sda21(r13) ble
lbl_803407A8 bl __dl__FPv
lbl_803407A8:
lwz r0, 0x14(r1)
mr r3, r31
lwz r31, 0xc(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
namespace PSGame {
} // namespace PSGame
/*
* --INFO--
* Address: 803407C0
* Size: 000004
*/
void Builder_EvnSe_Perspective::onBuild(PSSystem::EnvSeBase*) { }
} // namespace PSSystem
namespace PSSystem {
/*
* --INFO--
* Address: 803407C4
* Size: 00000C
*/
void EnvSeBase::getCastType()
{
/*
lis r3, 0x62617365@ha
addi r3, r3, 0x62617365@l
blr
*/
}
/*
* --INFO--
* Address: 803407D0
* Size: 000004
*/
void EnvSeBase::setPanAndDolby(JAISound*) { }
namespace PSGame {
} // namespace PSGame
/*
* --INFO--
* Address: 803407D4
* Size: 000064
*/
SeMgr::~SeMgr()
{
/*
stwu r1, -0x10(r1)
mflr r0
stw r0, 0x14(r1)
stw r31, 0xc(r1)
or. r31, r3, r3
beq lbl_80340820
lis r3, __vt__Q26PSGame5SeMgr@ha
addi r0, r3, __vt__Q26PSGame5SeMgr@l
stw r0, 0(r31)
beq lbl_80340810
lis r3, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@ha
li r0, 0
addi r3, r3, "__vt__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@l
stw r3, 0(r31)
stw r0,
"sInstance__Q28PSSystem30SingletonBase<Q26PSGame5SeMgr>"@sda21(r13)
lbl_80340810:
extsh. r0, r4
ble lbl_80340820
mr r3, r31
bl __dl__FPv
lbl_80340820:
lwz r0, 0x14(r1)
mr r3, r31
lwz r31, 0xc(r1)
mtlr r0
addi r1, r1, 0x10
blr
*/
}
} // namespace PSSystem
| 19.987716
| 86
| 0.556939
|
projectPiki
|
00349196d94850f17f334ed09b7811c8a9995fba
| 997
|
cpp
|
C++
|
src/examples/04_module/01_bank/main.cpp
|
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-redondoem
|
19a44954ebef1b621b851fb0089e1c72c6d7f935
|
[
"MIT"
] | null | null | null |
src/examples/04_module/01_bank/main.cpp
|
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-redondoem
|
19a44954ebef1b621b851fb0089e1c72c6d7f935
|
[
"MIT"
] | null | null | null |
src/examples/04_module/01_bank/main.cpp
|
acc-cosc-1337-spring-2020/acc-cosc-1337-spring-2020-redondoem
|
19a44954ebef1b621b851fb0089e1c72c6d7f935
|
[
"MIT"
] | null | null | null |
#include "bank_account.h"
#include "savings_account.h"
#include "customer.h"
#include<iostream>
#include<vector>
#include<string>
using std::cout; using std::cin;
int main()
{
SavingsAccount* s = new SavingsAccount(500);
SavingsAccount s{ 90 };
SavingsAccount s{ 90 };
CheckingAccount checking{ 100 };
CheckingAccount checking1{ 90 };
std::vector<BankAccount> accounts{ s,c };
/*std::vector<BankAccount> accounts{ BankAccount(100),
BankAccount(200) };
for (auto act : accounts)
{
cout << act.get_balance() << "\n";
}*/
BankAccount account(500);
Customer cust;
cust.add_account(account);
/*cin >> account;
cout << account;
display_balance(account);
auto balance = account.get_balance();
cout << "Balance is: \n" << balance;
auto amount{ 0 };
cout << "\nEnter deposit amount: \n";
cin >> amount;*/
try
{
account.deposit(amount);
cout << "Balance is: " << account.get_balance();
}
catch (Invalid e)
{
cout << e.get_error() << "\n";
}
return 0;
}
| 18.127273
| 55
| 0.656971
|
acc-cosc-1337-spring-2020
|
003b19cff897ccba73dd90d6c03796dd068c6f63
| 2,889
|
cc
|
C++
|
projects/SimpleApplication/code/main.cc
|
Destinum/S0008E
|
25344cc26c92ee022d7d7eac7428a113aa0be3a2
|
[
"MIT"
] | null | null | null |
projects/SimpleApplication/code/main.cc
|
Destinum/S0008E
|
25344cc26c92ee022d7d7eac7428a113aa0be3a2
|
[
"MIT"
] | null | null | null |
projects/SimpleApplication/code/main.cc
|
Destinum/S0008E
|
25344cc26c92ee022d7d7eac7428a113aa0be3a2
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <thread>
#include<cmath>
#include <unistd.h>
#include <sys/utsname.h>
#include <thread>
#include <vector>
using namespace std;
unsigned long int Calculation()
{
unsigned long int Result = 0;
for (int i = 1; i <= 50000; i++)
{
for (int j = 1; j <= i; j++)
{
Result += sqrt(i * j);
}
}
return Result;
}
void ThreadFunction()
{
cout << "Thread " << this_thread::get_id() << " created. Calculating..." << endl;
unsigned long int Result = Calculation();
cout << "Thread " << this_thread::get_id() << " finished calculation. Result: " << Result << endl;
}
int main()
{
string Command;
int Value;
struct utsname SystemInfo;
cout << "List of Commands: " << endl <<
"'-i' to show system information." << endl <<
"'-f' and an integer to run X calculations using forks." << endl <<
"'-t' and an integer to run X calculations using threads." << endl << endl;
while(true)
{
cout << "Enter Command: ";
cin >> Command;
if (!cin.good())
{
cout << "Invalid Command." << endl;
}
else if (Command == "-i")
{
char Hostname[1024];
gethostname(Hostname, 1024);
uname(&SystemInfo);
cout << "Number of Processors: " << std::thread::hardware_concurrency() << endl;
cout << "Hostname: " << Hostname << endl;
cout << "Hardware Platform: " << SystemInfo.machine << endl;
cout << "Total RAM: " << sysconf(_SC_PHYS_PAGES) * sysconf(_SC_PAGE_SIZE) / pow(10, 9) << " GB" << endl;
}
else if (Command == "-f")
{
cin >> Value;
while (!cin.good() || Value < 1)
{
cout << "Invalid Value. Enter an integer of 1 or more: ";
cin.clear();
cin.ignore(123, '\n');
cin >> Value;
}
pid_t Parent = getpid();
pid_t Forks[Value];
cout << "Parent Process ID: " << Parent << endl;
for (int i = 0; i < Value; i++)
{
Forks[i] = fork();
if (Parent != getpid())
break;
cout << "PID of child #" << i + 1 << ": " << Forks[i] << endl;
}
cout << "Process " << getpid() << " finished calculation. Result: " << Calculation() << endl;
if (Parent != getpid())
{
return 0;
}
sleep(4);
}
else if (Command == "-t")
{
cin >> Value;
while (!cin.good() || Value < 1)
{
cout << "Invalid Value. Enter an integer of 1 or more: ";
cin.clear();
cin.ignore(123, '\n');
cin >> Value;
}
//cout << "Command is " << Command << " with value " << Value << "."<< endl;
vector<thread> ListOfThreads;
for (int i = 0; i < Value; i++)
{
//thread thread(ThreadFunction);
//thread.detach();
//thread(ThreadFunction).detach();
ListOfThreads.emplace_back(thread(ThreadFunction));
}
sleep(1);
cout << endl;
for (auto& th : ListOfThreads)
th.join();
}
else
{
cout << "Invalid Command." << endl;
}
cout << endl;
cin.clear();
cin.ignore(123, '\n');
}
}
| 19.787671
| 107
| 0.555556
|
Destinum
|
00441f3298b17a8640d117909d59f37f59af3b46
| 2,196
|
cc
|
C++
|
src/libs/common/plugin/plugin_request.cc
|
warm-byte/DTC
|
ff98a585c07712000e486cfd2d71515e6538435f
|
[
"Apache-2.0"
] | 24
|
2021-08-22T12:17:50.000Z
|
2022-03-03T06:39:00.000Z
|
src/libs/common/plugin/plugin_request.cc
|
warm-byte/DTC
|
ff98a585c07712000e486cfd2d71515e6538435f
|
[
"Apache-2.0"
] | 2
|
2021-09-06T08:16:40.000Z
|
2021-11-04T06:06:57.000Z
|
src/libs/common/plugin/plugin_request.cc
|
warm-byte/DTC
|
ff98a585c07712000e486cfd2d71515e6538435f
|
[
"Apache-2.0"
] | 15
|
2021-08-22T14:44:22.000Z
|
2022-01-30T02:03:22.000Z
|
/*
* Copyright [2021] JD.com, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "plugin_request.h"
#include "plugin_sync.h"
#include "plugin_dgram.h"
#include "../log/log.h"
#include "plugin_mgr.h"
int PluginStream::handle_process(void)
{
if (0 != _dll->handle_process(_recv_buf, _real_len, &_send_buf,
&_send_len, &_skinfo)) {
mark_handle_fail();
log4cplus_error("invoke handle_process failed, worker[%d]",
_gettid_());
} else {
mark_handle_succ();
}
if (_incoming_notifier->Push(this) != 0) {
log4cplus_error(
"push plugin request to incoming failed, worker[%d]",
_gettid_());
delete this;
return -1;
}
return 0;
}
int PluginDatagram::handle_process(void)
{
if (0 != _dll->handle_process(_recv_buf, _real_len, &_send_buf,
&_send_len, &_skinfo)) {
mark_handle_fail();
log4cplus_error("invoke handle_process failed, worker[%d]",
_gettid_());
} else {
mark_handle_succ();
}
if (_incoming_notifier->Push(this) != 0) {
log4cplus_error(
"push plugin request to incoming failed, worker[%d]",
_gettid_());
delete this;
return -1;
}
return 0;
}
int PluginStream::job_ask_procedure(void)
{
if (disconnect()) {
DELETE(_plugin_sync);
delete this;
return -1;
}
if (!handle_succ()) {
DELETE(_plugin_sync);
delete this;
return -1;
}
if (NULL == _plugin_sync) {
delete this;
return -1;
}
_plugin_sync->set_stage(PLUGIN_SEND);
_plugin_sync->send_response();
return 0;
}
int PluginDatagram::job_ask_procedure(void)
{
if (!handle_succ()) {
delete this;
return -1;
}
if (NULL == _plugin_dgram) {
delete this;
return -1;
}
_plugin_dgram->send_response(this);
return 0;
}
| 20.333333
| 74
| 0.68898
|
warm-byte
|
00496c1a78cefa3402280a38f591de341fa1f608
| 14,602
|
cpp
|
C++
|
Bonsai/graphics/D3D.cpp
|
Resoona/Bonsai-Engine
|
d820455f940c03bd6cebc6ab1bd55b8ab524d88f
|
[
"MIT"
] | null | null | null |
Bonsai/graphics/D3D.cpp
|
Resoona/Bonsai-Engine
|
d820455f940c03bd6cebc6ab1bd55b8ab524d88f
|
[
"MIT"
] | null | null | null |
Bonsai/graphics/D3D.cpp
|
Resoona/Bonsai-Engine
|
d820455f940c03bd6cebc6ab1bd55b8ab524d88f
|
[
"MIT"
] | null | null | null |
#include "D3D.h"
namespace bonsai
{
namespace graphics {
Direct3D::Direct3D()
{
m_SwapChain = nullptr;
m_Device = nullptr;
m_DeviceContext = nullptr;
m_RenderTargetView = nullptr;
m_DepthStencilBuffer = nullptr;
m_DepthStencilState = nullptr;
m_DepthDisabledStencilState = nullptr;
m_DepthStencilView = nullptr;
m_RasterState = nullptr;
m_AlphaDisableBlendingState = nullptr;
m_AlphaEnableBlendingState = nullptr;
}
Direct3D::Direct3D(const Direct3D&)
{
}
Direct3D::~Direct3D()
{
}
bool Direct3D::Initialize(int screenWidth, int screenHeight, bool vsync, HWND hwnd, bool fullscreen, float screenDepth,
float screenNear)
{
HRESULT result;
IDXGIFactory* factory;
IDXGIAdapter* adapter;
IDXGIOutput* adapterOutput;
UINT numModes, i, numerator, denominator;
ULONGLONG stringLength;
DXGI_MODE_DESC* displayModeList;
DXGI_ADAPTER_DESC adapterDesc;
INT error;
DXGI_SWAP_CHAIN_DESC swapChainDesc;
D3D_FEATURE_LEVEL featureLevel;
ID3D11Texture2D* backBufferPtr;
D3D11_TEXTURE2D_DESC depthBufferDesc;
D3D11_DEPTH_STENCIL_DESC depthStencilDesc;
D3D11_DEPTH_STENCIL_DESC depthDisabledStencilDesc;
D3D11_DEPTH_STENCIL_VIEW_DESC depthStencilViewDesc;
D3D11_RASTERIZER_DESC rasterDesc;
D3D11_VIEWPORT viewport;
D3D11_BLEND_DESC blendStateDesc;
m_vsync_enabled = vsync;
//Create a DirectX graphics interface factory
result = CreateDXGIFactory(__uuidof(IDXGIFactory), (void**)&factory);
if (FAILED(result)) return false;
// Use the factory to create an adapter for the primary graphics interface (video card).
result = factory->EnumAdapters(0, &adapter);
if (FAILED(result)) return false;
// Enumerate the primary adapter output (monitor).
result = adapter->EnumOutputs(0, &adapterOutput);
if (FAILED(result)) return false;
// Get the number of modes that fit the DXGI_FORMAT_R8G8B8A8_UNORM display format for the adapter output (monitor).
result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, NULL);
if (FAILED(result)) return false;
// Create a list to hold all the possible display modes for this monitor/video card combination.
displayModeList = new DXGI_MODE_DESC[numModes];
if (!displayModeList) return false;
// Now fill the display mode list structures.
result = adapterOutput->GetDisplayModeList(DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_ENUM_MODES_INTERLACED, &numModes, displayModeList);
if (FAILED(result)) return false;
// Now go through all the display modes and find the one that matches the screen width and height.
// When a match is found store the numerator and denominator of the refresh rate for that monitor.
for(i=0; i<numModes; i++)
{
if ((displayModeList[i].Width == (UINT)screenWidth) && displayModeList[i].Height == (UINT)screenHeight)
{
numerator = displayModeList[i].RefreshRate.Numerator;
denominator = displayModeList[i].RefreshRate.Denominator;
}
}
//Get the video card description
result = adapter->GetDesc(&adapterDesc);
if (FAILED(result)) return false;
//store in MB
m_VideoCardMemory = (int)(adapterDesc.DedicatedVideoMemory / 1024 / 1024);
//Convert the name of the video card to a character array and store it.
error = wcstombs_s(&stringLength, m_VideoCardDescription, 128, adapterDesc.Description, 128);
if (error != 0) return false;
//Release ptrs
delete[] displayModeList;
displayModeList = nullptr;
adapterOutput->Release();
adapterOutput = nullptr;
adapter->Release();
adapter = nullptr;
factory->Release();
factory = nullptr;
//Init swap chain (back and front buffers)
//Self note ZeroMemory == memset(dest,0,size)
ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));
//Set to a single back buffer
swapChainDesc.BufferCount = 1;
//Set the widths and height of the back buffer
swapChainDesc.BufferDesc.Width = screenWidth;
swapChainDesc.BufferDesc.Height = screenHeight;
//Set regular 32-bit surface for the back buffer
swapChainDesc.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
//refresh rate
if(m_vsync_enabled)
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = numerator;
swapChainDesc.BufferDesc.RefreshRate.Denominator = denominator;
} else
{
swapChainDesc.BufferDesc.RefreshRate.Numerator = 0;
swapChainDesc.BufferDesc.RefreshRate.Denominator = 1;
}
//Set usage of back buffer
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
//Set the handle for the window to render to
swapChainDesc.OutputWindow = hwnd;
//Turn multisampling off
swapChainDesc.SampleDesc.Count = 1;
swapChainDesc.SampleDesc.Quality = 0;
//Set to fullscreen or windowed mode
if (fullscreen) swapChainDesc.Windowed = false;
else swapChainDesc.Windowed = true;
//Set the scan line ordering and scaling to unspecified
swapChainDesc.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
swapChainDesc.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
//Discard the back buffer after presenting
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
//Dont set the advanced flags
swapChainDesc.Flags = 0;
//Set feature level (can swap to lower versions to support lower end hardware)
featureLevel = D3D_FEATURE_LEVEL_11_0;
//Create swap chain, D3D device and D3d device context - if no dx11 support swap driver type hardward to reference for cpu rendering
result = D3D11CreateDeviceAndSwapChain(NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, &featureLevel, 1, D3D11_SDK_VERSION, &swapChainDesc, &m_SwapChain, &m_Device, NULL, &m_DeviceContext);
if (FAILED(result)) return false;
//Get the pointer to the backbuffer
result = m_SwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&backBufferPtr);
if (FAILED(result)) return false;
//Create render target view with the back buffer pointer
result = m_Device->CreateRenderTargetView(backBufferPtr, NULL, &m_RenderTargetView);
if (FAILED(result)) return false;
//Release pointer to the back buffer as we no longer need it
backBufferPtr->Release();
backBufferPtr = nullptr;
//Initalize the description and the depth buffer
ZeroMemory(&depthBufferDesc, sizeof(depthBufferDesc));
//Setup the description of the depth buffer (with attached stencil for blur, vol shadows, etc)
depthBufferDesc.Width = screenWidth;
depthBufferDesc.Height = screenHeight;
depthBufferDesc.MipLevels = 1;
depthBufferDesc.ArraySize = 1;
depthBufferDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthBufferDesc.SampleDesc.Count = 1;
depthBufferDesc.SampleDesc.Quality = 0;
depthBufferDesc.Usage = D3D11_USAGE_DEFAULT;
depthBufferDesc.BindFlags = D3D11_BIND_DEPTH_STENCIL;
depthBufferDesc.CPUAccessFlags = 0;
depthBufferDesc.MiscFlags = 0;
//Create the texture for the depth buffer using the filled out desc
result = m_Device->CreateTexture2D(&depthBufferDesc, NULL, &m_DepthStencilBuffer);
if (FAILED(result)) return false;
//setup the depth stensil desc
//init the description
ZeroMemory(&depthStencilDesc, sizeof(depthStencilDesc));
depthStencilDesc.DepthEnable = true;
depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthStencilDesc.StencilEnable = true;
depthStencilDesc.StencilReadMask = 0xFF;
depthStencilDesc.StencilWriteMask = 0xFF;
//if the pixel is front facing
depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
//if the pixel is back-facing
depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
result = m_Device->CreateDepthStencilState(&depthStencilDesc, &m_DepthStencilState);
if (FAILED(result)) return false;
//Set the depth stencil state
m_DeviceContext->OMSetDepthStencilState(m_DepthStencilState, 1);
//FOR 2D
ZeroMemory(&depthDisabledStencilDesc, sizeof(depthDisabledStencilDesc));
depthDisabledStencilDesc.DepthEnable = false;
depthDisabledStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL;
depthDisabledStencilDesc.DepthFunc = D3D11_COMPARISON_LESS;
depthDisabledStencilDesc.StencilEnable = true;
depthDisabledStencilDesc.StencilReadMask = 0xFF;
depthDisabledStencilDesc.StencilWriteMask = 0xFF;
//if the pixel is front facing
depthDisabledStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_INCR;
depthDisabledStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
//if the pixel is back-facing
depthDisabledStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_DECR;
depthDisabledStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP;
depthDisabledStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS;
result = m_Device->CreateDepthStencilState(&depthDisabledStencilDesc, &m_DepthDisabledStencilState);
if (FAILED(result)) return false;
//initalize the depth stencil view
ZeroMemory(&depthStencilViewDesc, sizeof(depthStencilViewDesc));
//setup the depth stencil view desc
depthStencilViewDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
depthStencilViewDesc.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
depthStencilViewDesc.Texture2D.MipSlice = 0;
//create the depth stencil view
result = m_Device->CreateDepthStencilView(m_DepthStencilBuffer, &depthStencilViewDesc, &m_DepthStencilView);
if (FAILED(result)) return false;
//bind the render target view and depth stencil buffer to the output render pipeline
m_DeviceContext->OMSetRenderTargets(1, &m_RenderTargetView, m_DepthStencilView);
//setup the raster description which will determine h ow and what polygons will be drawn
rasterDesc.AntialiasedLineEnable = false;
rasterDesc.CullMode = D3D11_CULL_BACK;
rasterDesc.DepthBias = 0;
rasterDesc.DepthBiasClamp = 0.0f;
rasterDesc.DepthClipEnable = true;
rasterDesc.FillMode = D3D11_FILL_SOLID;
rasterDesc.FrontCounterClockwise = false;
rasterDesc.MultisampleEnable = false;
rasterDesc.ScissorEnable = false;
rasterDesc.SlopeScaledDepthBias = 0.0f;
//Create the rasterizer state from the desc
result = m_Device->CreateRasterizerState(&rasterDesc, &m_RasterState);
if (FAILED(result)) return false;
//Now set the rasterizer state
m_DeviceContext->RSSetState(m_RasterState);
//Setup the viewport for rendering
viewport.Width = (float)screenWidth;
viewport.Height = (float)screenHeight;
viewport.MaxDepth = 1.0f;
viewport.MinDepth = 0.0f;
viewport.TopLeftX = 0.0f;
viewport.TopLeftY = 0.0f;
//Create the viewport
m_DeviceContext->RSSetViewports(1, &viewport);
//Init blend state desc
ZeroMemory(&blendStateDesc, sizeof(D3D11_BLEND_DESC));
//For when we want blending
blendStateDesc.RenderTarget[0].BlendEnable = true;
blendStateDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;
blendStateDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC1_ALPHA;
blendStateDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
blendStateDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
blendStateDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
blendStateDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
blendStateDesc.RenderTarget[0].RenderTargetWriteMask = 0x0f;
result = m_Device->CreateBlendState(&blendStateDesc, &m_AlphaEnableBlendingState);
if (FAILED(result)) return false;
//For when we dont want blending
blendStateDesc.RenderTarget[0].BlendEnable = false;
result = m_Device->CreateBlendState(&blendStateDesc, &m_AlphaDisableBlendingState);
if (FAILED(result)) return false;
//World Matrix
m_WorldMatrix = XMMatrixIdentity();
return true;
}
void Direct3D::Shutdown()
{
//before shutdown set to windowed to avoid throwing exceptions
if(m_SwapChain)
{
m_SwapChain->SetFullscreenState(false, NULL);
}
if (m_RasterState)
{
m_RasterState->Release();
m_RasterState = nullptr;
}
if (m_DepthStencilView)
{
m_DepthStencilView->Release();
m_DepthStencilView = nullptr;
}
if (m_DepthStencilState)
{
m_DepthStencilState->Release();
m_DepthStencilState = nullptr;
}
if (m_DepthDisabledStencilState)
{
m_DepthDisabledStencilState->Release();
m_DepthDisabledStencilState = nullptr;
}
if (m_DepthStencilBuffer)
{
m_DepthStencilBuffer->Release();
m_DepthStencilBuffer = nullptr;
}
if (m_RenderTargetView)
{
m_RenderTargetView->Release();
m_RenderTargetView = nullptr;
}
if (m_DeviceContext)
{
m_DeviceContext->Release();
m_DeviceContext = nullptr;
}
if (m_Device)
{
m_Device->Release();
m_Device = nullptr;
}
if (m_SwapChain)
{
m_SwapChain->Release();
m_SwapChain = nullptr;
}
if (m_AlphaDisableBlendingState)
{
m_AlphaDisableBlendingState->Release();
m_AlphaDisableBlendingState = nullptr;
}
if (m_AlphaEnableBlendingState)
{
m_AlphaEnableBlendingState->Release();
m_AlphaEnableBlendingState = nullptr;
}
}
void Direct3D::BeginScene(float red, float green, float blue, float alpha)
{
float color[4];
color[0] = red;
color[1] = green;
color[2] = blue;
color[3] = alpha;
//clear the back buffer
m_DeviceContext->ClearRenderTargetView(m_RenderTargetView, color);
//clear the depth buffer
m_DeviceContext->ClearDepthStencilView(m_DepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0.0f);
}
void Direct3D::EndScene()
{
if (m_vsync_enabled)
{
//lock refresh rate
m_SwapChain->Present(1, 0);
} else
{
m_SwapChain->Present(0, 0);
}
}
void Direct3D::GetVideoCardInfo(char* cardName, int& memory)
{
strcpy_s(cardName, 128, m_VideoCardDescription);
memory = m_VideoCardMemory;
}
}
}
| 32.73991
| 185
| 0.751472
|
Resoona
|
004a36e80a95872435312482183c0ab60c68c30e
| 1,071
|
cc
|
C++
|
test/class/class-impl.cc
|
gabrielschulhof/webidl-napi
|
88a9f9aa6975351b52b4a787468185c8a5024685
|
[
"MIT"
] | 3
|
2020-10-20T17:58:24.000Z
|
2020-11-10T21:04:56.000Z
|
test/class/class-impl.cc
|
gabrielschulhof/webidl-napi
|
88a9f9aa6975351b52b4a787468185c8a5024685
|
[
"MIT"
] | 18
|
2020-10-20T17:05:23.000Z
|
2020-11-16T07:04:28.000Z
|
test/class/class-impl.cc
|
gabrielschulhof/webidl-napi
|
88a9f9aa6975351b52b4a787468185c8a5024685
|
[
"MIT"
] | 9
|
2020-10-20T14:40:31.000Z
|
2021-03-04T07:33:38.000Z
|
#include "class-impl.h"
struct value__ {
value__(unsigned long initial): val(initial) {}
unsigned long val = 0;
size_t refcount = 1;
inline void Ref() { refcount++; }
inline void Unref() {
if (refcount == 0) abort();
if (--refcount == 0) delete this;
}
};
void Decrementor::operator=(const Decrementor& other) {
val = other.val;
val->Ref();
}
Decrementor::Decrementor() {}
Decrementor::Decrementor(const Incrementor& inc) {
val = inc.val;
val->Ref();
}
Decrementor::~Decrementor() { val->Unref(); }
unsigned long Decrementor::decrement() { return --(val->val); }
Incrementor::Incrementor(): Incrementor(0) {}
Incrementor::Incrementor(DOMString initial_value)
: Incrementor(std::stoul(initial_value)) {}
Incrementor::Incrementor(unsigned long initial_value): props{"blah", 42} {
val = new value__(initial_value);
val->val = initial_value;
}
unsigned long Incrementor::increment() { return ++(val->val); }
Decrementor Incrementor::getDecrementor() { return Decrementor(*this); }
Incrementor::~Incrementor() { val->Unref(); }
| 23.8
| 74
| 0.678805
|
gabrielschulhof
|
004bac6cdf5d212c65c44505d14ab2ee73bc0985
| 1,618
|
cpp
|
C++
|
tests/Cases/Allocators/TestStackAllocator.cpp
|
cpv-project/cpv-framework
|
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
|
[
"MIT"
] | 86
|
2018-04-20T04:40:20.000Z
|
2022-02-09T08:36:28.000Z
|
tests/Cases/Allocators/TestStackAllocator.cpp
|
cpv-project/cpv-framework
|
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
|
[
"MIT"
] | 16
|
2018-04-25T09:34:40.000Z
|
2020-10-16T03:55:05.000Z
|
tests/Cases/Allocators/TestStackAllocator.cpp
|
cpv-project/cpv-framework
|
b0da79c8c57ceecb6b13f4d8658ec4d4c0237668
|
[
"MIT"
] | 10
|
2019-10-07T08:06:15.000Z
|
2021-07-26T18:46:11.000Z
|
#include <functional>
#include <CPVFramework/Allocators/StackAllocator.hpp>
#include <CPVFramework/Testing/GTestUtils.hpp>
TEST(StackAllocator, allocate) {
static constexpr const std::size_t Size = sizeof(int)*4;
cpv::StackAllocatorStorage<Size> storage;
cpv::StackAllocator<int, Size> allocator(storage);
using ptr_type = std::unique_ptr<int, std::function<void(int*)>>;
ptr_type first(allocator.allocate(1), [&allocator] (int* p) { allocator.deallocate(p, 1); });
ptr_type second(allocator.allocate(2), [&allocator] (int* p) { allocator.deallocate(p, 2); });
ptr_type forth(allocator.allocate(1), [&allocator] (int* p) { allocator.deallocate(p, 1); });
ptr_type fifth(allocator.allocate(1), [&allocator] (int* p) { allocator.deallocate(p, 1); });
ptr_type sixth(allocator.allocate(2), [&allocator] (int* p) { allocator.deallocate(p, 2); });
void* begin = static_cast<void*>(&storage);
void* end = static_cast<void*>(&storage + 1);
ASSERT_GE(static_cast<void*>(first.get()), begin);
ASSERT_LT(static_cast<void*>(first.get()), end);
ASSERT_GE(static_cast<void*>(second.get()), begin);
ASSERT_LT(static_cast<void*>(second.get()), end);
ASSERT_GE(static_cast<void*>(forth.get()), begin);
ASSERT_LT(static_cast<void*>(forth.get()), end);
ASSERT_EQ(static_cast<void*>(first.get() + 1), static_cast<void*>(second.get()));
ASSERT_EQ(static_cast<void*>(second.get() + 2), static_cast<void*>(forth.get()));
ASSERT_TRUE(static_cast<void*>(fifth.get()) < begin || static_cast<void*>(fifth.get()) > end);
ASSERT_TRUE(static_cast<void*>(sixth.get()) < begin || static_cast<void*>(sixth.get()) > end);
}
| 52.193548
| 95
| 0.70581
|
cpv-project
|
005a90986635ba22239690be245bb249f0927d70
| 2,420
|
cpp
|
C++
|
engine/calculators/source/SoakCalculator.cpp
|
sidav/shadow-of-the-wyrm
|
747afdeebed885b1a4f7ab42f04f9f756afd3e52
|
[
"MIT"
] | 60
|
2019-08-21T04:08:41.000Z
|
2022-03-10T13:48:04.000Z
|
engine/calculators/source/SoakCalculator.cpp
|
cleancoindev/shadow-of-the-wyrm
|
51b23e98285ecb8336324bfd41ebf00f67b30389
|
[
"MIT"
] | 3
|
2021-03-18T15:11:14.000Z
|
2021-10-20T12:13:07.000Z
|
engine/calculators/source/SoakCalculator.cpp
|
cleancoindev/shadow-of-the-wyrm
|
51b23e98285ecb8336324bfd41ebf00f67b30389
|
[
"MIT"
] | 8
|
2019-11-16T06:29:05.000Z
|
2022-01-23T17:33:43.000Z
|
#include "SoakCalculator.hpp"
#include "Wearable.hpp"
using namespace std;
SoakCalculator::SoakCalculator()
{
}
SoakCalculator::~SoakCalculator()
{
}
// A creature gets 1 point of Soak for every 4 Health over 10,
// plus any bonuses or penalties from equipment.
int SoakCalculator::calculate_soak(const CreaturePtr& c)
{
int soak = 0;
if (c)
{
soak = c->get_base_soak().get_current();
soak += get_equipment_bonus(c);
soak += get_modifier_bonus(c);
soak += get_health_bonus(c);
soak += get_rage_bonus(c);
}
return soak;
}
int SoakCalculator::get_equipment_bonus(const CreaturePtr& c)
{
int equipment_soak_bonus = 0;
Equipment& eq = c->get_equipment();
EquipmentMap equipment = eq.get_equipment();
for (const EquipmentMap::value_type& item : equipment)
{
WearablePtr equipped = dynamic_pointer_cast<Wearable>(item.second);
if (equipped)
{
// The player can equip a lot of things in the ammunition slot.
// Prevent the use of anything but ammunition when calculating
// soak.
if (item.first == EquipmentWornLocation::EQUIPMENT_WORN_AMMUNITION)
{
if (equipped->get_type() == ItemType::ITEM_TYPE_AMMUNITION)
{
equipment_soak_bonus += equipped->get_evade();
}
}
else
{
equipment_soak_bonus += equipped->get_soak();
}
}
}
return equipment_soak_bonus;
}
int SoakCalculator::get_modifier_bonus(const CreaturePtr& c)
{
int mod_bonus = 0;
if (c)
{
const map<double, vector<pair<string, Modifier>>> modifiers = c->get_active_modifiers();
for (const auto& mod_pair : modifiers)
{
for (const auto& current_mod_pair : mod_pair.second)
{
mod_bonus += current_mod_pair.second.get_soak_modifier();
}
}
}
return mod_bonus;
}
int SoakCalculator::get_health_bonus(const CreaturePtr& c)
{
int health_bonus = 0;
if (c != nullptr)
{
int health = c->get_health().get_current();
if (health > 10)
{
health_bonus = (health - 10) / 4;
}
}
return health_bonus;
}
int SoakCalculator::get_rage_bonus(const CreaturePtr& c)
{
int rage_bonus = 0;
if (c != nullptr)
{
if (c->has_status(StatusIdentifiers::STATUS_ID_RAGE))
{
rage_bonus = c->get_level().get_current();
}
}
return rage_bonus;
}
#ifdef UNIT_TESTS
#include "unit_tests/SoakCalculator_test.cpp"
#endif
| 19.836066
| 92
| 0.656612
|
sidav
|
005c03dd374a0553105b5f618a997b48d8d309d4
| 7,908
|
cpp
|
C++
|
main.cpp
|
Daria602/AdventureIn10
|
4ad0418d4020cfb552a5cb1ab894ffa895caab3e
|
[
"MIT"
] | 1
|
2021-05-03T12:29:52.000Z
|
2021-05-03T12:29:52.000Z
|
main.cpp
|
Daria602/AdventureIn10
|
4ad0418d4020cfb552a5cb1ab894ffa895caab3e
|
[
"MIT"
] | null | null | null |
main.cpp
|
Daria602/AdventureIn10
|
4ad0418d4020cfb552a5cb1ab894ffa895caab3e
|
[
"MIT"
] | null | null | null |
#include "Game.h"
void addSpaces()
{
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
std::cout << std::endl;
}
void mainMenu(Character& boss)
{
std::cout << "You meet " << boss << std::endl;
std::cout << "What will you do?" << std::endl;
std::cout << "1 - > attack him" << std::endl;
std::cout << "2 - > try to run away (if failed, you will have to fight)" << std::endl;
std::cout << "3 - > open inventory" << std::endl;
}
void menuFight()
{
std::cout << "What will you do?" << std::endl;
std::cout << "1 - > attack him again" << std::endl;
std::cout << "2 - > open inventory" << std::endl;
}
void eatFromInventory(Player& player, Inventory& inventory)
{
std::cout << "What would you like to eat?\n";
for (size_t i = 0; i < inventory.getInventory().size(); i++)
{
std::cout << i + 1 << " - >" << inventory.getInventory()[i];
}
std::cout << "0 - > go back" << std::endl;
int index = 0;
std::cin >> index;
if (index == 0)
{
return;
}
while (index != 0 && inventory.getInventory().size() != 0)
{
Edible e = inventory.getInventory()[index - 1];
player.increaseStamina(e.getReplenishStamina());
player.increaseHealth(e.getReplenishHealth());
inventory.eraseFromInventory(index - 1);
std::cout << "What would you like to eat?\n";
for (size_t i = 0; i < inventory.getInventory().size(); i++)
{
std::cout << i + 1 << " - >" << inventory.getInventory()[i];
}
std::cout << "0 - > go back" << std::endl;
int index;
std::cin >> index;
}
}
void inBossFight(Character &boss, Player &player, Inventory &inventory,Pet &pet)
{
Character* c;
Character* p;
p = &pet;
c = &player;
if (boss.getHP() > 0 && player.getStamina() < 2 && inventory.getInventory().size() == 0)
{
std::cout << "You are exhausted and have nothing to eat. Game over for you.";
return;
}
boss.wasAttacked(c->attack());
if (boss.getHP() > 0)
{
c->wasAttacked(boss.attack());
}
while (boss.getHP() > 0)
{
player.seeStats();
menuFight();
if (pet.getIsPresent() == true)
{
std::cout << "3 - > ask " << pet.getName() << " to attack" << std::endl;
}
int answer;
std::cin >> answer;
if (answer == 1 && player.getStamina() >= 2)
{
boss.wasAttacked(c->attack());
if (boss.getHP() > 0)
{
c->wasAttacked(boss.attack());
}
}
else if (answer == 1 && player.getStamina() < 2)
{
std::cout << "You are too tired to fight ";
if (inventory.getInventory().size() == 0 && boss.getHP() > 0)
{
std::cout << "and you have nothing to eat... GAME OVER";
return;
}
else
{
std::cout << ".\nDo you want to eat something?\n1 - > yes\n2 - > no" << std::endl;
int answer1;
std::cin >> answer1;
if (answer1 == 1)
{
eatFromInventory(player, inventory);
}
else
{
if (boss.getHP() > 0)
{
std::cout << "GAME OVER";
return;
}
}
}
}
if (answer == 2)
{
eatFromInventory(player, inventory);
}
if (answer == 3)
{
int damage;
damage = p->attack();
if (damage != 0)
{
boss.wasAttacked(damage);
if (boss.getHP() > 0)
{
c->wasAttacked(boss.attack());
}
}
pet.setIsPresent(false);
}
}
}
std::vector<Character> getAllMonsters()
{
std::vector<Character> monsters;
Character mutant("Mutant", 3, 3, 0, 2), goblin("Goblin", 4, 4, 0, 2),
businessman("Businessman", 5, 5, 0, 1), evilMagician("Evil Magician", 6, 6, 0, 3);
monsters.push_back(mutant);
monsters.push_back(goblin);
monsters.push_back(businessman);
monsters.push_back(evilMagician);
return monsters;
}
std::vector<Edible> getAllEdible()
{
std::vector<Edible> edibles;
Edible apple("Apple", 3, 3), caveCarrot("Cave carrot", 2, 2), pizza("Pizza", 4, 4);
edibles.push_back(apple);
edibles.push_back(caveCarrot);
edibles.push_back(pizza);
return edibles;
}
bool inRoom = true;
int main()
{
srand((unsigned int)time(NULL));
Game game;
std::vector<Character> all_monsters = getAllMonsters();
std::vector<Edible> all_edible = getAllEdible();
std::vector<Room> all_rooms;
for (int i = 1; i <= 10; i++)
{
RoomBuilder rb;
int indexMonster = rand() % (all_monsters.size() - 1);
int indexEdible = rand() % (all_edible.size() - 2);
Room r = rb.indexRoom(i).monsterInRoom(all_monsters[indexMonster]).edibleInRoom(all_edible[indexEdible]).build();
all_rooms.push_back(r);
}
Inventory inventory;
Pet pet("Barsik", 5, 5, 1, 4);
std::cout << "Welcome to the ADVENTURE IN 10!" << std::endl;
std::cout << "What is your name?" << std::endl;
std::string name;
std::cin >> name;
Player player(name, 10, 10, 1, 2, 10, 10);
std::cout << "Hello, " << player.getName() << "!" << std::endl;
std::cout << "The goal is to get to the treasure room in 10 days. \nEvery action you take will drain your stamina. \nAfter you rest, your stamina will be back to max, but the day count will increase.\n";
int i = 0;
while (i < all_rooms.size() && game.getDayCount() <= 10 && player.getHP() > 0)
{
Room room = all_rooms[i];
std::cout << "You enter the room number " << room.getRoomIndex() << "." << std::endl;
if (i == 3)
{
std::cout << "You see a cat. It seems to like you. You pet him and it decides to stick around." << std::endl;
pet.setIsPresent(true);
}
if (room.getRoomIndex() == 10)
{
std::cout << "IT'S A TREASURE ROOM!\nCongratulations!!! You won!" << std::endl;
return 0;
}
Character boss = room.getMonster();
mainMenu(boss);
inRoom = true;
while (inRoom == true)
{
int answer;
std::cin >> answer;
switch (answer)
{
case 1:
{
if (room.getRoomIndex() > 3)
{
pet.setIsPresent(true);
}
inBossFight(boss, player, inventory, pet);
if (boss.getHP() > 0)
{
return 0;
}
int answer2;
std::cout << "Press 1 to continue to the next room.\nPress 2 to scope the room." << std::endl;
std::cin >> answer2;
if (answer2 == 1)
{
inRoom = false;
}
else
{
Edible eat = room.getEdible();
std::cout << "You found " << eat << "\nWould you like to add it to the inventory?\n1 - > yes\n2 - > no" << std::endl;
std::cin >> answer2;
if (answer2 == 1)
{
inventory.addToInventory(eat);
std::cout << "The " << eat.getName() << " has been added to your inventory." << std::endl;
}
inRoom = false;
}
}break;
case 2:
{
int chance;
chance = player.run();
if (chance == 1)
{
//Character* c;
std::cout << "The " << boss.getName() << " is approaching. You raise your weapon." << std::endl;
inBossFight(boss, player, inventory, pet);
if (boss.getHP() > 0)
{
return 0;
}
}
else
{
inRoom = false;
}
}break;
case 3:
{
eatFromInventory(player, inventory);
std::cout << boss.getName() << " is patiently waiting for you. But everybody has their limits..." << std::endl;
std::cout << "What will you do?" << std::endl;
std::cout << "1 - > attack him" << std::endl;
std::cout << "2 - > try to run away (if failed, you will have to fight)" << std::endl;
std::cout << "3 - > open inventory" << std::endl;
} break;
}
}
std::cout << "Would you like to rest?\n1 - > yes\n2 - > no" << std::endl;
int answer;
std::cin >> answer;
if (answer == 1)
{
player.rest();
game.incrementDayCount();
}
i++;
}
}
| 25.758958
| 205
| 0.552226
|
Daria602
|
005c7dd846eae5eb9e39de2162ec96740911b3c7
| 580
|
hpp
|
C++
|
peek-mill-utils.hpp
|
andybarry/peekmill
|
d990877ef943a791f66d19ed897f1421b8e6e0ea
|
[
"BSD-3-Clause"
] | 1
|
2016-08-22T13:46:32.000Z
|
2016-08-22T13:46:32.000Z
|
peek-mill-utils.hpp
|
andybarry/peekmill
|
d990877ef943a791f66d19ed897f1421b8e6e0ea
|
[
"BSD-3-Clause"
] | null | null | null |
peek-mill-utils.hpp
|
andybarry/peekmill
|
d990877ef943a791f66d19ed897f1421b8e6e0ea
|
[
"BSD-3-Clause"
] | null | null | null |
/*
* Utility functions for opencv-stereo
*
* Copyright 2013, Andrew Barry <abarry@csail.mit.edu>
*
*/
#ifndef PEEK_MILL_UTIL
#define PEEK_MILL_UTIL
#include "opencv2/legacy/legacy.hpp"
#include "opencv2/opencv.hpp"
#include <stdio.h>
using namespace std;
using namespace cv;
struct OpenCvCalibration
{
Mat M1;
Mat D1;
};
bool LoadCalibration(OpenCvCalibration *calibration);
//void Draw3DPointsOnImage(Mat camera_image, vector<Point3f> *points_list_in, Mat cam_mat_m, Mat cam_mat_d, Mat cam_mat_r, int color = 128, float x=0, float y=0, float z=0);
#endif
| 18.125
| 173
| 0.737931
|
andybarry
|
005d101e3205b261677a7a2160e17d31325af760
| 19,044
|
cc
|
C++
|
code/addons/locale/localeserver.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 67
|
2015-03-30T19:56:16.000Z
|
2022-03-11T13:52:17.000Z
|
code/addons/locale/localeserver.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 5
|
2015-04-15T17:17:33.000Z
|
2016-02-11T00:40:17.000Z
|
code/addons/locale/localeserver.cc
|
gscept/nebula-trifid
|
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
|
[
"BSD-2-Clause"
] | 34
|
2015-03-30T15:08:00.000Z
|
2021-09-23T05:55:10.000Z
|
//------------------------------------------------------------------------------
// locale/localeserver_main.cc
// (C) 2004 RadonLabs GmbH
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "locale/localeserver.h"
#include "locale/localeattributes.h"
#include "db/reader.h"
#include "db/sqlite3/sqlite3database.h"
#include "db/sqlite3/sqlite3factory.h"
#include "io/filestream.h"
#include "io/ioserver.h"
#include "io/textreader.h"
#include "io/textwriter.h"
namespace Locale
{
__ImplementClass(Locale::LocaleServer, 'LOCA', Core::RefCounted);
__ImplementSingleton(Locale::LocaleServer);
using namespace Db;
using namespace IO;
using namespace Util;
//------------------------------------------------------------------------------
/**
*/
LocaleServer::LocaleServer() :
isOpen(false)
{
__ConstructSingleton;
}
//------------------------------------------------------------------------------
/**
*/
LocaleServer::~LocaleServer()
{
if (this->IsOpen())
{
this->Close();
}
__DestructSingleton;
}
//------------------------------------------------------------------------------
/**
*/
bool
LocaleServer::Open()
{
n_assert(!this->IsOpen());
this->isOpen = true;
return true;
}
//------------------------------------------------------------------------------
/**
*/
String
LocaleServer::ParseText(const String& text)
{
// replace \n and \t
String str(text);
str.SubstituteString("\\t", "\t");
str.SubstituteString("\\n", "\n");
return str;
}
//------------------------------------------------------------------------------
/**
*/
void
LocaleServer::Close()
{
n_assert(this->IsOpen());
this->dictionary.Clear();
this->isOpen = false;
}
//------------------------------------------------------------------------------
/**
*/
String
LocaleServer::GetLocaleText(const String& id)
{
n_assert(this->IsOpen());
if(!id.IsValid())
{
return "";
}
String idStr(id);
if (this->dictionary.Contains(idStr))
{
return this->dictionary[idStr];
}
else
{
n_printf("WARNING: Locale::LocaleServer: id string '%s' not found!!\n", id.AsCharPtr());
static String msg;
msg = "LOCALIZE: '";
msg.Append(idStr);
msg.Append("'");
return msg;
}
}
//------------------------------------------------------------------------------
/**
*/
String
LocaleServer::GetLocaleTextFemale(const String& id)
{
n_assert(this->IsOpen());
if(!id.IsValid())
{
return "";
}
String idStr = id;
idStr.Append("-female");
if (this->dictionary.Contains(idStr))
{
return this->dictionary[idStr];
}
else
{
return this->GetLocaleText(id);
}
}
//------------------------------------------------------------------------------
/**
Analyzes argument statements of id which can be:
"...{<ArgIdx>:s}..." for string arguments
"...{<ArgIdx>:l}..." for string arguments which also will be localized
"...{<ArgIdx>:i}..." for integer arguments
The argument index must be of type integer ([0-9]*).
Gets the locale text with id and replaces the argument statements in the
locale text with the arguments.
Additionally it's possible to specify a plural choice statement:
"...{<ArgIdx>:p:<plural choice>}..." (see PluralChoice(...))
*/
String __cdecl
LocaleServer::GetLocaleTextArgs(const char* id, ...)
{
n_assert(this->IsOpen());
// id string
String idStr(id);
n_assert(idStr.IsValid());
// replaced id
String text = "";
// localized text (text with replaced argument statements)
String localeText = "";
// analyze argument statements
if (!this->AnalyzeArgumentStatements(id))
{
n_error("Locale::LocaleServer: %s", this->errMsg.AsCharPtr());
return "Localization Error:" + idStr;
}
// get arguments and interpret them with help of 'argTypes'
va_list vArgList;
va_start(vArgList, id);
this->InterpretArguments(vArgList);
va_end(vArgList);
// get text with id
text = this->GetLocaleText(idStr);
// build localized text by replacing argument statements in text with arguments
localeText = this->BuildLocalizedText(text);
if (localeText.IsValid())
{
return localeText;
}
else
{
n_error("Locale::LocaleServer: %s", this->errMsg.AsCharPtr());
return "Localization Error:" + idStr;
}
}
//------------------------------------------------------------------------------
/**
Analyzes argument statements and puts results to 'argTypes'.
Will return 'false' if there are errors while analyzing process (e.g. syntax
errors). Will place error message in 'errMsg'.
Type 'l' for localisation will be handled as 's' (string).
Type 'p' for plural choice will be handled as 'i' (integer).
*/
bool
LocaleServer::AnalyzeArgumentStatements(const String& str)
{
n_assert(str.IsValid());
this->argTypes.Clear();
IndexT idxOpenBracket = 0; // index of last found open bracket
IndexT idxColon = 0; // index of last found colon
String argIdxStr = ""; // argument index (between open bracket and colon)
IndexT argIdx = InvalidIndex; // argument index as integer
char argType = '\0'; // argument type (character after colon)
while (true)
{
// find open bracket
idxOpenBracket = str.FindCharIndex('{', idxColon);
// if there is no open bracket: stop
if (idxOpenBracket == InvalidIndex) break;
// find colon
idxColon = str.FindCharIndex(':', idxOpenBracket);
// if there is no colon: stop
if (idxColon == InvalidIndex)
{
this->errMsg.Format("Syntax error in id string '%s'! Colon missing.", str);
return false;
}
// get argument index as string
argIdxStr = str.ExtractRange(idxOpenBracket + 1, idxColon - idxOpenBracket - 1);
// check if argument index string is valid for converting to integer
SizeT argIdxStrLength = argIdxStr.Length();
IndexT idx;
for (idx = 0; idx < argIdxStrLength; idx++)
{
if (argIdxStr[idx] < '0' || argIdxStr[idx] > '9')
{
this->errMsg.Format("Syntax error in id string '%s'! Argument index at position '%d' invalid.", str, idxOpenBracket);
return false;
}
}
// convert argument index string to integer
argIdx = argIdxStr.AsInt();
// get argument type
argType = str[idxColon + 1];
// argument type l (localize) also is of type string
if ('l' == argType)
{
argType = 's';
}
// argument type p (plural choice) also is of type integer
if ('p' == argType)
{
argType = 'i';
}
// interpret argument type
switch (argType)
{
case 's': // string type
case 'i': // integer type
// add argument index and type to argTypes dictionary
if (!argTypes.Contains(argIdx))
{
// argument index is not in direcory: add index and type to dictionary
argTypes.Add(argIdx, argType);
}
else if (argType != argTypes[argIdx])
{
// argument index is in direcory: generate error message if types are not equal (type of argument is ambiguous)
this->errMsg.Format("Parsing error in id string '%s'! Different types for argument %d specified.", str, argIdx);
return false;
}
break;
default:
this->errMsg.Format("Syntax error in id string '%s'! Type '%c' of argument %d invalid.", str, argType, argIdx);
return false;
}
}
return true;
}
//------------------------------------------------------------------------------
/**
Gets arguments and interprets them with help of 'argTypes' storing arguments
to 'argInts' and 'argStrs'.
*/
void
LocaleServer::InterpretArguments(va_list vArgList)
{
IndexT argIdx = 0; // argument index
char argType = '\0'; // argument type
String strArg = "";
this->argStrs.Clear();
this->argInts.Clear();
while(true)
{
if (argTypes.Contains(argIdx))
{
// get argument type
argType = argTypes[argIdx];
// interpret argument type
switch (argType)
{
case 's': // string type
// get next argument, interpret as string and add to argStrs dictionary
strArg = va_arg(vArgList, char*);
argStrs.Add(argIdx, strArg);
break;
case 'i': // integer type
// get next argument, interpret as integer and add to argInts dictionary
argInts.Add(argIdx, va_arg(vArgList, int));
break;
default: // should be impossible
n_error("Locale::LocaleServer: Internal error!\nType '%c' of argument %d invalid.", argType, argIdx);
break;
}
argIdx++;
}
else
{
// stop searching for arguments if argument index cannot be found in argTypes dictionary
break;
}
}
}
//------------------------------------------------------------------------------
/**
Builds the localized text by replacing argument statements with arguments.
Returns "" if there are errors.
*/
String
LocaleServer::BuildLocalizedText(const String& str)
{
n_assert(str.IsValid());
IndexT idxOpenBracket = 0; // index of last found open bracket
IndexT idxAfterCloseBracket = 0; // index of last found close bracket + 1
IndexT idxColon = 0; // index of last found colon
String argIdxStr = ""; // argument index (between open bracket and colon)
IndexT argIdx = InvalidIndex; // argument index as integer
char argType = '\0'; // argument type (character after colon)
String localizedText; // localized text (text with replaced argument statements)
while (idxAfterCloseBracket < str.Length())
{
// find open bracket
idxOpenBracket = str.FindCharIndex('{', idxAfterCloseBracket);
// if there is no open bracket stop
if (idxOpenBracket == InvalidIndex)
{
// add rest of text to localized text
localizedText += str.ExtractToEnd(idxAfterCloseBracket);
break;
}
// add text between close and open bracket to localized text
localizedText += str.ExtractRange(idxAfterCloseBracket, idxOpenBracket - idxAfterCloseBracket);
// find colon
idxColon = str.FindCharIndex(':', idxOpenBracket);
// if there is no colon: stop
if (idxColon == InvalidIndex)
{
this->errMsg.Format("Syntax error in localized text string '%s'! Colon missing.", str);
return "";
}
// find close bracket
idxAfterCloseBracket = str.FindCharIndex('}', idxColon) + 1;
// get argument index as string
argIdxStr = str.ExtractRange(idxOpenBracket + 1, idxColon - idxOpenBracket - 1);
// check if argument index string is valid for converting to integer
SizeT argIdxStrLength = argIdxStr.Length();
IndexT idx;
for (idx = 0; idx < argIdxStrLength; idx++)
{
if (argIdxStr[idx] < '0' || argIdxStr[idx] > '9')
{
this->errMsg.Format("Syntax error in localized text string '%s'! Argument index at position '%d' invalid.", str, idxOpenBracket);
return "";
}
}
// convert argument index string to integer
argIdx = argIdxStr.AsInt();
// get argument type
argType = str[idxColon + 1];
// interpret argument type
switch (argType)
{
case 's': // string type
// check if argument index is in string directory
if (!argStrs.Contains(argIdx))
{
// argument index is not in string direcory: generate error message
this->errMsg.Format("Argument error in localized text string '%s'! Argument %d of type string was not available in id string.", str, argIdx);
return "";
}
else
{
// add argument to localized text
localizedText += argStrs[argIdx];
}
break;
case 'l': // string type (argument string have be localized, too)
// check if argument index is in string directory
if (!argStrs.Contains(argIdx))
{
// argument index is not in string direcory: generate error message
this->errMsg.Format("Argument error in localized text string '%s'! Argument %d of type string was not available in id string. For localization string type is needed.", str, argIdx);
return "";
}
else
{
// add argument to localized text
localizedText += this->GetLocaleText(argStrs[argIdx]);
}
break;
case 'i': // integer type
// check if argument index is in integer directory
if (!argInts.Contains(argIdx))
{
// argument index is not in integer direcory: generate error message
this->errMsg.Format("Argument error in localized text string '%s'! Argument %d of type integer was not available in id string.", str, argIdx);
return "";
}
else
{
// add argument to localized text
localizedText += String::FromInt(argInts[argIdx]);
}
break;
case 'p': // plural choice
// check if argument index is in integer directory
if (!argInts.Contains(argIdx))
{
// argument index is not in integer direcory: generate error message
this->errMsg.Format("Argument error in localized text string '%s'! Argument %d of type integer was not available in id string. For plural choice integer type is needed.", str, argIdx);
return "";
}
else
{
// add plural choice to localized text
localizedText += this->PluralChoice(argInts[argIdx], str.ExtractRange(idxColon + 3, idxAfterCloseBracket - idxColon - 4));
}
break;
default:
this->errMsg.Format("Argument error in localized text string '%s'! Type '%c' of argument %d invalid.", str, argType, argIdx);
return "";
}
}
return localizedText;
}
//------------------------------------------------------------------------------
/**
Chooses the part of the plural choice string which fits best to the amount.
The plural choice string must match to this pattern:
[<is zero text>|]<is one text>|<else text>
Example 1:
PluralChoice(1, "Child|Children"); // Child
PluralChoice(4, "Child|Children"); // Children
Example 2:
PluralChoice(0, "no Children|one Child|many Children"); // no Children
PluralChoice(1, "no Children|one Child|many Children"); // one Child
PluralChoice(5, "no Children|one Child|many Children"); // many Children
*/
String
LocaleServer::PluralChoice(int amount, const String& pluralChoice)
{
n_assert(pluralChoice.IsValid());
Array<String> choices = pluralChoice.Tokenize("|");
switch (choices.Size())
{
case 2:
if ( 1 == amount) return choices[0]; // is one text
else return choices[1]; // else text
break;
case 3:
if ( 0 == amount) return choices[0]; // is zero text
else if ( 1 == amount) return choices[1]; // is one text
else return choices[2]; // else text
break;
default:
n_error("Locale::LocaleServer: Syntax error in plural choice '%s'!", pluralChoice.AsCharPtr());
return pluralChoice;
break;
}
}
//------------------------------------------------------------------------------
/**
Add a locale table from db
*/
void
LocaleServer::AddLocaleDBTable(const String& tableName, const IO::URI& dbUri)
{
LocaPath newPath;
newPath.path = dbUri.AsString();
newPath.tableName = tableName;
this->fileList.Append(newPath);
this->LoadLocaleDataFromDB(tableName, dbUri);
}
//------------------------------------------------------------------------------
/**
Clears the complete locale data dictionary
*/
void
LocaleServer::ClearLocaleData()
{
this->dictionary.Clear();
this->fileList.Clear();
}
//------------------------------------------------------------------------------
/**
reload locaDB
*/
void
LocaleServer::ReloadLocaDB()
{
this->dictionary.Clear();
SizeT numFilePaths = this->fileList.Size();
IndexT idx;
for(idx = 0; idx < numFilePaths; idx++)
{
this->LoadLocaleDataFromDB(this->fileList[idx].tableName, this->fileList[idx].path);
}
}
//------------------------------------------------------------------------------
/**
Add a locale table from db
*/
void
LocaleServer::LoadLocaleDataFromDB(const String& tableName, const IO::URI& dbUri)
{
n_assert(dbUri.IsValid());
__MEMORY_CHECKPOINT("> Locale::LocaleServer::LoadLocaleDataFromDB()");
Ptr<Sqlite3Factory> dbFactory = 0;
if(!Sqlite3Factory::HasInstance())
{
dbFactory = Sqlite3Factory::Create();
}
else
{
dbFactory = Sqlite3Factory::Instance();
}
Ptr<Sqlite3Database> db = dbFactory->CreateDatabase().downcast<Sqlite3Database>();
db->SetURI(dbUri);
db->SetAccessMode(Database::ReadOnly);
db->SetExclusiveMode(true);
db->SetIgnoreUnknownColumns(false);
if (db->Open())
{
if (db->HasTable(tableName))
{
Ptr<Reader> reader = Reader::Create();
reader->SetDatabase(db.cast<Database>());
reader->SetTableName(tableName);
if (reader->Open())
{
SizeT numRows = reader->GetNumRows();
this->dictionary.Reserve(numRows);
IndexT rowIndex;
for (rowIndex = 0; rowIndex < numRows; rowIndex++)
{
reader->SetToRow(rowIndex);
this->dictionary.Add(reader->GetString(Attr::LocaId), reader->GetString(Attr::LocaText));
}
}
reader->Close();
}
db->Close();
}
__MEMORY_CHECKPOINT("< Locale::LocaleServer::LoadLocaleDataFromDB()");
}
}; // namespace Locale
//----------------------------------------------------------------------------
| 30.421725
| 200
| 0.53765
|
gscept
|
005d99e5dc4bc70053c9030d4942372b518209db
| 1,412
|
cpp
|
C++
|
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter10Exercise7.cpp
|
Ziezi/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
|
6fd64801863e883508f15d16398744405f4f9e34
|
[
"Unlicense"
] | 9
|
2018-10-24T15:16:47.000Z
|
2021-12-14T13:53:50.000Z
|
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter10Exercise7.cpp
|
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
|
6fd64801863e883508f15d16398744405f4f9e34
|
[
"Unlicense"
] | null | null | null |
Visual Studio 2010/Projects/bjarneStroustrupC++PartI/object_oriented_examples/Chapter10Exercise7.cpp
|
ChrisBKirov/Programming-Principles-and-Practice-Using-C-by-Bjarne-Stroustrup-
|
6fd64801863e883508f15d16398744405f4f9e34
|
[
"Unlicense"
] | 7
|
2018-10-29T15:30:37.000Z
|
2021-01-18T15:15:09.000Z
|
/*
TITLE Roman numerals Chapter10Exercise7.cpp
Bjarne Stroustrup "Programming: Principles and Practice Using C++"
COMMENT
Objective: Include calculations with Roman numerals.
Input: -
Output: -
Author: Chris B. Kirov
Data: 15.02.2015
*/
/*
Calculator Grammar:
Calculation:
Print
Quit
Statement
Calculation Statement
Statement:
Declaration ----------------------------> Declaration: "let" name "=" Expression
constant variable Declaration: "let" "const" name "=" Expression
Expression
Expression:
Term
Expression +;- Term
Term:
Primary
Term *; / ; % Primary
Primary:
Floating point Numbers / Roman numerals
'(' Expressions ')'
sqrt-----------------------------------> sqrt: "sqrt" "(" Expression ")"
pow------------------------------------> pow: "pow" "("double, integer ")"
factorial------------------------------> factorial: integer"!"
+; - primary
name-----------------------------------> returns the value of a defined variable previously introduced by "let" command
sin------------------------------------> returns the sinus of the an angle within [0,360] degrees.
*/
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <forward_list>
#include "Chapter10Exercise7.h"
int main()
{
std::cout << "\t\tWelcome to our calculator!" << std::endl;
calculate(ts);
}
| 28.24
| 122
| 0.568697
|
Ziezi
|
005f2774a7ee51980431db92e3eaec5ce6112e93
| 30,403
|
cpp
|
C++
|
engine/xbox/generic/xboxport.cpp
|
christianhaitian/openbor
|
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
|
[
"BSD-3-Clause"
] | 600
|
2017-04-05T07:52:07.000Z
|
2022-03-31T07:56:47.000Z
|
engine/xbox/generic/xboxport.cpp
|
christianhaitian/openbor
|
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
|
[
"BSD-3-Clause"
] | 166
|
2017-04-16T12:16:11.000Z
|
2022-03-02T21:42:48.000Z
|
engine/xbox/generic/xboxport.cpp
|
christianhaitian/openbor
|
ce64eaffce90c407cc5a56e52c31ec8e62378bc8
|
[
"BSD-3-Clause"
] | 105
|
2017-04-05T08:18:08.000Z
|
2022-03-31T06:44:04.000Z
|
/*
* OpenBOR - http://www.LavaLit.com
* -----------------------------------------------------------------------
* Licensed under the BSD license, see LICENSE in OpenBOR root for details.
*
* Copyright (c) 2004 - 2011 OpenBOR Team
*/
#include <XBApp.h>
#include <XBFont.h>
#include <XBHelp.h>
#include <XBSound.h>
#include <xgraphics.h>
#include <assert.h>
#include <d3d8perf.h>
#include "SndXBOX.hxx"
#include <stdio.h>
#include <vector>
#include "undocumented.h"
#include "iosupport.h"
#include "panel.h"
#include "custom_launch_params.h"
#include "keyboard_api.h"
#include "gamescreen.h"
DWORD g_dwSoundThreadId ;
HANDLE g_hSoundThread ;
#ifdef __cplusplus
extern "C" {
#endif
#include "xboxport.h"
#include "packfile.h"
#define uint8 unsigned char
#define uint32 unsigned int
void xbox_init(void);
void xbox_return(void);
void _2xSaI(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void _2xSaIScanline(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void SuperEagle(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void SuperEagleScanline(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Super2xSaI(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Super2xSaIScanline(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Scale2x(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void SuperScale(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void SuperScaleScanline(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Eagle(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void EagleScanline(uint8 *srcPtr, uint32 srcPitch,
uint8 *deltaPtr,
uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode);
void Simple2x(unsigned char *srcPtr, uint32 srcPitch, unsigned char * /* deltaPtr */,
unsigned char *dstPtr, uint32 dstPitch, int width, int height, int scanlines) ;
void AdMame2x(unsigned char *srcPtr, uint32 srcPitch, unsigned char * /* deltaPtr */,
unsigned char *dstPtr, uint32 dstPitch, int width, int height, int scanline) ;
char packfile[128] = {"d:\\Paks\\menu.pak"};
#ifdef __cplusplus
}
#endif
#pragma warning(disable:4244)
#pragma warning(disable:4018)
#pragma warning(disable:4101)
#define PLATFORM_SAV L"OPENBORSAV"
#define PLATFORM_INI "OpenBoR.ini"
#define DEFAULT_SAVE_PATH "d:\\Saves"
//-----------------------------------------------------------------------------
// Name: class CXBoxSample
// Desc: Main class to run this application. Most functionality is inherited
// from the CXBApplication base class.
//-----------------------------------------------------------------------------
class CXBoxSample : public CXBApplication
{
public:
CXBoxSample();
virtual HRESULT Initialize();
virtual HRESULT InitializeWithScreen();
virtual HRESULT FrameMove();
virtual void initConsole(UINT32 idx, int isFavorite, int forceConfig);
virtual int init_texture();
virtual void doScreenSize();
virtual BOOL SetRefreshRate(INT iRefreshRate);
virtual int render_to_texture(int src_w, int src_h, s_screen* source);
virtual void saveSettings(char *filename);
virtual int loadSettings(char *filename);
void setPalette(unsigned char *palette);
virtual void pollXBoxControllers(void);
virtual void xboxChangeFilter();
void ClearScreen();
void ResetResolution();
virtual void fillPresentationParams();
D3DCOLOR m_color_palette[256];
DWORD m_startTime ;
DWORD m_joypad ;
D3DCOLOR color_palette[256];
unsigned long m_xboxControllers[4] ;
D3DXVECTOR2 m_gameVecScale ;
D3DXVECTOR2 m_gameVecTranslate ;
RECT m_gameRectSource ;
int m_throttle ;
int m_xboxSFilter ;
unsigned int m_pitch ;
D3DPRESENT_PARAMETERS m_origPP ;
CPanel m_pnlBackgroundMain ;
CPanel m_pnlBackgroundSelect ;
CPanel m_pnlBackgroundOther ;
CPanel m_pnlSplashEmu ;
CPanel m_pnlSplashGame ;
CPanel m_pnlPopup ;
CPanel m_pnlGameScreen ;
CPanel m_pnlGameScreen2 ;
CIoSupport m_io ;
LPDIRECT3DTEXTURE8 Texture;
LPDIRECT3DTEXTURE8 Texture2;
LPDIRECT3DTEXTURE8 WhiteTexture;
LPD3DXSPRITE Sprite;
LPD3DXSPRITE MenuSprite;
byte* g_pBlitBuff ;
byte* g_pDeltaBuff ;
WCHAR m_strMessage[80];
UINT32 m_msgDelay ;
SoundXBOX m_sound;
char g_savePath[500] ;
char g_saveprefix[500] ;
// Indicates the width and height of the screen
UINT32 theWidth;
UINT32 theHeight;
RECT SrcRect;
RECT DestRect;
int m_nScreenX, m_nScreenY, m_nScreenMaxX, m_nScreenMaxY ;
};
#ifdef __cplusplus
extern "C" {
#endif
void hq2x_16(unsigned char*, unsigned char*, DWORD, DWORD, DWORD, DWORD, DWORD);
unsigned int LUT16to32[65536];
unsigned int RGBtoYUV[65536];
#ifdef __cplusplus
}
#endif
void hq2x_16_stub(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode )
{
hq2x_16( srcPtr, dstPtr, width, height, dstPitch, srcPitch - (width<<1), dstPitch - (width<<2));
}
void dummy_blitter(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode )
{
}
struct blitters
{
void (*blitfunc)(uint8 *srcPtr, uint32 srcPitch, uint8 *deltaPtr, uint8 *dstPtr, uint32 dstPitch, int width, int height, int scanmode ) ;
char name[100] ;
float multiplier ;
} SOFTWARE_FILTERS[] =
{
{ dummy_blitter, "None", 1 },
{ _2xSaI, "2xSai", 2},
{ Super2xSaI, "Super 2xSai", 2},
{ hq2x_16_stub, "HQ2X", 2},
{ Eagle, "Eagle2x", 2},
{ SuperEagle, "Super Eagle 2x", 2},
{ SuperScale, "SuperScale 2x", 2},
{ AdMame2x, "AdvanceMame 2x", 2},
{ Simple2x, "Simple 2x", 2},
{ _2xSaIScanline, "2xSai Scanline", 2},
{ Super2xSaIScanline, "Super 2xSai Scanline", 2},
{ EagleScanline, "Eagle2x Scanline", 2},
{ SuperEagleScanline, "Super Eagle2x Scanline", 2},
{ SuperScaleScanline, "SuperScale 2x Scanline", 2},
} ;
#define HQFILTERNUM 1
#define NUM_SOFTWARE_FILTERS 14
void InitLUTs(void)
{
int i, j, k, r, g, b, Y, u, v;
for (i=0; i<65536; i++)
LUT16to32[i] = ((i & 0xF800) << 8) + ((i & 0x07E0) << 5) + ((i & 0x001F) << 3);
for (i=0; i<32; i++)
for (j=0; j<64; j++)
for (k=0; k<32; k++)
{
r = i << 3;
g = j << 2;
b = k << 3;
Y = (r + g + b) >> 2;
u = 128 + ((r - b) >> 2);
v = 128 + ((-r + 2*g -b)>>3);
RGBtoYUV[ (i << 11) + (j << 5) + k ] = (Y<<16) + (u<<8) + v;
}
}
CXBoxSample *g_app ;
char global_error_message[1024] ;
unsigned int m_performanceFreq[2] ;
unsigned int m_performancePrev[2] ;
int recreate( D3DPRESENT_PARAMETERS *pparams )
{
char tmpfilename[500] ;
SAFE_RELEASE( g_app->Sprite ) ;
SAFE_RELEASE( g_app->MenuSprite ) ;
g_app->m_pd3dDevice->Release();
//g_app->fillPresentationParams() ;
if( FAILED( g_app->m_pD3D->CreateDevice( 0, D3DDEVTYPE_HAL, NULL,
D3DCREATE_HARDWARE_VERTEXPROCESSING,
pparams, &g_app->m_pd3dDevice ) ) )
{
return 0 ;
}
else
{
g_pd3dDevice = g_app->m_pd3dDevice ;
g_app->m_pnlBackgroundMain.Recreate( g_app->m_pd3dDevice );
g_app->m_pnlBackgroundSelect.Recreate( g_app->m_pd3dDevice );
g_app->m_pnlBackgroundOther.Recreate( g_app->m_pd3dDevice );
g_app->m_pnlSplashEmu.Recreate( g_app->m_pd3dDevice );
g_app->m_pnlSplashGame.Recreate( g_app->m_pd3dDevice );
g_app->m_pnlPopup.Recreate( g_app->m_pd3dDevice );
g_app->m_pnlGameScreen.Recreate( g_app->m_pd3dDevice );
return 1 ;
}
}
void xbox_set_refreshrate( int rate )
{
int nativeRate ;
D3DPRESENT_PARAMETERS holdpp ;
if(XGetVideoStandard() == XC_VIDEO_STANDARD_PAL_I)
{
//get supported video flags
DWORD videoFlags = XGetVideoFlags();
//set pal60 if available.
if(videoFlags & XC_VIDEO_FLAGS_PAL_60Hz)
nativeRate = 60 ;
else
nativeRate = 50 ;
}
else
nativeRate = 60 ;
if ( rate != g_app->m_d3dpp.FullScreen_RefreshRateInHz )
{
g_app->m_d3dpp.FullScreen_RefreshRateInHz = rate ;
if ( nativeRate != rate )
{
g_app->m_d3dpp.Flags |= D3DPRESENTFLAG_EMULATE_REFRESH_RATE ;
}
else
{
g_app->m_d3dpp.Flags &= ~D3DPRESENTFLAG_EMULATE_REFRESH_RATE ;
}
memcpy( &holdpp, &g_app->m_d3dpp, sizeof(D3DPRESENT_PARAMETERS) ) ;
recreate( &g_app->m_d3dpp ) ;
memcpy( &g_app->m_d3dpp, &holdpp, sizeof(D3DPRESENT_PARAMETERS) ) ;
g_app->m_pd3dDevice->Reset(&g_app->m_d3dpp);
memcpy( &g_app->m_d3dpp, &holdpp, sizeof(D3DPRESENT_PARAMETERS) ) ;
}
}
int CXBoxSample::init_texture()
{
D3DCOLOR *palette ;
// Release any previous texture
if (Texture)
{
return 1 ;
Texture->BlockUntilNotBusy() ;
Texture->Release();
Texture = NULL;
}
theWidth = 320*4 ;
theHeight = 240*4 ;
// Create the texture
if (D3DXCreateTextureFromFileInMemoryEx(m_pd3dDevice, GAMESCREEN_FILE, sizeof(GAMESCREEN_FILE),
theWidth, theHeight, 1, 0, D3DFMT_LIN_R5G6B5, D3DPOOL_MANAGED,
//D3DX_DEFAULT, D3DX_DEFAULT, 1, 0, D3DFMT_LIN_A8R8G8B8, D3DPOOL_MANAGED,
D3DX_FILTER_NONE , D3DX_FILTER_NONE, 0, NULL, NULL, &Texture)==D3D_OK)
{
m_pnlGameScreen.m_pTexture = NULL ;
if ( FAILED(m_pnlGameScreen.Create(m_pd3dDevice, Texture, FALSE, theWidth, theHeight)) )
{
//popupMsg( "no create panel", &m_pnlBackgroundOther ) ;
}
}
else
{
//popupMsg( "no load texture", &m_pnlBackgroundOther ) ;
}
D3DSURFACE_DESC desc;
Texture->GetLevelDesc(0, &desc);
if (g_pBlitBuff != NULL)
{
delete [] g_pBlitBuff;
g_pBlitBuff = NULL;
}
// Allocate a buffer to blit our frames to
g_pBlitBuff = new byte[ desc.Size ];
if (g_pDeltaBuff != NULL)
{
delete [] g_pDeltaBuff;
g_pDeltaBuff = NULL;
}
// Allocate a buffer to blit our frames to
g_pDeltaBuff = new byte[desc.Size];
if ( g_pDeltaBuff == NULL )
return 1 ;
memset( g_pDeltaBuff, 0x00, desc.Size ) ;
RECT rectSource;
rectSource.top = 0;
rectSource.left = 0;
rectSource.bottom = theHeight-1 ;
rectSource.right = theWidth-1 ;
D3DLOCKED_RECT d3dlr;
Texture->LockRect(0, &d3dlr, &rectSource, 0);
m_pitch = d3dlr.Pitch ;
// Unlock our texture
Texture->UnlockRect(0);
return 0;
}
void CXBoxSample::ResetResolution() {
m_pd3dDevice->Reset(&m_d3dpp);
m_pd3dDevice->Clear(0,NULL,D3DCLEAR_TARGET,0x0,1.0f,0);
m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
//Device->SetFlickerFilter(FlickerFilter) ;
//Device->SetSoftDisplayFilter(Soften) ;
}
void CXBoxSample::saveSettings( char *filename )
{
FILE *setfile ;
setfile = fopen( filename, "wb" ) ;
if ( !setfile )
return ;
fwrite( &m_xboxSFilter, sizeof(unsigned int), 1, setfile ) ;
fwrite( &m_nScreenX, sizeof(unsigned int), 1, setfile ) ;
fwrite( &m_nScreenY, sizeof(unsigned int), 1, setfile ) ;
fwrite( &m_nScreenMaxX, sizeof(unsigned int), 1, setfile ) ;
fwrite( &m_nScreenMaxY, sizeof(unsigned int), 1, setfile ) ;
fclose( setfile ) ;
}
void CXBoxSample::setPalette( unsigned char *palette)
{
memset( color_palette, 0, 256*sizeof(D3DCOLOR) ) ;
DWORD r, g, b;
for (int i = 0; i < 256; i++)
{
r = palette[i*3] ;
g = palette[(i*3)+1] ;
b = palette[(i*3)+2] ;
color_palette[i] = ( ( r >> 3 ) << 11 ) | ( ( g >> 2 ) << 5 ) | ( b >> 3 ) ;
}
}
int CXBoxSample::loadSettings(char *filename)
{
FILE *setfile ;
setfile = fopen( filename, "rb" ) ;
if ( !setfile )
{
saveSettings( filename ) ;
return 1;
}
fread( &m_xboxSFilter, sizeof(unsigned int), 1, setfile ) ;
fread( &m_nScreenX, sizeof(unsigned int), 1, setfile ) ;
fread( &m_nScreenY, sizeof(unsigned int), 1, setfile ) ;
fread( &m_nScreenMaxX, sizeof(unsigned int), 1, setfile ) ;
fread( &m_nScreenMaxY, sizeof(unsigned int), 1, setfile ) ;
fclose( setfile ) ;
if ( ( m_xboxSFilter < 0 ) || ( m_xboxSFilter >= NUM_SOFTWARE_FILTERS ))
{
m_xboxSFilter = 0 ;
}
return 0 ;
}
HRESULT CXBoxSample::InitializeWithScreen()
{
FILE *debugfile ;
char initext[100] ;
char szDevice[2000] ;
char *fpos, *epos ;
int numread ;
char tmpfilename[MAX_PATH] ;
XBInput_GetInput();
XMountUtilityDrive( TRUE ) ;
m_io.Unmount("C:") ;
m_io.Unmount("E:") ;
m_io.Unmount("F:") ;
m_io.Unmount("G:") ;
m_io.Unmount("X:") ;
m_io.Unmount("Y:") ;
m_io.Unmount("Z:") ;
m_io.Unmount("R:") ;
m_io.Mount("C:", "Harddisk0\\Partition2");
m_io.Mount("E:", "Harddisk0\\Partition1");
m_io.Mount("F:", "Harddisk0\\Partition6");
m_io.Mount("G:", "Harddisk0\\Partition7");
m_io.Mount("X:", "Harddisk0\\Partition3");
m_io.Mount("Y:", "Harddisk0\\Partition4");
m_io.Mount("Z:", "Harddisk0\\Partition5");
m_io.Mount("R:","Cdrom0");
XFormatUtilityDrive() ;
char szNewDir[MAX_PATH] ;
char *s, *p ;
strcpy( szNewDir, DEFAULT_SAVE_PATH ) ;
s = szNewDir+3 ;
while ( p = strchr( s, '\\' ) )
{
*p = 0 ;
CreateDirectory( szNewDir, NULL ) ;
*p = '\\' ;
p++ ;
s = p ;
}
CreateDirectory( DEFAULT_SAVE_PATH, NULL ) ;
m_xboxSFilter = 0 ;
m_nScreenMaxX = 640 ;
m_nScreenMaxY = 480 ;
m_nScreenX = 0 ;
m_nScreenY = 0 ;
DWORD tdiff = GetTickCount() ;
tdiff = GetTickCount() - tdiff ;
m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL|D3DCLEAR_TARGET,
0x00000000, 0.0f, 0L );
m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
QueryPerformanceFrequency((union _LARGE_INTEGER *) m_performanceFreq);
InitLUTs() ;
XGetCustomLaunchData() ;
m_msgDelay = 0 ;
wcscpy( m_strMessage, L" " ) ;
g_pBlitBuff = NULL ;
g_pDeltaBuff = NULL ;
WhiteTexture = NULL ;
Texture = NULL ;
Sprite = NULL ;
MenuSprite = NULL ;
g_saveprefix[0] = 0 ;
initConsole(0,0,0) ;
return S_OK;
}
//-----------------------------------------------------------------------------
// Name: FrameMove
// Desc: Performs per-frame updates
//-----------------------------------------------------------------------------
HRESULT CXBoxSample::FrameMove()
{
InitializeWithScreen() ;
return S_OK;
}
int CXBoxSample::render_to_texture(int src_w, int src_h, s_screen* source)
{
int vp_vstart ;
int vp_vend ;
int vp_hstart ;
int vp_hend ;
int w,h ;
RECT src, dst;
WORD *curr1 ;
byte *curr2 ;
DWORD pitchDiff1 ;
DWORD pitchDiff2 ;
D3DCOLOR *palette ;
char palstr[200] ;
DWORD pixel ;
byte r,g,b ;
// Get a description of our level 0 texture so we can figure
// out the pitch of the texture
D3DSURFACE_DESC desc;
Texture->GetLevelDesc(0, &desc);
// Allocate a buffer to blit our frames to
unsigned char *bsrc = source->data;
unsigned short *bdst = (unsigned short*)g_pBlitBuff;
for ( int y = 0 ; y < source->height ; y++ )
{
for ( int x = 0 ; x < source->width ; x++ )
{
*(bdst+x) = color_palette[ *bsrc++ ] ;
}
bdst += m_pitch/2 ;
}
// Figure out how big of a rect to lock in our texture
RECT rectSource;
rectSource.top = 0;
rectSource.left = 0;
rectSource.bottom = source->height;
rectSource.right = source->width;
// Lock the rect in our texture
D3DLOCKED_RECT d3dlr;
Texture->LockRect(0, &d3dlr, &rectSource, 0);
float mx, my ;
if ( m_xboxSFilter )
{
SOFTWARE_FILTERS[m_xboxSFilter].blitfunc(g_pBlitBuff + m_pitch,m_pitch, g_pDeltaBuff+m_pitch, ((unsigned char*)d3dlr.pBits)+m_pitch, m_pitch, src_w, src_h, 0 ) ;
Texture->UnlockRect(0);
g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0L);
g_pd3dDevice->BeginScene();
mx = (float)m_nScreenMaxX / ((float)src_w*SOFTWARE_FILTERS[m_xboxSFilter].multiplier) ;
my = (float)m_nScreenMaxY / ((float)src_h*SOFTWARE_FILTERS[m_xboxSFilter].multiplier);
m_gameRectSource.top = 0 ;
m_gameRectSource.left = 0 ;
m_gameRectSource.bottom = (src_h)*SOFTWARE_FILTERS[m_xboxSFilter].multiplier ;
m_gameRectSource.right = (src_w)*SOFTWARE_FILTERS[m_xboxSFilter].multiplier ;
}
else
{
unsigned char *src = g_pBlitBuff;
unsigned char *dst = (unsigned char*)d3dlr.pBits;
for ( int y = 0 ; y < src_h ; y++ )
{
memcpy( dst, src, src_w*2 ) ;
dst += m_pitch ;
src += m_pitch ;
}
Texture->UnlockRect(0);
g_pd3dDevice->Clear(0L, NULL, D3DCLEAR_TARGET, D3DCOLOR_XRGB(0,0,0), 1.0f, 0L);
g_pd3dDevice->BeginScene();
mx = (float)m_nScreenMaxX / ((float)src_w) ;
my = (float)m_nScreenMaxY / ((float)src_h);
m_gameRectSource.top = 0;
m_gameRectSource.left = 0;
m_gameRectSource.bottom = src_h;
m_gameRectSource.right = src_w;
}
m_gameVecScale.x = mx ; m_gameVecScale.y = my;
m_gameVecTranslate.x = m_nScreenX ; m_gameVecTranslate.y = m_nScreenY ;
D3DXCOLOR d3color(1.0, 1.0, 1.0, 1.0);
m_pnlGameScreen.Render( m_gameRectSource.left, m_gameRectSource.top,m_gameRectSource.right,m_gameRectSource.bottom,m_nScreenX ,m_nScreenY, m_nScreenMaxX, m_nScreenMaxY) ;
if ( global_error_message[0] )
{
WCHAR msg[500] ;
m_msgDelay-- ;
swprintf( msg, L"%S", global_error_message ) ;
if ( m_msgDelay <= 0 )
{
global_error_message[0] = 0 ;
}
}
// End the scene.
g_pd3dDevice->EndScene();
g_pd3dDevice->Present(NULL, NULL, NULL, NULL);
return 1;
}
struct vidmodes
{
char name[100] ;
unsigned int width ;
unsigned int height ;
char progressive ;
float multx ;
float multy ;
} VIDEOMODES[] =
{
{ "Standard 480i", 640, 480, 0, 1.0f, 1.0f },
{ "480p", 640, 480, 1, 1.0f, 1.0f },
{ "720p", 1280, 720, 1, 2.0f, 1.5f },
{ "1080i", 1920, 1080, 0, 3.0f, 2.25f },
{ "720x480", 720, 480, 0, 1.125f, 1.0f },
{ "720x576", 720, 576, 0, 1.125f, 1.2f },
} ;
void CXBoxSample::fillPresentationParams()
{
IDirect3D8 *pD3D;
DWORD videoFlags = XGetVideoFlags();
ZeroMemory(&m_d3dpp, sizeof(m_d3dpp));
m_d3dpp.BackBufferWidth = 640;
m_d3dpp.BackBufferHeight = 480;
m_d3dpp.BackBufferFormat = D3DFMT_LIN_R5G6B5;
m_d3dpp.Flags = D3DPRESENTFLAG_INTERLACED;
m_d3dpp.BackBufferCount = 1;
m_d3dpp.EnableAutoDepthStencil = TRUE;
m_d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
m_d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
m_d3dpp.FullScreen_PresentationInterval = D3DPRESENT_INTERVAL_DEFAULT;
m_d3dpp.MultiSampleType = D3DMULTISAMPLE_NONE;
if(XGetVideoStandard() == XC_VIDEO_STANDARD_PAL_I)
{
// Set pal60 if available.
if(videoFlags & XC_VIDEO_FLAGS_PAL_60Hz) m_d3dpp.FullScreen_RefreshRateInHz = 60;
else m_d3dpp.FullScreen_RefreshRateInHz = 50;
}
else m_d3dpp.FullScreen_RefreshRateInHz = 60;
if(XGetAVPack() == XC_AV_PACK_HDTV)
{
if(videoFlags & XC_VIDEO_FLAGS_HDTV_1080i)
{
m_d3dpp.Flags = D3DPRESENTFLAG_WIDESCREEN | D3DPRESENTFLAG_INTERLACED;
m_d3dpp.BackBufferWidth = 1920;
m_d3dpp.BackBufferHeight = 1080;
return;
}
else if(videoFlags & XC_VIDEO_FLAGS_HDTV_720p)
{
m_d3dpp.Flags = D3DPRESENTFLAG_PROGRESSIVE | D3DPRESENTFLAG_WIDESCREEN;
m_d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
m_d3dpp.BackBufferWidth = 1280;
m_d3dpp.BackBufferHeight = 720;
return;
}
else if(videoFlags & XC_VIDEO_FLAGS_HDTV_480p)
{
m_d3dpp.Flags = D3DPRESENTFLAG_PROGRESSIVE;
m_d3dpp.BackBufferFormat = D3DFMT_A8R8G8B8;
m_d3dpp.BackBufferWidth = 640;
m_d3dpp.BackBufferHeight = 480;
return;
}
}
}
CXBoxSample xbApp;
extern "C" {
void changeResolution() {
xbApp.fillPresentationParams() ;
xbApp.ResetResolution();
}
}
VOID __cdecl main()
{
g_app = &xbApp ;
xbApp.fillPresentationParams() ;
memcpy( &xbApp.m_origPP, &xbApp.m_d3dpp, sizeof(xbApp.m_origPP) ) ;
if( FAILED( xbApp.Create() ) )
{
return;
}
xbApp.Run();
}
//-----------------------------------------------------------------------------
// Name: CXBoxSample (constructor)
// Desc: Constructor for CXBoxSample class
//-----------------------------------------------------------------------------
CXBoxSample::CXBoxSample()
:CXBApplication()
{
global_error_message[0] = 0 ;
}
void CXBoxSample::ClearScreen()
{
m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL|D3DCLEAR_TARGET,
0x00000000, 1.0f, 0L );
m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
}
#define XBOX_DPAD_UP 0x00000001
#define XBOX_DPAD_RIGHT 0x00000002
#define XBOX_DPAD_DOWN 0x00000004
#define XBOX_DPAD_LEFT 0x00000008
#define XBOX_A 0x00000010
#define XBOX_B 0x00000020
#define XBOX_X 0x00000040
#define XBOX_Y 0x00000080
#define XBOX_BLACK 0x00000100
#define XBOX_WHITE 0x00000200
#define XBOX_START 0x00000400
#define XBOX_BACK 0x00000800
#define XBOX_LEFT_TRIGGER 0x00001000
#define XBOX_RIGHT_TRIGGER 0x00002000
#define XBOX_LEFT_THUMB 0x00004000
#define XBOX_RIGHT_THUMB 0x00008000
#define XBOX_LTHUMB_UP 0x00010000
#define XBOX_LTHUMB_RIGHT 0x00020000
#define XBOX_LTHUMB_DOWN 0x00040000
#define XBOX_LTHUMB_LEFT 0x00080000
#define XBOX_RTHUMB_UP 0x00100000
#define XBOX_RTHUMB_RIGHT 0x00200000
#define XBOX_RTHUMB_DOWN 0x00400000
#define XBOX_RTHUMB_LEFT 0x00800000
void CXBoxSample::pollXBoxControllers(void)
{
int i = 0;
static int didfilter = 0;
XBInput_GetInput();
for(i=0; i<4; i++)
{
m_xboxControllers[i] = 0;
if(g_Gamepads[i].hDevice)
{
if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_A] > 25) m_xboxControllers[i] |= XBOX_A;
if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_B] > 25) m_xboxControllers[i] |= XBOX_B;
if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_X] > 25) m_xboxControllers[i] |= XBOX_X;
if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_Y] > 25) m_xboxControllers[i] |= XBOX_Y;
if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_BLACK] > 25) m_xboxControllers[i] |= XBOX_BLACK;
if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_WHITE] > 25) m_xboxControllers[i] |= XBOX_WHITE;
if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_DPAD_UP) m_xboxControllers[i] |= XBOX_DPAD_UP;
if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_DPAD_RIGHT) m_xboxControllers[i] |= XBOX_DPAD_RIGHT;
if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_DPAD_DOWN) m_xboxControllers[i] |= XBOX_DPAD_DOWN;
if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_DPAD_LEFT) m_xboxControllers[i] |= XBOX_DPAD_LEFT;
if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_START) m_xboxControllers[i] |= XBOX_START;
if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_BACK) m_xboxControllers[i] |= XBOX_BACK;
if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_LEFT_TRIGGER] > 25) m_xboxControllers[i] |= XBOX_LEFT_TRIGGER;
if(g_Gamepads[i].bAnalogButtons[XINPUT_GAMEPAD_RIGHT_TRIGGER] > 25) m_xboxControllers[i] |= XBOX_RIGHT_TRIGGER;
if(g_Gamepads[i].fX1 > 0.40f) m_xboxControllers[i] |= XBOX_DPAD_RIGHT;
if(g_Gamepads[i].fX1 < -0.40f) m_xboxControllers[i] |= XBOX_DPAD_LEFT;
if(g_Gamepads[i].fY1 > 0.40f) m_xboxControllers[i] |= XBOX_DPAD_UP;
if(g_Gamepads[i].fY1 < -0.40f) m_xboxControllers[i] |= XBOX_DPAD_DOWN;
if(g_Gamepads[i].fX2 > 0.40f) m_xboxControllers[i] |= XBOX_RTHUMB_RIGHT;
if(g_Gamepads[i].fX2 < -0.40f) m_xboxControllers[i] |= XBOX_RTHUMB_LEFT;
if(g_Gamepads[i].fY2 > 0.40f) m_xboxControllers[i] |= XBOX_RTHUMB_UP;
if(g_Gamepads[i].fY2 < -0.40f) m_xboxControllers[i] |= XBOX_RTHUMB_DOWN;
if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_LEFT_THUMB) m_xboxControllers[i] |= XBOX_LEFT_THUMB;
if(g_Gamepads[i].wButtons & XINPUT_GAMEPAD_RIGHT_THUMB)
{
m_xboxControllers[i] |= XBOX_RIGHT_THUMB;
if(!didfilter)
{
xboxChangeFilter();
didfilter = 1;
}
}
else didfilter = 0;
if((g_Gamepads[i].wButtons & XINPUT_GAMEPAD_START) && (g_Gamepads[i].wButtons & XINPUT_GAMEPAD_BACK))
{
PLAUNCH_DATA ldata;
memset(&ldata, 0, sizeof(PLAUNCH_DATA));
XLaunchNewImage("D:\\default.xbe", ldata);
}
}
}
}
BOOL CXBoxSample::SetRefreshRate(INT iRefreshRate)
{
char xmsg[100] ;
m_d3dpp.FullScreen_RefreshRateInHz = iRefreshRate;
DWORD res = m_pd3dDevice->Reset(&m_d3dpp);
return TRUE;
}
HRESULT CXBoxSample::Initialize()
{
//m_logfile = fopen( "D:\\err.log", "wb" ) ;
// Create DirectSound
if( FAILED( DirectSoundCreate( NULL, &(m_sound.dsound), NULL ) ) )
return E_FAIL;
if ( ( XCreateSaveGame( "U:\\", PLATFORM_SAV, OPEN_ALWAYS, 0, g_savePath, 500 ) ) != ERROR_SUCCESS )
{
//return E_FAIL;
}
m_sound.dsound_init() ;
m_sound.m_fps = m_d3dpp.FullScreen_RefreshRateInHz ;
return S_OK ;
}
void CXBoxSample::xboxChangeFilter()
{
g_app->m_xboxSFilter = (g_app->m_xboxSFilter+1)%NUM_SOFTWARE_FILTERS ;
saveSettings( "d:\\Saves\\settings.cfg" ) ;
memset( g_app->g_pDeltaBuff, 0x00, 480*g_app->m_pitch ) ;
sprintf( global_error_message, "%s Filtering", SOFTWARE_FILTERS[m_xboxSFilter].name ) ;
debug_printf("%s Filtering", SOFTWARE_FILTERS[m_xboxSFilter].name);
m_msgDelay = 120 ;
}
DWORD WINAPI Sound_ThreadFunc( LPVOID lpParam )
{
float FPS ;
unsigned int perfCurr[2] ;
unsigned int perfPrev[2] ;
QueryPerformanceCounter((union _LARGE_INTEGER *) perfPrev);
while ( 1 )
{
do
{
QueryPerformanceCounter((union _LARGE_INTEGER *) perfCurr);
if (perfCurr[0] != perfPrev[0])
{
FPS = (float) (m_performanceFreq[0]) / (float) (perfCurr[0] - perfPrev[0]);
}
else
{
FPS = 200.0f ;
}
Sleep(1) ;
} while ( FPS > 120 ) ;
perfPrev[0] = perfCurr[0];
g_app->m_sound.process( g_app->m_throttle ) ;
}
return 0;
}
void CXBoxSample::doScreenSize()
{
WCHAR str[200];
int x, y, maxx, maxy ;
float fx, fy, fmaxx, fmaxy ;
float origw, origh ;
DWORD mtime ;
mtime = GetTickCount() ;
x = m_nScreenX ;
y = m_nScreenY ;
maxx = m_nScreenMaxX;
maxy = m_nScreenMaxY ;
fx = (float)x ;
fy = (float)y ;
fmaxx = (float)maxx ;
fmaxy = (float)maxy ;
origw = (float)m_nScreenMaxX/m_gameVecScale.x ;
origh = (float)m_nScreenMaxY/m_gameVecScale.y ;
while ( 1 )
{
m_pd3dDevice->Clear( 0L, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER|D3DCLEAR_STENCIL,
0x00000000, 1.0f, 0L );
x = (int)fx ;
y = (int)fy ;
maxx = (int)fmaxx ;
maxy = (int)fmaxy ;
D3DXCOLOR d3color(1.0, 1.0, 1.0, 1.0);
m_gameVecScale.x = (float)maxx / ((float)origw);
m_gameVecScale.y = (float)maxy / ((float)origh);
m_gameVecTranslate.x = x ;
m_gameVecTranslate.y = y ;
m_pnlGameScreen.Render(m_gameRectSource.left,m_gameRectSource.top,m_gameRectSource.right,m_gameRectSource.bottom,x,y,maxx,maxy) ;
m_pd3dDevice->Present( NULL, NULL, NULL, NULL );
XBInput_GetInput();
if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_B])
{
break ;
}
else if(g_Gamepads[0].hDevice && g_Gamepads[0].bPressedAnalogButtons[XINPUT_GAMEPAD_A])
{
m_nScreenX = x ;
m_nScreenY = y ;
m_nScreenMaxX = maxx ;
m_nScreenMaxY = maxy ;
saveSettings( "d:\\Saves\\settings.cfg" ) ;
break ;
}
else
{
if ( g_Gamepads[0].hDevice )
{
if ( GetTickCount() - mtime > 5 )
{
mtime = GetTickCount() ;
fx += (g_Gamepads[0].fX1) ;
fy -= (g_Gamepads[0].fY1) ;
fmaxx += (g_Gamepads[0].fX2) ;
fmaxy -= (g_Gamepads[0].fY2) ;
}
}
}
}
}
void CXBoxSample::initConsole( UINT32 idx, int isFavorite, int forceConfig )
{
char filename[500];
char shortpath[100];
unsigned char *gimage;
int ntsccol;
FILE *infile;
UINT32 fsize;
char *forcebuf;
int isOther;
setSystemRam();
// Create necessary directories First
CreateDirectory("d:\\Paks", NULL);
CreateDirectory("d:\\Saves", NULL);
CreateDirectory("d:\\Logs", NULL);
CreateDirectory("d:\\ScreenShots", NULL);
m_throttle = 0 ;
global_error_message[0] = 0 ;
m_sound.init() ;
// Create our texture
init_texture();
// Create our sprite driver
if ( Sprite == NULL )
D3DXCreateSprite(m_pd3dDevice, &Sprite);
m_fAppTime = 0.0f ;
m_startTime = GetTickCount() ;
QueryPerformanceCounter((union _LARGE_INTEGER *) m_performancePrev);
xbox_set_refreshrate(60) ;
//Then start it up
m_sound.pause( FALSE ) ;
loadSettings("d:\\Saves\\settings.cfg");
g_hSoundThread = CreateThread(
NULL, // (this parameter is ignored)
0, // use default stack size
Sound_ThreadFunc, // thread function
NULL, // argument to thread function
0, // use default creation flags
&g_dwSoundThreadId); // returns the thread identifier
xbox_init();
packfile_mode(0);
openborMain(0,NULL);
}
#ifdef __cplusplus
extern "C" {
#endif
void borExit(int reset)
{
tracemalloc_dump();
xbox_return() ;
}
void xbox_resize()
{
g_app->doScreenSize() ;
}
void xbox_clear_screen()
{
g_app->ClearScreen() ;
}
void xbox_pause_audio( int state )
{
g_app->m_sound.pause( state ? true : false ) ;
}
void xbox_check_events(void)
{
g_app->pollXBoxControllers();
}
unsigned long xbox_get_playerinput( int playernum )
{
return g_app->m_xboxControllers[playernum];
}
void xbox_put_image(int src_w, int src_h, s_screen* source)
{
if ( g_app->m_throttle )
g_app->m_throttle-- ;
if ( g_app->m_throttle == 0 )
g_app->render_to_texture(src_w, src_h, source) ;
}
void xbox_set_palette( char *palette )
{
g_app->setPalette( (unsigned char*)palette) ;
}
void xbox_init()
{
XGetCustomLaunchData();
}
void xbox_return()
{
XReturnToLaunchingXBE() ;
}
void xbox_Sleep( int d )
{
Sleep( d ) ;
}
unsigned int xbox_get_throttle()
{
return g_app->m_throttle ;
}
int xbox_get_filter()
{
return g_app->m_xboxSFilter ;
}
#ifdef __cplusplus
}
#endif
| 23.733802
| 171
| 0.66181
|
christianhaitian
|
006217f72f5d9786e94dbc7379d375ef41c4e270
| 4,020
|
cpp
|
C++
|
src/Overlay/Window/RoomWindow.cpp
|
GrimFlash/BBCF-Improvement-Mod-GGPO
|
9482ead2edd70714f427d3a5683d17b19ab8ac2e
|
[
"MIT"
] | 48
|
2020-06-09T22:53:52.000Z
|
2022-01-02T12:44:33.000Z
|
src/Overlay/Window/RoomWindow.cpp
|
GrimFlash/BBCF-Improvement-Mod-GGPO
|
9482ead2edd70714f427d3a5683d17b19ab8ac2e
|
[
"MIT"
] | 2
|
2020-05-27T21:25:49.000Z
|
2020-05-27T23:56:56.000Z
|
src/Overlay/Window/RoomWindow.cpp
|
GrimFlash/BBCF-Improvement-Mod-GGPO
|
9482ead2edd70714f427d3a5683d17b19ab8ac2e
|
[
"MIT"
] | 12
|
2020-06-17T20:44:17.000Z
|
2022-01-04T18:15:27.000Z
|
#include "RoomWindow.h"
#include "Core/interfaces.h"
#include "Core/utils.h"
#include "Game/gamestates.h"
#include "Overlay/imgui_utils.h"
#include "Overlay/WindowManager.h"
#include "Overlay/Widget/ActiveGameModeWidget.h"
#include "Overlay/Widget/GameModeSelectWidget.h"
#include "Overlay/Widget/StageSelectWidget.h"
#include "Overlay/Window/PaletteEditorWindow.h"
void RoomWindow::BeforeDraw()
{
ImGui::SetWindowPos(m_windowTitle.c_str(), ImVec2(200, 200), ImGuiCond_FirstUseEver);
//ImVec2 windowSizeConstraints;
//switch (Settings::settingsIni.menusize)
//{
//case 1:
// windowSizeConstraints = ImVec2(250, 190);
// break;
//case 3:
// windowSizeConstraints = ImVec2(400, 230);
// break;
//default:
// windowSizeConstraints = ImVec2(330, 230);
//}
ImVec2 windowSizeConstraints = ImVec2(300, 190);
ImGui::SetNextWindowSizeConstraints(windowSizeConstraints, ImVec2(1000, 1000));
}
void RoomWindow::Draw()
{
if (!g_interfaces.pRoomManager->IsRoomFunctional())
{
ImGui::TextDisabled("YOU ARE NOT IN A ROOM OR ONLINE MATCH!");
m_windowTitle = m_origWindowTitle;
return;
}
std::string roomTypeName = g_interfaces.pRoomManager->GetRoomTypeName();
SetWindowTitleRoomType(roomTypeName);
ImGui::Text("Online type: %s", roomTypeName.c_str());
ImGui::PushStyleVar(ImGuiStyleVar_ChildRounding, 5.0f);
if (isStageSelectorEnabledInCurrentState())
{
ImGui::VerticalSpacing(10);
StageSelectWidget();
}
if (isOnCharacterSelectionScreen() || isOnVersusScreen() || isInMatch())
{
ImGui::VerticalSpacing(10);
ActiveGameModeWidget();
}
if (isGameModeSelectorEnabledInCurrentState())
{
bool isThisPlayerSpectator = g_interfaces.pRoomManager->IsRoomFunctional() && g_interfaces.pRoomManager->IsThisPlayerSpectator();
if (!isThisPlayerSpectator)
{
GameModeSelectWidget();
}
}
if (isInMatch())
{
ImGui::VerticalSpacing(10);
WindowManager::GetInstance().GetWindowContainer()->
GetWindow<PaletteEditorWindow>(WindowType_PaletteEditor)->ShowAllPaletteSelections("Room");
}
if (isInMenu())
{
ImGui::VerticalSpacing(10);
DrawRoomImPlayers();
}
if (isOnCharacterSelectionScreen() || isOnVersusScreen() || isInMatch())
{
ImGui::VerticalSpacing(10);
DrawMatchImPlayers();
}
ImGui::PopStyleVar();
}
void RoomWindow::SetWindowTitleRoomType(const std::string& roomTypeName)
{
m_windowTitle = "Online - " + roomTypeName + "###Room";
}
void RoomWindow::ShowClickableSteamUser(const char* playerName, const CSteamID& steamId) const
{
ImGui::TextUnformatted(playerName);
ImGui::HoverTooltip("Click to open Steam profile");
if (ImGui::IsItemClicked())
{
g_interfaces.pSteamFriendsWrapper->ActivateGameOverlayToUser("steamid", steamId);
}
}
void RoomWindow::DrawRoomImPlayers()
{
ImGui::BeginGroup();
ImGui::TextUnformatted("Improvement Mod users in Room:");
ImGui::BeginChild("RoomImUsers", ImVec2(230, 150), true);
for (const IMPlayer& imPlayer : g_interfaces.pRoomManager->GetIMPlayersInCurrentRoom())
{
ShowClickableSteamUser(imPlayer.steamName.c_str(), imPlayer.steamID);
ImGui::NextColumn();
}
ImGui::EndChild();
ImGui::EndGroup();
}
void RoomWindow::DrawMatchImPlayers()
{
ImGui::BeginGroup();
ImGui::TextUnformatted("Improvement Mod users in match:");
ImGui::BeginChild("MatchImUsers", ImVec2(230, 150), true);
if (g_interfaces.pRoomManager->IsThisPlayerInMatch())
{
ImGui::Columns(2);
for (const IMPlayer& imPlayer : g_interfaces.pRoomManager->GetIMPlayersInCurrentMatch())
{
uint16_t matchPlayerIndex = g_interfaces.pRoomManager->GetPlayerMatchPlayerIndexByRoomMemberIndex(imPlayer.roomMemberIndex);
std::string playerType;
if (matchPlayerIndex == 0)
playerType = "Player 1";
else if (matchPlayerIndex == 1)
playerType = "Player 2";
else
playerType = "Spectator";
ShowClickableSteamUser(imPlayer.steamName.c_str(), imPlayer.steamID);
ImGui::NextColumn();
ImGui::TextUnformatted(playerType.c_str());
ImGui::NextColumn();
}
}
ImGui::EndChild();
ImGui::EndGroup();
}
| 25.283019
| 131
| 0.74005
|
GrimFlash
|
006ab54d6ebae19511ea7481b2eb6e35854eb37a
| 15,657
|
hpp
|
C++
|
test/simulation_tests.hpp
|
marekpetrik/CRAAM
|
62cc392e876b5383faa5cb15ab1f6b70b26ff395
|
[
"MIT"
] | 22
|
2015-09-28T14:41:00.000Z
|
2020-07-03T00:16:19.000Z
|
test/simulation_tests.hpp
|
marekpetrik/CRAAM
|
62cc392e876b5383faa5cb15ab1f6b70b26ff395
|
[
"MIT"
] | 6
|
2017-08-10T18:35:40.000Z
|
2018-10-13T01:38:04.000Z
|
test/simulation_tests.hpp
|
marekpetrik/CRAAM
|
62cc392e876b5383faa5cb15ab1f6b70b26ff395
|
[
"MIT"
] | 10
|
2016-09-19T18:31:07.000Z
|
2018-07-05T08:59:45.000Z
|
// This file is part of CRAAM, a C++ library for solving plain
// and robust Markov decision processes.
//
// MIT License
//
// 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.
#pragma once
#include "craam/Simulation.hpp"
#include "craam/modeltools.hpp"
#include "craam/RMDP.hpp"
#include "craam/algorithms/values.hpp"
#include "craam/simulators/inventory_simulation.hpp"
#include "craam/simulators/invasive_species_simulation.hpp"
#include <iostream>
#include <sstream>
#include <random>
#include <utility>
#include <functional>
#include <boost/functional/hash.hpp>
using namespace std;
using namespace craam;
using namespace craam::msen;
using namespace craam::algorithms;
using namespace util::lang;
struct TestState{
int index;
TestState(int i) : index(i){
};
};
class TestSim {
public:
typedef TestState State;
typedef int Action;
TestState init_state() const{
return TestState(1);
}
pair<double,TestState> transition(TestState, int) const{
return pair<double,TestState>(1.0,TestState(1));
};
bool end_condition(TestState) const{
return false;
};
long action_count(TestState) const{return 1;}
int action(TestState, long) const{return 1;}
};
int test_policy(TestState){
return 0;
}
BOOST_AUTO_TEST_CASE(basic_simulation) {
TestSim sim;
auto samples = simulate<TestSim>(sim,test_policy,10,5);
BOOST_CHECK_EQUAL(samples.size(), 50);
}
/**
A simple simulator class. The state represents a position in a chain
and actions move it up and down. The reward is equal to the position.
Representation
~~~~~~~~~~~~~~
- State: position (int)
- Action: change (int)
*/
class Counter{
private:
default_random_engine gen;
bernoulli_distribution d;
const vector<int> actions_list;
const int initstate;
public:
using State = int;
using Action = int;
/**
Define the success of each action
\param success The probability that the action is actually applied
*/
Counter(double success, int initstate, random_device::result_type seed = random_device{}())
: gen(seed), d(success), actions_list({1,-1}), initstate(initstate) {};
int init_state() const {
return initstate;
}
pair<double,int> transition(int pos, int action) {
int nextpos = d(gen) ? pos + action : pos;
return make_pair((double) pos, nextpos);
}
bool end_condition(const int){
return false;
}
int action(State , long index) const{
return actions_list[index];
}
virtual vector<int> get_valid_actions(State state) const{
return actions_list;
}
size_t action_count(State) const{return actions_list.size();};
};
/** A counter that terminates at either end as defined by the end state */
class CounterTerminal : public Counter {
public:
int endstate;
CounterTerminal(double success, int initstate, int endstate, random_device::result_type seed = random_device{}())
: Counter(success, initstate, seed), endstate(endstate) {};
bool end_condition(const int state){
return (abs(state) >= endstate);
}
};
/** A counter that has bound states */
class CounterBound : public Counter {
private:
int min_state;
int max_state;
vector<int> min_state_actions;
vector<int> max_state_actions;
public:
CounterBound(double success, int init_state, int min_state, int max_state, random_device::result_type seed = random_device{}())
: Counter(success, init_state, seed), min_state(min_state), max_state(max_state), min_state_actions({1}), max_state_actions({-1}) {};
virtual vector<int> get_valid_actions(State state) const{
if ( state == min_state )
return min_state_actions;
else if ( state == max_state )
return max_state_actions;
else
return Counter::get_valid_actions(state);
}
};
// Hash function for the Counter / CounterTerminal EState above
namespace std{
template<> struct hash<pair<int,int>>{
size_t operator()(pair<int,int> const& s) const{
boost::hash<pair<int,int>> h;
return h(s);
};
};
}
BOOST_AUTO_TEST_CASE(simulation_multiple_counter_si ) {
Counter sim(0.9,0,1);
RandomPolicy<Counter> random_pol(sim,1);
auto samples = simulate(sim,random_pol,20,20);
BOOST_CHECK_CLOSE(samples.mean_return(0.9), -3.51759102217019, 0.0001);
samples = simulate(sim,random_pol,1,20);
BOOST_CHECK_CLOSE(samples.mean_return(0.9), 0, 0.0001);
Counter sim2(0.9,3,1);
samples = simulate(sim2,random_pol,1,20);
BOOST_CHECK_CLOSE(samples.mean_return(0.9), 3, 0.0001);
}
BOOST_AUTO_TEST_CASE(simulation_multiple_counter_si_return ) {
Counter sim(0.9,0,1);
RandomPolicy<Counter> random_pol(sim,1); // sets the random seed
auto samples_returns = simulate_return(sim,0.9,random_pol,20,20);
auto v = samples_returns.second;
auto meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size());
BOOST_CHECK_CLOSE(meanreturn, -3.51759102217019, 0.0001);
samples_returns = simulate_return(sim,0.9,random_pol,1,20);
v = samples_returns.second;
meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size());
BOOST_CHECK_CLOSE(meanreturn, 0, 0.0001);
Counter sim2(0.9,3,1);
samples_returns = simulate_return(sim2,0.9,random_pol,1,20);
v = samples_returns.second;
meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size());
BOOST_CHECK_CLOSE(meanreturn, 3, 0.0001);
// test termination probability equals to discount
samples_returns = simulate_return(sim,1.0,DeterministicPolicy<Counter>(sim,indvec{0,1,1}),1000,100,0.1,1);
v = samples_returns.second;
meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size());
BOOST_CHECK_CLOSE(meanreturn, 4.73684, 10.0);
// test stochastic policies
CounterBound stochastic_sim(0.9,0,0,2,1);
prob_matrix_t prob_matrix;
prob_list_t prob_list1;
prob_list_t prob_list2;
prob_list_t prob_list3;
prob_list1.push_back(1);
prob_list1.push_back(0);
prob_list2.push_back(0.6);
prob_list2.push_back(0.4);
prob_list3.push_back(0);
prob_list3.push_back(1);
prob_matrix.push_back(prob_list1);
prob_matrix.push_back(prob_list2);
prob_matrix.push_back(prob_list3);
samples_returns = simulate_return(stochastic_sim,1.0,StochasticPolicy<Counter>(sim,prob_matrix,1),1000,4,0.1,1);
v = samples_returns.second;
meanreturn = accumulate(v.begin(), v.end(), 0.0) / prec_t(v.size());
BOOST_CHECK_EQUAL(meanreturn, 3);
}
BOOST_AUTO_TEST_CASE(cumulative_rewards){
// check that the reward is constructed correctly from samples
DiscreteSamples samples;
samples.add_sample(0,0,1,1.0,3.0,0,0);
samples.add_sample(0,0,1,2.0,2.0,0,0);
samples.add_sample(0,0,1,3.0,1.0,0,0);
samples.add_sample(0,0,2,7.0,1.0,0,1);
samples.add_sample(0,0,3,2.0,1.0,0,1);
samples.add_sample(0,0,0,0.0,1.0,0,1);
samples.add_sample(DiscreteSample(0,0,1,1,1,0,2));
samples.add_sample(DiscreteSample(0,0,1,11,1,0,2));
BOOST_CHECK_EQUAL(samples.get_cumulative_rewards()[2], 6);
BOOST_CHECK_EQUAL(samples.get_cumulative_rewards()[5], 9);
BOOST_CHECK_EQUAL(samples.get_cumulative_rewards()[7], 12);
}
BOOST_AUTO_TEST_CASE(sampled_mdp_reward){
// check that the reward is constructed correctly from samples
DiscreteSamples samples;
// relevant samples (transition to 1)
samples.add_sample(0,0,1,1.0,3.0,0,0);
samples.add_sample(0,0,1,2.0,2.0,0,0);
samples.add_sample(0,0,1,3.0,1.0,0,0);
// irrelevant samples (do not transition to 1)
samples.add_sample(0,0,2,0.0,1.0,0,0);
samples.add_sample(0,0,3,0.0,1.0,0,0);
samples.add_sample(0,0,0,0.0,1.0,0,0);
SampledMDP smdp;
smdp.add_samples(samples);
auto reward = (*smdp.get_mdp())[0][0][0].get_rewards()[1];
//cout << (*smdp.get_mdp())[0][0][0].get_rewards()[1] << endl;
BOOST_CHECK_CLOSE(reward, 1.666666, 1e-4);
// check that the reward is constructed correctly from samples
DiscreteSamples samples2;
// relevant samples (transition to 1)
samples2.add_sample(0,0,1,2.0,9.0,0,0);
samples2.add_sample(0,0,1,4.0,6.0,0,0);
samples2.add_sample(0,0,1,6.0,3.0,0,0);
// irrelevant samples (do not transition to 1)
samples2.add_sample(0,0,2,0.0,1.0,0,0);
samples2.add_sample(0,0,3,0.0,1.0,0,0);
samples2.add_sample(0,0,0,0.0,1.0,0,0);
smdp.add_samples(samples2);
//cout << (*smdp.get_mdp())[0][0][0].get_rewards()[1] << endl;
reward = (*smdp.get_mdp())[0][0][0].get_rewards()[1];
BOOST_CHECK_CLOSE(reward, 2.916666666666, 1e-4);
}
BOOST_AUTO_TEST_CASE(construct_mdp_from_samples_si_pol){
CounterTerminal sim(0.9,0,10,1);
RandomPolicy<CounterTerminal> random_pol(sim,1);
auto samples = make_samples<CounterTerminal>();
simulate(sim,samples,random_pol,50,50);
simulate(sim,samples,[](int){return 1;},10,20);
simulate(sim,samples,[](int){return -1;},10,20);
SampleDiscretizerSD<typename CounterTerminal::State,
typename CounterTerminal::Action> sd;
sd.add_samples(samples);
BOOST_CHECK_EQUAL(samples.get_initial().size(), sd.get_discrete()->get_initial().size());
BOOST_CHECK_EQUAL(samples.size(), sd.get_discrete()->size());
SampledMDP smdp;
smdp.add_samples(*sd.get_discrete());
shared_ptr<const MDP> mdp = smdp.get_mdp();
// check that the number of actions is correct (2)
for(size_t i = 0; i < mdp->state_count(); i++){
if(mdp->get_state(i).action_count() > 0)
BOOST_CHECK_EQUAL(mdp->get_state(i).action_count(), 2);
}
auto&& sol = mpi_jac(*mdp,0.9);
BOOST_CHECK_CLOSE(sol.total_return(smdp.get_initial()), 51.313973, 1e-3);
}
template<class Model>
Model create_test_mdp_sim(){
Model rmdp(3);
// nonrobust
// action 1 is optimal, with transition matrix [[0,1,0],[0,0,1],[0,0,1]] and rewards [0,0,1.1]
add_transition<Model>(rmdp,0,1,1,1.0,0.0);
add_transition<Model>(rmdp,1,1,2,1.0,0.0);
add_transition<Model>(rmdp,2,1,2,1.0,1.1);
add_transition<Model>(rmdp,0,0,0,1.0,0.0);
add_transition<Model>(rmdp,1,0,0,1.0,1.0);
add_transition<Model>(rmdp,2,0,1,1.0,1.0);
add_transition<Model>(rmdp,1,2,1,0.5,0.5);
return rmdp;
}
BOOST_AUTO_TEST_CASE(simulate_mdp){
shared_ptr<MDP> m = make_shared<MDP>();
*m = create_test_mdp_sim<MDP>();
Transition initial({0},{1.0});
ModelSimulator ms(m, initial,13);
ModelRandomPolicy rp(ms,10);
auto samples = simulate(ms, rp, 1000, 5, -1, 0.0, 10);
BOOST_CHECK_EQUAL(samples.size(), 49);
//cout << "Number of samples " << samples.size() << endl;
SampledMDP smdp;
smdp.add_samples(samples);
auto newmdp = smdp.get_mdp();
auto solution1 = mpi_jac(*m, 0.9);
auto solution2 = mpi_jac(*newmdp, 0.9);
BOOST_CHECK_CLOSE(solution1.total_return(initial),8.90971,1e-3);
//cout << "Return in original MDP " << solution1.total_return(initial) << endl;
BOOST_CHECK_CLOSE(solution2.total_return(initial),8.90971,1e-3);
//cout << "Return in sampled MDP " << solution2.total_return(initial) << endl;
// need to remove the terminal state from the samples
indvec policy = solution2.policy;
policy.pop_back();
//cout << "Computed policy " << policy << endl;
indvec policytarget{1,1,1};
BOOST_CHECK_EQUAL_COLLECTIONS(policy.begin(), policy.end(), policytarget.begin(), policytarget.end());
auto solution3 = mpi_jac(*m, 0.9, numvec(0), PlainBellman(policy));
BOOST_CHECK_CLOSE(solution3.total_return(initial), 8.90916, 1e-2);
//cout << "Return of sampled policy in the original MDP " << solution3.total_return(initial) << endl;
ModelDeterministicPolicy dp(ms, policy);
auto samples_policy = simulate(ms, dp, 1000, 5);
BOOST_CHECK_CLOSE(samples_policy.mean_return(0.9), 8.91, 1e-3);
//cout << "Return of sampled " << samples_policy.mean_return(0.9) << endl;
ModelRandomizedPolicy rizedp(ms, {{0.5,0.5},{0.5,0.4,0.1},{0.5,0.5}},0);
auto randomized_samples = simulate(ms, rizedp, 1000, 5, -1, 0.0, 10);
BOOST_CHECK_CLOSE(randomized_samples.mean_return(0.9), 4.01147, 1e-3);
//cout << "Return of randomized samples " << randomized_samples.mean_return(0.9) << endl;
}
BOOST_AUTO_TEST_CASE(inventory_simulator){
long horizon = 10;
long num_runs = 5;
long initial=0, max_inventory=15;
int rand_seed=7;
double purchase_cost=2, sale_price=3;
double prior_mean = 4, prior_std=1, demand_std=1.3;
InventorySimulator simulator(initial, prior_mean, prior_std, demand_std, purchase_cost, sale_price,
max_inventory, rand_seed);
ModelInventoryPolicy rp(simulator, max_inventory, rand_seed);
auto samples = simulate(simulator, rp, horizon, num_runs, -1, 0.0, rand_seed);
BOOST_CHECK_EQUAL(samples.size(), 50); //horizon*num_runs
SampledMDP smdp;
smdp.add_samples(samples);
auto newmdp = smdp.get_mdp();
auto solution = mpi_jac(*newmdp, 0.9);
Transition init({initial},{1.0});
//The actual return for the mdp is not calculated to be 49.52, it's just picked to pass the test.
//Need to know what the exact return should be to make the below test meaningful.
BOOST_CHECK_CLOSE(solution.total_return(init),29.5768,1e-2);
}
BOOST_AUTO_TEST_CASE(invasive_species_simulator){
long horizon = 10;
long num_runs = 5;
long initial_population=30, carrying_capacity=1000;
int rand_seed=7;
long n_hat = 300, threshold_control = 0;
prec_t mean_lambda=1.02, sigma2_lambda=0.02, sigma2_y=20, beta_1=0.001, beta_2=-0.0000021, prob_control = 0.5;
InvasiveSpeciesSimulator simulator(initial_population, carrying_capacity, mean_lambda, sigma2_lambda, sigma2_y,
beta_1, beta_2, n_hat, rand_seed);
ModelInvasiveSpeciesPolicy rp(simulator, threshold_control, prob_control, rand_seed);
auto samples = simulate(simulator, rp, horizon, num_runs, -1, 0.0, rand_seed);
BOOST_CHECK_EQUAL(samples.size(), 50); //horizon*num_runs
SampledMDP smdp;
smdp.add_samples(samples);
auto newmdp = smdp.get_mdp();
auto solution = mpi_jac(*newmdp, 0.9);
Transition init({initial_population},{1.0});
//The actual return for the mdp is not calculated to be 49.52, it's just picked to pass the test.
//Need to know what the exact return should be to make the below test meaningful.
//BOOST_CHECK_CLOSE(solution.total_return(init),-0.4245,1e-2);
}
| 32.686848
| 141
| 0.685444
|
marekpetrik
|
006f6420103afc3273e353bb3a3cb285d6dd4a18
| 4,673
|
cpp
|
C++
|
Tga3D/Source/tga2dcore/tga2d/windows/WindowsWindow.cpp
|
sarisman84/C-CommonUtilities
|
a3649c32232ec342c25b804001c16c295885ce0c
|
[
"MIT"
] | 1
|
2022-03-10T11:43:24.000Z
|
2022-03-10T11:43:24.000Z
|
Tga3D/Source/tga2dcore/tga2d/windows/WindowsWindow.cpp
|
sarisman84/C-CommonUtilities
|
a3649c32232ec342c25b804001c16c295885ce0c
|
[
"MIT"
] | null | null | null |
Tga3D/Source/tga2dcore/tga2d/windows/WindowsWindow.cpp
|
sarisman84/C-CommonUtilities
|
a3649c32232ec342c25b804001c16c295885ce0c
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include <tga2d/windows/WindowsWindow.h>
#include "resource.h"
#include <WinUser.h>
#include <tga2d/imguiinterface/ImGuiInterface.h>
using namespace Tga2D;
WindowsWindow::WindowsWindow(void)
:myWndProcCallback(nullptr)
{
}
WindowsWindow::~WindowsWindow(void)
{
}
bool WindowsWindow::Init(Vector2ui aWindowSize, HWND*& aHwnd, EngineCreateParameters* aSetting, HINSTANCE& aHInstanceToFill, callback_function_wndProc aWndPrcCallback)
{
if (!aSetting)
{
return false;
}
myWndProcCallback = aWndPrcCallback;
HINSTANCE instance = GetModuleHandle(NULL);
aHInstanceToFill = instance;
ZeroMemory(&myWindowClass, sizeof(WNDCLASSEX));
myWindowClass.cbSize = sizeof(WNDCLASSEX);
myWindowClass.style = CS_HREDRAW | CS_VREDRAW;
myWindowClass.lpfnWndProc = WindowProc;
myWindowClass.hInstance = instance;
myWindowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
myWindowClass.hbrBackground = (HBRUSH)COLOR_WINDOW;
myWindowClass.lpszClassName = L"WindowClass1";
myWindowClass.hIcon = ::LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1));
myWindowClass.hIconSm = LoadIcon(instance, MAKEINTRESOURCE(IDI_ICON1));
RegisterClassEx(&myWindowClass);
RECT wr = {0, 0, static_cast<long>(aWindowSize.x), static_cast<long>(aWindowSize.y)}; // set the size, but not the position
//AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); // adjust the size
DWORD windowStyle = 0;
switch (aSetting->myWindowSetting)
{
case WindowSetting::Overlapped:
windowStyle = WS_OVERLAPPEDWINDOW;
break;
case WindowSetting::Borderless:
windowStyle = WS_VISIBLE | WS_POPUP | WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
break;
default:
break;
}
if (!aHwnd)
{
myWindowHandle = CreateWindowEx(WS_EX_APPWINDOW,
L"WindowClass1", // name of the window class
aSetting->myApplicationName.c_str(), // title of the window
windowStyle, // window style
CW_USEDEFAULT, // x-position of the window
CW_USEDEFAULT, // y-position of the window
wr.right - wr.left, // width of the window
wr.bottom - wr.top, // height of the window
NULL, // we have no parent window, NULL
NULL, // we aren't using menus, NULL
instance, // application handle
NULL); // used with multiple windows, NULL
ShowWindow(myWindowHandle, true);
aHwnd = &myWindowHandle;
}
else
{
myWindowHandle = *aHwnd;
}
SetWindowLongPtr(myWindowHandle, GWLP_USERDATA, (LONG_PTR)this);
// Fix to set the window to the actual resolution as the borders will mess with the resolution wanted
myResolution = aWindowSize;
myResolutionWithBorderDifference = myResolution;
if (aSetting->myWindowSetting == WindowSetting::Overlapped)
{
RECT r;
GetClientRect(myWindowHandle, &r); //get window rect of control relative to screen
int horizontal = r.right - r.left;
int vertical = r.bottom - r.top;
int diffX = aWindowSize.x - horizontal;
int diffY = aWindowSize.y - vertical;
SetResolution(aWindowSize + Vector2ui(diffX, diffY));
myResolutionWithBorderDifference = aWindowSize + Vector2ui(diffX, diffY);
}
INFO_PRINT("%s %i %i", "Windows created with size ", aWindowSize.x, aWindowSize.y);
return true;
}
#ifndef _RETAIL
IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
#endif
LRESULT WindowsWindow::LocWindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
#ifndef _RETAIL
if (ImGui_ImplWin32_WndProcHandler(hWnd, message, wParam, lParam))
{
return S_OK;
}
#endif
if (myWndProcCallback)
{
return myWndProcCallback(hWnd, message, wParam, lParam);
}
return S_OK;
}
LRESULT CALLBACK WindowsWindow::WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
WindowsWindow* windowsClass = (WindowsWindow*)GetWindowLongPtr(hWnd, GWLP_USERDATA);
if (windowsClass)
{
LRESULT result = windowsClass->LocWindowProc(hWnd, message, wParam, lParam);
if (result)
{
return DefWindowProc(hWnd, message, wParam, lParam);
}
}
switch(message)
{
case WM_DESTROY:
{
PostQuitMessage(0);
return 0;
} break;
case WM_SIZE:
{
if (Engine::GetInstance())
Engine::GetInstance()->SetWantToUpdateSize();
break;
}
}
return DefWindowProc (hWnd, message, wParam, lParam);
}
void Tga2D::WindowsWindow::SetResolution(Vector2ui aResolution)
{
::SetWindowPos(myWindowHandle, 0, 0, 0, aResolution.x, aResolution.y, SWP_NOMOVE | SWP_NOOWNERZORDER | SWP_NOZORDER);
}
void Tga2D::WindowsWindow::Close()
{
DestroyWindow(myWindowHandle);
}
| 27.815476
| 168
| 0.711748
|
sarisman84
|
006fc1f49ec8f6c0970729038579eb100d4bf8d5
| 254
|
cpp
|
C++
|
sdk/src/layers/ItemAton.cpp
|
Fpepe943/fairwindplusplus
|
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
|
[
"Apache-2.0"
] | 4
|
2021-07-07T10:42:53.000Z
|
2022-01-11T12:53:25.000Z
|
sdk/src/layers/ItemAton.cpp
|
Fpepe943/fairwindplusplus
|
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
|
[
"Apache-2.0"
] | 2
|
2022-02-13T19:59:25.000Z
|
2022-03-25T01:02:17.000Z
|
sdk/src/layers/ItemAton.cpp
|
Fpepe943/fairwindplusplus
|
8b9f5e13c751bb331f9f1b9979bf3049cc3a94d5
|
[
"Apache-2.0"
] | 7
|
2021-06-07T07:12:55.000Z
|
2022-01-12T16:09:55.000Z
|
//
// Created by Raffaele Montella on 03/05/21.
//
#include "FairWindSdk/layers/ItemAton.hpp"
ItemAton::ItemAton(QString &typeUuid): ItemSignalK(typeUuid) {
}
QImage ItemAton::getImage() const {
return QImage(":/resources/images/ais_aton.png");
}
| 19.538462
| 62
| 0.720472
|
Fpepe943
|
00786a1ab462b9cae550f5dfbb92685202f08563
| 1,603
|
hpp
|
C++
|
libs/gui/include/sge/gui/widget/bar.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/gui/include/sge/gui/widget/bar.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/gui/include/sge/gui/widget/bar.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_GUI_WIDGET_BAR_HPP_INCLUDED
#define SGE_GUI_WIDGET_BAR_HPP_INCLUDED
#include <sge/gui/fill_color.hpp>
#include <sge/gui/fill_level.hpp>
#include <sge/gui/detail/symbol.hpp>
#include <sge/gui/renderer/base_fwd.hpp>
#include <sge/gui/style/const_reference.hpp>
#include <sge/gui/widget/bar_fwd.hpp>
#include <sge/gui/widget/base.hpp>
#include <sge/renderer/context/ffp_fwd.hpp>
#include <sge/rucksack/axis.hpp>
#include <sge/rucksack/dim_fwd.hpp>
#include <sge/rucksack/widget/base_fwd.hpp>
#include <sge/rucksack/widget/dummy.hpp>
#include <fcppt/nonmovable.hpp>
#include <fcppt/strong_typedef.hpp>
namespace sge::gui::widget
{
class bar : public sge::gui::widget::base
{
FCPPT_NONMOVABLE(bar);
public:
SGE_GUI_DETAIL_SYMBOL
bar(sge::gui::style::const_reference,
sge::rucksack::dim const &,
sge::rucksack::axis,
sge::gui::fill_color,
sge::gui::fill_level);
SGE_GUI_DETAIL_SYMBOL
~bar() override;
SGE_GUI_DETAIL_SYMBOL
void value(sge::gui::fill_level);
private:
void on_draw(sge::gui::renderer::base &, sge::renderer::context::ffp &) override;
[[nodiscard]] sge::rucksack::widget::base &layout() override;
sge::gui::style::const_reference const style_;
sge::rucksack::axis const axis_;
sge::gui::fill_color const foreground_;
sge::gui::fill_level value_;
sge::rucksack::widget::dummy layout_;
};
}
#endif
| 25.046875
| 83
| 0.726138
|
cpreh
|
0078fea0aae13cf93b439c1dca7535689c1ed16e
| 622
|
cpp
|
C++
|
Online-Judge-Solution/URI Solutions/1099(Sum of Consecutive Odd Numbers II).cpp
|
arifparvez14/Basic-and-competetive-programming
|
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
|
[
"MIT"
] | null | null | null |
Online-Judge-Solution/URI Solutions/1099(Sum of Consecutive Odd Numbers II).cpp
|
arifparvez14/Basic-and-competetive-programming
|
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
|
[
"MIT"
] | null | null | null |
Online-Judge-Solution/URI Solutions/1099(Sum of Consecutive Odd Numbers II).cpp
|
arifparvez14/Basic-and-competetive-programming
|
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main()
{
int x,y,i,sum,t,k;
while(cin>>t)
{
for(k=1; k<=t; k++)
{
cin>>x>>y;
sum=0;
if(x<=y)
{
for(i=x+1; i<y; i++)
{
if(i%2!=0)
sum=sum+i;
}
}
else
{
for(i=y+1; i<x; i++)
{
if(i%2!=0)
sum=sum+i;
}
}
printf("%d\n",sum);
}
}
return 0;
}
| 18.294118
| 36
| 0.233119
|
arifparvez14
|
007c70b8547794cca85d109520cab277ee4f94b7
| 3,579
|
cxx
|
C++
|
Filters/Parallel/vtkPPartitionedDataSetCollectionToMultiBlockDataSet.cxx
|
akenmorris/VTK
|
cf80447580ff48cbdb4a588aaafe1d3397af3791
|
[
"BSD-3-Clause"
] | null | null | null |
Filters/Parallel/vtkPPartitionedDataSetCollectionToMultiBlockDataSet.cxx
|
akenmorris/VTK
|
cf80447580ff48cbdb4a588aaafe1d3397af3791
|
[
"BSD-3-Clause"
] | 2
|
2018-05-04T02:00:02.000Z
|
2018-05-04T02:15:19.000Z
|
Filters/Parallel/vtkPPartitionedDataSetCollectionToMultiBlockDataSet.cxx
|
akenmorris/VTK
|
cf80447580ff48cbdb4a588aaafe1d3397af3791
|
[
"BSD-3-Clause"
] | 1
|
2020-08-18T11:44:39.000Z
|
2020-08-18T11:44:39.000Z
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkPPartitionedDataSetCollectionToMultiBlockDataSet.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkPPartitionedDataSetCollectionToMultiBlockDataSet.h"
#include "vtkCommunicator.h"
#include "vtkMultiBlockDataSet.h"
#include "vtkMultiProcessController.h"
#include "vtkObjectFactory.h"
#include "vtkPartitionedDataSet.h"
#include "vtkPartitionedDataSetCollection.h"
#include "vtkSmartPointer.h"
#include <vector>
vtkObjectFactoryNewMacro(vtkPPartitionedDataSetCollectionToMultiBlockDataSet);
vtkCxxSetObjectMacro(
vtkPPartitionedDataSetCollectionToMultiBlockDataSet, Controller, vtkMultiProcessController);
//----------------------------------------------------------------------------
vtkPPartitionedDataSetCollectionToMultiBlockDataSet::
vtkPPartitionedDataSetCollectionToMultiBlockDataSet()
: Controller(nullptr)
{
this->SetController(vtkMultiProcessController::GetGlobalController());
}
//----------------------------------------------------------------------------
vtkPPartitionedDataSetCollectionToMultiBlockDataSet::
~vtkPPartitionedDataSetCollectionToMultiBlockDataSet()
{
this->SetController(nullptr);
}
//----------------------------------------------------------------------------
int vtkPPartitionedDataSetCollectionToMultiBlockDataSet::RequestData(
vtkInformation*, vtkInformationVector** inputVector, vtkInformationVector* outputVector)
{
vtkSmartPointer<vtkPartitionedDataSetCollection> input =
vtkPartitionedDataSetCollection::GetData(inputVector[0], 0);
auto output = vtkMultiBlockDataSet::GetData(outputVector, 0);
if (this->Controller && this->Controller->GetNumberOfProcesses() > 1 &&
input->GetNumberOfPartitionedDataSets() > 0)
{
// ensure that we have exactly the same number of partitions on all ranks.
vtkNew<vtkPartitionedDataSetCollection> clone;
clone->ShallowCopy(input);
const auto count = input->GetNumberOfPartitionedDataSets();
std::vector<unsigned int> piece_counts(count);
for (unsigned int cc = 0; cc < count; ++cc)
{
piece_counts[cc] = clone->GetPartitionedDataSet(cc)
? clone->GetPartitionedDataSet(cc)->GetNumberOfPartitions()
: 0;
}
std::vector<unsigned int> result(piece_counts.size());
this->Controller->AllReduce(
&piece_counts[0], &result[0], static_cast<vtkIdType>(count), vtkCommunicator::MAX_OP);
for (unsigned int cc = 0; cc < count; ++cc)
{
if (result[cc] > 0)
{
if (clone->GetPartitionedDataSet(cc) == nullptr)
{
clone->SetPartitionedDataSet(cc, vtkNew<vtkPartitionedDataSet>{});
}
clone->GetPartitionedDataSet(cc)->SetNumberOfPartitions(result[cc]);
}
}
input = clone;
}
return this->Execute(input, output) ? 1 : 0;
}
//----------------------------------------------------------------------------
void vtkPPartitionedDataSetCollectionToMultiBlockDataSet::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os, indent);
os << indent << "Controller: " << this->Controller << endl;
}
| 37.673684
| 98
| 0.654652
|
akenmorris
|
007fc689f124f891c8ab4743497c17a90a6fe25d
| 148
|
cpp
|
C++
|
Ch01/Ex1_20.cpp
|
boscotsang/CppPrimerCode
|
65eed86652f5ec475dec593bd731b7752cb46c51
|
[
"MIT"
] | 4
|
2015-04-20T10:04:49.000Z
|
2018-04-19T12:46:01.000Z
|
Ch01/Ex1_20.cpp
|
boscotsang/CppPrimerCode
|
65eed86652f5ec475dec593bd731b7752cb46c51
|
[
"MIT"
] | null | null | null |
Ch01/Ex1_20.cpp
|
boscotsang/CppPrimerCode
|
65eed86652f5ec475dec593bd731b7752cb46c51
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include "Sales_item.h"
int main(){
Sales_item s1;
while(std::cin >> s1) std::cout << s1 << std::endl;
return 0;
}
| 16.444444
| 55
| 0.594595
|
boscotsang
|
0083d8116dbf8c73d9daf185fe21ad206df3a45f
| 9,227
|
cpp
|
C++
|
src/main.cpp
|
lscandolo/Compressed-shadow-maps
|
3cb6c11cfb3c3cbdbfc48a6cc33d54758b7d19cf
|
[
"MIT"
] | 7
|
2020-04-07T18:53:12.000Z
|
2022-01-25T15:06:30.000Z
|
src/main.cpp
|
lscandolo/Compressed-shadow-maps
|
3cb6c11cfb3c3cbdbfc48a6cc33d54758b7d19cf
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
lscandolo/Compressed-shadow-maps
|
3cb6c11cfb3c3cbdbfc48a6cc33d54758b7d19cf
|
[
"MIT"
] | 1
|
2021-07-14T02:14:45.000Z
|
2021-07-14T02:14:45.000Z
|
#include "common.h"
#include "helpers/OpenGLHelpers.h"
#include "helpers/FPCamera.h"
#include "helpers/CameraRecord.h"
#include "helpers/MeshData.h"
#include "helpers/LightData.h"
#include "helpers/ScopeTimer.h"
#include "helpers/Ini.h"
#include "gui/MeshGUI.h"
#include "gui/LightGUI.h"
#include "gui/FPCameraGUI.h"
#include "gui/RenderGUI.h"
#include "csm/CSMTechnique.h"
#include "managers/GLStateManager.h"
#include "managers/TextureManager.h"
#include "managers/GUIManager.h"
#include "managers/GLShapeManager.h"
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <GLFW/glfw3.h>
#include <freeimage.h>
#include <tiny_obj_loader.h>
#include <iostream>
#include <random>
using namespace glm;
std::vector<Technique*> techniques = { new CSMTechnique };
bool display_gui = true;
bool full_screen = false;
RenderStats renderstats;
#define INIT_WIN_WIDTH 1280
#define INIT_WIN_HEIGHT 720
FPCamera fpcamera;
glm::vec3 fpcamera_speed(0.f, 0.f, 0.f);
glm::vec2 fpcamera_rotational_speed(0.f, 0.f);
bool cursor_lock = false;
using namespace GLHelpers;
static void resize_callback(GLFWwindow* window, int width, int height)
{
DefaultRenderOptions().window_size = size2D(width, height);
DefaultRenderOptions().output_size = size2D(width, height);
DefaultRenderOptions().current_technique()->output_resize_callback(size2D(width, height));
fpcamera.aspect = DefaultRenderOptions().output_size.width / float(DefaultRenderOptions().output_size.height);
fpcamera.jitter_plane = glm::ivec2(DefaultRenderOptions().output_size.width, DefaultRenderOptions().output_size.height);
}
static void camera_key_callback(int key, int scancode, int action, int mods)
{
if (action != GLFW_PRESS && action != GLFW_RELEASE) return;
if (key == GLFW_KEY_W) fpcamera_speed.z = action == GLFW_PRESS ? 1.0f : 0.0f;
if (key == GLFW_KEY_S) fpcamera_speed.z = action == GLFW_PRESS ? -1.0f : 0.0f;
if (key == GLFW_KEY_D) fpcamera_speed.x = action == GLFW_PRESS ? 1.0f : 0.0f;
if (key == GLFW_KEY_A) fpcamera_speed.x = action == GLFW_PRESS ? -1.0f : 0.0f;
if (key == GLFW_KEY_E) fpcamera_speed.y = action == GLFW_PRESS ? 1.0f : 0.0f;
if (key == GLFW_KEY_Q) fpcamera_speed.y = action == GLFW_PRESS ? -1.0f : 0.0f;
}
static void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
size2D& window_size = DefaultRenderOptions().window_size;
if (GUIManager::instance().key_callback(key, scancode, action, mods)) return; // If GUIManager uses the input then skip passing it to the rest of the systems
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GLFW_TRUE);
if (key == GLFW_KEY_F) {
if (action == GLFW_PRESS) cursor_lock = !cursor_lock;
if (cursor_lock) {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN | GLFW_CURSOR_DISABLED);
glfwSetCursorPos(window, window_size.width/2.0, window_size.height/2.0);
} else {
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
if (key == GLFW_KEY_M && action == GLFW_PRESS) {
display_gui = !display_gui;
}
camera_key_callback(key, scancode, action, mods);
}
static void char_callback(GLFWwindow* window, unsigned int c)
{
if (GUIManager::instance().char_callback(c)) return;
}
static void cursor_callback(GLFWwindow* window, double xpos, double ypos)
{
size2D& window_size = DefaultRenderOptions().window_size;
double half_width = window_size.width / 2.0;
double half_height = window_size.height / 2.0;
if (!cursor_lock) return;
if (xpos == half_width && ypos == half_height) return;
fpcamera_rotational_speed = glm::vec2(float(xpos - half_width), float(ypos - half_height));
glfwSetCursorPos(window, half_width, half_height);
return;
}
int main()
{
//dl_main();
//return 0;
////////////////
FreeImage_Initialise();
////////////////
if (!glfwInit())
{
std::cerr << "Error initializing GLFW." << std::endl;
return -1;
}
std::cout << "Initialized glfw." << std::endl;
glfwSetErrorCallback(errorCallbackGLFW);
////////////////
////////////////
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);
glfwWindowHint(GLFW_DOUBLEBUFFER, true);
glfwWindowHint(GLFW_DEPTH_BITS, 0);
GLFWwindow* window = glfwCreateWindow(INIT_WIN_WIDTH, INIT_WIN_HEIGHT, "Compressed shadow maps demo", NULL, NULL);
if (!window)
{
std::cerr << "Error creating window." << std::endl;
glfwTerminate();
return -1;
}
std::cout << "Created window." << std::endl;
size2D& output_size = DefaultRenderOptions().output_size;
size2D& window_size = DefaultRenderOptions().window_size;
output_size = size2D(INIT_WIN_WIDTH, INIT_WIN_HEIGHT);
window_size = size2D(INIT_WIN_WIDTH, INIT_WIN_HEIGHT);
////////////////
glfwSetWindowSizeCallback(window, resize_callback);
glfwSetKeyCallback(window, key_callback);
glfwSetCharCallback(window, char_callback);
glfwSetCursorPosCallback(window, cursor_callback);
glfwMakeContextCurrent(window);
glfwSwapInterval(0);
////////////////
GLenum glewInitResult = glewInit();
if (glewInitResult != GL_NO_ERROR) {
std::cerr << "Error creating window." << std::endl;
glfwTerminate();
return -1;
}
std::cout << "Initialized glew." << std::endl;
//////////////// Default render options
for (auto& o : DefaultRenderOptions().debug_var) o = 0.5f;
////////////////
// During init, enable debug output
#ifdef _DEBUG
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback(DebugCallbackGL, 0);
#endif
////////////////
MeshData mesh;
LightData lights;
fpcamera.aspect = output_size.width / float(output_size.height);
fpcamera.jitter_plane = ivec2(output_size.width, output_size.height);
fpcamera.mov_speed = 0.25f;
fpcamera.rot_speed = 0.001f;
Ini ini;
std::string tecname;
ini.load("data/inis/default.ini", IniInfo(&mesh, &fpcamera, &lights, &tecname));
////////////////
GLStateManager::instance().resetState(true);
for (int i = 0; i < techniques.size(); ++i)
{
DefaultRenderOptions().add_technique(techniques[i]);
}
////////////////
GUIManager::instance().initialize(window);
GUIManager::instance().addGUI("1_rendergui", std::shared_ptr<BaseGUI>(new RenderGUI(&DefaultRenderOptions(), &renderstats)));
GUIManager::instance().addGUI("2_camfpgui", std::shared_ptr<BaseGUI>(new FPCameraGUI(&fpcamera)));
GUIManager::instance().addGUI("3_meshgui", std::shared_ptr<BaseGUI>(new MeshGUI(&mesh)));
////////////////
GLShapeManager::instance().initialize();
bool first_frame = true;
Camera* camera = &fpcamera;
////////////////
std::cout << "Starting main loop." << std::endl;
check_opengl();
while (!glfwWindowShouldClose(window))
{
PROFILE_SCOPE("Main loop")
glfwMakeContextCurrent(window);
lights.updateGLResources();
mesh.materialdata.updateGLResources();
DefaultRenderOptions().new_frame();
if (first_frame)
{
DefaultRenderOptions().request_technique(techniques[0]->name());
first_frame = false;
}
if (DefaultRenderOptions().get_flag(RenderOptions::FLAG_DIRTY_TECHNIQUE))
{
Technique::SetupData ts;
ts.output_size = DefaultRenderOptions().output_size;
ts.mesh = &mesh;
ts.lightdata = &lights;
ts.camera = camera;
DefaultRenderOptions().switch_to_requested_technique();
DefaultRenderOptions().initialize_technique(ts);
GUIManager::instance().setTechnique(DefaultRenderOptions().current_technique());
DefaultRenderOptions().reset_flag(RenderOptions::FLAG_DIRTY_TECHNIQUE);
}
//// Update vsync options
glfwSwapInterval(DefaultRenderOptions().vsync ? 1 : 0);
//// Swap current and previous depth tex
//std::swap(depthtex, prev_depthtex);
//fbo.AttachDepthTexture(depthtex);
{ PROFILE_SCOPE("Render")
DefaultRenderOptions().current_technique()->output_resize_callback(output_size);
DefaultRenderOptions().current_technique()->frame_prologue();
DefaultRenderOptions().current_technique()->frame_render();
DefaultRenderOptions().current_technique()->frame_epilogue();
}
//// Draw GUI
fpcamera.copied = false;
if (display_gui) GUIManager::instance().draw();
//// Swap buffers
glfwSwapBuffers(window);
//// Update timings
TimingManager::instance().endFrame();
TimingStats s = TimingManager::instance().getTimingStats("Render");
renderstats.time_cpu_ms = s.cpu_time;
renderstats.time_gl_ms = s.gl_time;
renderstats.time_cuda_ms = s.cuda_time;
//// Get input
glfwPollEvents();
//// Update camera
s = TimingManager::instance().getTimingStats("Main loop");
float time = std::max(s.gl_time, std::max(s.cpu_time, s.cuda_time));
if (fpcamera_rotational_speed != vec2(0.f, 0.f) || fpcamera_speed != vec3(0.f, 0.f, 0.f)) {
fpcamera.update(fpcamera_rotational_speed, fpcamera_speed * time * 0.001f);
fpcamera_rotational_speed = vec2(0.f, 0.f);
fpcamera.moved = true;
} else {
fpcamera.update(fpcamera_rotational_speed, fpcamera_speed);
fpcamera.moved = false;
}
}
for (auto t : techniques) t->destroy();
// Clear textures before leaving context
TextureManager::instance().clear();
GUIManager::instance().finalize(window);
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
| 28.744548
| 158
| 0.715834
|
lscandolo
|
0084908178ca0bc782ff19fd8e2cb48f57b035e7
| 12,523
|
cpp
|
C++
|
script/src/llasm_var.cpp
|
tweber-ill/ill_mirror-takin2-tlibs2
|
669fd34c306625fd306da278a5b29fb6aae16a87
|
[
"BSD-3-Clause-Open-MPI"
] | null | null | null |
script/src/llasm_var.cpp
|
tweber-ill/ill_mirror-takin2-tlibs2
|
669fd34c306625fd306da278a5b29fb6aae16a87
|
[
"BSD-3-Clause-Open-MPI"
] | null | null | null |
script/src/llasm_var.cpp
|
tweber-ill/ill_mirror-takin2-tlibs2
|
669fd34c306625fd306da278a5b29fb6aae16a87
|
[
"BSD-3-Clause-Open-MPI"
] | 1
|
2021-09-20T19:30:13.000Z
|
2021-09-20T19:30:13.000Z
|
/**
* llvm three-address code generator -- variables
* @author Tobias Weber <tweber@ill.fr>
* @date apr/may-2020
* @license GPLv3, see 'LICENSE' file
* @desc Forked on 18/July/2020 from my privately developed "matrix_calc" project (https://github.com/t-weber/matrix_calc).
*
* References:
* - https://llvm.org/docs/LangRef.html
* - https://llvm.org/docs/tutorial/MyFirstLanguageFrontend/LangImpl03.html
* - https://llvm.org/docs/GettingStarted.html
*
* ----------------------------------------------------------------------------
* tlibs
* Copyright (C) 2017-2021 Tobias WEBER (Institut Laue-Langevin (ILL),
* Grenoble, France).
* Copyright (C) 2015-2017 Tobias WEBER (Technische Universitaet Muenchen
* (TUM), Garching, Germany).
* matrix_calc
* Copyright (C) 2020 Tobias WEBER (privately developed).
*
* 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, version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* ----------------------------------------------------------------------------
*/
#include "llasm.h"
#include <sstream>
t_astret LLAsm::visit(const ASTVar* ast)
{
t_astret sym = get_sym(ast->GetIdent());
if(sym == nullptr)
throw std::runtime_error("ASTVar: Symbol \"" + ast->GetIdent() + "\" not in symbol table.");
std::string var = std::string{"%"} + sym->name;
if(sym->ty == SymbolType::SCALAR || sym->ty == SymbolType::INT)
{
t_astret retvar = get_tmp_var(sym->ty, &sym->dims);
std::string ty = LLAsm::get_type_name(sym->ty);
(*m_ostr) << "%" << retvar->name << " = load "
<< ty << ", " << ty << "* " << var << "\n";
return retvar;
}
else if(sym->ty == SymbolType::VECTOR || sym->ty == SymbolType::MATRIX)
{
return sym;
}
else if(sym->ty == SymbolType::STRING)
{
return sym;
}
else
{
throw std::runtime_error("ASTVar: Invalid type for visited variable: \"" + sym->name + "\".");
}
return nullptr;
}
t_astret LLAsm::visit(const ASTVarDecl* ast)
{
for(const auto& _var : ast->GetVariables())
{
t_astret sym = get_sym(_var);
std::string ty = LLAsm::get_type_name(sym->ty);
if(sym->ty == SymbolType::SCALAR || sym->ty == SymbolType::INT)
{
(*m_ostr) << "%" << sym->name << " = alloca " << ty << "\n";
}
else if(sym->ty == SymbolType::VECTOR || sym->ty == SymbolType::MATRIX)
{
std::size_t dim = get_arraydim(sym);
// allocate the array's memory
(*m_ostr) << "%" << sym->name << " = alloca [" << dim << " x double]\n";
}
else if(sym->ty == SymbolType::STRING)
{
std::size_t dim = std::get<0>(sym->dims);
// allocate the string's memory
(*m_ostr) << "%" << sym->name << " = alloca [" << dim << " x i8]\n";
// get a pointer to the string
t_astret strptr = get_tmp_var(sym->ty);
(*m_ostr) << "%" << strptr->name << " = getelementptr [" << dim << " x i8], ["
<< dim << " x i8]* %" << sym->name << ", i64 0, i64 0\n";
// set first element to zero
(*m_ostr) << "store i8 0, i8* %" << strptr->name << "\n";
}
else
{
throw std::runtime_error("ASTVarDecl: Invalid type in declaration: \"" + sym->name + "\".");
}
// optional assignment
if(ast->GetAssignment())
ast->GetAssignment()->accept(this);
}
return nullptr;
}
t_astret LLAsm::visit(const ASTAssign* ast)
{
t_astret expr = ast->GetExpr()->accept(this);
// multiple assignments
if(ast->IsMultiAssign())
{
if(expr->ty != SymbolType::COMP)
{
throw std::runtime_error("ASTAssign: Need a compound symbol for multi-assignment.");
}
const auto& vars = ast->GetIdents();
if(expr->elems.size() != vars.size())
{
std::ostringstream ostrerr;
ostrerr << "ASTAssign: Mismatch in multi-assign size, "
<< "expected " << vars.size() << " symbols, received "
<< expr->elems.size() << " symbols.";
throw std::runtime_error(ostrerr.str());
}
std::size_t elemidx = 0;
for(std::size_t idx=0; idx<vars.size(); ++idx)
{
const SymbolPtr retsym = expr->elems[idx];
const std::string& var = vars[idx];
t_astret sym = get_sym(var);
// get current memory block pointer
t_astret varmemptr = get_tmp_var(SymbolType::STRING);
(*m_ostr) << "%" << varmemptr->name << " = getelementptr i8, i8* %"
<< expr->name << ", i64 " << elemidx << "\n";
// directly read scalar value from memory block
if(sym->ty == SymbolType::SCALAR || sym->ty == SymbolType::INT)
{
std::string symty = LLAsm::get_type_name(sym->ty);
std::string retty = LLAsm::get_type_name(retsym->ty);
t_astret varptr = get_tmp_var(sym->ty);
(*m_ostr) << "%" << varptr->name << " = bitcast i8* %" << varmemptr->name
<< " to " << retty << "*\n";
t_astret _varval = get_tmp_var(sym->ty);
(*m_ostr) << "%" << _varval->name << " = load " <<
retty << ", " << retty << "* %" << varptr->name << "\n";
if(!check_sym_compat(
sym->ty, std::get<0>(sym->dims), std::get<1>(sym->dims),
retsym->ty, std::get<0>(retsym->dims), std::get<1>(retsym->dims)))
{
std::ostringstream ostrErr;
ostrErr << "ASTAssign: Multi-assignment type or dimension mismatch: ";
ostrErr << Symbol::get_type_name(sym->ty) << "["
<< std::get<0>(sym->dims) << ", " << std::get<1>(sym->dims)
<< "] != " << Symbol::get_type_name(retsym->ty) << "["
<< std::get<0>(retsym->dims) << ", " << std::get<1>(retsym->dims)
<< "].";
throw std::runtime_error(ostrErr.str());
}
// cast if needed
_varval = convert_sym(_varval, sym->ty);
(*m_ostr) << "store " << symty << " %" << _varval->name << ", "<< symty << "* %" << var << "\n";
}
// read double array from memory block
else if(sym->ty == SymbolType::VECTOR || sym->ty == SymbolType::MATRIX)
{
cp_mem_vec(varmemptr, sym, false);
}
// read char array from memory block
else if(sym->ty == SymbolType::STRING)
{
cp_mem_str(varmemptr, sym, false);
}
// nested compound symbols
else if(sym->ty == SymbolType::COMP)
{
cp_mem_comp(varmemptr, sym);
}
elemidx += get_bytesize(sym);
}
// free heap return value (TODO: check if it really is on the heap)
(*m_ostr) << "call void @ext_heap_free(i8* %" << expr->name << ")\n";
}
// single assignment
else
{
std::string var = ast->GetIdent();
t_astret sym = get_sym(var);
if(!check_sym_compat(
sym->ty, std::get<0>(sym->dims), std::get<1>(sym->dims),
expr->ty, std::get<0>(expr->dims), std::get<1>(expr->dims)))
{
std::ostringstream ostrErr;
ostrErr << "ASTAssign: Assignment type or dimension mismatch: ";
ostrErr << Symbol::get_type_name(sym->ty) << "["
<< std::get<0>(sym->dims) << ", " << std::get<1>(sym->dims)
<< "] != " << Symbol::get_type_name(expr->ty) << "["
<< std::get<0>(expr->dims) << ", " << std::get<1>(expr->dims)
<< "].";
throw std::runtime_error(ostrErr.str());
}
// cast if needed
expr = convert_sym(expr, sym->ty);
if(expr->ty == SymbolType::SCALAR || expr->ty == SymbolType::INT)
{
std::string ty = LLAsm::get_type_name(expr->ty);
(*m_ostr) << "store " << ty << " %" << expr->name << ", "<< ty << "* %" << var << "\n";
}
else if(sym->ty == SymbolType::VECTOR || sym->ty == SymbolType::MATRIX)
{
std::size_t dimDst = get_arraydim(sym);
std::size_t dimSrc = get_arraydim(expr);
// copy elements in a loop
generate_loop(0, dimDst, [this, expr, sym, dimDst, dimSrc](t_astret ctrval)
{
// loop statements
t_astret elemptr_src = get_tmp_var(SymbolType::SCALAR);
(*m_ostr) << "%" << elemptr_src->name << " = getelementptr [" << dimSrc << " x double], ["
<< dimSrc << " x double]* %" << expr->name << ", i64 0, i64 %" << ctrval->name << "\n";
t_astret elemptr_dst = get_tmp_var(SymbolType::SCALAR);
(*m_ostr) << "%" << elemptr_dst->name << " = getelementptr [" << dimDst << " x double], ["
<< dimDst << " x double]* %" << sym->name << ", i64 0, i64 %" << ctrval->name << "\n";
t_astret elem_src = get_tmp_var(SymbolType::SCALAR);
(*m_ostr) << "%" << elem_src->name << " = load double, double* %" << elemptr_src->name << "\n";
(*m_ostr) << "store double %" << elem_src->name << ", double* %" << elemptr_dst->name << "\n";
});
}
else if(sym->ty == SymbolType::STRING)
{
std::size_t src_dim = std::get<0>(expr->dims);
std::size_t dst_dim = std::get<0>(sym->dims);
//if(src_dim > dst_dim) // TODO
// throw std::runtime_error("ASTAssign: Buffer of string \"" + sym->name + "\" is not large enough.");
std::size_t dim = std::min(src_dim, dst_dim);
// copy elements in a loop
generate_loop(0, dim, [this, expr, sym, src_dim, dst_dim](t_astret ctrval)
{
// loop statements
t_astret elemptr_src = get_tmp_var();
(*m_ostr) << "%" << elemptr_src->name << " = getelementptr [" << src_dim << " x i8], ["
<< src_dim << " x i8]* %" << expr->name << ", i64 0, i64 %" << ctrval->name << "\n";
t_astret elemptr_dst = get_tmp_var();
(*m_ostr) << "%" << elemptr_dst->name << " = getelementptr [" << dst_dim << " x i8], ["
<< dst_dim << " x i8]* %" << sym->name << ", i64 0, i64 %" << ctrval->name << "\n";
t_astret elem_src = get_tmp_var();
(*m_ostr) << "%" << elem_src->name << " = load i8, i8* %" << elemptr_src->name << "\n";
(*m_ostr) << "store i8 %" << elem_src->name << ", i8* %" << elemptr_dst->name << "\n";
});
}
return expr;
}
return nullptr;
}
t_astret LLAsm::visit(const ASTNumConst<double>* ast)
{
double val = ast->GetVal();
t_astret retvar = get_tmp_var(SymbolType::SCALAR);
t_astret retval = get_tmp_var(SymbolType::SCALAR);
(*m_ostr) << "%" << retvar->name << " = alloca double\n";
(*m_ostr) << "store double " << std::scientific << val << ", double* %" << retvar->name << "\n";
(*m_ostr) << "%" << retval->name << " = load double, double* %" << retvar->name << "\n";
return retval;
}
t_astret LLAsm::visit(const ASTNumConst<std::int64_t>* ast)
{
std::int64_t val = ast->GetVal();
t_astret retvar = get_tmp_var(SymbolType::INT);
t_astret retval = get_tmp_var(SymbolType::INT);
(*m_ostr) << "%" << retvar->name << " = alloca i64\n";
(*m_ostr) << "store i64 " << val << ", i64* %" << retvar->name << "\n";
(*m_ostr) << "%" << retval->name << " = load i64, i64* %" << retvar->name << "\n";
return retval;
}
t_astret LLAsm::visit(const ASTStrConst* ast)
{
const std::string& str = ast->GetVal();
std::size_t dim = str.length()+1;
std::array<std::size_t, 2> dims{{dim, 1}};
t_astret str_mem = get_tmp_var(SymbolType::STRING, &dims);
// allocate the string's memory
(*m_ostr) << "%" << str_mem->name << " = alloca [" << dim << " x i8]\n";
// set the individual chars
for(std::size_t idx=0; idx<dim; ++idx)
{
t_astret ptr = get_tmp_var();
(*m_ostr) << "%" << ptr->name << " = getelementptr [" << dim << " x i8], ["
<< dim << " x i8]* %" << str_mem->name << ", i64 0, i64 " << idx << "\n";
int val = (idx<dim-1) ? str[idx] : 0;
(*m_ostr) << "store i8 " << val << ", i8* %" << ptr->name << "\n";
}
return str_mem;
}
t_astret LLAsm::visit(const ASTExprList* ast)
{
// only double arrays are handled here
if(!ast->IsScalarArray())
{
throw std::runtime_error("ASTExprList: General expression list should not be directly evaluated.");
}
// array values and size
const auto& lst = ast->GetList();
std::size_t len = lst.size();
std::array<std::size_t, 2> dims{{len, 1}};
// allocate double array
t_astret vec_mem = get_tmp_var(SymbolType::VECTOR, &dims);
(*m_ostr) << "%" << vec_mem->name << " = alloca [" << len << " x double]\n";
// set the individual array elements
auto iter = lst.begin();
for(std::size_t idx=0; idx<len; ++idx)
{
t_astret ptr = get_tmp_var();
(*m_ostr) << "%" << ptr->name << " = getelementptr [" << len << " x double], ["
<< len << " x double]* %" << vec_mem->name << ", i64 0, i64 " << idx << "\n";
t_astret val = (*iter)->accept(this);
val = convert_sym(val, SymbolType::SCALAR);
(*m_ostr) << "store double %" << val->name << ", double* %" << ptr->name << "\n";
++iter;
}
return vec_mem;
}
| 32.275773
| 123
| 0.577737
|
tweber-ill
|
0a5263a045fa4ad3ccc150da1fc9ab4aaca1471d
| 268
|
cpp
|
C++
|
production/subsystems/gui/src/status_bar.cpp
|
ratelware/logreader
|
6ca96c49a342dcaef59221dd3497563f54b63ae7
|
[
"MIT"
] | null | null | null |
production/subsystems/gui/src/status_bar.cpp
|
ratelware/logreader
|
6ca96c49a342dcaef59221dd3497563f54b63ae7
|
[
"MIT"
] | 3
|
2017-11-21T22:16:51.000Z
|
2017-11-21T23:34:31.000Z
|
production/subsystems/gui/src/status_bar.cpp
|
ratelware/logreader
|
6ca96c49a342dcaef59221dd3497563f54b63ae7
|
[
"MIT"
] | null | null | null |
#include <gui/status_bar.hpp>
#include <nana/gui/filebox.hpp>
namespace gui {
status_bar::status_bar(nana::form& window_form) : bar_panel(window_form) {
bar_panel.bgcolor(nana::colors::red);
}
nana::widget& status_bar::get_widget()
{
return bar_panel;
}
}
| 17.866667
| 75
| 0.716418
|
ratelware
|
0a58656e35d6a41487b1e652fc8f4bd7cb8c1d9e
| 6,721
|
cpp
|
C++
|
plll/src/lattices/enumimpl-simpleenum.cpp
|
KudrinMatvey/myfplll
|
99fa018201097b6c078c00721cdc409cdcd4092c
|
[
"MIT"
] | null | null | null |
plll/src/lattices/enumimpl-simpleenum.cpp
|
KudrinMatvey/myfplll
|
99fa018201097b6c078c00721cdc409cdcd4092c
|
[
"MIT"
] | null | null | null |
plll/src/lattices/enumimpl-simpleenum.cpp
|
KudrinMatvey/myfplll
|
99fa018201097b6c078c00721cdc409cdcd4092c
|
[
"MIT"
] | null | null | null |
/*
Copyright (c) 2011-2014 University of Zurich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef PLLL_INCLUDE_GUARD__ENUMIMPL_SIMPLEENUM_CPP
#define PLLL_INCLUDE_GUARD__ENUMIMPL_SIMPLEENUM_CPP
namespace plll
{
template<class RealTypeContext, class IntTypeContext>
class SimpleEnumerator
{
public:
typedef boost::function<void(const linalg::math_matrix<typename IntTypeContext::Integer> & basis,
int p,
const linalg::math_rowvector<typename IntTypeContext::Integer> & vec)> CallbackFunction;
private:
Updater<RealTypeContext, IntTypeContext> d_update;
Verbose & d_verbose;
public:
SimpleEnumerator(Verbose & v)
: d_update(), d_verbose(v)
{
}
SimpleEnumerator(Verbose & v, GaussianFactorComputer &, unsigned enumdimension)
: d_update(), d_verbose(v)
{
}
bool enumerate(Lattice<RealTypeContext, IntTypeContext> & lattice, unsigned begin, unsigned end,
linalg::math_rowvector<typename IntTypeContext::Integer> & result,
typename RealTypeContext::Real & bound)
// Finds a shortest vector in the lattice generated by the orthogonal projections of the vectors
// A.row(begin) to A.row(end) into the orthogonal complement of the vectors A.row(0) to
// A.row(begin-1). Uses the Kannan-Schnorr-Euchner enumeration method.
{
// Initialize updater
RealTypeContext & rc = lattice.rc();
IntTypeContext & ic = lattice.ic();
d_update.initialize(d_verbose, lattice, begin, end, bound);
const unsigned dim = end - begin + 1;
// Prepare enumeration
linalg::math_rowvector<typename IntTypeContext::Integer> x(dim);
linalg::math_rowvector<typename RealTypeContext::Real> x_real(dim);
for (unsigned i = 0; i < dim; ++i)
{
x_real[i].setContext(rc);
setZero(x_real[i]);
}
linalg::base_rowvector<long> delta(dim);
linalg::base_rowvector<int> delta2(dim);
linalg::base_rowvector<int> r(dim + 1);
linalg::math_matrix<typename RealTypeContext::Real> sigma(dim, dim);
for (unsigned i = 0; i < dim; ++i)
{
r[i] = dim - 1;
for (unsigned j = 0; j < dim; ++j)
{
sigma(i, j).setContext(rc);
setZero(sigma(i, j));
}
}
setOne(x[0]);
setOne(x_real[0]);
delta[0] = 1;
delta2[0] = 1;
for (unsigned i = 1; i < dim; ++i)
delta2[i] = -1;
linalg::math_rowvector<typename RealTypeContext::Real> c(dim), ell(dim + 1);
for (unsigned i = 0; i < dim; ++i)
{
c[i].setContext(rc);
setZero(c[i]);
}
for (unsigned i = 0; i <= dim; ++i)
{
ell[i].setContext(rc);
setZero(ell[i]);
}
// Do enumeration
unsigned stage = 0, last_nonzero_stage = 0;
bool noSolutionYet = true;
typename RealTypeContext::Real tmp(rc);
while (true)
{
tmp = x_real[stage] - c[stage];
square(ell[stage], tmp);
ell[stage] *= lattice.getNormSq(begin + stage);
ell[stage] += ell[stage + 1];
if (ell[stage] <= bound)
{
if (stage == 0)
{
d_update(lattice, begin, end, result, bound, x, ell[0], noSolutionYet);
}
else
{
--stage;
if (stage > 0)
{
if (r[stage - 1] < r[stage])
r[stage - 1] = r[stage];
}
for (unsigned j = r[stage]; j > stage; --j) // this is the summation order considered in Pujol-Stehle
{
tmp = x_real[j] * lattice.getCoeff(begin + j, begin + stage);
sigma(stage, j - 1) = sigma(stage, j) + tmp;
}
c[stage] = -sigma(stage, stage);
bool ru;
arithmetic::convert_round(x[stage], c[stage], ru, ic);
arithmetic::convert(x_real[stage], x[stage], rc);
delta[stage] = 0;
delta2[stage] = ru ? 1 : -1;
continue;
}
}
if (++stage >= dim)
break;
r[stage - 1] = stage;
if (stage >= last_nonzero_stage)
{
last_nonzero_stage = stage;
++x[stage];
}
else
{
delta2[stage] = -delta2[stage];
delta[stage] = -delta[stage] + delta2[stage];
x[stage] += arithmetic::convert(delta[stage], ic);
}
arithmetic::convert(x_real[stage], x[stage], rc);
}
return !noSolutionYet;
}
static void setCallback(CallbackFunction)
{
}
};
}
#endif
| 39.769231
| 125
| 0.502009
|
KudrinMatvey
|
0a60ff787f117849dd7641ad0070d95f852d964e
| 1,383
|
cpp
|
C++
|
json_source/test/test_json_source.cpp
|
waltronix/smaep
|
05d90c6ab9d1c76a6da1fa285857f7ec30fc8497
|
[
"MIT"
] | 1
|
2019-12-21T15:09:40.000Z
|
2019-12-21T15:09:40.000Z
|
json_source/test/test_json_source.cpp
|
waltronix/smaep
|
05d90c6ab9d1c76a6da1fa285857f7ec30fc8497
|
[
"MIT"
] | null | null | null |
json_source/test/test_json_source.cpp
|
waltronix/smaep
|
05d90c6ab9d1c76a6da1fa285857f7ec30fc8497
|
[
"MIT"
] | null | null | null |
#include <string>
#define CATCH_CONFIG_MAIN
#include "catch2/catch.hpp"
#include "json_source.h"
TEST_CASE("some_simple_jsonpath", "json_tests") {
const std::string json = R"JSON(
{
"x": "1",
"y": "2"
}
)JSON";
smaep::data::json_source<double> jw(json);
auto rs = jw.get_value_for("$.x");
REQUIRE(1 == rs);
}
TEST_CASE("nested jsonpath", "json_tests") {
const std::string json = R"JSON(
{
"A": {
"x": "1",
"y": "2"
},
"B": {
"x": "3",
"y": "4"
}
}
)JSON";
smaep::data::json_source<double> jw(json);
REQUIRE(1 == jw.get_value_for("$.A.x"));
REQUIRE(3 == jw.get_value_for("$.B.x"));
}
TEST_CASE("select temp", "json_tests") {
const std::string json = R"JSON(
{
"A": {
"temp": "25.71",
"pressure": "1013",
"humidity": "53"
}
}
)JSON";
smaep::data::json_source<double> jw(json);
auto temp = jw.get_value_for("$..temp");
REQUIRE(25.71 == temp);
}
TEST_CASE("no_result", "json_tests") {
const std::string json = R"JSON(
{
"y": "2"
}
)JSON";
smaep::data::json_source<double> jw(json);
REQUIRE_THROWS(jw.get_value_for("$.x"));
}
TEST_CASE("more_then_one_result", "json_tests") {
const std::string json = R"JSON(
{
"A": {
"x": "1"
},
"B": {
"x": "2"
}
}
)JSON";
smaep::data::json_source<double> jw(json);
REQUIRE_THROWS(jw.get_value_for("$.x"));
}
| 15.896552
| 49
| 0.561099
|
waltronix
|
0a64c7e5115802a1f0bdc4b0b2ffb390c42348b2
| 931
|
hpp
|
C++
|
src/Components/PlayerInputComponent.hpp
|
DylanConvery/2D-Game-Engine-Prototype
|
55e5adbb687ccec593a3f5063ad2195e760bd3b6
|
[
"MIT"
] | null | null | null |
src/Components/PlayerInputComponent.hpp
|
DylanConvery/2D-Game-Engine-Prototype
|
55e5adbb687ccec593a3f5063ad2195e760bd3b6
|
[
"MIT"
] | null | null | null |
src/Components/PlayerInputComponent.hpp
|
DylanConvery/2D-Game-Engine-Prototype
|
55e5adbb687ccec593a3f5063ad2195e760bd3b6
|
[
"MIT"
] | null | null | null |
#ifndef PLAYERINPUTCOMPONENT_H
#define PLAYERINPUTCOMPONENT_H
#include "../AssetManager.hpp"
#include "../Component.hpp"
#include "SpriteComponent.hpp"
#include "TransformComponent.hpp"
#include "string"
class SpriteComponent;
class PlayerInputComponent : public Component {
public:
PlayerInputComponent();
PlayerInputComponent(float speed, std::string up_key, std::string down_key, std::string left_key, std::string right_key, std::string action_key);
std::string getSDLStringCode(std::string key) const;
void initialize() override;
void update(float delta_time) override;
void render() override;
std::string _up_key;
std::string _down_key;
std::string _left_key;
std::string _right_key;
std::string _action_key;
TransformComponent* _transform;
SpriteComponent* _sprite;
float _speed;
private:
void boundingBoxCheck();
};
#endif // !PLAYERINPUTCOMPONENT_H
| 25.861111
| 149
| 0.736842
|
DylanConvery
|
0a68a7b34aad2694b2096f1fa098fe432a023e73
| 8,396
|
cpp
|
C++
|
FaceTracking/src/shape_model.cpp
|
johmathe/ComputerVisionStuff
|
8182e2a1284721cb1ac6091174ff5aa0d6aa561e
|
[
"Apache-2.0"
] | null | null | null |
FaceTracking/src/shape_model.cpp
|
johmathe/ComputerVisionStuff
|
8182e2a1284721cb1ac6091174ff5aa0d6aa561e
|
[
"Apache-2.0"
] | null | null | null |
FaceTracking/src/shape_model.cpp
|
johmathe/ComputerVisionStuff
|
8182e2a1284721cb1ac6091174ff5aa0d6aa561e
|
[
"Apache-2.0"
] | null | null | null |
/*****************************************************************************
* Non-Rigid Face Tracking
******************************************************************************
* by Jason Saragih, 5th Dec 2012
* http://jsaragih.org/
******************************************************************************
* Ch6 of the book "Mastering OpenCV with Practical Computer Vision Projects"
* Copyright Packt Publishing 2012.
* http://www.packtpub.com/cool-projects-with-opencv/book
*****************************************************************************/
/*
shape_model: A combined local-global 2D point distribution model
Jason Saragih (2012)
*/
#include "shape_model.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#define fl at<float>
//==============================================================================
void shape_model::calc_params(const vector<Point2f> &pts, const Mat weight,
const float c_factor) {
int n = pts.size();
assert(V.rows == 2 * n);
Mat s = Mat(pts).reshape(1, 2 * n); // point set to vector format
if (weight.empty())
p = V.t() * s; // simple projection
else { // scaled projection
if (weight.rows != n) {
cout << "Invalid weighting matrix" << endl;
abort();
}
int K = V.cols;
Mat H = Mat::zeros(K, K, CV_32F), g = Mat::zeros(K, 1, CV_32F);
for (int i = 0; i < n; i++) {
Mat v = V(Rect(0, 2 * i, K, 2));
float w = weight.fl(i);
H += w * v.t() * v;
g += w * v.t() * Mat(pts[i]);
}
solve(H, g, p, DECOMP_SVD);
}
this->clamp(c_factor); // clamp resulting parameters
}
//==============================================================================
Mat shape_model::center_shape(const Mat &pts) {
int n = pts.rows / 2;
float mx = 0, my = 0;
for (int i = 0; i < n; i++) {
mx += pts.fl(2 * i);
my += pts.fl(2 * i + 1);
}
Mat p(2 * n, 1, CV_32F);
mx /= n;
my /= n;
for (int i = 0; i < n; i++) {
p.fl(2 * i) = pts.fl(2 * i) - mx;
p.fl(2 * i + 1) = pts.fl(2 * i + 1) - my;
}
return p;
}
//==============================================================================
vector<Point2f> shape_model::calc_shape() {
Mat s = V * p;
int n = s.rows / 2;
vector<Point2f> pts;
for (int i = 0; i < n; i++)
pts.push_back(Point2f(s.fl(2 * i), s.fl(2 * i + 1)));
return pts;
}
//==============================================================================
void shape_model::set_identity_params() {
p = 0.0;
p.fl(0) = 1.0; // 1'st parameter is scale
}
//==============================================================================
void shape_model::train(const vector<vector<Point2f> > &points,
const vector<Vec2i> &con, const float frac,
const int kmax) {
// vectorize points
Mat X = this->pts2mat(points);
int N = X.cols, n = X.rows / 2;
// align shapes
Mat Y = this->procrustes(X);
// compute rigid transformation
Mat R = this->calc_rigid_basis(Y);
// compute non-rigid transformation
Mat P = R.t() * Y;
Mat dY = Y - R * P;
SVD svd(dY * dY.t());
int m = min(min(kmax, N - 1), n - 1);
float vsum = 0;
for (int i = 0; i < m; i++) vsum += svd.w.fl(i);
float v = 0;
int k = 0;
for (k = 0; k < m; k++) {
v += svd.w.fl(k);
if (v / vsum >= frac) {
k++;
break;
}
}
if (k > m) k = m;
Mat D = svd.u(Rect(0, 0, k, 2 * n));
// combine bases
V.create(2 * n, 4 + k, CV_32F);
Mat Vr = V(Rect(0, 0, 4, 2 * n));
R.copyTo(Vr);
Mat Vd = V(Rect(4, 0, k, 2 * n));
D.copyTo(Vd);
// compute variance (normalized wrt scale)
Mat Q = V.t() * X;
for (int i = 0; i < N; i++) {
float v = Q.fl(0, i);
Mat q = Q.col(i);
q /= v;
}
e.create(4 + k, 1, CV_32F);
pow(Q, 2, Q);
for (int i = 0; i < 4 + k; i++) {
if (i < 4)
e.fl(i) = -1;
else
e.fl(i) = Q.row(i).dot(Mat::ones(1, N, CV_32F)) / (N - 1);
}
// store connectivity
if (con.size() > 0) { // default connectivity
int m = con.size();
C.create(m, 2, CV_32F);
for (int i = 0; i < m; i++) {
C.at<int>(i, 0) = con[i][0];
C.at<int>(i, 1) = con[i][1];
}
} else { // user-specified connectivity
C.create(n, 2, CV_32S);
for (int i = 0; i < n - 1; i++) {
C.at<int>(i, 0) = i;
C.at<int>(i, 1) = i + 1;
}
C.at<int>(n - 1, 0) = n - 1;
C.at<int>(n - 1, 1) = 0;
}
}
//==============================================================================
Mat shape_model::pts2mat(const vector<vector<Point2f> > &points) {
int N = points.size();
assert(N > 0);
int n = points[0].size();
for (int i = 1; i < N; i++) assert(int(points[i].size()) == n);
Mat X(2 * n, N, CV_32F);
for (int i = 0; i < N; i++) {
Mat x = X.col(i), y = Mat(points[i]).reshape(1, 2 * n);
y.copyTo(x);
}
return X;
}
//==============================================================================
Mat shape_model::procrustes(const Mat &X, const int itol, const float ftol) {
int N = X.cols, n = X.rows / 2;
// remove centre of mass
Mat P = X.clone();
for (int i = 0; i < N; i++) {
Mat p = P.col(i);
float mx = 0, my = 0;
for (int j = 0; j < n; j++) {
mx += p.fl(2 * j);
my += p.fl(2 * j + 1);
}
mx /= n;
my /= n;
for (int j = 0; j < n; j++) {
p.fl(2 * j) -= mx;
p.fl(2 * j + 1) -= my;
}
}
// optimise scale and rotation
Mat C_old;
for (int iter = 0; iter < itol; iter++) {
Mat C = P * Mat::ones(N, 1, CV_32F) / N;
normalize(C, C);
if (iter > 0) {
if (norm(C, C_old) < ftol) break;
}
C_old = C.clone();
for (int i = 0; i < N; i++) {
Mat R = this->rot_scale_align(P.col(i), C);
for (int j = 0; j < n; j++) {
float x = P.fl(2 * j, i), y = P.fl(2 * j + 1, i);
P.fl(2 * j, i) = R.fl(0, 0) * x + R.fl(0, 1) * y;
P.fl(2 * j + 1, i) = R.fl(1, 0) * x + R.fl(1, 1) * y;
}
}
}
return P;
}
//=============================================================================
Mat shape_model::rot_scale_align(const Mat &src, const Mat &dst) {
// construct linear system
int n = src.rows / 2;
float a = 0, b = 0, d = 0;
for (int i = 0; i < n; i++) {
d += src.fl(2 * i) * src.fl(2 * i) + src.fl(2 * i + 1) * src.fl(2 * i + 1);
a += src.fl(2 * i) * dst.fl(2 * i) + src.fl(2 * i + 1) * dst.fl(2 * i + 1);
b += src.fl(2 * i) * dst.fl(2 * i + 1) - src.fl(2 * i + 1) * dst.fl(2 * i);
}
a /= d;
b /= d; // solved linear system
return (Mat_<float>(2, 2) << a, -b, b, a);
}
//==============================================================================
Mat shape_model::calc_rigid_basis(const Mat &X) {
// compute mean shape
int N = X.cols, n = X.rows / 2;
Mat mean = X * Mat::ones(N, 1, CV_32F) / N;
// construct basis for similarity transform
Mat R(2 * n, 4, CV_32F);
for (int i = 0; i < n; i++) {
R.fl(2 * i, 0) = mean.fl(2 * i);
R.fl(2 * i + 1, 0) = mean.fl(2 * i + 1);
R.fl(2 * i, 1) = -mean.fl(2 * i + 1);
R.fl(2 * i + 1, 1) = mean.fl(2 * i);
R.fl(2 * i, 2) = 1.0;
R.fl(2 * i + 1, 2) = 0.0;
R.fl(2 * i, 3) = 0.0;
R.fl(2 * i + 1, 3) = 1.0;
}
// Gram-Schmidt orthonormalization
for (int i = 0; i < 4; i++) {
Mat r = R.col(i);
for (int j = 0; j < i; j++) {
Mat b = R.col(j);
r -= b * (b.t() * r);
}
normalize(r, r);
}
return R;
}
//==============================================================================
void shape_model::clamp(const float c) {
double scale = p.fl(0);
for (int i = 0; i < e.rows; i++) {
if (e.fl(i) < 0) continue;
float v = c * sqrt(e.fl(i));
if (fabs(p.fl(i) / scale) > v) {
if (p.fl(i) > 0)
p.fl(i) = v * scale;
else
p.fl(i) = -v * scale;
}
}
}
//==============================================================================
void shape_model::write(FileStorage &fs) const {
assert(fs.isOpened());
fs << "{"
<< "V" << V << "e" << e << "C" << C << "}";
}
//==============================================================================
void shape_model::read(const FileNode &node) {
assert(node.type() == FileNode::MAP);
node["V"] >> V;
node["e"] >> e;
node["C"] >> C;
p = Mat::zeros(e.rows, 1, CV_32F);
}
//==============================================================================
| 30.754579
| 80
| 0.407932
|
johmathe
|
0a68fd4158f11695b65ff930a8fa9778ff613572
| 5,283
|
cpp
|
C++
|
bfcp/common/bfcp_msg.cpp
|
Issic47/bfcp
|
b0e78534f58820610df6133dc4043f902c001173
|
[
"BSD-3-Clause"
] | 10
|
2015-08-05T06:07:41.000Z
|
2020-12-17T04:28:48.000Z
|
bfcp/common/bfcp_msg.cpp
|
Issic47/bfcp
|
b0e78534f58820610df6133dc4043f902c001173
|
[
"BSD-3-Clause"
] | null | null | null |
bfcp/common/bfcp_msg.cpp
|
Issic47/bfcp
|
b0e78534f58820610df6133dc4043f902c001173
|
[
"BSD-3-Clause"
] | 8
|
2015-11-27T13:22:30.000Z
|
2021-01-28T07:20:50.000Z
|
#include <bfcp/common/bfcp_msg.h>
#include <algorithm>
#include <muduo/base/Logging.h>
using muduo::net::Buffer;
using muduo::net::InetAddress;
using muduo::strerror_tl;
namespace bfcp
{
namespace detail
{
int printToString(const char *p, size_t size, void *arg)
{
string *str = static_cast<string*>(arg);
str->append(p, p + size);
return 0;
}
} // namespace detail
BfcpMsg::BfcpMsg(muduo::net::Buffer *buf,
const muduo::net::InetAddress &src,
muduo::Timestamp receivedTime)
: msg_(nullptr), receivedTime_(receivedTime)
{
mbuf_t mb;
mbuf_init(&mb);
mb.buf = reinterpret_cast<uint8_t*>(const_cast<char*>(buf->peek()));
mb.size = buf->readableBytes();
mb.end = mb.size;
err_ = bfcp_msg_decode(&msg_, &mb);
buf->retrieveAll();
if (err_ == 0)
setSrc(src);
isComplete_ = !valid() || !msg_->f;
if (valid() && msg_->f)
{
fragments_.emplace(msg_->fragoffset, msg_->fraglen, msg_->fragdata);
}
}
std::list<BfcpAttr> BfcpMsg::getAttributes() const
{
std::list<BfcpAttr> attrs;
struct le *le = list_head(&msg_->attrl);
while (le)
{
bfcp_attr_t *attr = static_cast<bfcp_attr_t*>(le->data);
le = le->next;
attrs.push_back(BfcpAttr(*attr));
}
return attrs;
}
std::list<BfcpAttr> BfcpMsg::findAttributes( ::bfcp_attrib attrType ) const
{
std::list<BfcpAttr> attrs;
struct le *le = list_head(&msg_->attrl);
while (le)
{
bfcp_attr_t *attr = static_cast<bfcp_attr_t*>(le->data);
le = le->next;
if (attr->type == attrType)
attrs.push_back(BfcpAttr(*attr));
}
return attrs;
}
string BfcpMsg::toString() const
{
char buf[256];
if (!valid())
{
snprintf(buf, sizeof buf, "{errcode=%d,errstr='%s'}",
err_, strerror_tl(err_));
}
else
{
snprintf(buf, sizeof buf, "{ver=%u,cid=%u,tid=%u,uid=%u,prim=%s}",
msg_->ver, msg_->confid, msg_->tid, msg_->userid,
bfcp_prim_name(msg_->prim));
}
return buf;
}
bfcp_floor_id_list BfcpMsg::getFloorIDs() const
{
bfcp_floor_id_list floorIDs;
auto attrs = findAttributes(BFCP_FLOOR_ID);
floorIDs.reserve(attrs.size());
for (auto &attr : attrs)
{
floorIDs.push_back(attr.getFloorID());
}
return floorIDs;
}
string BfcpMsg::toStringInDetail() const
{
string str;
struct re_printf printFunc;
printFunc.vph = &detail::printToString;
printFunc.arg = &str;
bfcp_msg_print(&printFunc, msg_);
return str;
}
void BfcpMsg::addFragment( const BfcpMsgPtr &msg )
{
assert(this != &(*msg));
if (!valid() || !canMergeWith(msg))
{
LOG_WARN << "Cannot merge fragment: " << msg->toString();
err_ = EBADMSG;
return;
}
if (!isComplete_ && holes_.empty())
{
holes_.emplace_back(0, getLength() - 1);
doAddFragment(this);
}
doAddFragment(&(*msg));
if (holes_.empty())
{
isComplete_ = true;
mergeFragments();
}
}
bool BfcpMsg::canMergeWith( const BfcpMsgPtr &msg ) const
{
return (isFragment() && msg->isFragment()) &&
getEntity() == msg->getEntity() &&
primitive() == msg->primitive() &&
getLength() == msg->getLength() &&
isResponse() == msg->isResponse();
}
void BfcpMsg::doAddFragment(const BfcpMsg *msg)
{
bool isInHole = false;
uint16_t fragOffset = msg->msg_->fragoffset;
uint16_t fragBack = fragOffset + msg->msg_->fraglen - 1;
for (auto it = holes_.begin(); it != holes_.end(); ++it)
{
if ((*it).front <= fragOffset && fragBack <= (*it).back)
{
isInHole = true;
if ((*it).front < fragOffset)
{
holes_.emplace_back((*it).front, fragOffset - 1);
}
if (fragBack < (*it).back)
{
holes_.emplace_back(fragBack + 1, (*it).back);
}
it = holes_.erase(it);
break;
}
}
if (!isInHole)
{
LOG_WARN << "Ignore fragment not in the hole: " << msg->toString();
}
else
{
fragments_.emplace(
msg->msg_->fragoffset, msg->msg_->fraglen, msg->msg_->fragdata);
}
}
bool BfcpMsg::checkComplete()
{
isComplete_ = false;
auto it = fragments_.begin();
if ((*it).getOffset() != 0)
{
return false;
}
auto nextIt = it;
++nextIt;
size_t len = it->getLen();
for (; nextIt != fragments_.end(); ++it, ++nextIt)
{
size_t offsetEnd = (*it).getOffset() + (*it).getLen();
if (offsetEnd < (*nextIt).getOffset())
{
return false;
}
else if (offsetEnd > (*nextIt).getOffset())
{
LOG_WARN << "Received overlap fragments: " << toString();
err_ = EBADMSG;
return false;
}
len += (*nextIt).getLen();
}
if (len == msg_->len)
{
isComplete_ = true;
return true;
}
else if (len > msg_->len)
{
LOG_WARN << "Received too large fragments: " << toString();
err_ = EBADMSG;
return false;
}
return false;
}
void BfcpMsg::mergeFragments()
{
assert(valid());
uint8_t buf[65536];
mbuf_t mb;
mbuf_init(&mb);
mb.buf = buf;
mb.pos = 0;
mb.end = 0;
mb.size = sizeof buf;
for (auto &fragment : fragments_)
{
mbuf_t *fragBuf = fragment.getBuf();
err_ = mbuf_write_mem(&mb, fragBuf->buf, fragBuf->end);
assert(err_ == 0);
}
mb.pos = 0;
err_ = bfcp_attrs_decode(&msg_->attrl, &mb, 4 * msg_->len, &msg_->uma);
fragments_.clear();
}
} // namespace bfcp
| 21.388664
| 75
| 0.605338
|
Issic47
|
0a74e732b1a1b7620b37cf7c5074d79a87a6c213
| 3,229
|
hpp
|
C++
|
source/modules/distribution/multivariate/normal/normal.hpp
|
JonathanLehner/korali
|
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
|
[
"MIT"
] | 43
|
2018-07-26T07:20:42.000Z
|
2022-03-02T10:23:12.000Z
|
source/modules/distribution/multivariate/normal/normal.hpp
|
JonathanLehner/korali
|
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
|
[
"MIT"
] | 212
|
2018-09-21T10:44:07.000Z
|
2022-03-22T14:33:05.000Z
|
source/modules/distribution/multivariate/normal/normal.hpp
|
JonathanLehner/korali
|
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
|
[
"MIT"
] | 16
|
2018-07-25T15:00:36.000Z
|
2022-03-22T14:19:46.000Z
|
/** \namespace multivariate
* @brief Namespace declaration for modules of type: multivariate.
*/
/** \file
* @brief Header file for module: Normal.
*/
/** \dir distribution/multivariate/normal
* @brief Contains code, documentation, and scripts for module: Normal.
*/
#pragma once
#include "modules/distribution/multivariate/multivariate.hpp"
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_vector.h>
namespace korali
{
namespace distribution
{
namespace multivariate
{
;
/**
* @brief Class declaration for module: Normal.
*/
class Normal : public Multivariate
{
private:
/**
* @brief Temporal storage for covariance matrix
*/
gsl_matrix_view _sigma_view;
/**
* @brief Temporal storage for variable means
*/
gsl_vector_view _mean_view;
/**
* @brief Temporal storage for work
*/
gsl_vector_view _work_view;
public:
/**
* @brief Means of the variables.
*/
std::vector<double> _meanVector;
/**
* @brief Cholesky Decomposition of the covariance matrix.
*/
std::vector<double> _sigma;
/**
* @brief [Internal Use] Auxiliary work vector.
*/
std::vector<double> _workVector;
/**
* @brief Obtains the entire current state and configuration of the module.
* @param js JSON object onto which to save the serialized state of the module.
*/
void getConfiguration(knlohmann::json& js) override;
/**
* @brief Sets the entire state and configuration of the module, given a JSON object.
* @param js JSON object from which to deserialize the state of the module.
*/
void setConfiguration(knlohmann::json& js) override;
/**
* @brief Applies the module's default configuration upon its creation.
* @param js JSON object containing user configuration. The defaults will not override any currently defined settings.
*/
void applyModuleDefaults(knlohmann::json& js) override;
/**
* @brief Applies the module's default variable configuration to each variable in the Experiment upon creation.
*/
void applyVariableDefaults() override;
/*
* @brief Updates distribution to new covariance matrix.
*/
void updateDistribution() override;
/**
* @brief Updates a specific property with a vector of values.
* @param propertyName The name of the property to update
* @param values double Numerical values to assign.
*/
void setProperty(const std::string &propertyName, const std::vector<double> &values) override;
/**
* @brief Gets the probability density of the distribution at points x.
* @param x points to evaluate
* @param result P(x) at the given points
* @param n number of points
*/
void getDensity(double *x, double *result, const size_t n) override;
/**
* @brief Gets Log probability density of the distribution at points x.
* @param x points to evaluate
* @param result log(P(x)) at the given points
* @param n number of points
*/
void getLogDensity(double *x, double *result, const size_t n) override;
/**
* @brief Draws and returns a random number vector from the distribution.
* @param x Random real number vector.
* @param n Vector size
*/
void getRandomVector(double *x, const size_t n) override;
};
} //multivariate
} //distribution
} //korali
;
| 26.040323
| 119
| 0.704552
|
JonathanLehner
|
0a78be8d5b181f93ad7df01797458b5a6cd2f9f3
| 651
|
cc
|
C++
|
EDMUtils/src/TFileUtils.cc
|
NTUHEP-Tstar/ManagerUtils
|
2536174671e537f210c330fe739f4cf0615e735e
|
[
"MIT"
] | null | null | null |
EDMUtils/src/TFileUtils.cc
|
NTUHEP-Tstar/ManagerUtils
|
2536174671e537f210c330fe739f4cf0615e735e
|
[
"MIT"
] | null | null | null |
EDMUtils/src/TFileUtils.cc
|
NTUHEP-Tstar/ManagerUtils
|
2536174671e537f210c330fe739f4cf0615e735e
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
*
* Filename : TFileUtils.cc
* Description : Implementation of utility functions
* Author : Yi-Mu "Enoch" Chen [ ensc@hep1.phys.ntu.edu.tw ]
*
*******************************************************************************/
#include "TFile.h"
#include <string>
using namespace std;
// Returing a clone of a object for safe use in edm plugis
TObject*
GetCloneFromFile( const string& filename, const string& objname )
{
TFile* file = TFile::Open( filename.c_str() );
TObject* ans = file->Get( objname.c_str() )->Clone();
file->Close();
return ans;
}
| 29.590909
| 80
| 0.509985
|
NTUHEP-Tstar
|
0a7c87e7d11a71320cbe4e5104f756505a98d13e
| 3,446
|
cpp
|
C++
|
src/lib/Components/WindowSizeComponent.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/Components/WindowSizeComponent.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/Components/WindowSizeComponent.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved.
* This code is licensed under a BSD-style license that can be
* found in the LICENSE file. The license can also be found at:
* http://www.boi-project.org/license
*/
#include <QSizeF>
#include <QPainter>
#include <QVariant>
#include <QStyleOptionGraphicsItem>
#include "CSI.h"
#include "StandardDataTypes.h"
#include "StandardComponents.h"
#include "Components/BasicComponentDrawData.h"
#include "Components/WindowSizeComponent.h"
namespace BOI {
BOI_BEGIN_RECEIVERS(WindowSizeComponent)
BOI_END_RECEIVERS(WindowSizeComponent)
BOI_BEGIN_EMITTERS(WindowSizeComponent)
BOI_DECLARE_EMITTER("{8d001b1b-c057-44c8-a4a6-aab8e9da1916}")
BOI_DECLARE_EMITTER("{24a74700-21ae-4e99-8e95-366901620655}")
BOI_DECLARE_EMITTER("{64078be7-c9eb-4851-bf29-5f2484a81401}")
BOI_END_EMITTERS(WindowSizeComponent)
BOI_BEGIN_FUNCSETS(WindowSizeComponent)
BOI_END_FUNCSETS(WindowSizeComponent)
BOI_BEGIN_CALLERS(WindowSizeComponent)
BOI_END_CALLERS(WindowSizeComponent)
WindowSizeComponent::WindowSizeComponent(const BasicComponentDrawData* pDrawData)
: Component(BOI_STD_C(WindowSize)),
m_sizeRef(),
m_widthRef(),
m_heightRef(),
m_pDrawData(pDrawData)
{
}
bool WindowSizeComponent::Initialize()
{
m_sizeRef = SI()->NewData(BOI_STD_D(Size));
m_widthRef = SI()->NewData(BOI_STD_D(Float));
m_heightRef = SI()->NewData(BOI_STD_D(Float));
QVariant value;
SI()->RegisterStateListener(StateId_WindowSize, this, value);
SetSize(value.toSizeF());
SetBoundingRect(m_pDrawData->BoundingRect());
return true;
}
void WindowSizeComponent::Destroy()
{
SI()->UnregisterStateListener(StateId_WindowSize, this);
}
void WindowSizeComponent::HandleStateChanged(StateId stateId, DRef& dref)
{
Q_UNUSED(stateId);
const QSizeF* pSize = dref.GetReadInstance<QSizeF>();
SetSize(*pSize);
}
void WindowSizeComponent::HandleEmitterConnected(int emitter,
int componentId)
{
Q_UNUSED(componentId);
if (EmitterHasNew(emitter))
{
if (emitter == Emitter_Size)
{
EmitToNew(Emitter_Size, m_sizeRef);
}
else if (emitter == Emitter_Width)
{
EmitToNew(Emitter_Width, m_widthRef);
}
else if (emitter == Emitter_Height)
{
EmitToNew(Emitter_Height, m_heightRef);
}
}
}
void WindowSizeComponent::SetSize(const QSizeF& size)
{
qreal width = size.width();
qreal height = size.height();
QSizeF* pSize = m_sizeRef.GetWriteInstance<QSizeF>();
pSize->setWidth(width);
pSize->setHeight(height);
if (EmitterConnected(Emitter_Size))
{
Emit(Emitter_Size, m_sizeRef);
}
float* pWidth = m_widthRef.GetWriteInstance<float>();
*pWidth = width;
if (EmitterConnected(Emitter_Width))
{
Emit(Emitter_Width, m_widthRef);
}
float* pHeight = m_heightRef.GetWriteInstance<float>();
*pHeight = height;
if (EmitterConnected(Emitter_Height))
{
Emit(Emitter_Height, m_heightRef);
}
}
void WindowSizeComponent::Draw(QPainter* pPainter,
const QStyleOptionGraphicsItem* pOption)
{
pPainter->drawImage(pOption->exposedRect,
m_pDrawData->Image(),
pOption->exposedRect);
}
} // namespace BOI
| 23.127517
| 81
| 0.680499
|
romoadri21
|
0a80ebb0bb5304e3df3e3c402222019b356db874
| 487
|
cpp
|
C++
|
ReverseAnArray/main.cpp
|
KhunJahad/Arrays
|
644e64fe2e88a4817afe1ce482e93f8876b85c6a
|
[
"MIT"
] | null | null | null |
ReverseAnArray/main.cpp
|
KhunJahad/Arrays
|
644e64fe2e88a4817afe1ce482e93f8876b85c6a
|
[
"MIT"
] | null | null | null |
ReverseAnArray/main.cpp
|
KhunJahad/Arrays
|
644e64fe2e88a4817afe1ce482e93f8876b85c6a
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
void read_input(){
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
}
int main(){
read_input();
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++) {
cin>>arr[i];
}
int i=0;
int j=n-1;
while(i<j){
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
i++;
j--;
}
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
return 0;
}
| 12.815789
| 35
| 0.527721
|
KhunJahad
|
0a82694de78ddc786187310c17ce3f7d0f5b6a0c
| 4,386
|
cpp
|
C++
|
Engine/Misc/Sources/Reflection/Archiver.cpp
|
kaluginadaria/YetAnotherProject
|
abedd20b484f868ded83e72261970703a27e024d
|
[
"MIT"
] | 1
|
2018-05-02T10:40:26.000Z
|
2018-05-02T10:40:26.000Z
|
Engine/Misc/Sources/Reflection/Archiver.cpp
|
kaluginadaria/YetAnotherProject
|
abedd20b484f868ded83e72261970703a27e024d
|
[
"MIT"
] | 9
|
2018-03-26T10:22:07.000Z
|
2018-05-22T20:43:14.000Z
|
Engine/Misc/Sources/Reflection/Archiver.cpp
|
kaluginadaria/YetAnotherProject
|
abedd20b484f868ded83e72261970703a27e024d
|
[
"MIT"
] | 6
|
2018-04-15T16:03:32.000Z
|
2018-05-21T22:02:49.000Z
|
#include "Archiver.hpp"
#include "boost/property_tree/ptree.hpp"
#include "boost/property_tree/json_parser.hpp"
#include <iostream>
namespace pt = boost::property_tree;
#define CAUGORY_PREFIX '@'
bool IsCategory(const std::string& str)
{
if (str.length())
{
return str[0] == CAUGORY_PREFIX;
}
throw std::runtime_error("enpty name is inawalible");
}
bool IsPlane(const std::string& str)
{
if (str.length())
{
return *str. begin() != '{'
|| *++str.rbegin() != '}';
}
throw std::runtime_error("enpty name is inawalible");
}
std::string ShieldCategory(const std::string name)
{
return CAUGORY_PREFIX + name;
}
std::string UnshieldCategory(const std::string name)
{
return name.substr(1);
}
/** fillin the archive
*/
void ConstructTree(Archiver& ar, pt::ptree& tree, std::string prefix)
{
for (auto& val : tree)
{
auto& name = val.first;
auto& subtree = val.second;
if (IsCategory(name))
{
auto freeName = UnshieldCategory(name);
auto next = prefix + '.' + freeName;
ConstructTree(ar, subtree, next);
}
else if (!subtree.empty())
{
std::string s;
std::stringstream ss(s);
pt::write_json(ss, subtree);
ar[prefix][name] = ss.str();
}
else
{
ar[prefix][name] = subtree.get_value<std::string>();
}
}
}
/** Contruct a ptree on base of the node
*/
pt::ptree ArchiveTree(Archiver::Node& node)
{
pt::ptree tree;
for (auto& pair : node.category.params)
{
auto& member = pair.first;
auto& value = pair.second;
if (IsPlane(value))
{
tree.add(member, value);
}
else
{
std::stringstream ss(value);
pt::ptree subtree;
pt::read_json(ss, subtree);
tree.add_child(member, subtree);
}
}
for (auto& child : node.children)
{
auto& name = ShieldCategory(child->name);
auto subtree = ArchiveTree(*child.get());
tree.add_child(name, subtree);
}
return tree;
}
/******************************************************************************
* Archiver
******************************************************************************/
Archiver::Archiver()
: root(*this, "")
{}
void Archiver::Constract(const std::string& json)
{
std::stringstream ss(json);
pt::ptree tree;
pt::read_json(ss, tree);
ConstructTree(*this, tree, "");
// to avoid double assign exceptions
members.clear();
}
std::string Archiver::Archive()
{
auto tree = ArchiveTree(root);
std::string s;
std::stringstream ss(s);
pt::write_json(ss, tree);
return ss.str();
}
Archiver::Category& Archiver::operator[](std::string category)
{
return GetCategory(category);
}
bool Archiver::RegisterMember(const std::string& member)
{
if (!members.count(member))
{
members.emplace(member);
return true;
}
else return false;
}
Archiver::Category& Archiver::GetCategory(const std::string& name)
{
auto tokens = GetTokens(name);
Node* node = &root;
for (auto& token : tokens)
{
if (token != "")
{
node = &node->GetOrCreate(token);
}
}
return node->category;
}
std::vector<std::string> Archiver::GetTokens(const std::string& name)
{
std::vector<std::string> tokens;
std::stringstream ss(name);
std::string s;
while (std::getline(ss, s, '.'))
{
tokens.emplace_back(s);
}
return tokens;
}
/******************************************************************************
* Category
******************************************************************************/
Archiver::Category::Category(Archiver& owner)
: owner(owner)
{}
std::string& Archiver::Category::operator[](std::string member)
{
if (!owner.RegisterMember(member))
{
throw std::runtime_error("The parametr already contains");
}
return params[member];
}
/******************************************************************************
* Node
******************************************************************************/
Archiver::Node::Node(Archiver& owner, const std::string& name)
: category(owner)
, owner (owner)
, name (name)
{}
Archiver::Node& Archiver::Node::GetOrCreate(const std::string& subCategory)
{
auto itr = children.begin();
auto end = children.end();
auto pos = std::find_if(itr, end, [&subCategory](auto& ptr)
{
return ptr->name == subCategory;
});
if (pos == end)
{
auto ptr = std::make_unique<Node>(owner, subCategory);
auto raw = ptr.get();
children.emplace_back(std::move(ptr));
return *raw;
}
else return *pos->get();
}
| 19.321586
| 79
| 0.581167
|
kaluginadaria
|
0a84a29252caed809898f8295a3b742c5a02e20d
| 3,066
|
cpp
|
C++
|
src/util/fileloader.cpp
|
JGeicke/sdl-game-engine
|
4a656145a9fc4f4490e61cbc87040de9f1abbb72
|
[
"MIT"
] | null | null | null |
src/util/fileloader.cpp
|
JGeicke/sdl-game-engine
|
4a656145a9fc4f4490e61cbc87040de9f1abbb72
|
[
"MIT"
] | null | null | null |
src/util/fileloader.cpp
|
JGeicke/sdl-game-engine
|
4a656145a9fc4f4490e61cbc87040de9f1abbb72
|
[
"MIT"
] | null | null | null |
#include "fileloader.h"
/**
* @brief Loads, parses and creates the tilemap from tilemap json files created with tiled.
* @param path - File path to json file.
* @param layerCount - Layer count of the tilemap.
* @return Created tilemap.
*/
Tilemap* FileLoader::loadTilemap(const char* path, size_t layerCount) {
std::ifstream file;
std::string s;
file.open(path);
if (file.is_open()) {
// first argument creates iterator at the beginning of the ifstream, second argument is the default constructor which represents the end of the stream.
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
json tilemap_raw = json::parse(content);
Tilemap* result = new Tilemap(tilemap_raw["tilewidth"], tilemap_raw["tileheight"], tilemap_raw["width"], tilemap_raw["height"]);
for (size_t i = 0; i < layerCount; i++)
{
std::string layerName = tilemap_raw["layers"][i]["name"];
std::string type = tilemap_raw["layers"][i]["type"];
if ((layerName == "Collision" || layerName == "collision") && type == "objectgroup") {
for (auto obj : tilemap_raw["layers"][i]["objects"])
{
result->addTilemapCollider({ obj["x"].get<int>(), obj["y"].get<int>() , obj["width"].get<int>() ,obj["height"].get<int>()});
}
result->setCollisionLayerIndex(i);
}
else if (type == "objectgroup") {
// add objects
for (auto obj : tilemap_raw["layers"][i]["objects"])
{
result->addTilemapObject({ obj["x"].get<int>(), obj["y"].get<int>() , obj["width"].get<int>() ,obj["height"].get<int>() });
}
result->setTilemapObjectLayerIndex(i);
}
else {
// add layer
result->addLayer(i, tilemap_raw["layers"][i]["data"].get<std::vector<unsigned int>>());
}
}
file.close();
return result;
}
return NULL;
}
/**
* @brief Loads texture from given path.
* @param path - File path to texture file.
* @param renderer - Reference to window renderer.
* @return Created texture.
*/
Texture FileLoader::loadTexture(const char* path, SDL_Renderer* renderer) {
Texture result;
// create texture
SDL_Surface* tempSurface = IMG_Load(path);
if (!tempSurface) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Texture IO Error", IMG_GetError(), NULL);
}
result.texture = SDL_CreateTextureFromSurface(renderer, tempSurface);
// get width & height of texture
SDL_QueryTexture(result.texture, NULL, NULL, &result.textureWidth, &result.textureHeight);
// cleanup surface
SDL_FreeSurface(tempSurface);
return result;
}
/**
* @brief Loads SDL_Texture from given path.
* @param path - File path to texture file.
* @param renderer - Reference to window renderer.
* @return Pointer to created SDL_Texture.
*/
SDL_Texture* FileLoader::loadSDLTexture(const char* path, SDL_Renderer* renderer) {
SDL_Surface* tempSurface = IMG_Load(path);
if (!tempSurface) {
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Texture IO Error", IMG_GetError(), NULL);
}
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, tempSurface);
SDL_FreeSurface(tempSurface);
return texture;
}
| 33.326087
| 153
| 0.69439
|
JGeicke
|
0a90b0ddbfc888a5313fc61f340dfb9c0ca68815
| 306
|
cpp
|
C++
|
tapi-master/test/Inputs/CPP2/CPP2.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
tapi-master/test/Inputs/CPP2/CPP2.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
tapi-master/test/Inputs/CPP2/CPP2.cpp
|
JunyiXie/ld64
|
ffaa615b31ff1baa5d6249e4d9a6a21c2ae603ae
|
[
"Apache-2.0"
] | null | null | null |
#include "Templates.h"
// Templates
namespace templates {
template int foo1<short>(short a);
template <> int foo1<>(int a) { return a; }
template <class T> Foo<T>::Foo() {}
template <class T> Foo<T>::~Foo() {}
template <class T> Bar<T>::Bar() {}
template class Bar<int>;
} // end namespace templates.
| 19.125
| 43
| 0.650327
|
JunyiXie
|
0a912c7fd635c13e6f7172ff61e5354d513b92d7
| 363
|
cpp
|
C++
|
Checking_tool_of_pouring_machine/main.cpp
|
MagicXran/artistic_work
|
7661f2df7ab642569752e64559e5176520b89369
|
[
"Apache-2.0"
] | 1
|
2022-03-02T13:57:33.000Z
|
2022-03-02T13:57:33.000Z
|
Checking_tool_of_pouring_machine/main.cpp
|
MagicXran/artistic_work
|
7661f2df7ab642569752e64559e5176520b89369
|
[
"Apache-2.0"
] | null | null | null |
Checking_tool_of_pouring_machine/main.cpp
|
MagicXran/artistic_work
|
7661f2df7ab642569752e64559e5176520b89369
|
[
"Apache-2.0"
] | null | null | null |
#define CONSOLE 1
#define DEBUG 0
#include "mainwindow.h"
#include <QApplication>
#include <cmath>
#include "HellQt_Clion.h"
int main(int argc , char *argv[]) {
#if (CONSOLE == 1)
setbuf(stdout , nullptr);
#endif
#if DEBUG == 0
QApplication a(argc , argv);
MainWindow w;
w.show();
return QApplication::exec();
#else
test();
#endif
}
| 13.961538
| 35
| 0.636364
|
MagicXran
|
0a995fa2a52abcfefcaf592e01ded35168548582
| 2,618
|
cpp
|
C++
|
src/FileWatcher/FileWatcher.cpp
|
MisterVento3/SteelEngine
|
403511b53b6575eb869b4ccfbda18514f0838e8d
|
[
"MIT"
] | 3
|
2017-05-10T10:58:17.000Z
|
2018-10-30T09:50:26.000Z
|
src/FileWatcher/FileWatcher.cpp
|
mVento3/SteelEngine
|
403511b53b6575eb869b4ccfbda18514f0838e8d
|
[
"MIT"
] | 3
|
2017-05-09T21:17:09.000Z
|
2020-02-24T14:46:22.000Z
|
src/FileWatcher/FileWatcher.cpp
|
mVento3/SteelEngine
|
403511b53b6575eb869b4ccfbda18514f0838e8d
|
[
"MIT"
] | null | null | null |
#include "FileWatcher/FileWatcher.h"
namespace SteelEngine {
bool FileWatcher::Contains(const std::string& key)
{
return m_Paths.find(key) != m_Paths.end();
}
void FileWatcher::UpdateRecursive()
{
for(auto& file : std::filesystem::recursive_directory_iterator(m_Path))
{
auto currentFileLastWriteTime = std::filesystem::last_write_time(file);
std::string file_ = file.path().string();
if(!Contains(file_))
{
m_Paths[file_] = currentFileLastWriteTime;
m_Action(file_, FileStatus::CREATED);
}
else if(m_Paths[file_] != currentFileLastWriteTime)
{
m_Paths[file_] = currentFileLastWriteTime;
m_Action(file_, FileStatus::MODIFIED);
}
}
}
void FileWatcher::UpdateNonRecursive()
{
for(auto& file : std::filesystem::directory_iterator(m_Path))
{
auto currentFileLastWriteTime = std::filesystem::last_write_time(file);
std::string file_ = file.path().string();
if(!Contains(file_))
{
m_Paths[file_] = currentFileLastWriteTime;
m_Action(file_, FileStatus::CREATED);
}
else if(m_Paths[file_] != currentFileLastWriteTime)
{
m_Paths[file_] = currentFileLastWriteTime;
m_Action(file_, FileStatus::MODIFIED);
}
}
}
FileWatcher::FileWatcher(
const std::filesystem::path& path,
ActionFunction action,
bool recursive) :
m_Path(path),
m_Action(action)
{
m_Running = true;
for(auto &file : std::filesystem::recursive_directory_iterator(path))
{
m_Paths[file.path().string()] = std::filesystem::last_write_time(file);
}
if(recursive)
{
m_UpdateFunction = std::bind(&FileWatcher::UpdateRecursive, this);
}
else
{
m_UpdateFunction = std::bind(&FileWatcher::UpdateNonRecursive, this);
}
}
FileWatcher::~FileWatcher()
{
}
void FileWatcher::Update()
{
auto it = m_Paths.begin();
while(it != m_Paths.end())
{
if(!std::filesystem::exists(it->first))
{
m_Action(it->first, FileStatus::DELETED);
it = m_Paths.erase(it);
}
else
{
it++;
}
}
m_UpdateFunction();
}
}
| 24.698113
| 83
| 0.524064
|
MisterVento3
|
0aa4e7039a887f59c61bd7854672b961561e533a
| 594
|
cpp
|
C++
|
Tool-IOStreams/src/Iconv/IconvStringStream.cpp
|
tryptichon/Tool-IOStreams-for-CPP
|
7da340735c95d7f0b7bd861a6335b1aecad02d21
|
[
"MIT"
] | 1
|
2018-06-21T16:23:17.000Z
|
2018-06-21T16:23:17.000Z
|
Tool-IOStreams/src/Iconv/IconvStringStream.cpp
|
tryptichon/Tool-IOStreams-for-CPP
|
7da340735c95d7f0b7bd861a6335b1aecad02d21
|
[
"MIT"
] | null | null | null |
Tool-IOStreams/src/Iconv/IconvStringStream.cpp
|
tryptichon/Tool-IOStreams-for-CPP
|
7da340735c95d7f0b7bd861a6335b1aecad02d21
|
[
"MIT"
] | null | null | null |
/**
* @file IconvStringStream.cpp
*
* @brief File for class IconvStringStream
* @date 04.08.2016
* @author duke
*/
#include "IconvStringStream.h"
using namespace std;
IconvStringStream::IconvStringStream(const string& a_from, const string& a_to) :
IconvStream(c_str, a_from, a_to)
{
}
IconvStringStream::IconvStringStream(const string& a_input, const string& a_from, const string& a_to) :
IconvStream(c_str, a_from, a_to)
{
*this << a_input;
}
IconvStringStream::~IconvStringStream()
{
}
string IconvStringStream::str()
{
flush();
return c_str.str();
}
| 17.470588
| 103
| 0.69697
|
tryptichon
|
0aaa65314229355d95678cc1327d75b31d72cdcc
| 866
|
c++
|
C++
|
42.1_Square_Root_Decomposition-introduction.c++
|
Sambitcr-7/DSA-C-
|
f3c80f54fa6160a99f39a934f330cdf40711de50
|
[
"Apache-2.0"
] | null | null | null |
42.1_Square_Root_Decomposition-introduction.c++
|
Sambitcr-7/DSA-C-
|
f3c80f54fa6160a99f39a934f330cdf40711de50
|
[
"Apache-2.0"
] | null | null | null |
42.1_Square_Root_Decomposition-introduction.c++
|
Sambitcr-7/DSA-C-
|
f3c80f54fa6160a99f39a934f330cdf40711de50
|
[
"Apache-2.0"
] | null | null | null |
#include "bits/stdc++.h"
using namespace std;
#define int long long
const int N = 1e5+2, MOD = 1e9+7;
signed main()
{
int n;
cin >> n;
vector<int> a(n);
for(int i = 0 ; i < n; i++)
cin >> a[i];
int len = sqrtl(n) + 1;
vector<int> b(len);
for(int i = 0; i < n; i++){
b[i/len] += a[i];
}
int q;
cin >> q;
while (q--)
{
int l,r;
cin >> l >> r;
l--; r--;
int sum = 0;
for(int i = l; i<=r; ){
if(i % len == 0 && i + len-1 <= r){
sum += b[i/len];
i += len;
}
else{
sum += a[i];
i++;
}
}
cout << sum << endl;
}
return 0;
}
// 9
// 1 5 -2 6 8 -7 2
// 1 11
// 2
// 1 6
// 2 7
| 16.653846
| 48
| 0.312933
|
Sambitcr-7
|
0aadb43caabd239e05efb407e6b17daf5194c6da
| 9,332
|
cpp
|
C++
|
Plugins/ProceduralToolkit/Source/ProceduralToolkit/Private/MeshDeformationComponent.cpp
|
normalvector/ue4_procedural_toolkit_demos
|
90021f805150d4af85cbcd063cef5379a3a2a184
|
[
"Unlicense",
"MIT"
] | 3
|
2017-03-23T10:22:50.000Z
|
2017-07-12T23:48:06.000Z
|
Plugins/ProceduralToolkit/Source/ProceduralToolkit/Private/MeshDeformationComponent.cpp
|
normalvector/ue4_procedural_toolkit_demos
|
90021f805150d4af85cbcd063cef5379a3a2a184
|
[
"Unlicense",
"MIT"
] | null | null | null |
Plugins/ProceduralToolkit/Source/ProceduralToolkit/Private/MeshDeformationComponent.cpp
|
normalvector/ue4_procedural_toolkit_demos
|
90021f805150d4af85cbcd063cef5379a3a2a184
|
[
"Unlicense",
"MIT"
] | null | null | null |
// (c)2017 Paul Golds, released under MIT License.
#include "ProceduralToolkit.h"
#include "MeshGeometry.h"
#include "MeshDeformationComponent.h"
// Sets default values for this component's properties
UMeshDeformationComponent::UMeshDeformationComponent()
{
// This component can never tick, it doesn't update itself.
PrimaryComponentTick.bCanEverTick = false;
// ...
}
bool UMeshDeformationComponent::LoadFromStaticMesh(UMeshDeformationComponent *&MeshDeformationComponent, UStaticMesh *staticMesh, int32 LOD /*= 0*/)
{
/// \todo Err.. ? Should this be here? Have I broken the API?
MeshDeformationComponent = this;
MeshGeometry = NewObject<UMeshGeometry>(this);
bool success = MeshGeometry->LoadFromStaticMesh(staticMesh);
if (!success) {
MeshGeometry = nullptr;
}
return success;
}
bool UMeshDeformationComponent::UpdateProceduralMeshComponent(UMeshDeformationComponent *&MeshDeformationComponent, UProceduralMeshComponent *proceduralMeshComponent, bool createCollision)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("UpdateProceduralMeshComponent: No meshGeometry loaded"));
return false;
}
return MeshGeometry->UpdateProceduralMeshComponent(proceduralMeshComponent, createCollision);
}
USelectionSet * UMeshDeformationComponent::SelectAll()
{
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("UMeshDeformationComponent: No meshGeometry loaded"));
return nullptr;
}
return MeshGeometry->SelectAll();
}
USelectionSet * UMeshDeformationComponent::SelectNear(FVector center /*= FVector::ZeroVector*/, float innerRadius /*= 0*/, float outerRadius /*= 100*/)
{
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("SelectNear: No meshGeometry loaded"));
return nullptr;
}
return MeshGeometry->SelectNear(center, innerRadius, outerRadius);
}
USelectionSet * UMeshDeformationComponent::SelectNearSpline(USplineComponent *spline, float innerRadius /*= 0*/, float outerRadius /*= 100*/)
{
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("SelectNearSpline: No meshGeometry loaded"));
return nullptr;
}
// Get the actor's local->world transform- we're going to need it for the spline.
FTransform actorTransform = this->GetOwner()->GetTransform();
return MeshGeometry->SelectNearSpline(spline, actorTransform, innerRadius, outerRadius);
}
USelectionSet * UMeshDeformationComponent::SelectNearLine(FVector lineStart, FVector lineEnd, float innerRadius /*=0*/, float outerRadius/*= 100*/, bool lineIsInfinite/* = false */)
{
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("SelectNearLine: No meshGeometry loaded"));
return nullptr;
}
return MeshGeometry->SelectNearLine(lineStart, lineEnd, innerRadius, outerRadius, lineIsInfinite);
}
USelectionSet * UMeshDeformationComponent::SelectFacing(FVector Facing /*= FVector::UpVector*/, float InnerRadiusInDegrees /*= 0*/, float OuterRadiusInDegrees /*= 30.0f*/)
{
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("SelectFacing: No meshGeometry loaded"));
return nullptr;
}
return MeshGeometry->SelectFacing(Facing, InnerRadiusInDegrees, OuterRadiusInDegrees);
}
USelectionSet * UMeshDeformationComponent::SelectByNoise(
int32 Seed /*= 1337*/,
float Frequency /*= 0.01*/,
ENoiseInterpolation NoiseInterpolation /*= ENoiseInterpolation::Quintic*/,
ENoiseType NoiseType /*= ENoiseType::Simplex */,
uint8 FractalOctaves /*= 3*/,
float FractalLacunarity /*= 2.0*/,
float FractalGain /*= 0.5*/,
EFractalType FractalType /*= EFractalType::FBM*/,
ECellularDistanceFunction CellularDistanceFunction /*= ECellularDistanceFunction::Euclidian*/
) {
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("SelectByNoise: No meshGeometry loaded"));
return nullptr;
}
return MeshGeometry->SelectByNoise(
Seed, Frequency, NoiseInterpolation, NoiseType,
FractalOctaves, FractalLacunarity, FractalGain, FractalType,
CellularDistanceFunction
);
}
USelectionSet * UMeshDeformationComponent::SelectByTexture(UTexture2D *Texture2D, ETextureChannel TextureChannel /*= ETextureChannel::Red*/)
{
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("SelectByTexture: No meshGeometry loaded"));
return nullptr;
}
return MeshGeometry->SelectByTexture(Texture2D, TextureChannel);
}
USelectionSet * UMeshDeformationComponent::SelectLinear(FVector LineStart, FVector LineEnd, bool Reverse /*= false*/, bool LimitToLine /*= false*/)
{
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Jitter: No meshGeometry loaded"));
return nullptr;
}
return MeshGeometry->SelectLinear(LineStart, LineEnd, Reverse, LimitToLine);
}
void UMeshDeformationComponent::Jitter(UMeshDeformationComponent *&MeshDeformationComponent, FRandomStream &randomStream, FVector min, FVector max, USelectionSet *selection)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Jitter: No meshGeometry loaded"));
return;
}
MeshGeometry->Jitter(randomStream, min, max, selection);
}
void UMeshDeformationComponent::Translate(UMeshDeformationComponent *&MeshDeformationComponent, FVector delta, USelectionSet *selection)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Translate: No meshGeometry loaded"));
return;
}
MeshGeometry->Translate(delta, selection);
}
void UMeshDeformationComponent::Rotate(UMeshDeformationComponent *&MeshDeformationComponent, FRotator Rotation/*= FRotator::ZeroRotator*/, FVector CenterOfRotation /*= FVector::ZeroVector*/, USelectionSet *Selection /*=nullptr*/)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Rotate: No meshGeometry loaded"));
return;
}
MeshGeometry->Rotate(Rotation, CenterOfRotation, Selection);
}
void UMeshDeformationComponent::Scale(UMeshDeformationComponent *&MeshDeformationComponent, FVector Scale3d /*= FVector(1, 1, 1)*/, FVector CenterOfScale /*= FVector::ZeroVector*/, USelectionSet *Selection /*= nullptr*/)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Scale: No meshGeometry loaded"));
return;
}
MeshGeometry->Scale(Scale3d, CenterOfScale, Selection);
}
void UMeshDeformationComponent::Transform(UMeshDeformationComponent *&MeshDeformationComponent, FTransform Transform, FVector CenterOfTransform /*= FVector::ZeroVector*/, USelectionSet *Selection /*= nullptr*/)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Transform: No meshGeometry loaded"));
return;
}
MeshGeometry->Transform(Transform, CenterOfTransform, Selection);
}
void UMeshDeformationComponent::Spherize(UMeshDeformationComponent *&MeshDeformationComponent, float SphereRadius /*= 100.0f*/, float FilterStrength /*= 1.0f*/, FVector SphereCenter /*= FVector::ZeroVector*/, USelectionSet *Selection /*= nullptr*/)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Spherize: No meshGeometry loaded"));
return;
}
MeshGeometry->Spherize(SphereRadius, FilterStrength, SphereCenter, Selection);
}
void UMeshDeformationComponent::Inflate(UMeshDeformationComponent *&MeshDeformationComponent, float Offset /*= 0.0f*/, USelectionSet *Selection /*= nullptr*/)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Spherize: No meshGeometry loaded"));
return;
}
MeshGeometry->Inflate(Offset, Selection);
}
void UMeshDeformationComponent::ScaleAlongAxis(UMeshDeformationComponent *&MeshDeformationComponent, FVector CenterOfScale /*= FVector::ZeroVector*/, FVector Axis /*= FVector::UpVector*/, float Scale /*= 1.0f*/, USelectionSet *Selection /*= nullptr*/)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Spherize: No meshGeometry loaded"));
return;
}
MeshGeometry->ScaleAlongAxis(CenterOfScale, Axis, Scale, Selection);
}
void UMeshDeformationComponent::RotateAroundAxis(UMeshDeformationComponent *&MeshDeformationComponent, FVector CenterOfRotation /*= FVector::ZeroVector*/, FVector Axis /*= FVector::UpVector*/, float AngleInDegrees /*= 0.0f*/, USelectionSet *Selection /*= nullptr*/)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Spherize: No meshGeometry loaded"));
return;
}
MeshGeometry->RotateAroundAxis(CenterOfRotation, Axis, AngleInDegrees, Selection);
}
void UMeshDeformationComponent::Lerp(
UMeshDeformationComponent *&MeshDeformationComponent,
UMeshDeformationComponent *TargetMeshDeformationComponent,
float Alpha /*= 0.0*/,
USelectionSet *Selection /*= nullptr*/)
{
MeshDeformationComponent = this;
if (!MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Lerp: No meshGeometry loaded"));
return;
}
if (!TargetMeshDeformationComponent) {
UE_LOG(LogTemp, Warning, TEXT("Lerp: No TargetMeshDeformationComponent"));
return;
}
if (!TargetMeshDeformationComponent->MeshGeometry) {
UE_LOG(LogTemp, Warning, TEXT("Lerp: TargetMeshDeformationComponent has no geometry"));
return;
}
MeshGeometry->Lerp(
TargetMeshDeformationComponent->MeshGeometry,
Alpha, Selection
);
}
| 37.031746
| 266
| 0.747857
|
normalvector
|
0ab0e4296c8448eed643b8b691d1ad461c57b101
| 677
|
cpp
|
C++
|
Arrays/Rearrange the array in alternating positive and negative items.cpp
|
akshay-thummar/DSA-Busted
|
8194411555d978bcf9bd66f9e0da5e502a94a493
|
[
"MIT"
] | 17
|
2021-12-03T14:29:01.000Z
|
2022-03-09T18:25:05.000Z
|
Arrays/Rearrange the array in alternating positive and negative items.cpp
|
riti2409/DSA-Busted
|
8194411555d978bcf9bd66f9e0da5e502a94a493
|
[
"MIT"
] | null | null | null |
Arrays/Rearrange the array in alternating positive and negative items.cpp
|
riti2409/DSA-Busted
|
8194411555d978bcf9bd66f9e0da5e502a94a493
|
[
"MIT"
] | 4
|
2022-01-29T14:03:48.000Z
|
2022-03-01T22:53:41.000Z
|
#include <bits/stdc++.h>
using namespace std;
void rearrange(int arr[], int n)
{
int i = -1, j = n;
while (i < j)
{
while(i <= n - 1 and arr[i] > 0)
i += 1;
while (j >= 0 and arr[j] < 0)
j -= 1;
if (i < j)
swap(arr[i], arr[j]);
}
if (i == 0 || i == n)
return;
int k = 0;
while (k < n && i < n)
{
swap(arr[k], arr[i]);
i = i + 1;
k = k + 2;
}
}
// Utility function to print an array
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
int main()
{
int arr[] = {2, 3, -4, -1, 6, -9};
int n = 6;
cout << "Given array is \n";
printArray(arr, n);
rearrange(arr, n);
return 0;
}
| 13.019231
| 37
| 0.472674
|
akshay-thummar
|
0aca5a38a4d748d628d59c2cdefe5d6ed8b86d93
| 6,578
|
hpp
|
C++
|
integrations/near/include/marlin/near/OnRampNear.hpp
|
marlinprotocol/OpenWeaver
|
7a8c668cccc933d652fabe8a141e702b8a0fd066
|
[
"MIT"
] | 60
|
2020-07-01T17:37:34.000Z
|
2022-02-16T03:56:55.000Z
|
integrations/near/include/marlin/near/OnRampNear.hpp
|
marlinpro/openweaver
|
0aca30fbda3121a8e507f48a52b718b5664a5bbc
|
[
"MIT"
] | 5
|
2020-10-12T05:17:49.000Z
|
2021-05-25T15:47:01.000Z
|
integrations/near/include/marlin/near/OnRampNear.hpp
|
marlinpro/openweaver
|
0aca30fbda3121a8e507f48a52b718b5664a5bbc
|
[
"MIT"
] | 18
|
2020-07-01T17:43:18.000Z
|
2022-01-09T14:29:08.000Z
|
#ifndef MARLIN_ONRAMP_NEAR_HPP
#define MARLIN_ONRAMP_NEAR_HPP
#include <marlin/multicast/DefaultMulticastClient.hpp>
#include <marlin/near/NearTransportFactory.hpp>
#include <marlin/near/NearTransport.hpp>
#include <cryptopp/blake2.h>
#include <libbase58.h>
#include <boost/filesystem.hpp>
#include <marlin/pubsub/attestation/SigAttester.hpp>
using namespace marlin::near;
using namespace marlin::core;
using namespace marlin::multicast;
using namespace marlin::pubsub;
namespace marlin {
namespace near {
class OnRampNear {
public:
DefaultMulticastClient<OnRampNear, SigAttester> multicastClient;
uint8_t static_sk[crypto_sign_SECRETKEYBYTES], static_pk[crypto_sign_PUBLICKEYBYTES]; // should be moved to DefaultMulticastClient and add a function there to sign a message.
NearTransportFactory<OnRampNear, OnRampNear> f;
std::unordered_set<NearTransport<OnRampNear>*> transport_set;
void handle_handshake(NearTransport<OnRampNear> &, core::Buffer &&message);
void handle_transaction(core::Buffer &&message);
void handle_block(core::Buffer &&message);
template<typename... Args>
OnRampNear(DefaultMulticastClientOptions clop, SocketAddress listen_addr, Args&&... args): multicastClient(clop, std::forward<Args>(args)...) {
multicastClient.delegate = this;
if(sodium_init() == -1) {
throw;
}
if(boost::filesystem::exists("./.marlin/keys/near_gateway")) {
std::ifstream sk("./.marlin/keys/near_gateway", std::ios::binary);
if(!sk.read((char *)static_sk, crypto_sign_SECRETKEYBYTES)) {
throw;
}
crypto_sign_ed25519_sk_to_pk(static_pk, static_sk);
} else {
crypto_sign_keypair(static_pk, static_sk);
boost::filesystem::create_directories("./.marlin/keys/");
std::ofstream sk("./.marlin/keys/near_gateway", std::ios::binary);
sk.write((char *)static_sk, crypto_sign_SECRETKEYBYTES);
}
char b58[65];
size_t sz = 65;
SPDLOG_DEBUG(
"PrivateKey: {} \n PublicKey: {}",
spdlog::to_hex(static_sk, static_sk + crypto_sign_SECRETKEYBYTES),
spdlog::to_hex(static_pk, static_pk + crypto_sign_PUBLICKEYBYTES)
);
if(b58enc(b58, &sz, static_pk, 32)) {
SPDLOG_INFO(
"Node identity: {}",
b58
);
} else {
SPDLOG_ERROR("Failed to create base 58 of public key.");
}
f.bind(listen_addr);
f.listen(*this);
}
void did_recv(NearTransport <OnRampNear> &transport, Buffer &&message) {
SPDLOG_DEBUG(
"Message received from Near: {} bytes: {}",
message.size(),
spdlog::to_hex(message.data(), message.data() + message.size())
);
SPDLOG_INFO(
"Message received from Near: {} bytes",
message.size()
);
if(message.data()[0] == 0x10 || message.data()[0] == 0x0) {
handle_handshake(transport, std::move(message));
} else if(message.data()[0] == 0xc) {
handle_transaction(std::move(message));
} else if(message.data()[0] == 0xb) {
handle_block(std::move(message));
} else if(message.data()[0] == 0xd) {
SPDLOG_DEBUG(
"This is a RoutedMessage"
);
} else {
SPDLOG_WARN(
"Unhandled: {}",
message.data()[0]
);
}
}
template<typename T> // TODO: Code smell, remove later
void did_recv(
DefaultMulticastClient<OnRampNear, SigAttester> &,
Buffer &&bytes [[maybe_unused]],
T,
uint16_t,
uint64_t
) {
SPDLOG_DEBUG(
"OnRampNear:: did_recv, forwarding message: {}",
spdlog::to_hex(bytes.data(), bytes.data() + bytes.size())
);
// for(auto iter = transport_set.begin(); iter != transport_set.end(); iter++) {
// Buffer buf(bytes.size());
// buf.write_unsafe(0, bytes.data(), bytes.size());
// (*iter)->send(std::move(buf));
// }
}
void did_send_message(NearTransport<OnRampNear> &, Buffer &&message [[maybe_unused]]) {
SPDLOG_DEBUG(
"Transport: Did send message: {} bytes",
// transport.src_addr.to_string(),
// transport.dst_addr.to_string(),
message.size()
);
}
void did_dial(NearTransport<OnRampNear> &) {
}
bool should_accept(SocketAddress const &) {
return true;
}
void did_subscribe(
DefaultMulticastClient<OnRampNear, SigAttester> &,
uint16_t
) {}
void did_unsubscribe(
DefaultMulticastClient<OnRampNear, SigAttester> &,
uint16_t
) {}
void did_close(NearTransport<OnRampNear> &transport, uint16_t) {
transport_set.erase(&transport);
}
void did_create_transport(NearTransport <OnRampNear> &transport) {
transport_set.insert(&transport);
transport.setup(this);
}
};
void OnRampNear::handle_transaction(core::Buffer &&message) {
SPDLOG_DEBUG(
"Handling transaction: {}",
spdlog::to_hex(message.data(), message.data() + message.size())
);
message.uncover_unsafe(4);
CryptoPP::BLAKE2b blake2b((uint)8);
blake2b.Update((uint8_t *)message.data(), message.size());
uint64_t message_id;
blake2b.TruncatedFinal((uint8_t *)&message_id, 8);
multicastClient.ps.send_message_on_channel(
1,
message_id,
message.data(),
message.size()
);
}
void OnRampNear::handle_block(core::Buffer &&message) {
SPDLOG_DEBUG("Handling block");
message.uncover_unsafe(4);
CryptoPP::BLAKE2b blake2b((uint)8);
blake2b.Update((uint8_t *)message.data(), message.size());
uint64_t message_id;
blake2b.TruncatedFinal((uint8_t *)&message_id, 8);
multicastClient.ps.send_message_on_channel(
0,
message_id,
message.data(),
message.size()
);
}
void OnRampNear::handle_handshake(NearTransport <OnRampNear> &transport, core::Buffer &&message) {
SPDLOG_DEBUG("Handshake replying");
uint8_t *buf = message.data();
uint32_t buf_size = message.size();
std::swap_ranges(buf + 9, buf + 42, buf + 42);
uint8_t near_key_offset = 42, gateway_key_offset = 9;
using namespace CryptoPP;
CryptoPP::SHA256 sha256;
uint8_t hashed_message[32];
int flag = std::memcmp(buf + near_key_offset, buf + gateway_key_offset, 33);
if(flag < 0) {
sha256.Update(buf + near_key_offset, 33);
sha256.Update(buf + gateway_key_offset, 33);
} else {
sha256.Update(buf + gateway_key_offset, 33);
sha256.Update(buf + near_key_offset, 33);
}
sha256.Update(buf + buf_size - 73, 8);
sha256.TruncatedFinal(hashed_message, 32);
uint8_t *near_node_signature = buf + buf_size - crypto_sign_BYTES;
if(crypto_sign_verify_detached(near_node_signature, hashed_message, 32, buf + near_key_offset + 1) != 0) {
SPDLOG_ERROR("Signature verification failed");
return;
} else {
SPDLOG_DEBUG("Signature verified successfully");
}
uint8_t *mySignature = buf + buf_size - 64;
crypto_sign_detached(mySignature, NULL, hashed_message, 32, static_sk);
message.uncover_unsafe(4);
transport.send(std::move(message));
}
} // near
} // marlin
#endif // MARLIN_ONRAMP_NEAR_HPP
| 27.991489
| 175
| 0.710702
|
marlinprotocol
|
0ad04d8b69dc66dd4d445976f266f906996e366d
| 14,363
|
cc
|
C++
|
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
|
fasShare/moxie-simple
|
9b21320f868ca1fe05ca5d39e70eb053d31155ee
|
[
"MIT"
] | 1
|
2018-09-27T09:10:11.000Z
|
2018-09-27T09:10:11.000Z
|
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
|
fasShare/moxie-simple
|
9b21320f868ca1fe05ca5d39e70eb053d31155ee
|
[
"MIT"
] | 1
|
2018-09-16T07:17:29.000Z
|
2018-09-16T07:17:29.000Z
|
example/Mcached/mraft/floyd/src/floyd_peer_thread.cc
|
fasShare/moxie-simple
|
9b21320f868ca1fe05ca5d39e70eb053d31155ee
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2015-present, Qihoo, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#include "floyd/src/floyd_peer_thread.h"
#include <google/protobuf/text_format.h>
#include <algorithm>
#include <climits>
#include <vector>
#include <string>
#include "slash/include/env.h"
#include "slash/include/slash_mutex.h"
#include "slash/include/xdebug.h"
#include "floyd/src/floyd_primary_thread.h"
#include "floyd/src/floyd_context.h"
#include "floyd/src/floyd_client_pool.h"
#include "floyd/src/raft_log.h"
#include "floyd/src/floyd.pb.h"
#include "floyd/src/logger.h"
#include "floyd/src/raft_meta.h"
#include "floyd/src/floyd_apply.h"
namespace floyd {
Peer::Peer(std::string server, PeersSet* peers, FloydContext* context, FloydPrimary* primary, RaftMeta* raft_meta,
RaftLog* raft_log, ClientPool* pool, FloydApply* apply, const Options& options, Logger* info_log)
: peer_addr_(server),
peers_(peers),
context_(context),
primary_(primary),
raft_meta_(raft_meta),
raft_log_(raft_log),
pool_(pool),
apply_(apply),
options_(options),
info_log_(info_log),
next_index_(1),
match_index_(0),
peer_last_op_time(0),
bg_thread_(1024 * 1024 * 256) {
next_index_ = raft_log_->GetLastLogIndex() + 1;
match_index_ = raft_meta_->GetLastApplied();
}
int Peer::Start() {
std::string name = "P" + std::to_string(options_.local_port) + ":" + peer_addr_.substr(peer_addr_.find(':'));
bg_thread_.set_thread_name(name);
LOGV(INFO_LEVEL, info_log_, "Peer::Start Start a peer thread to %s", peer_addr_.c_str());
return bg_thread_.StartThread();
}
Peer::~Peer() {
LOGV(INFO_LEVEL, info_log_, "Peer::~Peer peer thread %s exit", peer_addr_.c_str());
}
int Peer::Stop() {
return bg_thread_.StopThread();
}
bool Peer::CheckAndVote(uint64_t vote_term) {
if (context_->current_term != vote_term) {
return false;
}
return (++context_->vote_quorum) > (options_.members.size() / 2);
}
void Peer::UpdatePeerInfo() {
for (auto& pt : (*peers_)) {
pt.second->set_next_index(raft_log_->GetLastLogIndex() + 1);
pt.second->set_match_index(0);
}
}
void Peer::AddRequestVoteTask() {
/*
* int timer_queue_size, queue_size;
* bg_thread_.QueueSize(&timer_queue_size, &queue_size);
* LOGV(INFO_LEVEL, info_log_, "Peer::AddRequestVoteTask peer_addr %s timer_queue size %d queue_size %d",
* peer_addr_.c_str(),timer_queue_size, queue_size);
*/
bg_thread_.Schedule(&RequestVoteRPCWrapper, this);
}
void Peer::RequestVoteRPCWrapper(void *arg) {
reinterpret_cast<Peer*>(arg)->RequestVoteRPC();
}
void Peer::RequestVoteRPC() {
uint64_t last_log_term;
uint64_t last_log_index;
CmdRequest req;
{
slash::MutexLock l(&context_->global_mu);
raft_log_->GetLastLogTermAndIndex(&last_log_term, &last_log_index);
req.set_type(Type::kRequestVote);
CmdRequest_RequestVote* request_vote = req.mutable_request_vote();
request_vote->set_ip(options_.local_ip);
request_vote->set_port(options_.local_port);
request_vote->set_term(context_->current_term);
request_vote->set_last_log_term(last_log_term);
request_vote->set_last_log_index(last_log_index);
LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC server %s:%d Send RequestVoteRPC message to %s at term %d",
options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term);
}
CmdResponse res;
Status result = pool_->SendAndRecv(peer_addr_, req, &res);
if (!result.ok()) {
LOGV(DEBUG_LEVEL, info_log_, "Peer::RequestVoteRPC: RequestVote to %s failed %s",
peer_addr_.c_str(), result.ToString().c_str());
return;
}
{
slash::MutexLock l(&context_->global_mu);
if (!result.ok()) {
LOGV(WARN_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d SendAndRecv to %s failed %s",
options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), result.ToString().c_str());
return;
}
if (res.request_vote_res().term() > context_->current_term) {
// RequestVote fail, maybe opposite has larger term, or opposite has
// longer log. if opposite has larger term, this node will become follower
// otherwise we will do nothing
LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Become Follower, Candidate %s:%d vote request denied by %s,"
" request_vote_res.term()=%lu, current_term=%lu", options_.local_ip.c_str(), options_.local_port,
peer_addr_.c_str(), res.request_vote_res().term(), context_->current_term);
context_->BecomeFollower(res.request_vote_res().term());
raft_meta_->SetCurrentTerm(context_->current_term);
raft_meta_->SetVotedForIp(context_->voted_for_ip);
raft_meta_->SetVotedForPort(context_->voted_for_port);
return;
}
if (context_->role == Role::kCandidate) {
// kOk means RequestVote success, opposite vote for me
if (res.request_vote_res().vote_granted() == true) { // granted
LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d get vote from node %s at term %d",
options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term);
// However, we need check whether this vote is vote for old term
// we need ignore these type of vote
if (CheckAndVote(res.request_vote_res().term())) {
context_->BecomeLeader();
UpdatePeerInfo();
LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: %s:%d become leader at term %d",
options_.local_ip.c_str(), options_.local_port, context_->current_term);
primary_->AddTask(kHeartBeat, false);
}
} else {
LOGV(INFO_LEVEL, info_log_, "Peer::RequestVoteRPC: Candidate %s:%d deny vote from node %s at term %d, "
"transfer from candidate to follower",
options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), context_->current_term);
context_->BecomeFollower(res.request_vote_res().term());
raft_meta_->SetCurrentTerm(context_->current_term);
raft_meta_->SetVotedForIp(context_->voted_for_ip);
raft_meta_->SetVotedForPort(context_->voted_for_port);
}
} else if (context_->role == Role::kFollower) {
LOGV(INFO_LEVEL, info_log_, "Peer::RequestVotePPC: Server %s:%d have transformed to follower when doing RequestVoteRPC, "
"The leader is %s:%d, new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->leader_ip.c_str(),
context_->leader_port, context_->current_term);
} else if (context_->role == Role::kLeader) {
LOGV(INFO_LEVEL, info_log_, "Peer::RequestVotePPC: Server %s:%d is already a leader at term %lu, "
"get vote from node %s at term %d",
options_.local_ip.c_str(), options_.local_port, context_->current_term,
peer_addr_.c_str(), res.request_vote_res().term());
}
}
return;
}
uint64_t Peer::QuorumMatchIndex() {
std::vector<uint64_t> values;
std::map<std::string, Peer*>::iterator iter;
for (iter = peers_->begin(); iter != peers_->end(); iter++) {
if (iter->first == peer_addr_) {
values.push_back(match_index_);
continue;
}
values.push_back(iter->second->match_index());
}
LOGV(DEBUG_LEVEL, info_log_, "Peer::QuorumMatchIndex: Get peers match_index %d %d %d %d",
values[0], values[1], values[2], values[3]);
std::sort(values.begin(), values.end());
return values.at(values.size() / 2);
}
// only leader will call AdvanceCommitIndex
// follower only need set commit as leader's
void Peer::AdvanceLeaderCommitIndex() {
Entry entry;
uint64_t new_commit_index = QuorumMatchIndex();
if (context_->commit_index < new_commit_index) {
context_->commit_index = new_commit_index;
raft_meta_->SetCommitIndex(context_->commit_index);
}
return;
}
void Peer::AddAppendEntriesTask() {
/*
* int timer_queue_size, queue_size;
* bg_thread_.QueueSize(&timer_queue_size, &queue_size);
* LOGV(INFO_LEVEL, info_log_, "Peer::AddAppendEntriesTask peer_addr %s timer_queue size %d queue_size %d",
* peer_addr_.c_str(),timer_queue_size, queue_size);
*/
bg_thread_.Schedule(&AppendEntriesRPCWrapper, this);
}
void Peer::AppendEntriesRPCWrapper(void *arg) {
reinterpret_cast<Peer*>(arg)->AppendEntriesRPC();
}
void Peer::AppendEntriesRPC() {
uint64_t prev_log_index = 0;
uint64_t num_entries = 0;
uint64_t prev_log_term = 0;
uint64_t last_log_index = 0;
uint64_t current_term = 0;
CmdRequest req;
CmdRequest_AppendEntries* append_entries = req.mutable_append_entries();
{
slash::MutexLock l(&context_->global_mu);
prev_log_index = next_index_ - 1;
last_log_index = raft_log_->GetLastLogIndex();
/*
* LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntriesRPC: next_index_ %d last_log_index %d peer_last_op_time %lu nowmicros %lu",
* next_index_.load(), last_log_index, peer_last_op_time, slash::NowMicros());
*/
if (next_index_ > last_log_index && peer_last_op_time + options_.heartbeat_us > slash::NowMicros()) {
return;
}
peer_last_op_time = slash::NowMicros();
if (prev_log_index != 0) {
Entry entry;
if (raft_log_->GetEntry(prev_log_index, &entry) != 0) {
LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntriesRPC: Get my(%s:%d) Entry index %llu "
"not found", options_.local_ip.c_str(), options_.local_port, prev_log_index);
} else {
prev_log_term = entry.term();
}
}
current_term = context_->current_term;
req.set_type(Type::kAppendEntries);
append_entries->set_ip(options_.local_ip);
append_entries->set_port(options_.local_port);
append_entries->set_term(current_term);
append_entries->set_prev_log_index(prev_log_index);
append_entries->set_prev_log_term(prev_log_term);
append_entries->set_leader_commit(context_->commit_index);
}
Entry *tmp_entry = new Entry();
for (uint64_t index = next_index_; index <= last_log_index; index++) {
if (raft_log_->GetEntry(index, tmp_entry) == 0) {
// TODO(ba0tiao) how to avoid memory copy here
Entry *entry = append_entries->add_entries();
*entry = *tmp_entry;
} else {
LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntriesRPC: peer_addr %s can't get Entry "
"from raft_log, index %lld", peer_addr_.c_str(), index);
break;
}
num_entries++;
if (num_entries >= options_.append_entries_count_once
|| (uint64_t)append_entries->ByteSize() >= options_.append_entries_size_once) {
break;
}
}
delete tmp_entry;
LOGV(DEBUG_LEVEL, info_log_, "Peer::AppendEntriesRPC: peer_addr(%s)'s next_index_ %llu, my last_log_index %llu"
" AppendEntriesRPC will send %d iterm", peer_addr_.c_str(), next_index_.load(), last_log_index, num_entries);
// if the AppendEntries don't contain any log item
if (num_entries == 0) {
LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntryRpc server %s:%d Send pingpong appendEntries message to %s at term %d",
options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), current_term);
}
CmdResponse res;
Status result = pool_->SendAndRecv(peer_addr_, req, &res);
{
slash::MutexLock l(&context_->global_mu);
if (!result.ok()) {
LOGV(WARN_LEVEL, info_log_, "Peer::AppendEntries: Leader %s:%d SendAndRecv to %s failed, result is %s\n",
options_.local_ip.c_str(), options_.local_port, peer_addr_.c_str(), result.ToString().c_str());
return;
}
// here we may get a larger term, and transfer to follower
// so we need to judge the role here
if (context_->role == Role::kLeader) {
/*
* receiver has higer term than myself, so turn from candidate to follower
*/
if (res.append_entries_res().term() > context_->current_term) {
LOGV(INFO_LEVEL, info_log_, "Peer::AppendEntriesRPC: %s:%d Transfer from Leader to Follower since get A larger term"
"from peer %s, local term is %d, peer term is %d", options_.local_ip.c_str(), options_.local_port,
peer_addr_.c_str(), context_->current_term, res.append_entries_res().term());
context_->BecomeFollower(res.append_entries_res().term());
raft_meta_->SetCurrentTerm(context_->current_term);
raft_meta_->SetVotedForIp(context_->voted_for_ip);
raft_meta_->SetVotedForPort(context_->voted_for_port);
} else if (res.append_entries_res().success() == true) {
if (num_entries > 0) {
match_index_ = prev_log_index + num_entries;
// only log entries from the leader's current term are committed
// by counting replicas
if (append_entries->entries(num_entries - 1).term() == context_->current_term) {
AdvanceLeaderCommitIndex();
apply_->ScheduleApply();
}
next_index_ = prev_log_index + num_entries + 1;
}
} else {
LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: peer_addr %s Send AppEntriesRPC failed,"
"peer's last_log_index %lu, peer's next_index_ %lu",
peer_addr_.c_str(), res.append_entries_res().last_log_index(), next_index_.load());
uint64_t adjust_index = std::min(res.append_entries_res().last_log_index() + 1,
next_index_ - 1);
if (adjust_index > 0) {
// Prev log don't match, so we retry with more prev one according to
// response
next_index_ = adjust_index;
LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: peer_addr %s Adjust peer next_index_, Now next_index_ is %lu",
peer_addr_.c_str(), next_index_.load());
AddAppendEntriesTask();
}
}
} else if (context_->role == Role::kFollower) {
LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: Server %s:%d have transformed to follower when doing AppEntriesRPC, "
"new leader is %s:%d, new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->leader_ip.c_str(),
context_->leader_port, context_->current_term);
} else if (context_->role == Role::kCandidate) {
LOGV(INFO_LEVEL, info_log_, "Peer::AppEntriesRPC: Server %s:%d have transformed to candidate when doing AppEntriesRPC, "
"new term is %lu", options_.local_ip.c_str(), options_.local_port, context_->current_term);
}
}
return;
}
} // namespace floyd
| 40.803977
| 128
| 0.695537
|
fasShare
|
bd5f7e448e051e5da5b259abf12f1f6241da3b02
| 1,471
|
cpp
|
C++
|
src/ros_can_nodes/src/CANSendQueue.cpp
|
bluesat/ros_can_nodes
|
879114dc082c63c5d743e87a6f29e15ca6728156
|
[
"BSD-3-Clause"
] | 1
|
2020-07-13T02:15:23.000Z
|
2020-07-13T02:15:23.000Z
|
src/ros_can_nodes/src/CANSendQueue.cpp
|
bluesat/ros_can_nodes
|
879114dc082c63c5d743e87a6f29e15ca6728156
|
[
"BSD-3-Clause"
] | 3
|
2018-12-04T21:12:15.000Z
|
2019-09-08T05:54:48.000Z
|
src/ros_can_nodes/src/CANSendQueue.cpp
|
bluesat/ros_can_nodes
|
879114dc082c63c5d743e87a6f29e15ca6728156
|
[
"BSD-3-Clause"
] | null | null | null |
#include "CANSendQueue.hpp"
#include "CANHelpers.hpp"
#include <mutex>
#include <condition_variable>
#include <thread>
#include <ros/console.h>
//#define DEBUG
CANSendQueue& CANSendQueue::instance() {
static CANSendQueue instance;
return instance;
}
void CANSendQueue::push(const can_frame& frame) {
std::unique_lock<std::mutex> lock{mutex};
q.push(frame);
lock.unlock();
cv.notify_one();
}
CANSendQueue::CANSendQueue() {
std::thread sender{[this]() {
while (true) {
std::unique_lock<std::mutex> lock{mutex};
cv.wait(lock, [this](){ return q.size() > 0; });
const auto frame = q.front();
q.pop();
lock.unlock();
#ifdef DEBUG
// debug exit condition
if (frame.__res0 == 8) {
ROS_INFO("exit condition");
break;
}
char str[1000] = {0};
sprintf(str, "Sending header = %#08X, length = %d, data:", frame.can_id, frame.can_dlc);
for (int i = 0; i < frame.can_dlc;++i) {
sprintf(str, "%s %02x", str, frame.data[i]);
}
ROS_DEBUG("%s", str);
#endif // DEBUG
// CAN port is assumed to be open
if (CANHelpers::send_frame(frame) < 0) {
ROS_ERROR("send failed: frame could not be sent");
}
}
}};
sender.detach();
}
| 24.516667
| 100
| 0.511217
|
bluesat
|
bd5f9fe5cad422e6b19dcfafae452e65e41f1db0
| 641
|
cpp
|
C++
|
leetcode/1318.cpp
|
raghavxk/Competitive-Programming
|
131c9fffc92b638834c33e0ee0933adcd1e0d92a
|
[
"MIT"
] | 1
|
2021-09-29T13:10:03.000Z
|
2021-09-29T13:10:03.000Z
|
leetcode/1318.cpp
|
raghavxk/Competitive-Programming
|
131c9fffc92b638834c33e0ee0933adcd1e0d92a
|
[
"MIT"
] | null | null | null |
leetcode/1318.cpp
|
raghavxk/Competitive-Programming
|
131c9fffc92b638834c33e0ee0933adcd1e0d92a
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int minFlips(int a, int b, int c) {
int flips=0;
for(int i=0;i<32;++i){
bool aCheck=(a&(1<<i));
bool bCheck=(b&(1<<i));
bool aOrB= (aCheck | bCheck);
bool cCheck=(c&(1<<i));
if(aOrB!=cCheck){
if(cCheck==true){
++flips;
}
else{
if(aCheck==true && bCheck==true)
flips+=2;
else
++flips;
}
}
}
return flips;
}
};
| 23.740741
| 52
| 0.316693
|
raghavxk
|
bd611ede16ba1b25fefb73a03009e0673751893e
| 6,975
|
hpp
|
C++
|
tools/IYFEditor/include/assetImport/ConverterState.hpp
|
manvis/IYFEngine
|
741a8d0dcc9b3e3ff8a8adb92850633523516604
|
[
"BSD-3-Clause"
] | 5
|
2018-07-03T17:05:43.000Z
|
2020-02-03T00:23:46.000Z
|
tools/IYFEditor/include/assetImport/ConverterState.hpp
|
manvis/IYFEngine
|
741a8d0dcc9b3e3ff8a8adb92850633523516604
|
[
"BSD-3-Clause"
] | null | null | null |
tools/IYFEditor/include/assetImport/ConverterState.hpp
|
manvis/IYFEngine
|
741a8d0dcc9b3e3ff8a8adb92850633523516604
|
[
"BSD-3-Clause"
] | null | null | null |
// The IYFEngine
//
// Copyright (C) 2015-2018, Manvydas Šliamka
//
// 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.
#ifndef IYF_CONVERTER_STATE_HPP
#define IYF_CONVERTER_STATE_HPP
#include "core/Constants.hpp"
#include "core/Platform.hpp"
#include "io/interfaces/TextSerializable.hpp"
#include "utilities/NonCopyable.hpp"
#include "assetImport/ImportedAssetData.hpp"
namespace iyf::editor {
class Converter;
class InternalConverterState {
public:
InternalConverterState(const Converter* converter) : converter(converter) {
if (converter == nullptr) {
throw std::logic_error("Converter cannot be nullptr");
}
}
virtual ~InternalConverterState() = 0;
const Converter* getConverter() const {
return converter;
}
private:
const Converter* converter;
};
inline InternalConverterState::~InternalConverterState() {}
class ConverterState : private NonCopyable, public TextSerializable {
public:
ConverterState(PlatformIdentifier platformID, std::unique_ptr<InternalConverterState> internalState, const Path& sourcePath, FileHash sourceFileHash)
: sourcePath(sourcePath), sourceFileHash(sourceFileHash), conversionComplete(false), debugOutputRequested(false), systemAsset(false),
platformID(platformID), internalState(std::move(internalState)) {}
/// If true, this represents a system asset
inline bool isSystemAsset() const {
return systemAsset;
}
/// \warning This should only be used internally (e.g., in SystemAssetPacker). Do not expose this in the editor
inline void setSystemAsset(bool systemAsset) {
this->systemAsset = systemAsset;
}
inline const std::vector<std::string>& getTags() const {
return tags;
}
inline std::vector<std::string>& getTags() {
return tags;
}
/// If true, some converters may export additional debug data. This parameter is not serialized
inline void setDebugOutputRequested(bool requested) {
debugOutputRequested = requested;
}
/// If true, some converters may export additional debug data. This parameter is not serialized
inline bool isDebugOutputRequested() const {
return debugOutputRequested;
}
/// \warning This value should only be modified by the ConverterManager, tests or in VERY special cases.
inline void setConversionComplete(bool state) {
conversionComplete = state;
}
inline bool isConversionComplete() const {
return conversionComplete;
}
inline const InternalConverterState* getInternalState() const {
return internalState.get();
}
inline InternalConverterState* getInternalState() {
return internalState.get();
}
inline const Path& getSourceFilePath() const {
return sourcePath;
}
virtual AssetType getType() const = 0;
inline const std::vector<ImportedAssetData>& getImportedAssets() const {
return importedAssets;
}
/// \warning The contents of this vector should only be modified by the ConverterManager, the Converters or in VERY special cases.
inline std::vector<ImportedAssetData>& getImportedAssets() {
return importedAssets;
}
inline FileHash getSourceFileHash() const {
return sourceFileHash;
}
inline PlatformIdentifier getPlatformIdentifier() const {
return platformID;
}
/// Derived classes should not create a root object in serializeJSON()
virtual bool makesJSONRoot() const final override {
return false;
}
/// Serializes the conversion settings stored in this ConverterState instance.
virtual void serializeJSON(PrettyStringWriter& pw) const final override;
/// Deserialized the conversion settings from the provided JSON object and into this one
virtual void deserializeJSON(JSONObject& jo) final override;
/// Obtain the preferred version for the serialized data. Derived classes should increment this whenever their
/// serialization format changes. If an older format is provided, reasonable defaults should be set for data
/// that is not present in it.
virtual std::uint64_t getLatestSerializedDataVersion() const = 0;
protected:
virtual void serializeJSONImpl(PrettyStringWriter& pw, std::uint64_t version) const = 0;
virtual void deserializeJSONImpl(JSONObject& jo, std::uint64_t version) = 0;
private:
std::vector<ImportedAssetData> importedAssets;
std::vector<std::string> tags;
Path sourcePath;
FileHash sourceFileHash;
bool conversionComplete;
bool debugOutputRequested;
bool systemAsset;
PlatformIdentifier platformID;
/// The internal state of the importer. Calling Converter::initializeConverter() typically loads the file
/// into memory (to build initial metadata, importer settings, etc.). The contents of the said file can be
/// stored in this variable and reused in Converter::convert() to avoid duplicate work.
///
/// Moreover, by using an opaque pointer to a virtual base class, we allow the converters to safely store the
/// state of external helper libraries while keeping their includes confined to the converters' cpp files.
///
/// \warning This may depend on the context, Engine version, OS version, etc. and MUST NEVER BE SERIALIZED
std::unique_ptr<InternalConverterState> internalState;
};
}
#endif // IYF_CONVERTER_STATE_HPP
| 39.40678
| 153
| 0.723441
|
manvis
|
bd6498ebcf6b3862846ab9fbc7cd8e06f8914bc6
| 1,887
|
cpp
|
C++
|
test/test.cpp
|
ern0/tabletenniscounter
|
1157b6882978e3af8e6769d3a1cefc2db1fe446d
|
[
"MIT"
] | null | null | null |
test/test.cpp
|
ern0/tabletenniscounter
|
1157b6882978e3af8e6769d3a1cefc2db1fe446d
|
[
"MIT"
] | null | null | null |
test/test.cpp
|
ern0/tabletenniscounter
|
1157b6882978e3af8e6769d3a1cefc2db1fe446d
|
[
"MIT"
] | null | null | null |
# include <stdio.h>
enum Beep { B_IDLE1 = 1, B_IDLE2 = 2 };
int score[2];
char gameMode;
char firstPlayer;
# include "ttc_selectIdleBeep.cpp"
int pass = 0;
int fail = 0;
int total = 0;
void check(char gm, int sc0, int sc1, int res) {
gameMode = gm;
score[0] = sc0;
score[1] = sc1;
int r = selectIdleBeep();
printf(
"%s GM=%d SC=%02d:%02d R=%d -> %d \n"
,( r == res ? ". " : "F ")
,gm,sc0,sc1,res,r
);
total++;
if (r == res) {
pass++;
} else {
fail++;
}
} // checkfp()
void test21low() {
check(21,0,0, B_IDLE1);
check(21,1,0, B_IDLE1);
check(21,0,1, B_IDLE1);
check(21,4,0, B_IDLE1);
check(21,0,4, B_IDLE1);
check(21,5,0, B_IDLE2);
check(21,3,2, B_IDLE2);
check(21,5,4, B_IDLE2);
check(21,6,4, B_IDLE1);
check(21,14,0, B_IDLE1);
check(21,15,0, B_IDLE2);
check(21,16,0, B_IDLE2);
check(21,15,5, B_IDLE1);
check(21,15,10, B_IDLE2);
check(21,15,15, B_IDLE1);
check(21,20,15, B_IDLE2);
check(21,20,20, B_IDLE1);
}
void test11low() {
check(11,0,0, B_IDLE1);
check(11,1,0, B_IDLE1);
check(11,0,1, B_IDLE1);
check(11,3,0, B_IDLE2);
check(11,0,3, B_IDLE2);
check(11,2,1, B_IDLE2);
check(11,1,2, B_IDLE2);
check(11,3,2, B_IDLE2);
check(11,4,2, B_IDLE1);
check(11,9,0, B_IDLE2);
check(11,9,3, B_IDLE1);
check(11,9,6, B_IDLE2);
check(11,9,8, B_IDLE2);
check(11,9,9, B_IDLE1);
}
void test21high() {
check(21,20,20, B_IDLE1);
check(21,21,20, B_IDLE2);
check(21,21,21, B_IDLE1);
check(21,22,21, B_IDLE2);
check(21,22,22, B_IDLE1);
}
void test11high() {
check(11,9,9, B_IDLE1);
check(11,10,9, B_IDLE1);
check(11,10,10, B_IDLE1);
check(11,11,10, B_IDLE2);
check(11,11,11, B_IDLE1);
check(11,12,11, B_IDLE2);
}
int main() {
test21low();
test11low();
test21high();
test11high();
printf(
"--------------------------------\n"
" total=%d passed=%d failed=%d \n"
,total,pass,fail
);
return 0;
}
| 14.97619
| 48
| 0.595654
|
ern0
|
bd67a931654ebe222ab68bf555e3de5159fcec5a
| 1,315
|
cpp
|
C++
|
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
|
wmaxey/libcudacxx
|
f6a1e6067d0ccaae1c2717aef751622033481590
|
[
"Apache-2.0"
] | null | null | null |
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
|
wmaxey/libcudacxx
|
f6a1e6067d0ccaae1c2717aef751622033481590
|
[
"Apache-2.0"
] | null | null | null |
.upstream-tests/test/std/atomics/atomics.order/memory_order.pass.cpp
|
wmaxey/libcudacxx
|
f6a1e6067d0ccaae1c2717aef751622033481590
|
[
"Apache-2.0"
] | 1
|
2021-11-12T21:19:28.000Z
|
2021-11-12T21:19:28.000Z
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// UNSUPPORTED: libcpp-has-no-threads, pre-sm-60
// UNSUPPORTED: windows && pre-sm-70
// <cuda/std/atomic>
// typedef enum memory_order
// {
// memory_order_relaxed, memory_order_consume, memory_order_acquire,
// memory_order_release, memory_order_acq_rel, memory_order_seq_cst
// } memory_order;
#include <cuda/std/atomic>
#include <cuda/std/cassert>
#include "test_macros.h"
int main(int, char**)
{
assert(static_cast<int>(cuda::std::memory_order_relaxed) == 0);
assert(static_cast<int>(cuda::std::memory_order_consume) == 1);
assert(static_cast<int>(cuda::std::memory_order_acquire) == 2);
assert(static_cast<int>(cuda::std::memory_order_release) == 3);
assert(static_cast<int>(cuda::std::memory_order_acq_rel) == 4);
assert(static_cast<int>(cuda::std::memory_order_seq_cst) == 5);
cuda::std::memory_order o = cuda::std::memory_order_seq_cst;
assert(static_cast<int>(o) == 5);
return 0;
}
| 33.717949
| 80
| 0.624335
|
wmaxey
|
bd717254f479e9cdd051a705e97758ca777a24b8
| 9,223
|
hpp
|
C++
|
include/targets/LPC81x/lpc81x_pin.hpp
|
hparracho/Xarmlib
|
4a7c08fde796b3487845c3a4beecc21ceafde67c
|
[
"MIT"
] | 3
|
2018-03-21T18:04:42.000Z
|
2018-05-30T09:27:29.000Z
|
include/targets/LPC81x/lpc81x_pin.hpp
|
hparracho/Xarmlib
|
4a7c08fde796b3487845c3a4beecc21ceafde67c
|
[
"MIT"
] | 2
|
2018-06-28T14:39:19.000Z
|
2018-07-04T02:07:02.000Z
|
include/targets/LPC81x/lpc81x_pin.hpp
|
hparracho/Xarmlib
|
4a7c08fde796b3487845c3a4beecc21ceafde67c
|
[
"MIT"
] | 5
|
2018-05-24T10:59:32.000Z
|
2021-08-06T15:57:58.000Z
|
// ----------------------------------------------------------------------------
// @file lpc81x_pin.hpp
// @brief NXP LPC81x pin class.
// @date 28 February 2019
// ----------------------------------------------------------------------------
//
// Xarmlib 0.1.0 - https://github.com/hparracho/Xarmlib
// Copyright (c) 2018 Helder Parracho (hparracho@gmail.com)
//
// See README.md file for additional credits and acknowledgments.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// ----------------------------------------------------------------------------
#ifndef __XARMLIB_TARGETS_LPC81X_PIN_HPP
#define __XARMLIB_TARGETS_LPC81X_PIN_HPP
#include "targets/LPC81x/lpc81x_cmsis.hpp"
#include "core/target_specs.hpp"
#include <array>
#include <cassert>
namespace xarmlib
{
namespace targets
{
namespace lpc81x
{
class PinDriver
{
public:
// --------------------------------------------------------------------
// PUBLIC DEFINITIONS
// --------------------------------------------------------------------
// Pin names according to the target package
enum class Name
{
// The following pins are present in all packages
p0_0 = 0,
p0_1,
p0_2,
p0_3,
p0_4,
p0_5,
#if (TARGET_PACKAGE_PIN_COUNT >= 16)
// The following pins are only present in
// TSSOP16 / XSON16 / SO20 / TSSOP20 packages
p0_6,
p0_7,
p0_8,
p0_9,
p0_10,
p0_11,
p0_12,
p0_13,
#endif // (TARGET_PACKAGE_PIN_COUNT >= 16)
#if (TARGET_PACKAGE_PIN_COUNT == 20)
// The following pins are only present in
// SO20 / TSSOP20 packages
p0_14,
p0_15,
p0_16,
p0_17,
#endif // (TARGET_PACKAGE_PIN_COUNT == 20)
// Not connected
nc
};
// Function modes (defined to map the PIO register directly)
enum class FunctionMode
{
hiz = (0 << 3),
pull_down = (1 << 3),
pull_up = (2 << 3),
repeater = (3 << 3)
};
// Input hysteresis (defined to map the PIO register directly)
enum class InputHysteresis
{
disable = (0 << 5),
enable = (1 << 5)
};
// Input invert (defined to map the PIO register directly)
enum class InputInvert
{
normal = (0 << 6),
inverted = (1 << 6)
};
// I2C mode (defined to map the PIO register directly)
enum class I2cMode
{
standard_fast_i2c = (0 << 8),
standard_gpio = (1 << 8),
fast_plus_i2c = (2 << 8)
};
// Open-drain mode (defined to map the PIO register directly)
enum class OpenDrain
{
disable = (0 << 10),
enable = (1 << 10)
};
// Input filter samples (defined to map the PIO register directly)
enum class InputFilter
{
bypass = (0 << 11),
clocks_1_clkdiv0 = (1 << 11) | (0 << 13),
clocks_1_clkdiv1 = (1 << 11) | (1 << 13),
clocks_1_clkdiv2 = (1 << 11) | (2 << 13),
clocks_1_clkdiv3 = (1 << 11) | (3 << 13),
clocks_1_clkdiv4 = (1 << 11) | (4 << 13),
clocks_1_clkdiv5 = (1 << 11) | (5 << 13),
clocks_1_clkdiv6 = (1 << 11) | (6 << 13),
clocks_2_clkdiv0 = (2 << 11) | (0 << 13),
clocks_2_clkdiv1 = (2 << 11) | (1 << 13),
clocks_2_clkdiv2 = (2 << 11) | (2 << 13),
clocks_2_clkdiv3 = (2 << 11) | (3 << 13),
clocks_2_clkdiv4 = (2 << 11) | (4 << 13),
clocks_2_clkdiv5 = (2 << 11) | (5 << 13),
clocks_2_clkdiv6 = (2 << 11) | (6 << 13),
clocks_3_clkdiv0 = (3 << 11) | (0 << 13),
clocks_3_clkdiv1 = (3 << 11) | (1 << 13),
clocks_3_clkdiv2 = (3 << 11) | (2 << 13),
clocks_3_clkdiv3 = (3 << 11) | (3 << 13),
clocks_3_clkdiv4 = (3 << 11) | (4 << 13),
clocks_3_clkdiv5 = (3 << 11) | (5 << 13),
clocks_3_clkdiv6 = (3 << 11) | (6 << 13)
};
// --------------------------------------------------------------------
// PUBLIC MEMBER FUNCTIONS
// --------------------------------------------------------------------
// Set mode of normal pins
static void set_mode(const Name pin_name, const FunctionMode function_mode,
const OpenDrain open_drain = OpenDrain::disable,
const InputFilter input_filter = InputFilter::bypass,
const InputInvert input_invert = InputInvert::normal,
const InputHysteresis input_hysteresis = InputHysteresis::enable)
{
// Exclude NC
assert(pin_name != Name::nc);
#if (TARGET_PACKAGE_PIN_COUNT >= 16)
// Exclude true open-drain pins
assert(pin_name != Name::p0_10 && pin_name != Name::p0_11);
#endif
const int32_t pin_index = m_pin_number_to_iocon[static_cast<int32_t>(pin_name)];
LPC_IOCON->PIO[pin_index] = static_cast<uint32_t>(function_mode)
| static_cast<uint32_t>(input_hysteresis)
| static_cast<uint32_t>(input_invert)
| static_cast<uint32_t>(open_drain)
| (1 << 7) // RESERVED
| static_cast<uint32_t>(input_filter);
}
#if (TARGET_PACKAGE_PIN_COUNT >= 16)
// Set mode of true open-drain pins (only available on P0_10 and P0_11)
static void set_mode(const Name pin_name, const I2cMode i2c_mode,
const InputFilter input_filter,
const InputInvert input_invert)
{
// Available only on true open-drain pins
assert(pin_name == Name::p0_10 || pin_name == Name::p0_11);
const int32_t pin_index = m_pin_number_to_iocon[static_cast<int32_t>(pin_name)];
LPC_IOCON->PIO[pin_index] = static_cast<uint32_t>(input_invert)
| (1 << 7) // RESERVED
| static_cast<uint32_t>(i2c_mode)
| static_cast<uint32_t>(input_filter);
}
#endif
private:
// --------------------------------------------------------------------
// PRIVATE DEFINITIONS
// --------------------------------------------------------------------
// IOCON pin values
static constexpr std::array<uint8_t, TARGET_GPIO_COUNT> m_pin_number_to_iocon
{
// The following pins are present in all packages
// PORT0
0x11, // p0.0
0x0b, // p0.1
0x06, // p0.2
0x05, // p0.3
0x04, // p0.4
0x03, // p0.5
#if (TARGET_PACKAGE_PIN_COUNT >= 16)
// The following pins are only present in
// TSSOP16 / XSON16 / SO20 / TSSOP20 packages
0x10, // p0.6
0x0f, // p0.7
0x0e, // p0.8
0x0d, // p0.9
0x08, // p0.10
0x07, // p0.11
0x02, // p0.12
0x01, // p0.13
#endif // (TARGET_PACKAGE_PIN_COUNT >= 16)
#if (TARGET_PACKAGE_PIN_COUNT == 20)
// The following pins are only present in
// SO20 / TSSOP20 packages
0x12, // p0.14
0x0a, // p0.15
0x09, // p0.16
0x00 // p0.17
#endif // (TARGET_PACKAGE_PIN_COUNT == 20)
};
};
} // namespace lpc81x
} // namespace targets
} // namespace xarmlib
#endif // __XARMLIB_TARGETS_LPC81X_PIN_HPP
| 35.748062
| 115
| 0.479996
|
hparracho
|
bd75be9438489717135ee58ddca13deac6e3e5ae
| 444
|
cpp
|
C++
|
Diversos trabalhos/Matriz/novo vetor.cpp
|
ewertonpugliesi/Trabalhos-em-C-C--
|
fd6400ff1621ac00907adc531ac7ad38121c532c
|
[
"MIT"
] | null | null | null |
Diversos trabalhos/Matriz/novo vetor.cpp
|
ewertonpugliesi/Trabalhos-em-C-C--
|
fd6400ff1621ac00907adc531ac7ad38121c532c
|
[
"MIT"
] | null | null | null |
Diversos trabalhos/Matriz/novo vetor.cpp
|
ewertonpugliesi/Trabalhos-em-C-C--
|
fd6400ff1621ac00907adc531ac7ad38121c532c
|
[
"MIT"
] | null | null | null |
//Escrever um novo vetor,atraves de dois outros,mutiplicando valores de mesmo indice,
#include<stdio.h>
#include<conio.h>
main()
{
int cont,num[10],num2[10],resul[10];
for (cont=0 ; cont<=9 ; cont++)
{
printf("Digite um valor ");
scanf("%i",&num[10]);
}
for(cont=0; cont<=9 ; cont++)
{
printf("Digite um outro valor ");
scanf("%i",&num2[10]);
}
for(cont=0 ; cont<=9 ; cont++)
{
resul[10]=num[cont]*num2[cont];
printf("%i",&resul);
}
getch();
}
| 18.5
| 85
| 0.632883
|
ewertonpugliesi
|
bd7b938212717ab6beed501a09b3357878f69e54
| 22
|
cpp
|
C++
|
lib/StarAlign/starAlign.cpp
|
AndreiDiaconu97/tracket
|
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
|
[
"MIT"
] | null | null | null |
lib/StarAlign/starAlign.cpp
|
AndreiDiaconu97/tracket
|
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
|
[
"MIT"
] | null | null | null |
lib/StarAlign/starAlign.cpp
|
AndreiDiaconu97/tracket
|
10c680b99d8d37212f6ad1f2d28e9279f93c04a7
|
[
"MIT"
] | null | null | null |
#include "starAlign.h"
| 22
| 22
| 0.772727
|
AndreiDiaconu97
|
bd83c41cb6e725f59625eb34c8fce014d1f3f841
| 10,669
|
cpp
|
C++
|
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
|
ktotheoz/pixellight
|
43a661e762034054b47766d7e38d94baf22d2038
|
[
"MIT"
] | 83
|
2015-01-08T15:06:14.000Z
|
2021-07-20T17:07:00.000Z
|
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
|
PixelLightFoundation/pixellight
|
43a661e762034054b47766d7e38d94baf22d2038
|
[
"MIT"
] | 27
|
2019-06-18T06:46:07.000Z
|
2020-02-02T11:11:28.000Z
|
Base/PLRenderer/src/Renderer/ProgramGenerator.cpp
|
naetherm/PixelLight
|
d7666f5b49020334cbb5debbee11030f34cced56
|
[
"MIT"
] | 40
|
2015-02-25T18:24:34.000Z
|
2021-03-06T09:01:48.000Z
|
/*********************************************************\
* File: ProgramGenerator.cpp *
*
* Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/)
*
* This file is part of PixelLight.
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "PLRenderer/Renderer/Renderer.h"
#include "PLRenderer/Renderer/Program.h"
#include "PLRenderer/Renderer/VertexShader.h"
#include "PLRenderer/Renderer/FragmentShader.h"
#include "PLRenderer/Renderer/ShaderLanguage.h"
#include "PLRenderer/Renderer/ProgramGenerator.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
using namespace PLCore;
namespace PLRenderer {
//[-------------------------------------------------------]
//[ Public functions ]
//[-------------------------------------------------------]
/**
* @brief
* Constructor
*/
ProgramGenerator::ProgramGenerator(Renderer &cRenderer, const String &sShaderLanguage, const String &sVertexShader, const String &sVertexShaderProfile,
const String &sFragmentShader, const String &sFragmentShaderProfile) :
EventHandlerDirty(&ProgramGenerator::OnDirty, this),
m_pRenderer(&cRenderer),
m_sShaderLanguage(sShaderLanguage),
m_sVertexShader(sVertexShader),
m_sVertexShaderProfile(sVertexShaderProfile),
m_sFragmentShader(sFragmentShader),
m_sFragmentShaderProfile(sFragmentShaderProfile)
{
}
/**
* @brief
* Destructor
*/
ProgramGenerator::~ProgramGenerator()
{
// Clear the cache of the program generator
ClearCache();
}
/**
* @brief
* Returns a program
*/
ProgramGenerator::GeneratedProgram *ProgramGenerator::GetProgram(const Flags &cFlags)
{
// Get the unique vertex shader and fragment shader ID's, we're taking the flags for this :D
const uint32 nVertexShaderID = cFlags.GetVertexShaderFlags();
const uint32 nFragmentShaderID = cFlags.GetFragmentShaderFlags();
// Combine the two ID's into an unique 64 bit integer we can use to reference the linked program
const uint64 nProgramID = nVertexShaderID + static_cast<uint64>(static_cast<uint64>(nFragmentShaderID)<<32);
// Is there already a generated program with the requested flags?
GeneratedProgram *pGeneratedProgram = m_mapPrograms.Get(nProgramID);
if (!pGeneratedProgram) {
// Is there already a vertex shader with the requested flags?
VertexShader *pVertexShader = m_mapVertexShaders.Get(nVertexShaderID);
if (!pVertexShader) {
// Get the shader language to use
ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage);
if (pShaderLanguage) {
// Create a new vertex shader instance
pVertexShader = pShaderLanguage->CreateVertexShader();
if (pVertexShader) {
String sSourceCode;
// When using GLSL, the profile is the GLSL version to use - #version must occur before any other statement in the program!
if (m_sShaderLanguage == "GLSL" && m_sVertexShaderProfile.GetLength())
sSourceCode += "#version " + m_sVertexShaderProfile + '\n';
// Add flag definitions to the shader source code
const Array<const char *> &lstVertexShaderDefinitions = cFlags.GetVertexShaderDefinitions();
const uint32 nNumOfVertexShaderDefinitions = lstVertexShaderDefinitions.GetNumOfElements();
for (uint32 i=0; i<nNumOfVertexShaderDefinitions; i++) {
// Get the flag definition
const char *pszDefinition = lstVertexShaderDefinitions[i];
if (pszDefinition) {
sSourceCode += "#define ";
sSourceCode += pszDefinition;
sSourceCode += '\n';
}
}
// Add the shader source code
sSourceCode += m_sVertexShader;
// Set the combined shader source code
pVertexShader->SetSourceCode(sSourceCode, m_sVertexShaderProfile);
// Add the created shader to the cache of the program generator
m_lstVertexShaders.Add(pVertexShader);
m_mapVertexShaders.Add(nVertexShaderID, pVertexShader);
}
}
}
// If we have no vertex shader, we don't need to continue constructing a program...
if (pVertexShader) {
// Is there already a fragment shader with the requested flags?
FragmentShader *pFragmentShader = m_mapFragmentShaders.Get(nFragmentShaderID);
if (!pFragmentShader) {
// Get the shader language to use
ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage);
if (pShaderLanguage) {
// Create a new fragment shader instance
pFragmentShader = pShaderLanguage->CreateFragmentShader();
if (pFragmentShader) {
String sSourceCode;
// When using GLSL, the profile is the GLSL version to use - #version must occur before any other statement in the program!
if (m_sShaderLanguage == "GLSL" && m_sFragmentShaderProfile.GetLength())
sSourceCode += "#version " + m_sFragmentShaderProfile + '\n';
// Add flag definitions to the shader source code
const Array<const char *> &lstFragmentShaderDefinitions = cFlags.GetFragmentShaderDefinitions();
const uint32 nNumOfFragmentShaderDefinitions = lstFragmentShaderDefinitions.GetNumOfElements();
for (uint32 i=0; i<nNumOfFragmentShaderDefinitions; i++) {
// Get the flag definition
const char *pszDefinition = lstFragmentShaderDefinitions[i];
if (pszDefinition) {
sSourceCode += "#define ";
sSourceCode += pszDefinition;
sSourceCode += '\n';
}
}
// Add the shader source code
sSourceCode += m_sFragmentShader;
// Set the combined shader source code
pFragmentShader->SetSourceCode(sSourceCode, m_sFragmentShaderProfile);
// Add the created shader to the cache of the program generator
m_lstFragmentShaders.Add(pFragmentShader);
m_mapFragmentShaders.Add(nFragmentShaderID, pFragmentShader);
}
}
}
// If we have no fragment shader, we don't need to continue constructing a program...
if (pFragmentShader) {
// Get the shader language to use
ShaderLanguage *pShaderLanguage = m_pRenderer->GetShaderLanguage(m_sShaderLanguage);
if (pShaderLanguage) {
// Create a program instance and assign the created vertex and fragment shaders to it
Program *pProgram = pShaderLanguage->CreateProgram(pVertexShader, pFragmentShader);
if (pProgram) {
// Create a generated program contained
pGeneratedProgram = new GeneratedProgram;
pGeneratedProgram->pProgram = pProgram;
pGeneratedProgram->nVertexShaderFlags = cFlags.GetVertexShaderFlags();
pGeneratedProgram->nFragmentShaderFlags = cFlags.GetFragmentShaderFlags();
pGeneratedProgram->pUserData = nullptr;
// Add our nark which will inform us as soon as the program gets dirty
pProgram->EventDirty.Connect(EventHandlerDirty);
// Add the created program to the cache of the program generator
m_lstPrograms.Add(pGeneratedProgram);
m_mapPrograms.Add(nProgramID, pGeneratedProgram);
}
}
}
}
}
// Return the program
return pGeneratedProgram;
}
/**
* @brief
* Clears the cache of the program generator
*/
void ProgramGenerator::ClearCache()
{
// Destroy all generated program instances
for (uint32 i=0; i<m_lstPrograms.GetNumOfElements(); i++) {
GeneratedProgram *pGeneratedProgram = m_lstPrograms[i];
delete pGeneratedProgram->pProgram;
if (pGeneratedProgram->pUserData)
delete pGeneratedProgram->pUserData;
delete pGeneratedProgram;
}
m_lstPrograms.Clear();
m_mapPrograms.Clear();
// Destroy all generated fragment shader instances
for (uint32 i=0; i<m_lstFragmentShaders.GetNumOfElements(); i++)
delete m_lstFragmentShaders[i];
m_lstFragmentShaders.Clear();
m_mapFragmentShaders.Clear();
// Destroy all generated vertex shader instances
for (uint32 i=0; i<m_lstVertexShaders.GetNumOfElements(); i++)
delete m_lstVertexShaders[i];
m_lstVertexShaders.Clear();
m_mapVertexShaders.Clear();
}
//[-------------------------------------------------------]
//[ Private functions ]
//[-------------------------------------------------------]
/**
* @brief
* Copy constructor
*/
ProgramGenerator::ProgramGenerator(const ProgramGenerator &cSource) :
m_pRenderer(nullptr)
{
// No implementation because the copy constructor is never used
}
/**
* @brief
* Copy operator
*/
ProgramGenerator &ProgramGenerator::operator =(const ProgramGenerator &cSource)
{
// No implementation because the copy operator is never used
return *this;
}
/**
* @brief
* Called when a program became dirty
*/
void ProgramGenerator::OnDirty(Program *pProgram)
{
// Search for the generated program and destroy the user data
for (uint32 i=0; i<m_lstPrograms.GetNumOfElements(); i++) {
GeneratedProgram *pGeneratedProgram = m_lstPrograms[i];
if (pGeneratedProgram->pProgram == pProgram) {
// Is there user data we can destroy?
if (pGeneratedProgram->pUserData) {
delete pGeneratedProgram->pUserData;
pGeneratedProgram->pUserData = nullptr;
}
// We're done, get us out of the loop
i = m_lstPrograms.GetNumOfElements();
}
}
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // PLRenderer
| 37.566901
| 151
| 0.667823
|
ktotheoz
|
bd86280087c86bed9cc2a1f2459ef0297950c21d
| 1,350
|
hpp
|
C++
|
include/rua/callable.hpp
|
yulon/rua
|
acb14aa0e60b68f09e88c726965552f7f4f5ace0
|
[
"MIT"
] | null | null | null |
include/rua/callable.hpp
|
yulon/rua
|
acb14aa0e60b68f09e88c726965552f7f4f5ace0
|
[
"MIT"
] | null | null | null |
include/rua/callable.hpp
|
yulon/rua
|
acb14aa0e60b68f09e88c726965552f7f4f5ace0
|
[
"MIT"
] | null | null | null |
#ifndef _RUA_CALLABLE_HPP
#define _RUA_CALLABLE_HPP
#include "types/traits.hpp"
#include <functional>
#include <vector>
namespace rua {
template <typename Callable>
inline std::function<callable_prototype_t<decay_t<Callable>>>
wrap_callable(Callable &&c) {
return std::forward<Callable>(c);
}
////////////////////////////////////////////////////////////////////////////
template <typename Ret, typename... Args>
class _callchain_base : public std::vector<std::function<Ret(Args...)>> {
public:
_callchain_base() = default;
};
template <typename Callback, typename = void>
class callchain;
template <typename Ret, typename... Args>
class callchain<
Ret(Args...),
enable_if_t<!std::is_convertible<Ret, bool>::value>>
: public _callchain_base<Ret, Args...> {
public:
callchain() = default;
void operator()(Args &&... args) const {
for (auto &cb : *this) {
cb(std::forward<Args>(args)...);
}
}
};
template <typename Ret, typename... Args>
class callchain<
Ret(Args...),
enable_if_t<std::is_convertible<Ret, bool>::value>>
: public _callchain_base<Ret, Args...> {
public:
callchain() = default;
Ret operator()(Args &&... args) const {
for (auto &cb : *this) {
auto &&r = cb(std::forward<Args>(args)...);
if (static_cast<bool>(r)) {
return std::move(r);
}
}
return Ret();
}
};
} // namespace rua
#endif
| 20.769231
| 76
| 0.634074
|
yulon
|
bd879321d9b78defa9f3b6b25da6f5c29af8a2fc
| 1,571
|
hpp
|
C++
|
TicTacToe/Score.hpp
|
djanko1337/TicTacToe
|
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
|
[
"MIT"
] | 1
|
2018-02-14T18:00:52.000Z
|
2018-02-14T18:00:52.000Z
|
TicTacToe/Score.hpp
|
djanko1337/TicTacToe
|
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
|
[
"MIT"
] | null | null | null |
TicTacToe/Score.hpp
|
djanko1337/TicTacToe
|
6adcdf7b3a7ed947f36d473c965853edea4ddc8e
|
[
"MIT"
] | null | null | null |
#pragma once
namespace TicTacToe {
class Score {
public:
constexpr Score() noexcept;
constexpr auto count() const noexcept -> int;
constexpr auto increment() noexcept -> void;
constexpr auto reset() noexcept -> void;
private:
int mCount;
};
constexpr auto operator==(Score lhs, Score rhs) noexcept -> bool;
constexpr auto operator!=(Score lhs, Score rhs) noexcept -> bool;
constexpr auto operator<(Score lhs, Score rhs) noexcept -> bool;
constexpr auto operator>(Score lhs, Score rhs) noexcept -> bool;
constexpr auto operator<=(Score lhs, Score rhs) noexcept -> bool;
constexpr auto operator>=(Score lhs, Score rhs) noexcept -> bool;
constexpr Score::Score() noexcept
: mCount(0)
{
}
constexpr auto Score::count() const noexcept -> int
{
return mCount;
}
constexpr auto Score::increment() noexcept -> void
{
++mCount;
}
constexpr auto Score::reset() noexcept -> void
{
mCount = 0;
}
constexpr auto operator==(Score lhs, Score rhs) noexcept -> bool
{
return lhs.count() == rhs.count();
}
constexpr auto operator!=(Score lhs, Score rhs) noexcept -> bool
{
return !(lhs == rhs);
}
constexpr auto operator<(Score lhs, Score rhs) noexcept -> bool
{
return lhs.count() < rhs.count();
}
constexpr auto operator>(Score lhs, Score rhs) noexcept -> bool
{
return lhs.count() > rhs.count();
}
constexpr auto operator<=(Score lhs, Score rhs) noexcept -> bool
{
return !(lhs > rhs);
}
constexpr auto operator>=(Score lhs, Score rhs) noexcept -> bool
{
return !(lhs < rhs);
}
} // namespace TicTacToe
| 19.158537
| 65
| 0.674729
|
djanko1337
|
bd8c50deb2428e76a91e1731ad9a8523613d76dd
| 1,060
|
hpp
|
C++
|
libs/core/include/fcppt/enum/output.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/enum/output.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
libs/core/include/fcppt/enum/output.hpp
|
pmiddend/fcppt
|
9f437acbb10258e6df6982a550213a05815eb2be
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 2018.
// 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 FCPPT_ENUM_OUTPUT_HPP_INCLUDED
#define FCPPT_ENUM_OUTPUT_HPP_INCLUDED
#include <fcppt/enum/to_string.hpp>
#include <fcppt/io/ostream.hpp>
#include <fcppt/config/external_begin.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace enum_
{
/**
\brief Outputs an enum value to a stream.
\ingroup fcpptenum
Uses #fcppt::enum_::to_string to output \a _value to \a _stream.
This function is useful to implement <code>operator<<</code> for an enum type.
\tparam Enum Must be an enum type
\return \a _stream
*/
template<
typename Enum
>
fcppt::io::ostream &
output(
fcppt::io::ostream &_stream,
Enum const _value
)
{
static_assert(
std::is_enum<
Enum
>::value,
"Enum must be an enum type"
);
return
_stream
<<
fcppt::enum_::to_string(
_value
);
}
}
}
#endif
| 17.096774
| 78
| 0.711321
|
pmiddend
|
bd8cd24fba3ddb9a267618809b3a6ad818b1339b
| 945
|
hpp
|
C++
|
src/include/XEEditor/Editor.hpp
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 11
|
2017-01-17T15:02:25.000Z
|
2020-11-27T16:54:42.000Z
|
src/include/XEEditor/Editor.hpp
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 9
|
2016-10-23T20:15:38.000Z
|
2018-02-06T11:23:17.000Z
|
src/include/XEEditor/Editor.hpp
|
devxkh/FrankE
|
72faca02759b54aaec842831f3c7a051e7cf5335
|
[
"MIT"
] | 2
|
2019-08-29T10:23:51.000Z
|
2020-04-03T06:08:34.000Z
|
#ifndef EDITOR_HPP
#define EDITOR_HPP
#include <XEngine.hpp>
#include <XEEditor/Event/Event.h>
namespace EI {
class EditorCommand;
enum ObjType
{
Physic = 0,
GameEntity = 1,
};
enum Status
{
Unknown = 0,
OK = 1,
Error = 2,
};
class Editor
{
public:
Editor();
inline XE::XEngine* getEngine() { return m_engine; }
void* InitState(const char* stateName, int width, int height);
unsigned char* consoleCmd(const char* command, unsigned char* data, int len);
bool moveToState(const char* stateName);
void renderTargetSize(const char* rtName, Ogre::Real x, Ogre::Real y);
// void test(sf::String str, std::function<void()> fkttest);
int pushEvent(const sfEvent& event);
private :
// std::unordered_map<std::string, std::function<void(std::string)>> command_map;
XE::XEngine* m_engine;
//todo #################### XE::OgreConsole* m_console;
EditorCommand* mEditorCommand;
};
}
#endif //EDITOR_HPP
| 20.106383
| 82
| 0.674074
|
devxkh
|
bd8f12d6d2ef16317d360b1060caa92b0319eacb
| 373
|
cpp
|
C++
|
src/learn/test_bitset.cpp
|
wohaaitinciu/zpublic
|
0e4896b16e774d2f87e1fa80f1b9c5650b85c57e
|
[
"Unlicense"
] | 50
|
2015-01-07T01:54:54.000Z
|
2021-01-15T00:41:48.000Z
|
src/learn/test_bitset.cpp
|
lib1256/zpublic
|
64c2be9ef1abab878288680bb58122dcc25df81d
|
[
"Unlicense"
] | 1
|
2015-05-26T07:40:19.000Z
|
2015-05-26T07:40:19.000Z
|
src/learn/test_bitset.cpp
|
lib1256/zpublic
|
64c2be9ef1abab878288680bb58122dcc25df81d
|
[
"Unlicense"
] | 39
|
2015-01-07T02:03:15.000Z
|
2021-01-15T00:41:50.000Z
|
#include "stdafx.h"
#include "test_bitset.h"
void test_bitset()
{
std::bitset<32> bt32;
bt32.set();
assert(bt32.all());
bt32.reset();
assert(bt32.none());
bt32.set(0);
assert(bt32.any());
assert(bt32.size() == 32);
bt32.flip();
assert(bt32.count() == 31);
bt32 <<= 15;
std::cout << bt32.to_string('X', 'O') << std::endl;
}
| 18.65
| 55
| 0.544236
|
wohaaitinciu
|
bd93b99635fd75bddeaaea5d7980b57d005a85c0
| 21,349
|
cc
|
C++
|
src/tpl/vx_str.cc
|
eedsp/tlx
|
2555853646920168570bd630850dc22bc2cb327d
|
[
"Apache-2.0"
] | null | null | null |
src/tpl/vx_str.cc
|
eedsp/tlx
|
2555853646920168570bd630850dc22bc2cb327d
|
[
"Apache-2.0"
] | null | null | null |
src/tpl/vx_str.cc
|
eedsp/tlx
|
2555853646920168570bd630850dc22bc2cb327d
|
[
"Apache-2.0"
] | null | null | null |
//
// Created by Shiwon Cho on 2005.10.27.
//
#include <iostream>
#include "vx_str.h"
#define UPDATE_UCS_offset(p_offset_utf8, p_offset_utf8_s, pSTR, pSTR_len, p_offset_ucs) { \
int32_t __v_idx_utf8 = p_offset_utf8; \
while (__v_idx_utf8 < p_offset_utf8_s && __v_idx_utf8 < pSTR_len) \
{ \
UChar32 __c = 0; \
U8_NEXT (pSTR, __v_idx_utf8, pSTR_len, __c); \
p_offset_ucs++; \
} \
}
#define UPDATE_UCS_len(pSTR, pSTR_len, p_len_ucs) { \
int32_t __v_idx_utf8 = 0; \
while (__v_idx_utf8 < pSTR_len) \
{ \
UChar32 __c = 0; \
U8_NEXT (pSTR, __v_idx_utf8, pSTR_len, __c); \
p_len_ucs++; \
} \
}
static const char *_TPL_DEFAULT_TAG = "_PHRASE_";
vx_str::vx_str (apr_pool_t *p_pool, const hx_shm_rec_t *p_shm_t)
{
v_pool = nullptr;
vSTR = nullptr;
vSTR_len = 0;
v_number_of_codes = 0;
v_list_of_codes = nullptr;
v_ctx_general = nullptr;
v_error_code = v_error_offset = 0;
v_name_count = nullptr;
v_name_entry_size = nullptr;
v_name_table = nullptr;
v_name_entry_max_size = 0;
v_match_context = nullptr;
v_jit_stack = nullptr;
v_match_data = nullptr;
v_out_vector = nullptr;
v_token_list = nullptr;
v_status = APR_SUCCESS;
v_status = apr_pool_create (&v_pool, p_pool);
is_attached = false;
vDB = p_shm_t;
if (vDB && vDB->v_ptr)
{
is_attached = true;
}
}
vx_str::~vx_str ()
{
vSTR_len = 0;
if (v_token_list)
{
vtx_delete (v_token_list);
}
if (v_status == APR_SUCCESS && v_pool)
{
apr_pool_destroy(v_pool);
v_pool = NULL;
}
}
void *vx_str::ctx_malloc (PCRE2_SIZE pSIZE, void *pFUNC)
{
#if defined(USE_TCMALLOC)
void *block = (void *)tc_malloc ((size_t)pSIZE);
#elif defined(USE_JEMALLOC)
void *block = (void *) je_malloc((size_t) pSIZE);
#else
void *block = (void *)malloc ((size_t)pSIZE);
#endif
(void) pFUNC;
return block;
}
void vx_str::ctx_free (void *pBLOCK, void *pFUNC)
{
(void) pFUNC;
#if defined(USE_TCMALLOC)
tc_free ((void *)pBLOCK);
#elif defined(USE_JEMALLOC)
je_free((void *) pBLOCK);
#else
free ((void *)pBLOCK);
#endif
}
void vx_str::context_create ()
{
if (!vDB || !is_attached)
{
return;
}
if (!vDB->v_ptr)
{
return;
}
v_number_of_codes = pcre2_serialize_get_number_of_codes ((const uint8_t *)vDB->v_ptr);
if (v_number_of_codes > 0)
{
v_ctx_general = pcre2_general_context_create(ctx_malloc, ctx_free, NULL);
v_list_of_codes = (pcre2_code **) apr_palloc(v_pool, sizeof(pcre2_code *) * v_number_of_codes);
v_name_count = (int32_t *) apr_palloc(v_pool, sizeof(int32_t) * v_number_of_codes);
v_name_table = (PCRE2_SPTR *) apr_palloc(v_pool, sizeof(PCRE2_SPTR) * v_number_of_codes);
v_name_entry_size = (int32_t *) apr_palloc(v_pool, sizeof(int32_t) * v_number_of_codes);
v_match_context = (pcre2_match_context **) apr_palloc(v_pool, sizeof(pcre2_match_context *) * v_number_of_codes);
v_jit_stack = (pcre2_jit_stack **) apr_palloc(v_pool, sizeof(pcre2_jit_stack *) * v_number_of_codes);
v_match_data = (pcre2_match_data **) apr_palloc(v_pool, sizeof(pcre2_match_data *) * v_number_of_codes);
v_out_vector = (PCRE2_SIZE **) apr_palloc(v_pool, sizeof(PCRE2_SIZE *) * v_number_of_codes);
pcre2_serialize_decode(v_list_of_codes, v_number_of_codes, (const uint8_t *)vDB->v_ptr, v_ctx_general);
for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++)
{
pcre2_code *v_re = v_list_of_codes[v_idx_code];
pcre2_jit_compile(v_re, PCRE2_JIT_COMPLETE);
(void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMECOUNT, &v_name_count[v_idx_code]);
(void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMETABLE, &v_name_table[v_idx_code]);
(void) pcre2_pattern_info(v_re, PCRE2_INFO_NAMEENTRYSIZE, &v_name_entry_size[v_idx_code]);
if (v_name_entry_max_size < v_name_entry_size[v_idx_code])
{
v_name_entry_max_size = v_name_entry_size[v_idx_code];
}
v_match_context[v_idx_code] = pcre2_match_context_create(NULL);
pcre2_set_match_limit (v_match_context[v_idx_code], -1);
pcre2_set_recursion_limit (v_match_context[v_idx_code], 1);
v_jit_stack[v_idx_code] = pcre2_jit_stack_create(32 * 1024, 512 * 1024, NULL);
pcre2_jit_stack_assign(v_match_context[v_idx_code], NULL, v_jit_stack[v_idx_code]);
v_match_data[v_idx_code] = pcre2_match_data_create_from_pattern(v_re, NULL);
v_out_vector[v_idx_code] = pcre2_get_ovector_pointer(v_match_data[v_idx_code]);
}
#if 0
re = pcre2_compile(
(PCRE2_SPTR) pPATTERN, /* the pattern */
(PCRE2_SIZE) PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
PCRE2_UCP | PCRE2_UTF | PCRE2_DUPNAMES | PCRE2_CASELESS | PCRE2_ALLOW_EMPTY_CLASS, /* Option bits */
&v_error_code, /* for error code */
&v_error_offset, /* for error offset */
v_ctx_compile); /* use default compile context */
if (re != NULL)
{
pcre2_jit_compile(re, PCRE2_JIT_COMPLETE);
(void) pcre2_pattern_info(re, PCRE2_INFO_NAMECOUNT, &v_name_count);
(void) pcre2_pattern_info(re, PCRE2_INFO_NAMETABLE, &v_name_table);
(void) pcre2_pattern_info(re, PCRE2_INFO_NAMEENTRYSIZE, &v_name_entry_size);
}
else
{
PCRE2_UCHAR8 vBUF[512];
(void) pcre2_get_error_message(v_error_code, vBUF, 512);
std::cout << _INFO (v_pool) << __func__ << ":" << vBUF << std::endl << std::flush;
}
#endif
}
}
void vx_str::context_free ()
{
for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++)
{
pcre2_code *v_re = v_list_of_codes[v_idx_code];
pcre2_code_free (v_re);
pcre2_match_data_free(v_match_data[v_idx_code]); /* Release memory used for the match */
pcre2_match_context_free(v_match_context[v_idx_code]);
pcre2_jit_stack_free(v_jit_stack[v_idx_code]);
}
if (v_ctx_general)
{
pcre2_general_context_free(v_ctx_general);
}
}
#if 0
void vx_str::read (const char *pSTR, int32_t pSTR_len)
{
uSTR.remove();
uSTR_len = 0;
apr_pool_clear(v_pool_token);
vSTR = NULL;
vSTR_len = 0;
uSTR = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len));
uSTR_len = uSTR.length();
std::string szUTF8_tmp("");
uSTR.toLower().toUTF8String(szUTF8_tmp);
vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str());
vSTR_len = (int32_t) szUTF8_tmp.length();
szUTF8_tmp.clear();
}
void vx_str::Text_normalize (const char *pSTR, int32_t pSTR_len, bool toLower)
{
UErrorCode status = U_ZERO_ERROR;
uSTR.remove();
uSTR_len = 0;
apr_pool_clear(v_pool_token);
vSTR = NULL;
vSTR_len = 0;
const Normalizer2 &nNFC = *Normalizer2::getNFCInstance(status);
if (U_SUCCESS(status))
{
UnicodeString uSTR_tmp = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len));
status = U_ZERO_ERROR;
uSTR = nNFC.normalize((toLower) ? uSTR_tmp.toLower() : uSTR_tmp, status);
if (U_SUCCESS(status))
{
std::string szUTF8_tmp("");
uSTR.toUTF8String(szUTF8_tmp);
uSTR_len = uSTR.length();
vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str());
vSTR_len = (int32_t) szUTF8_tmp.length();
szUTF8_tmp.clear();
}
}
}
void vx_str::normalize (const char *pSTR, int32_t pSTR_len)
{
if (U_SUCCESS(v_error_code_normlzer))
{
uSTR.remove();
uSTR_len = 0;
apr_pool_clear(v_pool_token);
vSTR = NULL;
vSTR_len = 0;
UnicodeString uSTR_raw = UnicodeString::fromUTF8(StringPiece((char *) pSTR, pSTR_len));
UErrorCode status = U_ZERO_ERROR;
uSTR = v_NFC->normalize((opt_toLowerCase) ? uSTR_raw.toLower() : uSTR_raw, status);
if (U_SUCCESS(status))
{
std::string szUTF8_tmp("");
uSTR.toUTF8String(szUTF8_tmp);
uSTR_len = uSTR.length();
vSTR = (const char *) apr_pstrdup(v_pool_token, szUTF8_tmp.c_str());
vSTR_len = (int32_t) szUTF8_tmp.length();
szUTF8_tmp.clear();
}
}
}
#endif
PCRE2_SPTR vx_str::proc_token_tag (int32_t p_idx_code, int32_t p_offset_utf8, int32_t p_len_utf8, const PCRE2_SIZE *p_vector)
{
PCRE2_SPTR v_name = nullptr;
PCRE2_SPTR p_table = v_name_table[p_idx_code];
int32_t n = 0;
int32_t v_offset_utf8_s = 0; // 2 * n
int32_t v_offset_utf8_e = 0; // 2 * n + 1
int32_t v_len_utf8 = 0;
for (int32_t vIDX = 0; !v_name && vIDX < v_name_count[p_idx_code]; vIDX+=2)
{
if (!v_name && vIDX < v_name_count[p_idx_code])
{
n = (p_table[0] << 8) | p_table[1];
v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n
v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1
v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s);
if (v_offset_utf8_s == p_offset_utf8 && (v_len_utf8 > 0 && v_len_utf8 == p_len_utf8))
{
v_name = (PCRE2_SPTR) p_table + 2;
break;
}
p_table += v_name_entry_size[p_idx_code];
}
if (!v_name && (vIDX + 1) < v_name_count[p_idx_code])
{
n = (p_table[0] << 8) | p_table[1];
v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n
v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1
v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s);
if (v_offset_utf8_s == p_offset_utf8 && (v_len_utf8 > 0 && v_len_utf8 == p_len_utf8))
{
v_name = (PCRE2_SPTR) p_table + 2;
break;
}
p_table += v_name_entry_size[p_idx_code];
}
}
return v_name;
}
#if 0
PCRE2_SPTR vx_str::proc_token_tag_all (int32_t p_idx_token, int32_t p_idx_code, int32_t p_offset_utf8, int32_t p_len_utf8, int32_t p_offset_ucs_s, const PCRE2_SIZE *p_vector)
{
PCRE2_SPTR v_name = NULL;
PCRE2_SPTR p_name = v_name_table[p_idx_code];
// int32_t v_offset_utf8 = p_offset_utf8;
// int32_t v_offset_ucs = p_offset_ucs_s;
int32_t vFLAG = 1;
for (int32_t vIDX = 0; vFLAG && vIDX < v_name_count[p_idx_code]; vIDX++)
{
int32_t n = (p_name[0] << 8) | p_name[1];
int32_t v_offset_utf8_s = (int32_t) p_vector[2 * n]; // 2 * n
int32_t v_offset_utf8_e = (int32_t) p_vector[2 * n + 1]; // 2 * n + 1
int32_t v_len_utf8 = (int32_t) (v_offset_utf8_e - v_offset_utf8_s);
if (v_len_utf8 > 0)
{
if (
v_name == NULL && (v_offset_utf8_s == p_offset_utf8 && v_len_utf8 == p_len_utf8)
)
{
v_name = (PCRE2_SPTR) p_name + 2;
vFLAG = 0;
break;
}
int32_t v_offset_utf8 = p_offset_utf8;
int32_t v_offset_ucs = p_offset_ucs_s;
PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s;
UPDATE_UCS_offset (v_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs); // update UCS offset
int32_t v_len_ucs = 0;
UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length
// std::cout << apr_psprintf (v_pool, " (%d)", n);
// std::cout << apr_psprintf (v_pool, "[%2d/%d]", vIDX + 1, v_name_count);
std::cout << apr_psprintf(v_pool, "%6d %5d(%3d) %5d(%3d)",
p_idx_token,
(int32_t) v_offset_ucs, (int32_t) v_len_ucs,
(int32_t) v_offset_utf8_s, (int32_t) v_len_utf8
);
std::cout << apr_psprintf(v_pool, " [%*s]",
v_name_entry_max_size - 3,
(char *) (p_name + 2));
std::cout << apr_psprintf(v_pool, " [%.*s]",
(int32_t) v_len_utf8, v_ptr);
std::cout << std::endl;
}
p_name += v_name_entry_size[p_idx_code];
}
return v_name;
}
#endif
void vx_str::tokenize (const char *pSTR, size_t pSTR_len)
{
if (!v_ctx_general || !v_number_of_codes)
{
return;
}
int32_t v_idx_token = 0;
int32_t v_offset_utf8 = 0;
int32_t v_offset_ucs = 0;
int32_t v_offset_ucs_prev = -1;
int32_t v_idx_sgmt = 0;
int32_t v_idx_elt = 0;
int32_t vFLAG = 1;
vSTR = pSTR;
vSTR_len = pSTR_len;
if (v_token_list)
{
vtx_clear(v_token_list);
}
else
{
v_token_list = vtx_create(v_pool);
}
int32_t vIDX_code = v_number_of_codes - 1;
pcre2_code *v_re = v_list_of_codes[vIDX_code];
for (; vFLAG && v_offset_utf8 < (int32_t)vSTR_len;)
{
uint32_t v_options = 0; /* Normally no options */
int32_t rc = pcre2_jit_match(
v_re, /* the compiled pattern */
(PCRE2_SPTR) vSTR, /* the subject string */
(size_t) vSTR_len, /* the length of the subject */
(size_t) v_offset_utf8, /* start at offset 0 in the subject */
v_options, /* default options */
v_match_data[vIDX_code], /* block for storing the result */
v_match_context[vIDX_code]); /* use default match context */
if (rc == PCRE2_ERROR_NOMATCH)
{
vFLAG = 0;
break;
}
else if (rc > 0)
{
int32_t v_offset_utf8_s = (int32_t) v_out_vector[vIDX_code][0]; // 2 * vIDX
int32_t v_offset_utf8_e = (int32_t) v_out_vector[vIDX_code][1]; // 2 * vIDX + 1
int32_t v_len_utf8 = v_offset_utf8_e - v_offset_utf8_s;
if (v_offset_utf8_e > 0 && v_len_utf8 > 0)
{
PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s;
int32_t v_offset_ucs_s = v_offset_ucs;
int32_t v_len_ucs = 0;
UPDATE_UCS_offset (v_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs_s); // update UCS offset
v_offset_ucs = v_offset_ucs_s;
v_offset_utf8 = v_offset_utf8_e;
UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length
v_offset_ucs += v_len_ucs;
PCRE2_SPTR v_name = proc_token_tag(vIDX_code, v_offset_utf8_s, v_len_utf8, (const PCRE2_SIZE *) v_out_vector[vIDX_code]);
if (v_offset_ucs_prev != -1 && v_offset_ucs_prev != v_offset_ucs_s)
{
v_idx_sgmt++;
v_idx_elt = 0;
}
#if 0
std::cout << apr_psprintf(v_pool, "%6d [%6d] <%5d>%5d(%3d) %5d(%3d)",
v_idx_sgmt,
v_idx_token,
v_offset_ucs_prev,
(int32_t) v_offset_ucs_s, (int32_t) v_len_ucs,
(int32_t) v_offset_utf8_s, (int32_t) v_len_utf8
);
std::cout
<< apr_psprintf(v_pool, " [%*s]", v_name_entry_max_size - 3, (v_name == NULL) ? (char *) _TPL_DEFAULT_TAG : (char *) v_name);
std::cout << apr_psprintf(v_pool, " [%.*s]", (int32_t) v_len_utf8, (char *) v_ptr);
std::cout << std::endl;
#endif
vtx_push_back (v_token_list, v_idx_token,
v_idx_sgmt,
v_idx_elt,
(const char *) v_ptr, v_len_utf8,
v_offset_ucs_s, v_len_ucs,
v_offset_utf8_s, v_len_utf8,
(v_name == NULL) ? _TPL_DEFAULT_TAG : (const char *) v_name);
v_offset_ucs_prev = v_offset_ucs;
v_idx_token++;
v_idx_elt++;
} // if v_offset_utf8_e > 0
} // if else
else
{
std::cout << ">>> " << __LINE__ << ":" << v_offset_utf8 << ":" << rc << std::endl;
vFLAG = 0;
break;
}
} // for
}
void vx_str::print ()
{
if (v_token_list)
{
vtx_print(v_token_list);
}
}
const char * vx_str::dumps_text ()
{
const char *v_buffer = nullptr;
if (vDB && is_attached && v_token_list)
{
v_buffer = vtx_text_print(v_token_list);
}
return v_buffer;
}
const char * vx_str::dumps_json ()
{
const char *v_buffer = nullptr;
if (vDB && is_attached && v_token_list)
{
v_buffer = vtx_json_print(v_token_list);
}
return v_buffer;
}
#if 0
void vx_str::tokenize_2 ()
{
int32_t v_offset_utf8 = 0;
int32_t v_offset_ucs = 0;
int32_t vFLAG = 1;
int32_t vIDX_ = v_number_of_codes - 1;
int32_t *flag_code = new int32_t[vIDX_];
for (int32_t vIDX = 0; vIDX < vIDX_; vIDX++)
{
flag_code[vIDX] = 1;
}
while (vFLAG && v_offset_utf8 < vSTR_len)
{
// std::cout << _INFO (v_pool) << apr_psprintf(v_pool, "%4d/%d", v_offset_utf8, vSTR_len) << std::endl << std::flush;
int32_t v_offset_last_utf8 = vSTR_len;
int32_t l_idx = -1;
int32_t l_offset_ucs_s = 0;
int32_t l_offset_utf8_s = 0;
int32_t l_len_ucs = 0;
int32_t l_len_utf8 = 0;
for (int32_t v_idx_code = 0; v_idx_code < v_number_of_codes; v_idx_code++)
{
if (flag_code[v_idx_code] == 0)
{
continue;
}
pcre2_code *v_re = v_list_of_codes[v_idx_code];
int32_t t_offset_utf8 = v_offset_utf8;
uint32_t v_options = 0; /* Normally no options */
int32_t rc = pcre2_jit_match(
v_re, /* the compiled pattern */
(PCRE2_SPTR) vSTR, /* the subject string */
(size_t) vSTR_len, /* the length of the subject */
(size_t) t_offset_utf8, /* start at offset 0 in the subject */
v_options, /* default options */
v_match_data[v_idx_code], /* block for storing the result */
v_match_context[v_idx_code]); /* use default match context */
if (rc == PCRE2_ERROR_NOMATCH)
{
flag_code[v_idx_code] = 0;
continue;
}
else if (rc > 0)
{
int32_t v_offset_utf8_s = (int32_t) v_out_vector[v_idx_code][0]; // 2 * vIDX
int32_t v_offset_utf8_e = (int32_t) v_out_vector[v_idx_code][1]; // 2 * vIDX + 1
int32_t v_len_utf8 = v_offset_utf8_e - v_offset_utf8_s;
if (v_offset_utf8_e > 0 && v_len_utf8 > 0)
{
PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + v_offset_utf8_s;
int32_t v_offset_ucs_s = v_offset_ucs;
int32_t v_len_ucs = 0;
UPDATE_UCS_offset (t_offset_utf8, v_offset_utf8_s, vSTR, (int32_t)vSTR_len, v_offset_ucs_s); // update UCS offset
UPDATE_UCS_len (v_ptr, v_len_utf8, v_len_ucs); // update ucs length
if (t_offset_utf8 < v_offset_last_utf8)
{
l_idx = v_idx_code;
v_offset_last_utf8 = v_offset_utf8_s;
l_offset_utf8_s = v_offset_utf8_s;
l_offset_ucs_s = v_offset_ucs_s;
l_len_utf8 = v_len_utf8;
l_len_ucs = v_len_ucs;
//std::cout << _INFO (v_pool) << apr_psprintf(v_pool, "%4d/%d", v_offset_utf8_s, vSTR_len) << std::endl << std::flush;
}
} // if v_offset_utf8_e > 0
} // if else
} // for
v_offset_utf8 = l_offset_utf8_s + l_len_utf8;
v_offset_ucs = l_offset_ucs_s + l_len_ucs;
if (l_idx >= 0)
{
PCRE2_SPTR v_ptr = (PCRE2_SPTR) vSTR + l_offset_utf8_s;
PCRE2_SPTR v_name = proc_token_tag(l_idx, l_offset_utf8_s, l_len_utf8, l_offset_ucs_s, (const PCRE2_SIZE *) v_out_vector[l_idx]);
if (v_name == NULL)
{
std::cout << apr_psprintf(v_pool, "%5d(%3d) %5d(%3d)",
(int32_t) l_offset_ucs_s, (int32_t) l_len_ucs,
(int32_t) l_offset_utf8_s, (int32_t) l_len_utf8
);
std::cout
<< apr_psprintf(v_pool, " (%*s)", v_name_entry_max_size - 3, (v_name == NULL) ? (char *) "_PHRASE" : (char *) v_name);
std::cout << apr_psprintf(v_pool, " [%.*s]", (int32_t) l_len_utf8, (char *) v_ptr);
std::cout << std::endl;
}
}
else{
vFLAG = 0;
break;
}
} // while
delete flag_code;
}
#endif
| 33.357813
| 174
| 0.569582
|
eedsp
|
bd97711b92e2f01bc90806429d49e045296546de
| 961
|
hpp
|
C++
|
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
|
leighgarbs/toolbox
|
fd9ceada534916fa8987cfcb5220cece2188b304
|
[
"MIT"
] | null | null | null |
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
|
leighgarbs/toolbox
|
fd9ceada534916fa8987cfcb5220cece2188b304
|
[
"MIT"
] | null | null | null |
configuration/ConfigurationParameterTemplateBase_test/ConfigurationParameterTemplateBase_test.hpp
|
leighgarbs/toolbox
|
fd9ceada534916fa8987cfcb5220cece2188b304
|
[
"MIT"
] | null | null | null |
#if !defined CONFIGURATION_PARAMETER_TEMPLATE_BASE_TEST_HPP
#define CONFIGURATION_PARAMETER_TEMPLATE_BASE_TEST_HPP
#include "Test.hpp"
#include "TestCases.hpp"
#include "TestMacros.hpp"
#include "ConfigurationParameterTemplateBase.hpp"
namespace Configuration
{
TEST_CASES_BEGIN(ParameterTemplateBase_test)
TEST_CASES_BEGIN(SetValue)
TEST(Bool)
TEST(String)
TEST(Char)
TEST(Double)
TEST(Float)
TEST(Int)
TEST(Long)
TEST(LongDouble)
TEST(LongLong)
TEST(Short)
TEST(UnsignedChar)
TEST(UnsignedInt)
TEST(UnsignedLong)
TEST(UnsignedLongLong)
TEST(UnsignedShort)
template <class T>
static Test::Result test(const T& initial_value, const T& set_value);
TEST_CASES_END(SetValue)
TEST_CASES_END(ParameterTemplateBase_test)
}
#endif
| 23.439024
| 81
| 0.630593
|
leighgarbs
|
bd9ec24d3dab1b3d9fab7650571cb40639a1c1ec
| 61,331
|
cpp
|
C++
|
src/NLO_PL.cpp
|
gvita/RHEHpt
|
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
|
[
"MIT"
] | null | null | null |
src/NLO_PL.cpp
|
gvita/RHEHpt
|
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
|
[
"MIT"
] | null | null | null |
src/NLO_PL.cpp
|
gvita/RHEHpt
|
f320d8f4e2ef27af19cf62bded85afce8e0de7a7
|
[
"MIT"
] | null | null | null |
#include "NLO_PL.h"
#include "cuba.h"
#include <gsl/gsl_sf_dilog.h>
/*double B2pp_ANALITIC(long double x, long double xp)
{
return(1./3.*3.*5.*(2.+3.*xp)/(xp*(1.+xp))*std::log(x));
}*/ //Used to cross-check the complete form above
long double B2pp_ANALITICS(long double x, long double xp){
long double ymax=0.5*std::log((1.+std::sqrt(1.-4.*x*(1.+xp)/std::pow(1.+x,2)))/(1.-std::sqrt(1.-4.*x*(1.+xp)/std::pow(1.+x,2))));
long double wmax=std::exp(ymax);
long double R1=1./12.*x*xp*(1./std::sqrt(x)*(1./wmax*(2.+3.*x)*std::sqrt(1.+xp))
-2.*std::pow(wmax,2)*x*(1.+xp)-8.*std::pow(x,5)*xp*xp*std::pow(1.+xp,3)/(3.*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),3))
+4.*x/(wmax*std::sqrt(x*(1.+xp))-x)+wmax*std::sqrt(1.+xp)*(2.+3.*x-8.*x*x*(1.+2.*xp))/std::sqrt(x)
+2.*x*x*x*xp*std::pow(1.+xp,2)*(1.+x*x*(1.+7.*xp)-x*(4.+7.*xp))/((x-1.)*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),2))
-(4.*x*(2.*(1.+xp)+2.*x*xp*(1.+xp)+x*x*(-3.+4.*xp+18.*xp*xp+11.*xp*xp*xp)+x*x*x*x*(2.+9.*xp+18.*xp*xp+11.*xp*xp*xp)-x*x*x*(1.+15.*xp+36.*xp*xp+22.*xp*xp*xp)))
/(std::pow(x-1.,2)*(x+x*xp-wmax*std::sqrt(x*(1.+xp))))
-(-2.+3.*x+x*x+2.*xp-3.*x*xp)*std::log(wmax*std::sqrt(x*(1.+xp)))/x
-((2.+2.*xp-2.*xp*xp*xp+std::pow(x,6)*(2.+xp)-3.*std::pow(x,5)*(4.+3.*xp)+std::pow(x,4)*(30.+26.*xp+4.*xp*xp-3.*xp*xp*xp)
-x*(12.+23.*xp+4.*xp*xp+3.*xp*xp*xp)-std::pow(x,3)*(40.+48.*xp+9.*xp*xp*xp)+x*x*(30.+51.*xp+9.*xp*xp*xp))*std::log(1.+xp-wmax*std::sqrt(x*(1.+xp))))
/(std::pow(x-1.,3)*x*(x-xp-1.)*xp)
-1./(x*xp*(x-xp-1.))*(4.*x*x*x*x+x*x*x*(10.+xp)-2.*x*x*(3.+5.*xp)+2.*(1.-xp+xp*xp*xp)-x*(2.+7.*xp+3.*xp*xp*xp))*std::log(-x+wmax*std::sqrt(x*(1.+xp)))
-1./(std::pow(x-1.,3)*x*xp)*4.*(-1.+2.*x*(2.+xp)-x*x*(5.+6.*xp+3.*xp*xp)-6.*std::pow(x,5)*xp*(2.+6.*xp+5.*xp*xp)
-x*x*x*xp*(1.+8.*xp+10.*xp*xp)+std::pow(x,6)*(-1.+3.*xp+12.*xp*xp+10.*xp*xp*xp)
+std::pow(x,4)*(3.+14.*xp+33.*xp*xp+30.*xp*xp*xp))*std::log(wmax*std::sqrt(x*(1.+xp))-x*(1.+xp)));
ymax=std::log(((1.+x)-std::sqrt(std::pow(1.-x,2)-4.*x*xp))/(2.*std::sqrt(x*(1.+xp))));
wmax=std::exp(ymax);
long double R2=1./12.*x*xp*(1./std::sqrt(x)*(1./wmax*(2.+3.*x)*std::sqrt(1.+xp))
-2.*std::pow(wmax,2)*x*(1.+xp)-8.*std::pow(x,5)*xp*xp*std::pow(1.+xp,3)/(3.*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),3))
+4.*x/(wmax*std::sqrt(x*(1.+xp))-x)+wmax*std::sqrt(1.+xp)*(2.+3.*x-8.*x*x*(1.+2.*xp))/std::sqrt(x)
+2.*x*x*x*xp*std::pow(1.+xp,2)*(1.+x*x*(1.+7.*xp)-x*(4.+7.*xp))/((x-1.)*std::pow(x+x*xp-wmax*std::sqrt(x*(1.+xp)),2))
-(4.*x*(2.*(1.+xp)+2.*x*xp*(1.+xp)+x*x*(-3.+4.*xp+18.*xp*xp+11.*xp*xp*xp)+x*x*x*x*(2.+9.*xp+18.*xp*xp+11.*xp*xp*xp)-x*x*x*(1.+15.*xp+36.*xp*xp+22.*xp*xp*xp)))
/(std::pow(x-1.,2)*(x+x*xp-wmax*std::sqrt(x*(1.+xp))))
-(-2.+3.*x+x*x+2.*xp-3.*x*xp)*std::log(wmax*std::sqrt(x*(1.+xp)))/x
-((2.+2.*xp-2.*xp*xp*xp+std::pow(x,6)*(2.+xp)-3.*std::pow(x,5)*(4.+3.*xp)+std::pow(x,4)*(30.+26.*xp+4.*xp*xp-3.*xp*xp*xp)
-x*(12.+23.*xp+4.*xp*xp+3.*xp*xp*xp)-std::pow(x,3)*(40.+48.*xp+9.*xp*xp*xp)+x*x*(30.+51.*xp+9.*xp*xp*xp))*std::log(1.+xp-wmax*std::sqrt(x*(1.+xp))))
/(std::pow(x-1.,3)*x*(x-xp-1.)*xp)
-1./(x*xp*(x-xp-1.))*(4.*x*x*x*x+x*x*x*(10.+xp)-2.*x*x*(3.+5.*xp)+2.*(1.-xp+xp*xp*xp)-x*(2.+7.*xp+3.*xp*xp*xp))*std::log(-x+wmax*std::sqrt(x*(1.+xp)))
-1./(std::pow(x-1.,3)*x*xp)*4.*(-1.+2.*x*(2.+xp)-x*x*(5.+6.*xp+3.*xp*xp)-6.*std::pow(x,5)*xp*(2.+6.*xp+5.*xp*xp)
-x*x*x*xp*(1.+8.*xp+10.*xp*xp)+std::pow(x,6)*(-1.+3.*xp+12.*xp*xp+10.*xp*xp*xp)
+std::pow(x,4)*(3.+14.*xp+33.*xp*xp+30.*xp*xp*xp))*std::log(wmax*std::sqrt(x*(1.+xp))-x*(1.+xp)));
long double R3=-1./6.*(1.+x*x-x*(2.+xp))*(std::log(x)+std::log(1.+xp)+2.*std::log(2)-2.*std::log(1.+x+std::sqrt((1.-x)*(1.-x)-4.*x*xp)));
return(2./xp*(R1-R2+R3));
}
//Delta contribution
//gg channel
long double NLOPL::NLO_PL_delta(double xp){
const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp);
const long double t=0.5*(x-1.+rad);
const long double u=0.5*(x-1.-rad);
const long double MUR=pow(_muR/_mH,2.);
const long double MUF=pow(_muF/_mH,2.);
const long double b0=11./6.*_Nc-1./3.*_Nf;
const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc));
const long double delta=3./2.*b0*(std::log(MUR*x/(-t))+std::log(MUR*x/(-u)))+(67./18.*_Nc-5./9.*_Nf);
const long double U=1./2.*std::pow(std::log(u/t),2.)+M_PIl*M_PIl/3.-std::log(x)*std::log(x/(-t))-std::log(x)*std::log(x/(-u))
-std::log(x/(-t))*std::log(x/(-u))+std::pow(std::log(x),2.)+std::pow(std::log(x/(x-t)),2.)+std::pow(std::log(x/(x-u)),2.)
+2.*gsl_sf_dilog(1.-x)+2.*gsl_sf_dilog(x/(x-t))+2.*gsl_sf_dilog(x/(x-u));
const long double ris=x*(Delta+delta+_Nc*U)*_Nc*(pow(x,4)+1.+pow(t,4)+pow(u,4))/(u*t)
+(_Nc-_Nf)*_Nc/3.*(x*x+(x*x/t)+(x*x/u)+x);
const long double Jac1=-(1.-x-rad)/(2.*rad);
const long double Jac2=(1.-x+rad)/(2.*rad);
const long double Si5z1=1./t*(std::pow(x,4)+1.+std::pow(t,4)+std::pow(u,4))/(u*t)*std::log(x*MUF/(-t));
const long double Si5z2=1./u*(std::pow(x,4)+1.+std::pow(u,4)+std::pow(t,4))/(u*t)*std::log(x*MUF/(-u));
return (ris/rad*2.+2.*x*_Nc*b0*(Jac2*Si5z2-Jac1*Si5z1)+_Nc*_Nf*B2pp_ANALITICS(x,xp));
}
//gq channel
long double NLOPL::NLO_PL_delta_gq(double xp){
const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp);
const long double t=0.5*(x-1.+rad);
const long double u=0.5*(x-1.-rad);
const long double MUR=pow(_muR/_mH,2.);
const long double MUF=pow(_muF/_mH,2.);
const long double b0=11./6.*_Nc-1./3.*_Nf;
const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc));
const long double V11=0.5*std::pow(std::log(u/t),2.)+0.5*std::pow(std::log(1./(-u)),2.)-0.5*std::pow(std::log(1./(-t)),2.)
-std::log(x)*std::log((-t)/x)+std::log(x)*std::log((-u)/x)-std::log((-t)/x)*std::log((-u)/x)
+2.*dilog_r(x/(x-u))+std::pow(std::log(x/(x-u)),2.)+M_PIl*M_PIl;
const long double V21=std::pow(std::log(x),2)+std::pow(std::log(x/(x-t)),2)-2.*std::log(1./x)*std::log((-t)/x)+2.*dilog_r(1.-x)
+2.*dilog_r(x/(x-t))-7./2.-2.*M_PIl*M_PIl/3.;
const long double V31=b0*(2.*std::log(MUR*x/(-u))+std::log(MUR*x/(-t)))+(67./9.*_Nc-10./9.*_Nf);
const long double V12=0.5*std::pow(std::log(t/u),2.)+0.5*std::pow(std::log(1./(-t)),2.)-0.5*std::pow(std::log(1./(-u)),2.)
-std::log(x)*std::log((-u)/x)+std::log(x)*std::log((-t)/x)-std::log((-u)/x)*std::log((-t)/x)
+2.*dilog_r(x/(x-t))+std::pow(std::log(x/(x-t)),2.)+M_PIl*M_PIl;
const long double V22=std::pow(std::log(x),2)+std::pow(std::log(x/(x-u)),2)-2.*std::log(1./x)*std::log((-u)/x)+2.*dilog_r(1.-x)
+2.*dilog_r(x/(x-u))-7./2.-2.*M_PIl*M_PIl/3.;
const long double V32=b0*(2.*std::log(MUR*x/(-t))+std::log(MUR*x/(-u)))+(67./9.*_Nc-10./9.*_Nf);
long double ris=0.;
ris+=x*((Delta+_Nc*V11+_Cf*V21+V31)*_Cf*(1.+t*t)/(-u)+(_Nc-_Cf)*_Cf*((1.+t*t+u*u-u*x)/(-u)));
ris+=x*((Delta+_Nc*V12+_Cf*V22+V32)*_Cf*(1.+u*u)/(-t)+(_Nc-_Cf)*_Cf*((1.+u*u+t*t-t*x)/(-t)));
const long double Jac1=-(1.-x-rad)/(2.*rad);
const long double Jac2=(1.-x+rad)/(2.*rad);
const long double Sideltaz1=x/t*b0*std::log(MUF*x/(-t))*(1.+t*t)/(-x*xp/(t));
const long double Sideltaz2=x/u*b0*std::log(MUF*x/(-u))*(1.+u*u)/(-x*xp/(u));
const long double Sideltazb1=x/(t)*3./2.*_Cf*std::log(MUF*x/(-t))*_Cf*(1.+u*u)/(-t);
const long double Sideltazb2=x/(u)*3./2.*_Cf*std::log(MUF*x/(-u))*_Cf*(1.+t*t)/(-u);
return(ris/rad+Jac2*(Sideltaz2+Sideltazb2)-Jac1*(Sideltaz1+Sideltazb1)); // OK
}
//qqbar channel
long double NLOPL::NLO_PL_delta_qqbar(double xp){
const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp);
const long double t=0.5*(x-1.+rad);
const long double u=0.5*(x-1.-rad);
const long double MUR=pow(_muR/_mH,2.);
const long double MUF=pow(_muF/_mH,2.);
const long double b0=11./6.*_Nc-1./3.*_Nf;
const long double Delta=(5.*_Nc-3.*(_Nc*_Nc-1.)/(2.*_Nc));
const long double W1=std::log(-u/x)*std::log(-t/x)-std::log(1./x)*std::log(-u/x)-std::log(1./x)*std::log(-t/x)
+2.*dilog_r(1.-x)+std::pow(std::log(x),2)-0.5*std::pow(std::log(u/t),2)-5./3.*M_PIl*M_PIl;
const long double W2=3./2.*(std::log(1./(-t))+std::log(1./(-u)))+std::pow(std::log(u/t),2)-2.*std::log(-u/x)*std::log(-t/x)
+std::pow(std::log(x/(x-u)),2)+std::pow(std::log(x/(x-t)),2)+2.*dilog_r(x/(x-u))+2.*dilog_r(x/(x-t))-7.+2.*M_PIl*M_PIl;
const long double W3=b0/2.*(4.*std::log(MUR*x)+std::log(MUR*x/(-u))+std::log(MUR*x/(-t)))+(67./6.*_Nc-5./3.*_Nf);
const long double ris=x*((Delta+_Nc*W1+_Cf*W2+W3)*2.*_Cf*_Cf*(t*t+u*u)+(_Nc-_Cf)*2.*_Cf*_Cf*((t*t+u*u+1.-x)));
const long double Jac1=-(1.-x-rad)/(2.*rad);
const long double Jac2=(1.-x+rad)/(2.*rad);
const long double Sidelta1=2.*x/(t)*_Cf*3./2.*std::log(MUF*x/(-t))*2.*_Cf*_Cf*(x*x*xp*xp/(t*t)+t*t);
const long double Sidelta2=2.*x/(u)*_Cf*3./2.*std::log(MUF*x/(-u))*2.*_Cf*_Cf*(x*x*xp*xp/(u*u)+u*u);
return (2.*ris/rad+Jac2*Sidelta2-Jac1*Sidelta1); //OK No Logs
//return 0;
}
//Singular Part
//gg channel
long double NLOPL::NLO_PL_sing_doublediff(double xp, double zz)
{
long double ris=0.0;
//Set Energy, Transverse Momentum, Integration variable za
const long double xx=x;
const long double Nc=_Nc;
const long double Nf=_Nf;
const long double muF=_muF;
const long double muR=_muR;
const long double b0=11./6.*Nc-1./3.*Nf;
const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2);
const long double z=zmin+(1.-zmin)*zz;
//Set Mandelstam variable
const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z);
const long double t1=0.5*(xx-z+rad);
const long double u1=xx-0.5/z*(xx+z+rad);
const long double Q1=1.+t1+u1-xx;
const long double Qt1=Q1+xx*xp;
const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad));
const long double Jac1=(xx-z+rad)/(2.*z*rad);
const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp));
const long double t2=0.5*(xx-z-rad);
const long double u2=xx-0.5/z*(xx+z-rad);
const long double Q2=1.+t2+u2-xx;
const long double Qt2=Q2+xx*xp;
const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad));
const long double Jac2=-(xx-z-rad)/(2.*z*rad);
const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp));
//Define and add the different singular parts
const long double Si12=2.*xx/(-t2)*(1.+std::pow(z,4)+std::pow(1.-z,4))/(z)*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t2,4)+std::pow(xx*xp*z/t2,4))/(z*z*xx*xp);
const long double Si11=2.*xx/(-t1)*(1.+std::pow(z,4)+std::pow(1.-z,4))/(z)*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t1,4)+std::pow(xx*xp*z/t1,4))/(z*z*xx*xp);
const long double Si12z1=16.*Nc*Nc*(1.+std::pow(xx,4)-2.*xx*(1.+xp)-2*xx*xx*xx*(1.+xp)+xx*xx*(3.+4.*xp+xp*xp))/(xp*(1.-xx+sqrt(1.-2.*xx+xx*xx-4.*xx*xp)));
const long double Si11z1=16.*Nc*Nc*(1.+std::pow(xx,4)-2.*xx*(1.+xp)-2*xx*xx*xx*(1.+xp)+xx*xx*(3.+4.*xp+xp*xp))/(xp*(1.-xx-sqrt(1.-2.*xx+xx*xx-4.*xx*xp)));
ris+=std::log(1.-z)/(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1);
const long double Si21=2.*xx*(z/(-t1))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1,4)+std::pow(t1,4))+z*zb1*(std::pow(xx,4)
+1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1);
const long double Si22=2.*xx*(z/(-t2))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2,4)+std::pow(t2,4))+z*zb2*(std::pow(xx,4)
+1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2);
const long double Si21z1=(8.*Nc*Nc*(-std::pow(1.+(xx-1.)*xx,2)+2.*std::pow(1.-xx,2)*xx*xp-xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp))));
const long double Si22z1=(8.*Nc*Nc*(-std::pow(1.+(xx-1.)*xx,2)+2.*std::pow(1.-xx,2)*xx*xp-xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp))));
ris+=std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1);
const long double Si31=2.*xx*(z/(-t1))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1,4)+std::pow(t1,4))+z*zb1*(std::pow(xx,4)
+1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1)*(std::log(Qt1*z/(-t1)));
const long double Si32=2.*xx*(z/(-t2))*Nc*Nc/2.*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2,4)+std::pow(t2,4))+z*zb2*(std::pow(xx,4)
+1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2)*(std::log(Qt2*z/(-t2)));
const long double Si31z1=-(8.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))
*std::log(2.*xx*xp/(1.-xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp))));
const long double Si32z1=-(8.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))
*std::log(2.*xx*xp/(1.-xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp))));
ris+=-1./(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1);
const long double Si41=2.*xx*(z/t1)*b0*Nc/2.*(std::pow(xx,4)+1.+z*zb1*(std::pow(u1/zb1,4)+std::pow(t1/z,4)))/(u1*t1);
const long double Si42=2.*xx*(z/t2)*b0*Nc/2.*(std::pow(xx,4)+1.+z*zb2*(std::pow(u2/zb2,4)+std::pow(t2/z,4)))/(u2*t2);
const long double Si41z1=(4.*Nc*b0*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp))));
const long double Si42z1=(4.*Nc*b0*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp))));
ris+=1./(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1);
const long double Si51=2.*xx/t1*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(muF*xx*z/(-t1))*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t1,4)+std::pow(xx*xp*z/t1,4))/(z*z*xx*xp);
const long double Si52=2.*xx/t2*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(muF*xx*z/(-t2))*Nc*Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(t2,4)+std::pow(xx*xp*z/t2,4))/(z*z*xx*xp);
const long double Si51z1=(16.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp)))*std::log(muF*2.*xx/(1.-xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp))));
const long double Si52z1=(16.*Nc*Nc*(std::pow(1.+(xx-1.)*xx,2)-2.*std::pow(1.-xx,2)*xx*xp+xx*xx*xp*xp)/(xp*(-1.+xx-sqrt(std::pow(1.-xx,2)-4.*xx*xp)))*std::log(muF*2.*xx/(1.-xx+sqrt(std::pow(1.-xx,2)-4.*xx*xp))));
ris+=1./(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1);
ris*=(1.-zmin);
return ris;
}
//gq channel
long double NLOPL::NLO_PL_sing_doublediff_gq(double xp, double zz)
{
long double ris=0.0;
//Set Energy, Transverse Momentum, Integration variable za
const long double xx=x;
const long double Nc=_Nc;
const long double Nf=_Nf;
const long double MUF=std::pow(_muF/_mH,2);
const long double MUR=std::pow(_muR/_mH,2);
const long double b0=11./6.*Nc-1./3.*Nf;
const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2);
const long double z=zmin+(1.-zmin)*zz;
//Set Mandelstam variable
const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z);
const long double t1=0.5*(xx-z+rad);
const long double u1=xx-0.5/z*(xx+z+rad);
const long double rad1=std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp);
const long double t=0.5*(xx-1.+rad1);
const long double u=0.5*(xx-1.-rad1);
const long double Q1=1.+t1+u1-xx;
const long double Qt1=Q1+xx*xp;
const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad));
const long double Jac1=(xx-z+rad)/(2.*z*rad);
const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp));
const long double t2=0.5*(xx-z-rad);
const long double u2=xx-0.5/z*(xx+z-rad);
const long double Q2=1.+t2+u2-xx;
const long double Qt2=Q2+xx*xp;
const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad));
const long double Jac2=-(xx-z-rad)/(2.*z*rad);
const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp));
//Define and add the different singular parts
const long double Si11=xx/(t1)*_Nc*_Cf*((1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(MUF*xx*z/(-t1)))*(z*z+t1*t1)/(-xx*xp*z/(t1));
const long double Si12=xx/(t2)*_Nc*_Cf*((1.+std::pow(z,4)+std::pow(1.-z,4))/z*std::log(MUF*xx*z/(-t2)))*(z*z+t2*t2)/(-xx*xp*z/(t2));
const long double Si11z1=xx/(t)*_Nc*_Cf*(2.*std::log(MUF*xx/(-t)))*(1.+t*t)/(-xx*xp/(t));
const long double Si12z1=xx/(u)*_Nc*_Cf*(2.*std::log(MUF*xx/(-u)))*(1.+u*u)/(-xx*xp/(u));
ris+=1./(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1); // OK 4 Nc Cf Log(x)^2/xp
const long double Si21=xx/(-t1)*_Nc*_Cf*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*(z*z+t1*t1)/(-xx*xp*z/(t1));
const long double Si22=xx/(-t2)*_Nc*_Cf*(1.+std::pow(z,4)+std::pow(1.-z,4))/z*(z*z+t2*t2)/(-xx*xp*z/(t2));
const long double Si21z1=xx/(-t)*_Nc*_Cf*(2.)*(1.+t*t)/(-xx*xp/(t));
const long double Si22z1=xx/(-u)*_Nc*_Cf*(2.)*(1.+u*u)/(-xx*xp*z/(u));
ris+=std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1); //OK no logs
const long double Si31=xx/(t1)*(_Cf*(1.+z*z)*std::log(MUF*xx*z/(-t1)))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t1*t1))/(-t1);
const long double Si32=xx/(t2)*(_Cf*(1.+z*z)*std::log(MUF*xx*z/(-t2)))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t2*t2))/(-t2);
const long double Si31z1=xx/(t)*(_Cf*(2.)*std::log(MUF*xx/(-t)))*_Cf*(1.+xx*xx*xp*xp/(t*t))/(-t);
const long double Si32z1=xx/(u)*(_Cf*(2.)*std::log(MUF*xx/(-u)))*_Cf*(1.+xx*xx*xp*xp/(u*u))/(-u);
ris+=1./(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1); //OK no logs
const long double Si41=xx/(-t1)*(_Cf*(1.+z*z))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t1*t1))/(-t1);
const long double Si42=xx/(-t2)*(_Cf*(1.+z*z))*_Cf*(z*z+xx*xx*xp*xp*z*z/(t2*t2))/(-t2);
const long double Si41z1=xx/(-t)*(_Cf*(2.))*_Cf*(1.+xx*xx*xp*xp/(t*t))/(-t);
const long double Si42z1=xx/(-u)*(_Cf*(2.))*_Cf*(1.+xx*xx*xp*xp/(u*u))/(-u);
ris+=std::log(1.-z)/(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1); //OK no logs
const long double Si51=xx*z/(-t1)*_Nc*_Cf*((-t1-t1*t1*t1+Q1*Q1*Q1*t1+Q1*t1*t1*t1)/(u1*t1)
+(z*zb1*(-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*(u1/zb1)-Q1*std::pow(u1/zb1,3)))/(u1*t1));
const long double Si52=xx*z/(-t2)*_Nc*_Cf*((-t2-t2*t2*t2+Q2*Q2*Q2*t2+Q2*t2*t2*t2)/(u2*t2)
+(z*zb2*(-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*(u2/zb2)-Q2*std::pow(u2/zb2,3)))/(u2*t2));
const long double Si51z1=xx/(-t)*_Nc*_Cf*((-t-t*t*t)/(u*t)+(-(t)-std::pow(t,3))/(u*t));
const long double Si52z1=xx*z/(-u)*_Nc*_Cf*((-u-u*u*u)/(u*t)+(-(u)-std::pow(u,3))/(u*t));
ris+=std::log(1.-z)/(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1); //OK +Nc*Cf*Log(x)^2/xp
const long double Si61=xx*z/(t1)*std::log(Qt1*z/(-t1))*_Nc*_Cf*((-t1-t1*t1*t1+Q1*Q1*Q1*t1+Q1*t1*t1*t1)/(u1*t1)
+(z*zb1*(-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*(u1/zb1)-Q1*std::pow(u1/zb1,3)))/(u1*t1));
const long double Si62=xx*z/(t2)*std::log(Qt2*z/(-t2))*_Nc*_Cf*((-t2-t2*t2*t2+Q2*Q2*Q2*t2+Q2*t2*t2*t2)/(u2*t2)
+(z*zb2*(-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*(u2/zb2)-Q2*std::pow(u2/zb2,3)))/(u2*t2));
const long double Si61z1=xx/(t)*std::log(xx*xp/(-t))*_Nc*_Cf*((-t-t*t*t)/(u*t)+(-(t)-std::pow(t,3))/(u*t));
const long double Si62z1=xx/(u)*std::log(xx*xp/(-u))*_Nc*_Cf*((-u-u*u*u)/(u*t)+(-(u)-std::pow(u,3))/(u*t));
ris+=1./(1.-z)*(Jac2*Si62-Jac2z1*Si62z1-Jac1*Si61+Jac1z1*Si61z1); //OK -3Nc*Cf*Log(x)^2/xp
const long double Si71=xx*z/(t1)*3./2.*_Cf*_Cf*(u1*u1+1.)/(-t1);
const long double Si72=xx*z/(t2)*3./2.*_Cf*_Cf*(u2*u2+1.)/(-t2);
const long double Si71z1=xx*z/(t)*3./2.*_Cf*_Cf*(u*u+1.)/(-t);
const long double Si72z1=xx*z/(u)*3./2.*_Cf*_Cf*(t*t+1.)/(-u);
ris+=1./(1.-z)*(Jac2*Si72-Jac2z1*Si72z1-Jac1*Si71+Jac1z1*Si71z1);//OK (Log semplice non Log squared)
ris*=(1.-zmin);
return ris;
}
//qqbar channel
long double NLOPL::NLO_PL_sing_doublediff_qqbar(double xp, double zz)
{
long double ris=0.0;
//Set Energy, Transverse Momentum, Integration variable za
const long double xx=x;
const long double Nc=_Nc;
const long double Nf=_Nf;
const long double MUF=std::pow(_muF/_mH,2);
const long double MUR=std::pow(_muR/_mH,2);
const long double b0=11./6.*Nc-1./3.*Nf;
const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2);
const long double z=zmin+(1.-zmin)*zz;
//Set Mandelstam variable
const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z);
const long double t1=0.5*(xx-z+rad);
const long double u1=xx-0.5/z*(xx+z+rad);
const long double rad1=std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp);
const long double t=0.5*(xx-1.+rad1);
const long double u=0.5*(xx-1.-rad1);
const long double Q1=1.+t1+u1-xx;
const long double Qt1=Q1+xx*xp;
const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad));
const long double Jac1=(xx-z+rad)/(2.*z*rad);
const long double Jac1z1=(xx-1.+std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp));
const long double t2=0.5*(xx-z-rad);
const long double u2=xx-0.5/z*(xx+z-rad);
const long double Q2=1.+t2+u2-xx;
const long double Qt2=Q2+xx*xp;
const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad));
const long double Jac2=-(xx-z-rad)/(2.*z*rad);
const long double Jac2z1=-(xx-1.-std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp))/(2.*std::sqrt((1.-xx)*(1.-xx)-4.*xx*xp));
//Define and add the different singular parts
const long double Si11=xx/(-t1)*(-_Cf*(1.+z*z)*std::log(MUF*z*xx/(-t1)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t1*t1)*z*z+t1*t1)/z;
const long double Si12=xx/(-t2)*(-_Cf*(1.+z*z)*std::log(MUF*z*xx/(-t2)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t2*t2)*z*z+t2*t2)/z;
const long double Si11z1=xx/(-t)*(-_Cf*(2.)*std::log(MUF*xx/(-t)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t*t)+t*t);
const long double Si12z1=xx/(-t2)*(-_Cf*(2.)*std::log(MUF*xx/(-u)))*2.*_Cf*_Cf*(xx*xx*xp*xp/(u*u)+u*u);
ris+=2./(1.-z)*(Jac2*Si12-Jac2z1*Si12z1-Jac1*Si11+Jac1z1*Si11z1); //OK no Logs
const long double Si21= xx/(-t1)*(_Cf*(1.+z*z))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t1*t1)*z*z+t1*t1)/z;
const long double Si22=xx/(-t2)*(_Cf*(1.+z*z))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t2*t2)*z*z+t2*t2)/z;
const long double Si21z1=xx/(-t)*(_Cf*(2.))*2.*_Cf*_Cf*(xx*xx*xp*xp/(t*t)+t*t);
const long double Si22z1=xx/(-u)*(_Cf*(2.))*2.*_Cf*_Cf*(xx*xx*xp*xp/(u*u)+u*u);
ris+=2.*std::log(1.-z)/(1.-z)*(Jac2*Si22-Jac2z1*Si22z1-Jac1*Si21+Jac1z1*Si21z1); //OK no Logs
const long double Si31=xx*z/(-t1)*(2.*_Cf-_Nc)*_Cf*_Cf*((t1*t1+u1*u1+std::pow(t1/z,2)+std::pow(u1/zb1,2)));
const long double Si32=xx*z/(-t2)*(2.*_Cf-_Nc)*_Cf*_Cf*((t2*t2+u2*u2+std::pow(t2/z,2)+std::pow(u2/zb1,2)));
const long double Si31z1=xx/(-t)*(2.*_Cf-_Nc)*_Cf*_Cf*((t*t+u*u+std::pow(t,2)+std::pow(u,2)));
const long double Si32z1=xx/(-u)*(2.*_Cf-_Nc)*_Cf*_Cf*((u*u+t*t+std::pow(u,2)+std::pow(t,2)));
ris+=2.*std::log(1.-z)/(1.-z)*(Jac2*Si32-Jac2z1*Si32z1-Jac1*Si31+Jac1z1*Si31z1); // OK no Logs
const long double Si41=xx*z/(t1)*std::log(Qt1*z/(-t1))*(2.*_Cf-_Nc)*_Cf*_Cf*((t1*t1+u1*u1+std::pow(t1/z,2)+std::pow(u1/zb1,2)));
const long double Si42=xx*z/(t2)*std::log(Qt2*z/(-t2))*(2.*_Cf-_Nc)*_Cf*_Cf*((t2*t2+u2*u2+std::pow(t2/z,2)+std::pow(u2/zb1,2)));
const long double Si41z1=xx/t*std::log(xx*xp/(-t))*(2.*_Cf-_Nc)*_Cf*_Cf*((t*t+u*u+std::pow(t,2)+std::pow(u,2)));
const long double Si42z1=xx/u*std::log(xx*xp/(-u))*(2.*_Cf-_Nc)*_Cf*_Cf*((u*u+t*t+std::pow(u,2)+std::pow(t,2)));
ris+=2./(1.-z)*(Jac2*Si42-Jac2z1*Si42z1-Jac1*Si41+Jac1z1*Si41z1); //OK no Logs
const long double Si51=-xx*z/(-t1)*b0*_Cf*_Cf*((t1*t1+u1*u1));
const long double Si52=-xx*z/(-t2)*b0*_Cf*_Cf*((t2*t2+u2*u2));
const long double Si51z1=-xx/(-t)*b0*_Cf*_Cf*((t*t+u*u));
const long double Si52z1=-xx/(-u)*b0*_Cf*_Cf*((t*t+u*u));
ris+=2./(1.-z)*(Jac2*Si52-Jac2z1*Si52z1-Jac1*Si51+Jac1z1*Si51z1); //OK no Logs
ris*=(1.-zmin); //OK NO LOGS
return ris;
}
//Not-Singular Part
//gg channel
long double NLOPL::NLO_PL_notsing_doublediff(double xp, double zz){
long double ris=0.0;
//Set Energy, Transverse Momentum, Integration variable z
const long double xx=x;
const long double Nc=_Nc;
const long double Nf=_Nf;
const long double muF=_muF;
const long double muR=_muR;
const long double b0=11./6.*Nc-1./3.*Nf;
const long double Cf=(Nc*Nc-1.)/(2.*Nc);
const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2);
const long double z=zmin+(1.-zmin)*zz;
//Set Mandelstam variable
const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z);
const long double t1=0.5*(xx-z+rad);
const long double u1=xx-0.5/z*(xx+z+rad);
long double Q1=1.+t1+u1-xx;
const long double Qt1=Q1+xx*xp;
const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad));
const long double Jac1=(xx-z+rad)/(2.*z*rad);
const long double t2=0.5*(xx-z-rad);
const long double u2=xx-0.5/z*(xx+z-rad);
long double Q2=1.+t2+u2-xx;
const long double Qt2=Q2+xx*xp;
const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad));
const long double Jac2=-(xx-z-rad)/(2.*z*rad);
const long double A1=1.+xx-Q1;
const long double B1=std::sqrt(A1*A1-4.*xx);
const long double L1a1=std::log(xx/(z*z));
const long double L1b1=std::log(xx/(zb1*zb1));
const long double L2a1=std::log(xx/std::pow(A1-z,2));
const long double L2b1=std::log(xx/std::pow(A1-zb1,2));
const long double L31=std::log((A1+B1)/(A1-B1));
const long double A2=1.+xx-Q2;
const long double B2=std::sqrt(A2*A2-4.*xx);
const long double L1a2=std::log(xx/(z*z));
const long double L1b2=std::log(xx/(zb2*zb2));
const long double L2a2=std::log(xx/std::pow(A2-z,2));
const long double L2b2=std::log(xx/std::pow(A2-zb2,2));
const long double L32=std::log((A2+B2)/(A2-B2));
//Define and add regular parts in G2s (paper Glover for definition of G2s)
const long double Fi1_1=xx/(-t1)*(-2.*Nf*std::log(muF*xx/Q1)*0.5*(z*z+(1.-z)*(1.-z))+2.*Nf*z*(1.-z))*Cf*(z*z*xx*xx*xp*xp/(t1*t1)+z*z)/(-t1);
const long double Fi1_2=xx/(-t2)*(-2.*Nf*std::log(muF*xx/Q2)*0.5*(z*z+(1.-z)*(1.-z))+2.*Nf*z*(1.-z))*Cf*(z*z*xx*xx*xp*xp/(t2*t2)+z*z)/(-t2);
ris+=2.*(Jac2*Fi1_2-Jac1*Fi1_1);
//Separate divergent part Q->0 (ref Grazzini)
const long double tiny=1e-4;
const long double Fi2_1 = (Q1 > tiny*(xx*xp) ) ? Nc*Nc*((std::pow(xx,4)+1.+std::pow(Q1,4)+std::pow(u1/zb1,4)+std::pow(t1/z,4))*(Q1+Qt1)/(Q1*Qt1)
+(2.*xx*xx*(std::pow(xx-t1,4)+std::pow(xx-u1,4)+std::pow(u1,4)+std::pow(t1,4)))/(u1*t1*(xx-u1)*(xx-t1)))*1./(xp)
*std::log(xx*xp/Qt1) : -Nc*Nc*((std::pow(xx,4)+1.+std::pow(u1,4)+std::pow(t1,4))/(xx*xp*xp));
const long double Fi2_2 = ( Q2 > tiny*(xx*xp)) ? Nc*Nc*((std::pow(xx,4)+1.+std::pow(Q2,4)+std::pow(u2/zb2,4)+std::pow(t2/z,4))*(Q2+Qt2)/(Q2*Qt2)
+(2.*xx*xx*(std::pow(xx-t2,4)+std::pow(xx-u2,4)+std::pow(u2,4)+std::pow(t2,4)))/(u2*t2*(xx-u2)*(xx-t2)))*1./(xp)
*std::log(xx*xp/Qt2) : -Nc*Nc*((std::pow(xx,4)+1.+std::pow(u2,4)+std::pow(t2,4))/(xx*xp*xp));
ris+=(Jac2*Fi2_2-Jac1*Fi2_1);
//Define and add G2ns (paper Glover for definition of G2ns)
//A1234
const long double A1234_1_1=-0.5*((pow(xx*xp/t1,4)+pow(xx*Q1/t1,4))*L1a1+pow(u1,4)*L1b1);
const long double A1234_1_2=(pow(xx,2)*Q1*pow(u1,3))/(2.*t1*(u1-xx)*(t1-xx))*(L1a1+L1b1)
+(xx*xp*Q1*pow(u1,3))/(2.*A1*(t1-xx))*(L2b1-L1b1)
+(xx*xp*Q1*(pow(xx,4)+pow(u1-xx,4)))/(2.*A1*t1*(u1-xx))*(L2a1-L1a1);
const long double A1234_1_3=pow(xx,2)*xp*Q1*(pow(u1,4)/(2.*pow(B1*t1,2))+pow(u1,2)/(2.*pow(B1,2)))
+pow(xx,4)*pow(xp*Q1,2)*(-6./pow(B1,4)-4./pow(t1,4)+8./pow(B1*t1,2));
const long double A1234_1_4=L31*(xx*xp*pow(u1,3)*(u1+t1)/(B1*t1)+pow(xx,4)*pow(Q1*xp,2)*(3.*A1/pow(B1,5)-1./(A1*pow(B1,3)))
-pow(xx,2)*xp*Q1*(1./(B1*t1)*(t1*t1+t1*u1+4.*pow(u1,2)-2.*xx*Q1)
+A1/(2.*pow(B1,3))*(t1*t1+3.*t1*u1+3.*u1*u1-6*xx*Q1)+1./(2.*A1*B1)*(t1*t1+t1*u1+7.*u1*u1-2.*xx*Q1)));
const long double A1234_2_1=-0.5*((pow(xx*xp/t2,4)+pow(xx*Q2/t2,4))*L1a2+pow(u2,4)*L1b2);
const long double A1234_2_2=(pow(xx,2)*Q2*pow(u2,3))/(2.*t2*(u2-xx)*(t2-xx))*(L1a2+L1b2)
+(xx*xp*Q2*pow(u2,3))/(2.*A2*(t2-xx))*(L2b2-L1b2)
+(xx*xp*Q2*(pow(xx,4)+pow(u2-xx,4)))/(2.*A2*t2*(u2-xx))*(L2a2-L1a2);
const long double A1234_2_3=pow(xx,2)*xp*Q2*(pow(u2,4)/(2.*pow(B2*t2,2))+pow(u2,2)/(2.*pow(B2,2)))
+pow(xx,4)*pow(xp*Q2,2)*(-6./pow(B2,4)-4./pow(t2,4)+8./pow(B2*t2,2));
const long double A1234_2_4=L32*(xx*xp*pow(u2,3)*(u2+t2)/(B2*t2)+pow(xx,4)*pow(Q2*xp,2)*(3.*A2/pow(B2,5)-1./(A2*pow(B2,3)))
-pow(xx,2)*xp*Q2*(1./(B2*t2)*(t2*t2+t2*u2+4.*pow(u2,2)-2.*xx*Q2)
+A2/(2.*pow(B2,3))*(t2*t2+3.*t2*u2+3.*u2*u2-6*xx*Q2)+1./(2.*A2*B2)*(t2*t2+t2*u2+7.*u2*u2-2.*xx*Q2)));
ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A1234_2_1+A1234_2_2+A1234_2_3+A1234_2_4)-Jac1/(xp*Q1)*(A1234_1_1+A1234_1_2+A1234_1_3+A1234_1_4));
//A3412
const long double A3412_1_1=xx*xp*Q1*pow(A1,3)/(2.*t1*(u1-xx))*(L2a1+L1b1)
+xx*xp*(u1+t1)/(16.*u1*t1*B1)*(pow(A1,4)+6.*pow(A1*B1,2)+pow(B1,4))*L31;
const long double A3412_1_2=(-xx*xp/(2.*u1*t1)*(pow(1.-Q1,4)+pow(xx,4)+2.*Q1*A1*pow(1.-Q1,2)-2.*Q1*pow(xx,3))
-pow(xx,4)*pow(Q1*xp,2)/pow(u1,4)+(2.*pow(xx,2)*xp*Q1*(A1*A1-xx))/(u1*u1))*L1b1;
const long double A3412_1_3=xx*xp*pow(Q1-u1,3)/(8.*u1*t1*(Q1-t1))*((Q1-t1)+Q1*u1)*
(4./3.+2.*xx*xp/Qt1+4.*pow(xx*xp/Qt1,2)-44./3.*pow(xx*xp/Qt1,3))
+xx*xp*pow(Q1-t1,3)/(8.*u1*t1*(Q1-u1))*((Q1-u1)+Q1*t1)*
(4./3.+2.*xx*xp/Qt1+4.*pow(xx*xp/Qt1,2)-44./3.*pow(xx*xp/Qt1,3));
const long double A3412_1_4=xx*xp*pow(Q1-u1,2)/(4.*u1*t1*(Q1-t1))*
(-3.*(t1-xx)*((Q1-t1)+Q1*u1)-Q1*(xx*(t1-xx)+Q1*(u1-xx)))*(1.+2.*xx*xp/Qt1-6.*pow(xx*xp/Qt1,2))
+xx*xp*pow(Q1-t1,2)/(4.*u1*t1*(Q1-u1))*
(-3.*(u1-xx)*((Q1-u1)+Q1*t1)+3.*Q1*(xx*(u1-xx)+Q1*(t1-xx))+4.*u1)*(1.+2.*xx*xp/Qt1-6.*pow(xx*xp/Qt1,2));
const long double A3412_1_5=xx*xp*(Q1-t1)/(2.*u1*t1*(Q1-u1))*(3.*pow(u1-xx,2)*((Q1-u1)+Q1*t1)+8.*u1*t1+2.*u1-2.*Q1*u1*pow(u1-Q1,2)
-3.*xx*Q1*pow(t1-xx,2)-3.*Q1*(xx-Q1)*pow(t1,2)-Q1*u1*(4.*u1*t1-u1*xx-Q1*t1+2.*pow(t1,2)-4.*xx*xx)+3.*xx*pow(Q1,2)*(t1-xx)
+xx*Q1*u1*(t1-Q1))*(1.-2.*xx*xp/Qt1)+xx*xp*(Q1-u1)/(2.*u1*t1*(Q1-t1))*
(3.*pow(t1-xx,2)*((Q1-t1)+Q1*u1)+3.*(t1-xx)*Q1*(xx*(t1-xx)+Q1*(u1-xx))+Q1*u1*(xx*(t1-Q1)+Q1*(u1-xx)))*(1.-2.*xp*xx/Qt1);
const long double A3412_1_6=-4.*pow(xx,4)*pow(Q1*xp,2)/pow(u1,4)+xp*Q1*pow(xx*B1,2)/(2.*u1*u1)
+pow(xx,3)*xp/6.*((1.+Q1)/(u1*t1)+Q1/(u1*u1)+Q1/(t1*t1))+(2.*xp*pow(xx,3)*Q1)/(u1*u1)+pow(xx,3)*xp/u1
-xx*xp/(12.*t1*u1)*(30.*pow(xx,3)+54.*pow(Q1,2)*xx+8.*pow(Q1,3))
+xx*xp/(12*u1*t1)*(11.+17.*pow(xx,4)+Q1*(61.*u1*u1*t1+17.*pow(u1,3)+73.*u1*t1*t1+29.*pow(t1,3))
+xx*(24.*u1*u1*t1+6.*pow(u1,3)+36.*u1*t1*t1+18.*pow(t1,3))+Q1*Q1*(-21.*u1*u1-33.*t1*t1-52.*u1*t1)
+xx*Q1*(-73.*u1*u1-109.*t1*t1-170.*u1*t1)+xx*xx*(-23.*u1*u1-35.*t1*t1-52.*u1*t1)
+xx*xx*Q1*(134.*t1+110.*u1)+4.*pow(Q1,4)+52.*xx*pow(Q1,3)+20.*xx*xx*Q1*Q1-22.*pow(xx,3)*Q1);
const long double A3412_2_1=xx*xp*Q2*pow(A2,3)/(2.*t2*(u2-xx))*(L2a2+L1b2)
+xx*xp*(u2+t2)/(16.*u2*t2*B2)*(pow(A2,4)+6.*pow(A2*B2,2)+pow(B2,4))*L32;
const long double A3412_2_2=(-xx*xp/(2.*u2*t2)*(pow(1.-Q2,4)+pow(xx,4)+2.*Q2*A2*pow(1.-Q2,2)-2.*Q2*pow(xx,3))
-pow(xx,4)*pow(Q2*xp,2)/pow(u2,4)+(2.*pow(xx,2)*xp*Q2*(A2*A2-xx))/(u2*u2))*L1b2;
const long double A3412_2_3=xx*xp*pow(Q2-u2,3)/(8.*u2*t2*(Q2-t2))*((Q2-t2)+Q2*u2)*
(4./3.+2.*xx*xp/Qt2+4.*pow(xx*xp/Qt2,2)-44./3.*pow(xx*xp/Qt2,3))
+xx*xp*pow(Q2-t2,3)/(8.*u2*t2*(Q2-u2))*((Q2-u2)+Q2*t2)*
(4./3.+2.*xx*xp/Qt2+4.*pow(xx*xp/Qt2,2)-44./3.*pow(xx*xp/Qt2,3));
const long double A3412_2_4=xx*xp*pow(Q2-u2,2)/(4.*u2*t2*(Q2-t2))*
(-3.*(t2-xx)*((Q2-t2)+Q2*u2)-Q2*(xx*(t2-xx)+Q2*(u2-xx)))*(1.+2.*xx*xp/Qt2-6.*pow(xx*xp/Qt2,2))
+xx*xp*pow(Q2-t2,2)/(4.*u2*t2*(Q2-u2))*
(-3.*(u2-xx)*((Q2-u2)+Q2*t2)+3.*Q2*(xx*(u2-xx)+Q2*(t2-xx))+4.*u2)*(1.+2.*xx*xp/Qt2-6.*pow(xx*xp/Qt2,2));
const long double A3412_2_5=xx*xp*(Q2-t2)/(2.*u2*t2*(Q2-u2))*(3.*pow(u2-xx,2)*((Q2-u2)+Q2*t2)+8.*u2*t2+2.*u2-2.*Q2*u2*pow(u2-Q2,2)
-3*xx*Q2*pow(t2-xx,2)-3.*Q2*(xx-Q2)*pow(t2,2)-Q2*u2*(4.*u2*t2-u2*xx-Q2*t2+2.*pow(t2,2)-4.*xx*xx)+3.*xx*pow(Q2,2)*(t2-xx)
+xx*Q2*u2*(t2-Q2))*(1-2.*xx*xp/Qt2)+xx*xp*(Q2-u2)/(2.*u2*t2*(Q2-t2))*
(3.*pow(t2-xx,2)*((Q2-t2)+Q2*u2)+3.*(t2-xx)*Q2*(xx*(t2-xx)+Q2*(u2-xx))+Q2*u2*(xx*(t2-Q2)+Q2*(u2-xx)))*(1-2.*xp*xx/Qt2);
const long double A3412_2_6=-4.*pow(xx,4)*pow(Q2*xp,2)/pow(u2,4)+xp*Q2*pow(xx*B2,2)/(2.*u2*u2)
+pow(xx,3)*xp/6.*((1.+Q2)/(u2*t2)+Q2/(u2*u2)+Q2/(t2*t2))+(2.*xp*pow(xx,3)*Q2)/(u2*u2)+pow(xx,3)*xp/u2
-xx*xp/(12.*t2*u2)*(30.*pow(xx,3)+54.*pow(Q2,2)*xx+8.*pow(Q2,3))
+xx*xp/(12*u2*t2)*(11.+17.*pow(xx,4)+Q2*(61.*u2*u2*t2+17.*pow(u2,3)+73.*u2*t2*t2+29.*pow(t2,3))
+xx*(24.*u2*u2*t2+6.*pow(u2,3)+36.*u2*t2*t2+18.*pow(t2,3))+Q2*Q2*(-21.*u2*u2-33.*t2*t2-52.*u2*t2)
+xx*Q2*(-73.*u2*u2-109.*t2*t2-170.*u2*t2)+xx*xx*(-23.*u2*u2-35.*t2*t2-52.*u2*t2)
+xx*xx*Q2*(134.*t2+110.*u2)+4.*pow(Q2,4)+52.*xx*pow(Q2,3)+20.*xx*xx*Q2*Q2-22.*pow(xx,3)*Q2);
ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A3412_2_1+A3412_2_2+A3412_2_3+A3412_2_4+A3412_2_5+A3412_2_6)-Jac1/(xp*Q1)*(A3412_1_1+A3412_1_2+A3412_1_3+A3412_1_4+A3412_1_5+A3412_1_6));
//A1324
const long double A1324_1_1=-0.5*((pow(xx*xp/t1,4)+pow(xx*Q1/t1,4))*L1a1+pow(u1,4)*L1b1)
+pow(xx,3)*xp*Q1/(t1*t1)*L1a1+(pow(xx,2)*Q1*pow(u1,3)/(2.*t1*(u1-xx)*(t1-xx))+xx*xp*pow(u1,3)/(2.*t1))
*(L1a1+L1b1);
const long double A1324_1_2=xx*xp*(1.-zb1)*pow(u1,3)/(2.*A1*(t1-xx))*(L2b1-L1b1)
+(xx*xp*(1.-z)*(pow(xx,4)+pow(u1-xx,4)))/(2.*A1*t1*(u1-xx))*(L2a1-L1a1)
+pow(xx,3)*xp*Q1/(A1*B1)*L31+xx*xx*xp*Q1/(2.*pow(t1,4))*(pow(xx*xp,2)-6.*xx*xx*xp*Q1+pow(xx*Q1,2));
const long double A1324_2_1=-0.5*((pow(xx*xp/t2,4)+pow(xx*Q2/t2,4))*L1a2+pow(u2,4)*L1b2)
+pow(xx,3)*xp*Q2/(t2*t2)*L1a2+(pow(xx,2)*Q2*pow(u2,3)/(2.*t2*(u2-xx)*(t2-xx))+xx*xp*pow(u2,3)/(2.*t2))
*(L1a2+L1b2);
const long double A1324_2_2=xx*xp*(1.-zb2)*pow(u2,3)/(2.*A2*(t2-xx))*(L2b2-L1b2)
+(xx*xp*(1.-z)*(pow(xx,4)+pow(u2-xx,4)))/(2.*A2*t2*(u2-xx))*(L2a2-L1a2)
+pow(xx,3)*xp*Q2/(A2*B2)*L32+xx*xx*xp*Q2/(2.*pow(t2,4))*(pow(xx*xp,2)-6.*xx*xx*xp*Q2+pow(xx*Q2,2));
ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A1324_2_1+A1324_2_2)-Jac1/(xp*Q1)*(A1324_1_1+A1324_1_2));
//A3241
const long double A3241_1_1=xx*xp*pow(A1,3)*(1.-z)/(2.*t1*(u1-xx))*(L2a1-L1a1)
+(-pow(xx,4)*pow(xp*Q1,2)/pow(t1,4)+pow(xx,3)*xp*pow(Q1,2)/(u1*t1)
-xx*xx*xp*Q1*pow(A1,4)/(2.*u1*t1*(u1-xx)*(t1-xx))+xx*xx*xp*Q1*(u1+t1)*(2.*A1*A1-xx)/(u1*t1*t1))*L1a1;
const long double A3241_1_2=xx*xp*Q1*pow(Q1-u1,2)/(2.*u1*t1*pow(Q1-t1,2))*
(-u1*t1-pow(Q1-t1,2))*(-3.+10.*Q1/Qt1-6.*pow(Q1/Qt1,2))
+xx*xp*Q1*(Q1-u1)/(u1*t1*pow(Q1-t1,2))*(u1*t1*(Q1-u1)-pow(Q1-t1,3)-xx*pow(Q1-t1,2)-xx*(Q1-t1)*(Q1-u1))
*(-1.+2.*Q1/Qt1);
const long double A3241_1_3=xx*xx*xp*Q1*(B1*B1/(2.*t1*t1)-2.*xx*Q1/(t1*t1)+(u1+t1)*(u1+t1)/(2.*u1*t1))
-4.*pow(xx,4)*pow(xp*Q1,2)/pow(t1,4)+xx*xp*Q1/(4.*u1*t1)
*(pow(t1+u1,2)-(t1+u1)*(6.*Q1+4.*xx)+6.*Q1*Q1+8.*xx*Q1)+pow(xx,3)*xp*Q1*pow(t1+u1,2)/(4.*u1*u1*t1*t1);
const long double A3241_2_1=xx*xp*pow(A2,3)*(1.-z)/(2.*t2*(u2-xx))*(L2a2-L1a2)
+(-pow(xx,4)*pow(xp*Q2,2)/pow(t2,4)+pow(xx,3)*xp*pow(Q2,2)/(u2*t2)
-xx*xx*xp*Q2*pow(A2,4)/(2.*u2*t2*(u2-xx)*(t2-xx))+xx*xx*xp*Q2*(u2+t2)*(2.*A2*A2-xx)/(u2*t2*t2))*L1a2;
const long double A3241_2_2=xx*xp*Q2*pow(Q2-u2,2)/(2.*u2*t2*pow(Q2-t2,2))*
(-u2*t2-pow(Q2-t2,2))*(-3.+10.*Q2/Qt2-6.*pow(Q2/Qt2,2))
+xx*xp*Q2*(Q2-u2)/(u2*t2*pow(Q2-t2,2))*(u2*t2*(Q2-u2)-pow(Q2-t2,3)-xx*pow(Q2-t2,2)-xx*(Q2-t2)*(Q2-u2))
*(-1.+2.*Q2/Qt2);
const long double A3241_2_3=xx*xx*xp*Q2*(B2*B2/(2.*t2*t2)-2.*xx*Q2/(t2*t2)+(u2+t2)*(u2+t2)/(2.*u2*t2))
-4.*pow(xx,4)*pow(xp*Q2,2)/pow(t2,4)+xx*xp*Q2/(4.*u2*t2)
*(pow(t2+u2,2)-(t2+u2)*(6.*Q2+4.*xx)+6.*Q2*Q2+8.*xx*Q2)+pow(xx,3)*xp*Q2*pow(t2+u2,2)/(4.*u2*u2*t2*t2);
ris+=2.*Nc*Nc*(Jac2/(xp*Q2)*(A3241_2_1+A3241_2_2+A3241_2_3)-Jac1/(xp*Q1)*(A3241_1_1+A3241_1_2+A3241_1_3));
//Aepsilon
const long double Aepsilon_1=4.*pow(xx,4)*pow(xp*Q1,2)*(1./pow(t1,4)+1./pow(u1,4));
const long double Aepsilon_2=4.*pow(xx,4)*pow(xp*Q2,2)*(1./pow(t2,4)+1./pow(u2,4));
ris+=Nc*Nc*(Jac2/(xp*Q2)*(Aepsilon_2)-Jac1/(xp*Q1)*(Aepsilon_1));
//A0
const long double A0_1= (pow(t1/z,4)+pow(u1/zb1,4))*xx*xp/(Qt1*Qt1)*(5.-7.*Q1/Qt1+20./3.*pow(Q1/Qt1,2))
+xx*xp*(17./3.+4.*std::log(xx*xp/Qt1));
const long double A0_2=(pow(t2/z,4)+pow(u2/zb2,4))*xx*xp/(Qt2*Qt2)*(5.-7.*Q2/Qt2+20./3.*pow(Q2/Qt2,2))
+xx*xp*(17./3.+4.*std::log(xx*xp/Qt2));
ris+=Nc*Nc*(Jac2/(xp)*(A0_2)-Jac1/(xp)*(A0_1));
//B1pm
const long double B1pm_1=xx*xp*z*pow(1.-z,3)/t1+pow(xx*xp*z/t1,3)*(1.-z)
+4.*pow(xx*xp*z/t1*(1.-z),2)-xx*xp*Q1*(1.+std::log(xx*xp/Qt1));
const long double B1pm_2=xx*xp*z*pow(1.-z,3)/t2+pow(xx*xp*z/t2,3)*(1.-z)
+4.*pow(xx*xp*z/t2*(1.-z),2)-xx*xp*Q2*(1.+std::log(xx*xp/Qt2));
ris+=2.*Nf*Cf*(Jac2/(xp*Q2)*B1pm_2-Jac1/(xp*Q1)*B1pm_1);
//B2pm //FIXME? C'è una differenza con risultato mathematica ma non capisco da dove dipenda. Contributo completamente negiglible comunque
const long double B2pm_1=1./3.*pow(t1/z,4.)*xx*xp/Qt1*(-3./Qt1+3.*Q1/(Qt1*Qt1)-2.*Q1*Q1/(Qt1*Qt1*Qt1))
-1./3.*xx*xp;
const long double B2pm_2=1./3.*pow(t2/z,4.)*xx*xp/Qt2*(-3./Qt2+3.*Q1/(Qt2*Qt2)-2.*Q2*Q2/(Qt2*Qt2*Qt2))
-1./3.*xx*xp;
ris+=2.*Nf*Nc*(Jac2/xp*B2pm_2-Jac1/xp*B2pm_1);
//B1pp
const long double B1pp_1=xx*xp*pow(z,3)*(1.-z)/t1+pow(xx*xp*(1.-z)/t1,3)*z
+4.*pow(xx*xp*z*(1.-z)/t1,2)-xx*xp*Q1/(Qt1*Qt1*u1*t1)*(pow(u1*t1+xx*xp*Q1,2)+2.*xx*xp*Q1*Qt1)
+xx*xp*Q1/(u1*t1)*(1.+Q1*Q1)*std::log(1.+(xx*xp/Q1));
const long double B1pp_2=xx*xp*pow(z,3)*(1.-z)/t2+pow(xx*xp*(1.-z)/t2,3)*z
+4.*pow(xx*xp*z*(1.-z)/t2,2)-xx*xp*Q2/(Qt2*Qt2*u2*t2)*(pow(u2*t2+xx*xp*Q2,2)+2.*xx*xp*Q2*Qt2)
+xx*xp*Q2/(u2*t2)*(1.+Q2*Q2)*std::log(1.+(xx*xp/Q2));
ris+=2.*Nf*Cf*(Jac2/(xp*Q2)*B1pp_2-Jac1/(xp*Q1)*B1pp_1);
//B2pp
const long double B2pp_1_1=-xx*xp*Q1/(2.*u1*t1)*(1.+Q1*Q1)*std::log(Qt1/Q1);
const long double B2pp_1_2=+xx*xp*std::pow(Q1-u1,3.)/(2.*u1*t1*(Q1-t1))*((Q1-t1)+Q1*u1)
*(2./3.+Q1/Qt1-19./3.*std::pow(Q1/Qt1,3.))
-xx*xp*std::pow(Q1-u1,2.)/(2.*u1*t1*std::pow(Q1-t1,2.))
*(3.*std::pow(Q1-t1,3.)*Q1+(Q1-t1)*Q1*(2.*u1*t1+xx*xx)
+std::pow(Q1-t1,2.)*(1+4.*xx*Q1-u1*(Q1+xx))-u1*u1*Q1*Q1+u1*t1*t1*xx)*(1.-2.*Q1*Q1/(Qt1*Qt1))
+xx*xp*(Q1-u1)/(2.*u1*t1*(Q1-t1))*(3.*Q1*(Q1+1.)*(Q1-t1)-t1+xx*Q1+Q1*u1*(xx-Q1)*(xx-Q1))*(1.-2.*Q1/Qt1);
const long double B2pp_1_3=xx*xp/(12.*u1*t1)*(-2.+6.*xx*t1*(t1-xx)+2.*xx*xx*xx+8.*Q1*(1.-Q1)*(1.-Q1)
-2.*u1*t1*Q1+7.*xx*xp*Q1-2.*Q1*Q1*xx-xx*xx*xx*Q1+3.*xx*Q1*Q1*Q1-4.*u1*t1*xx*Q1)
+11./6.*xx*xp*Q1*Q1/(u1*t1)-xx*xp*xx*xx*Q1/(3.*t1*t1);
const long double B2pp_2_1=-xx*xp*Q2/(2.*u2*t2)*(1.+Q2*Q2)*std::log(Qt2/Q2);
const long double B2pp_2_2=+xx*xp*std::pow(Q2-u2,3.)/(2.*u2*t2*(Q2-t2))*((Q2-t2)+Q2*u2)
*(2./3.+Q2/Qt2-19./3.*std::pow(Q2/Qt2,3.))
-xx*xp*std::pow(Q2-u2,2.)/(2.*u2*t2*std::pow(Q2-t2,2.))
*(3.*std::pow(Q2-t2,3.)*Q2+(Q2-t2)*Q2*(2.*u2*t2+xx*xx)
+std::pow(Q2-t2,2.)*(1+4.*xx*Q2-u2*(Q2+xx))-u2*u2*Q2*Q2+u2*t2*t2*xx)*(1.-2.*Q2*Q2/(Qt2*Qt2))
+xx*xp*(Q2-u2)/(2.*u2*t2*(Q2-t2))*(3.*Q2*(Q2+1.)*(Q2-t2)-t2+xx*Q2+Q2*u2*(xx-Q2)*(xx-Q2))*(1.-2.*Q2/Qt2);
const long double B2pp_2_3=xx*xp/(12.*u2*t2)*(-2.+6.*xx*t2*(t2-xx)+2.*xx*xx*xx+8.*Q2*(1.-Q2)*(1.-Q2)
-2.*u2*t2*Q2+7.*xx*xp*Q2-2.*Q2*Q2*xx-xx*xx*xx*Q2+3.*xx*Q2*Q2*Q2-4.*u2*t2*xx*Q2)
+11./6.*xx*xp*Q2*Q2/(u2*t2)-xx*xp*xx*xx*Q2/(3.*t2*t2);
//res[0]+=2.*Nc*Nf*(Jac2/(xp*Q2)*(B2pp_2_1+B2pp_2_2+B2pp_2_3)-Jac1/(xp*Q1)*(B2pp_1_1+B2pp_1_2+B2pp_1_3));
ris+=2.*Nc*Nf*(Jac2/(xp*Q2)*(B2pp_2_1)-Jac1/(xp*Q1)*(B2pp_1_1)); // Il resto è integrato analiticamente in B2pp_ANALITICS
/*if (res[0]!=res[0]) {
std::cout << "nan Yes \t z= " << z << " x= " << xx << std::endl;
}*/
ris*=(1.-zmin);
return ris;
}
//gq channel
long double NLOPL::NLO_PL_notsing_doublediff_gq(double xp, double zz){
long double ris=0.0;
//Set Energy, Transverse Momentum, Integration variable z
const long double xx=x;
const long double Nc=_Nc;
const long double Nf=_Nf;
const long double MUF=std::pow(_muF/_mH,2);
const long double MUR=std::pow(_muR/_mH,2);
const long double b0=11./6.*Nc-1./3.*Nf;
const long double Cf=(Nc*Nc-1.)/(2.*Nc);
const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2);
const long double z=zmin+(1.-zmin)*zz;
//Set Mandelstam variable
const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z);
const long double t1=0.5*(xx-z+rad);
const long double u1=xx-0.5/z*(xx+z+rad);
long double Q1=1.+t1+u1-xx;
const long double Qt1=Q1+xx*xp;
const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad));
const long double Jac1=(xx-z+rad)/(2.*z*rad);
const long double t2=0.5*(xx-z-rad);
const long double u2=xx-0.5/z*(xx+z-rad);
long double Q2=1.+t2+u2-xx;
const long double Qt2=Q2+xx*xp;
const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad));
const long double Jac2=-(xx-z-rad)/(2.*z*rad);
const long double A1=1.+xx-Q1;
const long double B1=std::sqrt(A1*A1-4.*xx);
const long double L1a1=std::log(xx/(z*z));
const long double L1b1=std::log(xx/(zb1*zb1));
const long double L2a1=std::log(xx/std::pow(A1-z,2));
const long double L2b1=std::log(xx/std::pow(A1-zb1,2));
const long double L31=std::log((A1+B1)/(A1-B1));
const long double A2=1.+xx-Q2;
const long double B2=std::sqrt(A2*A2-4.*xx);
const long double L1a2=std::log(xx/(z*z));
const long double L1b2=std::log(xx/(zb2*zb2));
const long double L2a2=std::log(xx/std::pow(A2-z,2));
const long double L2b2=std::log(xx/std::pow(A2-zb2,2));
const long double L32=std::log((A2+B2)/(A2-B2));
//Define and add regular parts in G2s (refer to Glover paper for definition of G2s)
const long double Fi11=xx/(-t1)*(-0.5*(z*z+(1.-z)*(1.-z))*std::log(MUF*xx/Q1)+z*(1.-z))
*2.*_Cf*_Cf*(xx*xx*xp*xp*z*z/(t1*t1)+t1*t1)/(z)+xx/(-t1)*_Cf*(1.-z)*_Cf*(xx*xx*xp*xp*z*z/(t1*t1)+z*z)/(-t1)
+xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)
*_Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(z*xx*xp/t1,4)+std::pow(t1,4))/(z*z*xx*xp);
const long double Fi12=xx/(-t2)*(-0.5*(z*z+(1.-z)*(1.-z))*std::log(MUF*xx/Q2)+z*(1.-z))
*2.*_Cf*_Cf*(xx*xx*xp*xp*z*z/(t2*t2)+t2*t2)/(z)+xx/(-t2)*_Cf*(1.-z)*_Cf*(xx*xx*xp*xp*z*z/(t2*t2)+z*z)/(-t2)
+xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)
*_Nc*(std::pow(xx,4)+std::pow(z,4)+std::pow(z*xx*xp/t2,4)+std::pow(t2,4))/(z*z*xx*xp);
ris+=(Jac2*Fi12-Jac1*Fi11); // OK 6 Nc Cf Log(x)^2/xp
//Separate Divergent part (Q^2->0) see Grazzini
const long double tiny=1e-4;
const long double Fi21=(Q1>tiny*xx*xp) ? xx* _Nc*_Cf*(((-(t1/z)-std::pow(t1/z,3)-Q1*Q1*Q1*u1/zb1-Q1*std::pow(u1/zb1,3))*(Q1+Qt1))/(Q1*Qt1)
-(2.*xx*xx*((xx-t1)*(xx-t1)+t1*t1))/(u1*(xx-u1)))/(xx*xp)*std::log(xx*xp/Qt1) : (t1*t1*t1+t1*z*z)/(z*z*z*xx*xp*xp) ;
const long double Fi22=(Q2>tiny*xx*xp) ? xx* _Nc*_Cf*(((-(t2/z)-std::pow(t2/z,3)-Q2*Q2*Q2*u2/zb2-Q2*std::pow(u2/zb2,3))*(Q2+Qt2))/(Q2*Qt2)
-(2.*xx*xx*((xx-t2)*(xx-t2)+t2*t2))/(u2*(xx-u2)))/(xx*xp)*std::log(xx*xp/Qt2) : (t2*t2*t2+t2*z*z)/(z*z*z*xx*xp*xp) ;
ris+=(Jac2*Fi22-Jac1*Fi21); // OK -10 Nc Cf Log(x)^2/xp
const long double C1pm1=-2.*xx*gsl_sf_log(xx*xp/Qt1);
const long double C1pm2=-2.*xx*gsl_sf_log(xx*xp/Qt2);
ris+=_Cf*_Cf*(Jac2*(C1pm2)-Jac1*(C1pm1));
const long double C1mp1=xx*xp*Q1-3.*xx*xp*t1*t1/2./u1+xx*xp/(2.*Qt1)*(pow(Q1-t1,3)+Q1*pow(Q1-u1,3))*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1);
const long double C1mp2=xx*xp*Q2-3.*xx*xp*t2*t2/2./u2+xx*xp/(2.*Qt2)*(pow(Q2-t2,3)+Q1*pow(Q2-u2,3))*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2);
ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1mp2)-1./xp/Q1*Jac1*(C1mp1));
const long double C1pp1=-3.*xx*xp/(2.*u1)-xx*xp*Q1*A1*A1/u1*L2b1+xx*xp/(u1*t1*t1)*L1a1*((A1-xx)*(A1-xx)*t1*t1-2.*Q1*xx*u1*t1*A1-Q1*xx*xx*(Q1-t1)*u1)
+xx*xp/(u1*B1)*L31*((1.+Q1-xx)*((A1-xx)*(A1-xx)+Q1*A1*A1)-4.*Q1*A1*(A1-xx))+1./2.*xx*xp*(Q1-t1)*(Q1-t1)*(1./(Q1-u1)-Q1/u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1)
+1./2.*xx*xp*(Q1-u1)*(Q1-u1)*(Q1/(Q1-t1)+1./u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1)+xx*xp*(Q1-t1)/(u1*(Q1-u1))*(2.*u1*(1.+t1)
-Q1*(4.*xx*Q1-Q1*t1-xx*u1-2.*u1*t1))*(-1.+2.*Q1/Qt1)+xx*xp*(Q1-u1)/(u1*(Q1-t1))*(t1-2.*u1*t1+2.*Q1*u1*(Q1-t1))*(-1.+2.*Q1/Qt1)
+xx*xp*Q1*xx*(t1+u1)/t1-2.*xx*xp*Q1*Q1*xx*xx/(t1*t1)+xx*xp*Q1*xx*xx/(2.*u1*u1)+xx*xp/(2.*u1)*(-2.*(Q1+xx)*u1+2.*xx+xx*xx+xx*Q1*(2.*(1.-Q1)+3.*xx-u1)+5.*Q1*(1.-Q1));
const long double C1pp2=-3.*xx*xp/(2.*u2)-xx*xp*Q2*A2*A2/u2*L2b2+xx*xp/(u2*t2*t2)*L1a2*((A2-xx)*(A2-xx)*t2*t2-2.*Q2*xx*u2*t2*A2-Q2*xx*xx*(Q2-t2)*u2)
+xx*xp/(u2*B2)*L32*((1.+Q2-xx)*((A2-xx)*(A2-xx)+Q2*A2*A2)-4.*Q2*A2*(A2-xx))+1./2.*xx*xp*(Q2-t2)*(Q2-t2)*(1./(Q2-u2)-Q2/u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2)
+1./2.*xx*xp*(Q2-u2)*(Q2-u2)*(Q2/(Q2-t2)+1./u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2)+xx*xp*(Q2-t2)/(u2*(Q2-u2))*(2.*u2*(1.+t2)
-Q2*(4.*xx*Q2-Q2*t2-xx*u2-2.*u2*t2))*(-1.+2.*Q2/Qt2)+xx*xp*(Q2-u2)/(u2*(Q2-t2))*(t2-2.*u2*t2+2.*Q2*u2*(Q2-t2))*(-1.+2.*Q2/Qt2)
+xx*xp*Q2*xx*(t2+u2)/t2-2.*xx*xp*Q2*Q2*xx*xx/(t2*t2)+xx*xp*Q2*xx*xx/(2.*u2*u2)+xx*xp/(2.*u2)*(-2.*(Q2+xx)*u2+2.*xx+xx*xx+xx*Q2*(2.*(1.-Q2)+3.*xx-u2)+5.*Q2*(1.-Q2));
ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1pp2)-1./xp/Q1*Jac1*(C1pp1));
const long double C1mm1=xx*xp*t1*t1/u1*L1a1-xx*xp*Q1*(xx-t1)*(xx-t1)/u1*L2b1+xx*xp*xx*Q1/B1/B1*(t1*(u1+t1)-2.*xx*Q1)
+xx*xp/(u1*B1)*(t1*t1*B1*B1-xx*t1*t1*(u1+t1)+2.*Q1*Q1*xx*xx+Q1*xx*xx*(3.*t1-u1)+Q1*xx*xx*u1/(B1*B1)*(-t1*(u1+t1)+2.*xx*Q1+Q1*(t1-u1)))*L31;
const long double C1mm2=xx*xp*t2*t2/u2*L1a2-xx*xp*Q2*(xx-t2)*(xx-t2)/u2*L2b2+xx*xp*xx*Q2/B2/B2*(t2*(u2+t2)-2.*xx*Q2)
+xx*xp/(u2*B2)*(t2*t2*B2*B2-xx*t2*t2*(u2+t2)+2.*Q2*Q2*xx*xx+Q2*xx*xx*(3.*t2-u2)+Q2*xx*xx*u2/(B2*B2)*(-t2*(u2+t2)+2.*xx*Q2+Q2*(t2-u2)))*L32;
ris+=_Cf*_Cf*(1./xp/Q2*Jac2*(C1mm2)-1./xp/Q1*Jac1*(C1mm1));
const long double C2mp1=xx*xp*Q1/Qt1/Qt1*(pow(Q1-t1,3)+Q1*pow(Q1-u1,3))*(-2.+3.*Q1/Qt1)+2.*xx*xp*Q1+4.*xx*xp*Q1*gsl_sf_log(xx*xp/Qt1);
const long double C2mp2=xx*xp*Q2/Qt2/Qt2*(pow(Q2-t2,3)+Q2*pow(Q2-u2,3))*(-2.+3.*Q2/Qt2)+2.*xx*xp*Q2+4.*xx*xp*Q2*gsl_sf_log(xx*xp/Qt2);
ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2mp2)-1./xp/Q1*Jac1*(C2mp1));
const long double C2pp1=1./2.*xx*xp*A1*A1*(1.-z)*(L2a1-L1a1)+(xx*xp*(xx-t1)*A1*A1*(1.-zb1))/(2.*u1)*(L1b1-L2b1)
+xx*xp*pow(1.-Q1,3)/(2.*u1)*(L1b1-L1a1)+xx*xp*Q1*A1*A1/(xx-u1)*(L1b1+L2a1)
+xx*xp*Q1/(u1*u1)*L1b1*(2.*u1*(1.-Q1)*(1.-Q1)+4.*xx*(xx-t1)*A1-2.*xx*xx*(Q1-t1)-xx*xx*xx)
-1./2.*xx*xp*pow(Q1-t1,2)*(1./(Q1-u1)-Q1/u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1)
-1./2.*xx*xp*pow(Q1-u1,2)*(Q1/(Q1-t1)+1./u1)*(-3.+10.*Q1/Qt1-6.*Q1*Q1/Qt1/Qt1)
+xx*xp*(Q1-t1)/(2.*u1*(Q1-u1))*((-3.*xx*xp+u1*u1-Q1*Q1)*(1.+Q1)-xx*u1+2.*Q1*Q1*(Q1-u1))*(-1.+2.*Q1/Qt1)
+xx*xp*(Q1-u1)/(2.*u1*(Q1-t1))*(3.*xx*xp*(1.+Q1)-u1*Q1*(Q1-t1)+3.*Q1*xx*(Q1-u1)+t1*(u1+1.))*(-1.+2.*Q1/Qt1)
+xx*xp*xx*Q1/(2.*u1*u1)*(2.*(1.-Q1)*(1.-Q1)-2.*xx*(1.-xx)-u1*(Q1-u1)-4.*xx*Q1)+xx*xp*(u1-t1)*(xx+Q1)/(2.*u1)
-8.*pow(xx*xx*xp*Q1,2)/pow(u1,4)-2.*pow(xx*xx*xp*Q1,2)/pow(u1,4)*L1b1;
const long double C2pp2=1./2.*xx*xp*A2*A2*(1.-z)*(L2a2-L1a2)+(xx*xp*(xx-t2)*A2*A2*(1.-zb2))/(2.*u2)*(L1b2-L2b2)
+xx*xp*pow(1.-Q2,3)/(2.*u2)*(L1b2-L1a2)+xx*xp*Q2*A2*A2/(xx-u2)*(L1b2+L2a2)
+xx*xp*Q2/(u2*u2)*L1b2*(2.*u2*(1.-Q2)*(1.-Q2)+4.*xx*(xx-t2)*A2-2.*xx*xx*(Q2-t2)-xx*xx*xx)
-1./2.*xx*xp*pow(Q2-t2,2)*(1./(Q2-u2)-Q2/u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2)
-1./2.*xx*xp*pow(Q2-u2,2)*(Q2/(Q2-t2)+1./u2)*(-3.+10.*Q2/Qt2-6.*Q2*Q2/Qt2/Qt2)
+xx*xp*(Q2-t2)/(2.*u2*(Q2-u2))*((-3.*xx*xp+u2*u2-Q2*Q2)*(1.+Q2)-xx*u2+2.*Q2*Q2*(Q2-u2))*(-1.+2.*Q2/Qt2)
+xx*xp*(Q2-u2)/(2.*u2*(Q2-t2))*(3.*xx*xp*(1.+Q2)-u2*Q2*(Q2-t2)+3.*Q2*xx*(Q2-u2)+t2*(u2+1.))*(-1.+2.*Q2/Qt2)
+xx*xp*xx*Q2/(2.*u2*u2)*(2.*(1.-Q2)*(1.-Q2)-2.*xx*(1.-xx)-u2*(Q2-u2)-4.*xx*Q2)+xx*xp*(u2-t2)*(xx+Q2)/(2.*u2)
-8.*pow(xx*xx*xp*Q2,2)/pow(u2,4)-2.*pow(xx*xx*xp*Q2,2)/pow(u2,4)*L1b2;
ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2pp2)-1./xp/Q1*Jac1*(C2pp1));
const long double C2mm1=xx*xp*t1*t1*Q1/(2.*u1)*(L1a1+3.*L1b1)+1./2.*xx*xp*t1*t1*(1.-z)*(L2a1-L1a1)+xx*xp*Q1*pow(xx-t1,3)*zb1/(2.*u1*u1)*(L2b1-L1b1)+xx*xp*t1*t1*Q1/(xx-u1)*(L1b1+L2a1)
+xx*xp*t1*t1/(2.*u1)*(L1b1-L1a1)+xx*xp*xx*Q1/(u1*u1)*(4.*t1*(t1-xx)+xx*xx)*L1b1-2.*pow(xx*xx*xp*Q1,2)/pow(u1,4)*L1b1+xx*xp*t1*t1*xx*Q1/(u1*u1)-8.*pow(xx*xx*xp*Q1,2)/(pow(u1,4));
const long double C2mm2=xx*xp*t2*t2*Q2/(2.*u2)*(L1a2+3.*L1b2)+1./2.*xx*xp*t2*t2*(1.-z)*(L2a2-L1a2)+xx*xp*Q2*pow(xx-t2,3)*zb2/(2.*u2*u2)*(L2b2-L1b2)+xx*xp*t2*t2*Q2/(xx-u2)*(L1b2+L2a2)
+xx*xp*t2*t2/(2.*u2)*(L1b2-L1a2)+xx*xp*xx*Q2/(u2*u2)*(4.*t2*(t2-xx)+xx*xx)*L1b2-2.*pow(xx*xx*xp*Q2,2)/pow(u2,4)*L1b2+xx*xp*t2*t2*xx*Q2/(u2*u2)-8.*pow(xx*xx*xp*Q2,2)/(pow(u2,4));
ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2mm2)-1./xp/Q1*Jac1*(C2mm1));
const long double C2epsilon1=4.*pow(xx*xx*xp*Q1,2)/(pow(u1,4));
const long double C2epsilon2=4.*pow(xx*xx*xp*Q2,2)/(pow(u2,4));
ris+=_Nc*_Cf*(1./xp/Q2*Jac2*(C2epsilon2)-1./xp/Q1*Jac1*(C2epsilon1));// All C2's OK -2 Nc Cf Log(x)^2/xp
ris*=(1.-zmin);
return ris;
}
// qqbar channel
long double NLOPL::NLO_PL_notsing_doublediff_qqbar(double xp, double zz){
long double ris=0.0;
//Set Energy, Transverse Momentum, Integration variable z
const long double xx=x;
const long double Nc=_Nc;
const long double Nf=_Nf;
const long double MUF=std::pow(_muF/_mH,2);
const long double MUR=std::pow(_muR/_mH,2);
const long double b0=11./6.*Nc-1./3.*Nf;
const long double Cf=(Nc*Nc-1.)/(2.*Nc);
const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2);
const long double z=zmin+(1.-zmin)*zz;
//Set Mandelstam variable
const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z);
const long double t1=0.5*(xx-z+rad);
const long double u1=xx-0.5/z*(xx+z+rad);
long double Q1=1.+t1+u1-xx;
const long double Qt1=Q1+xx*xp;
const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad));
const long double Jac1=(xx-z+rad)/(2.*z*rad);
const long double t2=0.5*(xx-z-rad);
const long double u2=xx-0.5/z*(xx+z-rad);
long double Q2=1.+t2+u2-xx;
const long double Qt2=Q2+xx*xp;
const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad));
const long double Jac2=-(xx-z-rad)/(2.*z*rad);
const long double A1=1.+xx-Q1;
const long double B1=std::sqrt(A1*A1-4.*xx);
const long double L1a1=std::log(xx/(z*z));
const long double L1b1=std::log(xx/(zb1*zb1));
const long double L2a1=std::log(xx/std::pow(A1-z,2));
const long double L2b1=std::log(xx/std::pow(A1-zb1,2));
const long double L31=std::log((A1+B1)/(A1-B1));
const long double A2=1.+xx-Q2;
const long double B2=std::sqrt(A2*A2-4.*xx);
const long double L1a2=std::log(xx/(z*z));
const long double L1b2=std::log(xx/(zb2*zb2));
const long double L2a2=std::log(xx/std::pow(A2-z,2));
const long double L2b2=std::log(xx/std::pow(A2-zb2,2));
const long double L32=std::log((A2+B2)/(A2-B2));
//Define and add regular parts in G2s (refer to Glover paper for definition of G2s)
const long double Fi11= xx/(-t1)*_Cf*(1.-z)*2.*_Cf*_Cf*(t1*t1+z*z*xx*xx*xp*xp/(t1*t1))/z
+ xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(z*z+t1*t1)/(-xx*xp*z/(t1));
const long double Fi12= xx/(-t2)*_Cf*(1.-z)*2.*_Cf*_Cf*(t2*t2+z*z*xx*xx*xp*xp/(t2*t2))/z
+ xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(z*z+t2*t2)/(-xx*xp*z/(t2));
ris+=2.*(Jac2*Fi12-Jac1*Fi11);
const long double Fi21=1./xp*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+(u1+t1-2.*Q1)*(u1+t1-2.*Q1))*std::log(xx*xp/Qt1);
const long double Fi22=1./xp*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+(u2+t2-2.*Q2)*(u2+t2-2.*Q2))*std::log(xx*xp/Qt2);
ris+=(Jac2*Fi22-Jac1*Fi21); // OK Log squared cancel themselves with similar in Fi1
const long double D1pm1=-xx*xp*Q1*(1.+std::log(xx*xp/Qt1))-(xx*xp*xx*xp*z*(1.-z))/(t1)-xx*xp*(1.-z)*(1.-z);
const long double D1pm2=-xx*xp*Q2*(1.+std::log(xx*xp/Qt2))-(xx*xp*xx*xp*z*(1.-z))/(t2)-xx*xp*(1.-z)*(1.-z);
ris+=2.*2.*_Cf*_Cf*_Cf*(Jac2/xp/Q2*D1pm2-Jac1/xp/Q1*D1pm1); // OK no Logs
const long double D2pm1=-1./3.*xx*xp*Q1-xx*xp*t1*t1/(6.*z*z)*(11.-12.*Q1/Qt1+3.*Q1*Q1/Qt1/Qt1)+11.*xx*xp*t1*t1/6.;
const long double D2pm2=-1./3.*xx*xp*Q2-xx*xp*t2*t2/(6.*z*z)*(11.-12.*Q2/Qt2+3.*Q2*Q2/Qt2/Qt2)+11.*xx*xp*t2*t2/6.;
ris+=2.*2.*_Nc*_Cf*_Cf*(Jac2/xp/Q2*D2pm2-Jac1/xp/Q1*D2pm1); //OK no Logs
const long double D1pp1=xx*xp*u1*u1*(1.-zb1)/A1*(L2b1-L1b1)+xx*xp*(xx-u1)*(xx-u1)*(1.-z)/A1*(L2a1-L1a1)
+xx*xp*xx*Q1*(xx*xp+u1*t1)/(t1*t1)*L1a1-2.*xx*xp*xx*xx*Q1/(A1*B1)*L31+xx*xp*xx*Q1*(2.*xx*xp-u1*t1)/(t1*t1);
const long double D1pp2=xx*xp*u2*u2*(1.-zb2)/A2*(L2b2-L1b2)+xx*xp*(xx-u2)*(xx-u2)*(1.-z)/A2*(L2a2-L1a2)
+xx*xp*xx*Q2*(xx*xp+u2*t2)/(t2*t2)*L1a2-2.*xx*xp*xx*xx*Q2/(A2*B2)*L32+xx*xp*xx*Q2*(2.*xx*xp-u2*t2)/(t2*t2);
ris+=2.*2.*_Cf*_Cf*_Cf*(Jac2/xp/Q2*D1pp2-Jac1/xp/Q1*D1pp1); //OK no Logs
const long double D2pp1=xx*xp*u1*u1*(xx-t1)*(1.-zb1)/(2.*A1)*(L1b1-L2b1)+xx*xp*std::pow(xx-u1,3)*(1.-z)/(2.*A1)*(L1a1-L2a1)
-0.5*xx*xp*u1*u1*(L1a1+L1b1)+6.*std::pow(xx*xp*xx*Q1,2)/std::pow(B1,4)-xx*xp*xx*Q1*u1*u1/B1/B1
+L31*(xx*xp*u1*u1*(u1+t1)/B1+std::pow(xx*xp*xx*Q1,2)*(1./(A1*B1*B1*B1)-3.*A1/std::pow(B1,5))
+xx*xp*xx*Q1*((t1-3.*u1)/(2.*B1)+A1*(B1*B1+2.*u1*u1)/(4.*B1*B1*B1)+(t1*t1-6.*t1*u1+7.*u1+u1)/(4.*A1*B1)));
const long double D2pp2=xx*xp*u2*u2*(xx-t2)*(1.-zb2)/(2.*A2)*(L1b2-L2b2)+xx*xp*std::pow(xx-u2,3)*(1.-z)/(2.*A2)*(L1a2-L2a2)
-0.5*xx*xp*u2*u2*(L1a2+L1b2)+6.*std::pow(xx*xp*xx*Q2,2)/std::pow(B2,4)-xx*xp*xx*Q2*u2*u2/B2/B2
+L32*(xx*xp*u2*u2*(u2+t2)/B2+std::pow(xx*xp*xx*Q2,2)*(1./(A2*B2*B2*B2)-3.*A2/std::pow(B2,5))
+xx*xp*xx*Q2*((t2-3.*u2)/(2.*B2)+A2*(B2*B2+2.*u2*u2)/(4.*B2*B2*B2)+(t2*t2-6.*t2*u2+7.*u2+u2)/(4.*A2*B2)));
ris+=2.*2.*_Nc*_Cf*_Cf*(Jac2/xp/Q2*D2pp2-Jac1/xp/Q1*D2pp1); //OK no Logs
const long double E11=8./3.*xx-4./3.*xx*xx;
ris+=_Nf*_Cf*_Cf*E11*(Jac2-Jac1); //OK no Logs
const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx;
const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx;
ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21);
const long double E31=-2.*xx*xp*(std::pow(u1+t1-2.*Q1,2)-2.*xx*xp)*std::log(xx*xp/Qt1)
-xx*xp*Q1*(2.*Qt1+Q1)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))-6.*xp*xx*Q1;
const long double E32=-2.*xx*xp*(std::pow(u2+t2-2.*Q2,2)-2.*xx*xp)*std::log(xx*xp/Qt2)
-xx*xp*Q2*(2.*Qt2+Q2)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))-6.*xp*xx*Q2;
ris+=_Cf*_Cf/_Nc*(Jac2/(xp*Q2)*E32-Jac1/(xp*Q1)*E31); //OK no Logs
ris*=(1.-zmin);
return ris;
}
//qq channel
long double NLOPL::NLO_PL_notsing_doublediff_qq(double xp, double zz){
long double ris=0.0;
//Set Energy, Transverse Momentum, Integration variable z
const long double xx=x;
const long double Nc=_Nc;
const long double Nf=_Nf;
const long double MUF=std::pow(_muF/_mH,2);
const long double MUR=std::pow(_muR/_mH,2);
const long double b0=11./6.*Nc-1./3.*Nf;
const long double Cf=(Nc*Nc-1.)/(2.*Nc);
const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2);
const long double z=zmin+(1.-zmin)*zz;
//Set Mandelstam variable
const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z);
const long double t1=0.5*(xx-z+rad);
const long double u1=xx-0.5/z*(xx+z+rad);
long double Q1=1.+t1+u1-xx;
const long double Qt1=Q1+xx*xp;
const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad));
const long double Jac1=(xx-z+rad)/(2.*z*rad);
const long double t2=0.5*(xx-z-rad);
const long double u2=xx-0.5/z*(xx+z-rad);
long double Q2=1.+t2+u2-xx;
const long double Qt2=Q2+xx*xp;
const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad));
const long double Jac2=-(xx-z-rad)/(2.*z*rad);
const long double A1=1.+xx-Q1;
const long double B1=std::sqrt(A1*A1-4.*xx);
const long double L1a1=std::log(xx/(z*z));
const long double L1b1=std::log(xx/(zb1*zb1));
const long double L2a1=std::log(xx/std::pow(A1-z,2));
const long double L2b1=std::log(xx/std::pow(A1-zb1,2));
const long double L31=std::log((A1+B1)/(A1-B1));
const long double A2=1.+xx-Q2;
const long double B2=std::sqrt(A2*A2-4.*xx);
const long double L1a2=std::log(xx/(z*z));
const long double L1b2=std::log(xx/(zb2*zb2));
const long double L2a2=std::log(xx/std::pow(A2-z,2));
const long double L2b2=std::log(xx/std::pow(A2-zb2,2));
const long double L32=std::log((A2+B2)/(A2-B2));
//Define and add regular parts in G2s (refer to Glover paper for definition of G2s)
const long double Fi11=xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(t1*t1+z*z)/(-xx*xp*z/(t1));
const long double Fi12=xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(t2*t2+z*z)/(-xx*xp*z/(t2));
ris+=2.*(Jac2*Fi12-Jac1*Fi11);
const long double Fi21=xx*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+std::pow(u1+t1-2.*Q1,2))/(xx*xp)*std::log(xx*xp/Qt1);
const long double Fi22=xx*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+std::pow(u2+t2-2.*Q2,2))/(xx*xp)*std::log(xx*xp/Qt2);
ris+=(Jac2*Fi22-Jac1*Fi21);
const long double E41=2.*xx*(1.+Q1*Q1)/Qt1*std::log(x*xp/Q1)+4.*xx*std::log(xx*xp/Qt1);
const long double E42=2.*xx*(1.+Q2*Q2)/Qt2*std::log(x*xp/Q2)+4.*xx*std::log(xx*xp/Qt2);
ris+=_Cf*_Cf/_Nc*(Jac2*E42-Jac1*E41);
const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx;
const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx;
ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21);
ris*=(1.-zmin);
return ris;
}
//qqprime channel
long double NLOPL::NLO_PL_notsing_doublediff_qqprime(double xp, double zz){
long double ris=0.0;
//Set Energy, Transverse Momentum, Integration variable z
const long double xx=x;
const long double Nc=_Nc;
const long double Nf=_Nf;
const long double MUF=std::pow(_muF/_mH,2);
const long double MUR=std::pow(_muR/_mH,2);
const long double b0=11./6.*Nc-1./3.*Nf;
const long double Cf=(Nc*Nc-1.)/(2.*Nc);
const long double zmin=xx*std::pow(std::sqrt(1.+xp)+std::sqrt(xp),2);
const long double z=zmin+(1.-zmin)*zz;
//Set Mandelstam variable
const long double rad=std::sqrt((z-xx)*(z-xx)-4.*xx*xp*z);
const long double t1=0.5*(xx-z+rad);
const long double u1=xx-0.5/z*(xx+z+rad);
long double Q1=1.+t1+u1-xx;
const long double Qt1=Q1+xx*xp;
const long double zb1=(2.*xx*z-z-xx-rad)/(z*(-2.+xx+z-rad));
const long double Jac1=(xx-z+rad)/(2.*z*rad);
const long double t2=0.5*(xx-z-rad);
const long double u2=xx-0.5/z*(xx+z-rad);
long double Q2=1.+t2+u2-xx;
const long double Qt2=Q2+xx*xp;
const long double zb2=(2.*xx*z-xx-z+rad)/(z*(-2.+xx+z+rad));
const long double Jac2=-(xx-z-rad)/(2.*z*rad);
const long double A1=1.+xx-Q1;
const long double B1=std::sqrt(A1*A1-4.*xx);
const long double L1a1=std::log(xx/(z*z));
const long double L1b1=std::log(xx/(zb1*zb1));
const long double L2a1=std::log(xx/std::pow(A1-z,2));
const long double L2b1=std::log(xx/std::pow(A1-zb1,2));
const long double L31=std::log((A1+B1)/(A1-B1));
const long double A2=1.+xx-Q2;
const long double B2=std::sqrt(A2*A2-4.*xx);
const long double L1a2=std::log(xx/(z*z));
const long double L1b2=std::log(xx/(zb2*zb2));
const long double L2a2=std::log(xx/std::pow(A2-z,2));
const long double L2b2=std::log(xx/std::pow(A2-zb2,2));
const long double L32=std::log((A2+B2)/(A2-B2));
//Define and add regular parts in G2s (refer to Glover paper for definition of G2s)
const long double Fi11=xx/(-t1)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q1)+_Cf*z)*_Cf*(t1*t1+z*z)/(-xx*xp*z/(t1));
const long double Fi12=xx/(-t2)*(-_Cf*(1.+(1.-z)*(1.-z))/z*std::log(MUF*xx/Q2)+_Cf*z)*_Cf*(t2*t2+z*z)/(-xx*xp*z/(t2));
ris+=2.*(Jac2*Fi12-Jac1*Fi11);
const long double Fi21=xx*2.*_Cf*_Cf*((1.-Q1)*(1.-Q1)+std::pow(u1+t1-2.*Q1,2))/(xx*xp)*std::log(xx*xp/Qt1);
const long double Fi22=xx*2.*_Cf*_Cf*((1.-Q2)*(1.-Q2)+std::pow(u2+t2-2.*Q2,2))/(xx*xp)*std::log(xx*xp/Qt2);
ris+=(Jac2*Fi22-Jac1*Fi21);
const long double E21=xx*(Q1-xx*xp)/(Qt1*Qt1)*(std::pow(t1/z,2)+std::pow(u1/zb1,2))+2.*xx;
const long double E22=xx*(Q2-xx*xp)/(Qt2*Qt2)*(std::pow(t2/z,2)+std::pow(u2/zb2,2))+2.*xx;
ris+=_Cf*_Cf*(Jac2*E22-Jac1*E21);
ris*=(1.-zmin);
return ris;
}
long double NLOPL::NLO_PL_notsing_doublediff_qqbarprime(double xp, double zz)
{
return(NLO_PL_notsing_doublediff_qqprime(xp,zz));
}
long double NLOPL::LO_PL(double xp){ //we have to multiply later for sigma0 normalization
const long double rad=std::sqrt((1.-x)*(1.-x)-4.*x*xp);
const long double t=0.5*(x-1.+rad);
const long double u=0.5*(x-1.-rad);
switch(_channel){
case(1):{
return (4.*_Nc*(std::pow(1.+(x-1.)*x,2)-2.*(x-1.)*(x-1.)*x*xp+x*x*xp*xp)/(xp*rad)*_as/(2.*M_PIl));
break;
}
case(2):{
return(_as/(2.*M_PIl)*_Cf*x/rad*((1.+u*u)/(-t)+(1.+t*t)/(-u)));
break;
}
case(3):{
return(_as/(2.*M_PIl)*2.*_Cf*_Cf*x/rad*(u*u+t*t));
break;
}
case(4):{
return 0;
break;
}
case(5):{
return 0;
break;
}
case(6):{
return 0;
break;
}
}
}
| 58.466158
| 214
| 0.576788
|
gvita
|
bda5c0edf01f038f611d78c8ee2b7e90a0a7c0a1
| 9,628
|
cpp
|
C++
|
src/Game.cpp
|
M4T1A5/IndieSpeedRun2013
|
75b1adc4716c2e32f308289cce51a78a10681697
|
[
"Zlib"
] | null | null | null |
src/Game.cpp
|
M4T1A5/IndieSpeedRun2013
|
75b1adc4716c2e32f308289cce51a78a10681697
|
[
"Zlib"
] | null | null | null |
src/Game.cpp
|
M4T1A5/IndieSpeedRun2013
|
75b1adc4716c2e32f308289cce51a78a10681697
|
[
"Zlib"
] | null | null | null |
#include <Game.h>
#include <time.h>
#include <stdlib.h>
using namespace EGEMath;
using namespace EGEMotor;
Game::Game(Viewport& viewport, Input &input)
: input(&input),
viewport(&viewport),
gameState(MENU),
_clock(0),
Difficulty(1)
{
font = new Font("square.ttf");
resourceText = new Text("", font);
resourceText->setPosition(Vector(viewport.getWindowSize().x - 75, 0));
resourceText->setOriginPoint(9);
resourceText->setLayer(295);
resources = 6;
health = 5;
healthText = new Text("", font);
healthText->setPosition(Vector(viewport.getWindowSize().x - 75, 30));
healthText->setOriginPoint(9);
healthText->setLayer(295);
activeButton[FOREST]=false;
activeButton[SWAMP]=false;
activeButton[HURRICANE]=false;
activeButton[BUG]=false;
activeButton[CAT]=false;
activeButton[RIVER]=false;
srand(time(NULL));
camera = new Camera(input, viewport, map.GetSize());
_townTexture.loadTexture("village.png");
_villageTexture.loadTexture("settlement.png");
_explorerTexture.loadTexture("arke_sheet.png");
_villages.push_back(new Village(&_townTexture,Vector(300,800)));
// Menu
menuTexture = new Texture("menu.png");
menu.setTexture(menuTexture);
startTexture = new Texture("startbutton.png");
startButton = new GUIButton(startTexture, viewport.getWindowSize() / 2,
Rectangle(Vector(), startTexture->getTextureSize()), &input);
startButton->setOriginPoint(5);
gameOverTexture = new Texture("game over.png");
gameOver.setTexture(gameOverTexture);
gameOver.setPosition(startButton->getPosition());
gameOver.setOriginPoint(5);
tutorialNumber = 0;
for(int i = 0; i < 5; ++i)
{
char merkkijono[20];
sprintf(merkkijono, "tutorial-%d.png", i+1);
tutorialTexture.push_back(new Texture(merkkijono));
tutorial.push_back(new GameObject(tutorialTexture[i]));
tutorial[i]->setPosition(Vector(-1000,-1000));
tutorial[i]->setOriginPoint(5);
}
// Sidebar
sidebarTexture = new Texture("sidebar2.png");
sidebar.setTexture(sidebarTexture);
Vector sidebarPos = Vector(viewport.getWindowSize().x - sidebarTexture->getTextureSize().x, 0);
sidebar.setPosition(sidebarPos);
sidebar.setLayer(295);
// Buttons
buttonTexture = new Texture("buttons2.png");
for(int i = 0; i < 6; ++i)
{
Vector buttonPos = sidebarPos + Vector(0, i*120);
Rectangle crop = Rectangle(Vector(i*75, 0), Vector(150,150));
auto button = new GUIButton(buttonTexture, buttonPos, crop, &input);
button->setLayer(296);
buttons.push_back(button);
}
buttons[0]->elementToSpawn = Forest;
buttons[1]->elementToSpawn = Swamp;
buttons[2]->hazardToSpawn = tornado;
buttons[3]->hazardToSpawn = cat;
buttons[4]->hazardToSpawn = bug;
buttons[5];
particleEngine = new ParticleEngine();
}
Game::~Game()
{
delete startTexture;
delete startButton;
delete menuTexture;
delete sidebarTexture;
delete buttonTexture;
tutorialTexture.empty();
tutorial.empty();
buttons.empty();
}
// Public
void Game::Update(const double& dt)
{
char merkkijono[20];
Vector windowSize = viewport->getWindowSize();
Vector mousePos = input->getMousePosition();
switch (gameState)
{
case MENU:
if (tutorialNumber == 0 && startButton->isPressed() )
{
tutorial[tutorialNumber]->setPosition(startButton->getPosition());
tutorialNumber++;
}
if(tutorialNumber > 0 && tutorialNumber < tutorial.size())
{
if(input->isButtonPressed(MouseLeft))
{
tutorial[tutorialNumber]->setPosition(startButton->getPosition());
tutorialNumber++;
}
}
if(tutorialNumber == tutorial.size())
{
if(input->isButtonPressed(MouseLeft))
{
for(int i = 0; i < tutorial.size(); ++i)
tutorial[i]->setPosition(Vector(-1000,-1000));
gameState = WARMUP;
}
}
break;
case WARMUP:
sprintf(merkkijono, "Resources: %d", resources);
resourceText->setString(merkkijono);
resourceText->updateOrigin();
sprintf(merkkijono, "Health: %d", health);
healthText->setString(merkkijono);
healthText->updateOrigin();
_clock += dt;
if((windowSize.x - mousePos.x) < 5 || mousePos.x < 5)
{
camera->FollowMouse(dt);
}
else if((windowSize.y - mousePos.y) < 5 || mousePos.y < 5)
{
camera->FollowMouse(dt);
}
for(int i = 0; i < 2; ++i)
{
if(buttons[i]->isPressed())
spawnElement = buttons[i]->elementToSpawn;
}
if(spawnElement > 0 && input->isButtonPressed(Button::MouseLeft) && resources > 0)
{
map.AddElement(spawnElement, input->getMousePositionOnMap());
resources--;
}
if (_clock > 20)
{
_clock=0;
gameState = PLAY;
}
break;
case PLAY:
sprintf(merkkijono, "Health: %d", health);
healthText->setString(merkkijono);
healthText->updateOrigin();
if((windowSize.x - mousePos.x) < 5 || mousePos.x < 5)
{
camera->FollowMouse(dt);
}
else if((windowSize.y - mousePos.y) < 5 || mousePos.y < 5)
{
camera->FollowMouse(dt);
}
for(int i = 2; i < 5; ++i)
{
if(buttons[i]->isPressed())
{
spawnHazard = buttons[i]->hazardToSpawn;
spawnElement = Background;
}
}
if(spawnHazard >= 0 && input->isButtonPressed(Button::MouseLeft) )
{
switch(spawnHazard)
{
case tornado:
particleEngine->addTornado(input->getMousePositionOnMap(), Vector(1,1));
break;
case cat:
particleEngine->addCat(input->getMousePositionOnMap(), Vector(100,1));
break;
case bug:
particleEngine->addBug(input->getMousePositionOnMap(), Vector(100,1));
break;
}
}
for (int i=0; i<_villages.size(); ++i)
{
_villages[i]->Update(dt);
if (_villages[i]->Clock > _villages[i]->NextVillager)
{
_villages[i]->Clock -= _villages[i]->NextVillager;
_villages[i]->NextVillager = (rand()%5)/Difficulty;
_explorers.push_back(new Explorer(&_explorerTexture,16,
_explorerTexture.getTextureSize().x/4.0f,
_explorerTexture.getTextureSize().y/4.0f,
12,_villages[i]->getPosition()));
}
}
for (int i=0; i<_explorers.size(); ++i)
{
_explorers[i]->Update(dt, map._mapElements[Volcano][0]->getPosition());
for (int j=0; j<map._mapElements.size();++j)
{
for (int k=0; k<map._mapElements[j].size();++k)
{
switch(j)
{
case Background:
break;
case River:
if (map.GetPixel(_explorers[i]->getPosition()) != sf::Color::Transparent)
{
_explorers[i]->slowed=true;
if (activeButton[RIVER])
{
_explorers[i]->poison=true;
}
}
break;
case Forest:
_explorers[i]->getPosition();
map._mapElements[j][k]->getPosition();
if ((_explorers[i]->getPosition()-map._mapElements[j][k]->getPosition())
.getLenght()< map._mapElementList[j]->Radius)
{
_explorers[i]->slowed=true;
if (activeButton[FOREST])
{
if(rand()%10000 > 9999-10000*dt);
}
}
break;
case Swamp:
if ((_explorers[i]->getPosition()-map._mapElements[j][k]->getPosition())
.getLenght()< map._mapElementList[j]->Radius)
{
_explorers[i]->slowed=true;
_explorers[i]->poison=true;
if (activeButton[SWAMP])
{
}
}
break;
case Volcano:
if(map._mapElements[j][k]->
getGlobalBounds().contains(_explorers[i]->getPosition()))
{
health--;
_explorers.erase(_explorers.begin() + i);
}
break;
}
}
}
for (int j=0; j<particleEngine->m_TornadoParticles.size();++j)
{
if ((_explorers[i]->getPosition()-particleEngine->m_TornadoParticles[j]->m_position+Vector(0,-60)).getLenght() < particleEngine->m_TornadoParticles[j]->AreaOfEffect)
{
_explorers[i]->setPosition(particleEngine->m_TornadoParticles[j]->m_position+Vector(0,-10));
}
}
for (int j=0; j<particleEngine->m_BugParticles.size();++j)
{
if ((_explorers[i]->getPosition()-particleEngine->m_BugParticles[j]->m_position+Vector(0,80)).getLenght() < particleEngine->m_BugParticles[j]->AreaOfEffect)
{
_explorers[i]->poison = true;
}
}
for (int j=0; j<particleEngine->m_CatParticles.size();++j)
{
if ((_explorers[i]->getPosition()-particleEngine->m_CatParticles[j]->m_position).getLenght() < particleEngine->m_CatParticles[j]->AreaOfEffect)
{
_explorers[i]->dead = true;
}
}
if (_explorers[i]->dead)
_explorers.erase(_explorers.begin() + i);
}
if(health == 0)
gameState = GAMEOVER;
break;
case PAUSE:
break;
case GAMEOVER:
if(input->isButtonPressed(MouseLeft))
exit(0);
break;
}
for(size_t i = 0; i < buttons.size(); ++i)
{
if(buttons[i]->mouseOver())
buttons[i]->setColor(255,255,255,255);
else
buttons[i]->setColor(255,255,255,150);
}
map.Update(dt);
particleEngine->Update(dt);
}
void Game::Draw(EGEMotor::Viewport& viewport)
{
switch (gameState)
{
case MENU:
menu.Draw(viewport);
startButton->draw(viewport);
for(int i = 0; i < tutorial.size(); ++i)
tutorial[i]->Draw(viewport);
viewport.renderSprites();
break;
case PAUSE:
case WARMUP:
case PLAY:
map.Draw(viewport);
for (int i=0;i<_villages.size();++i)
_villages[i]->Draw(viewport);
for (int i=0;i<_explorers.size();++i)
_explorers[i]->Draw(viewport);
for(size_t i = 0; i < buttons.size(); ++i)
{
buttons[i]->draw(viewport);
}
sidebar.Draw(viewport);
viewport.draw(resourceText);
viewport.draw(healthText);
viewport.renderSprites();
break;
case GAMEOVER:
gameOver.Draw(viewport);
viewport.renderSprites();
break;
}
particleEngine->Draw(&viewport);
viewport.renderSprites();
}
void Game::reset()
{
health = 5;
resources = 6;
gameState = MENU;
_villages.empty();
_explorers.empty();
map.Reset();
}
| 24.498728
| 169
| 0.654342
|
M4T1A5
|
bdaf2f711fbe5aed14096c7ac4c7304eeab8ab0b
| 2,988
|
hpp
|
C++
|
include/makeshift/experimental/mpark/variant.hpp
|
mbeutel/makeshift
|
68e6bdee79060f3b258c031c53ff641325d13411
|
[
"BSL-1.0"
] | 3
|
2020-04-03T14:06:41.000Z
|
2021-11-09T23:55:52.000Z
|
include/makeshift/experimental/mpark/variant.hpp
|
mbeutel/makeshift
|
68e6bdee79060f3b258c031c53ff641325d13411
|
[
"BSL-1.0"
] | 2
|
2020-04-03T14:21:09.000Z
|
2022-02-08T14:37:01.000Z
|
include/makeshift/experimental/mpark/variant.hpp
|
mbeutel/makeshift
|
68e6bdee79060f3b258c031c53ff641325d13411
|
[
"BSL-1.0"
] | null | null | null |
#ifndef INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_
#define INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_
#include <utility> // for forward<>()
#include <type_traits> // for remove_cv<>, remove_reference<>
#include <gsl-lite/gsl-lite.hpp> // for gsl_Expects(), gsl_NODISCARD
#include <mpark/variant.hpp>
#include <makeshift/experimental/detail/variant.hpp>
namespace makeshift {
namespace gsl = ::gsl_lite;
namespace mpark {
//
// Given an argument of type `mpark::variant<Ts...>`, this is `mpark::variant<::mpark::monostate, Ts...>`.
//
template <typename V> using with_monostate = typename detail::with_monostate_<::mpark::variant, ::mpark::monostate, V>::type;
//
// Given an argument of type `mpark::variant<::mpark::monostate, Ts...>`, this is `mpark::variant<Ts...>`.
//
template <typename V> using without_monostate = typename detail::without_monostate_<::mpark::variant, ::mpark::monostate, V>::type;
//
// Casts an argument of type `mpark::variant<Ts...>` to the given variant type.
//
template <typename DstV, typename SrcV>
gsl_NODISCARD constexpr DstV
variant_cast(SrcV&& variant)
{
#if !(defined(_MSC_VER) && defined(__INTELLISENSE__))
return ::mpark::visit(
[](auto&& arg) -> DstV
{
return std::forward<decltype(arg)>(arg);
},
std::forward<SrcV>(variant));
#endif // MAKESHIFT_INTELLISENSE
}
//
// Converts an argument of type `mpark::variant<::mpark::monostate, Ts...>` to `std::optional<::mpark::variant<Ts...>>`.
//
//template <typename V>
//gsl_NODISCARD constexpr decltype(auto)
//variant_to_optional(V&& variantWithMonostate)
//{
// using R = without_monostate<std::remove_cv_t<std::remove_reference_t<V>>>;
// if (std::holds_alternative<::mpark::monostate>(variantWithMonostate))
// {
// return std::optional<R>(std::nullopt);
// }
//#if !(defined(_MSC_VER) && defined(__INTELLISENSE__))
// return std::optional<R>(::mpark::visit(
// detail::monostate_filtering_visitor<::mpark::monostate, R>{ },
// std::forward<V>(variantWithMonostate)));
//#endif // MAKESHIFT_INTELLISENSE
//}
//
// Converts an argument of type `std::optional<::mpark::variant<Ts...>>` to `mpark::variant<::mpark::monostate, Ts...>`.
//
//template <typename VO>
//gsl_NODISCARD constexpr decltype(auto)
//optional_to_variant(VO&& optionalVariant)
//{
// using R = with_monostate<typename std::remove_cv_t<std::remove_reference_t<VO>>::value_type>;
// if (!optionalVariant.has_value())
// {
// return R{ ::mpark::monostate{ } };
// }
// return variant_cast<R>(*std::forward<VO>(optionalVariant));
//}
//
// Concatenates the alternatives in the given variants.
//
template <typename... Vs> using variant_cat_t = typename detail::variant_cat_<::mpark::variant, Vs...>::type;
} // namespace mpark
} // namespace makeshift
#endif // INCLUDED_MAKESHIFT_EXPERIMENTAL_MPARK_VARIANT_HPP_
| 30.489796
| 131
| 0.670348
|
mbeutel
|
bdba0a9c8a4aa4bb8f2faa7e5818dc3bc650d72b
| 1,256
|
cpp
|
C++
|
lib/code/widgets/single_child.cpp
|
leddoo/cpp-gui
|
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
|
[
"MIT"
] | null | null | null |
lib/code/widgets/single_child.cpp
|
leddoo/cpp-gui
|
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
|
[
"MIT"
] | null | null | null |
lib/code/widgets/single_child.cpp
|
leddoo/cpp-gui
|
75f9d89df0bea8ac7d59179a17bd58c8a4e3ead7
|
[
"MIT"
] | null | null | null |
#include <cpp-gui/core/gui.hpp>
#include <cpp-gui/widgets/single_child.hpp>
Single_Child_Def::~Single_Child_Def() {
safe_delete(&this->child);
}
Widget* Single_Child_Def::on_get_widget(Gui* gui) {
return gui->create_widget_and_match<Single_Child_Widget>(*this);
}
Single_Child_Widget::~Single_Child_Widget() {
this->drop_maybe(this->child);
this->child = nullptr;
}
void Single_Child_Widget::match(const Single_Child_Def& def) {
this->child = this->reconcile(this->child, def.child);
this->mark_for_layout();
}
Bool Single_Child_Widget::on_try_match(Def* def) {
return try_match_t<Single_Child_Def>(this, def);
}
void Single_Child_Widget::on_layout(Box_Constraints constraints) {
// todo: sizing bias.
if(this->child != nullptr) {
this->child->layout(constraints);
this->size = this->child->size;
}
else {
this->size = { 0, 0 };
}
}
void Single_Child_Widget::on_paint(ID2D1RenderTarget* target) {
if(this->child != nullptr) {
this->child->paint(target);
}
}
Bool Single_Child_Widget::visit_children_for_hit_testing(std::function<Bool(Widget* child)> visitor, V2f point) {
UNUSED(point);
return this->child != nullptr && visitor(this->child);
}
| 22.836364
| 113
| 0.684713
|
leddoo
|
bdbb708a347c590ef630a45f6f1b3ef678bc7ce5
| 253
|
cpp
|
C++
|
src/process.cpp
|
Matthew-Zimmer/Harpoon
|
81420c815f8930d20c9e082973442d9fe7a7ddea
|
[
"BSL-1.0"
] | 1
|
2019-12-22T20:02:31.000Z
|
2019-12-22T20:02:31.000Z
|
src/process.cpp
|
Matthew-Zimmer/harpoon
|
81420c815f8930d20c9e082973442d9fe7a7ddea
|
[
"BSL-1.0"
] | null | null | null |
src/process.cpp
|
Matthew-Zimmer/harpoon
|
81420c815f8930d20c9e082973442d9fe7a7ddea
|
[
"BSL-1.0"
] | null | null | null |
#include "process.hpp"
namespace Slate::Harpoon
{
Base_Process::Base_Process(std::string const& name) : name{ name }
{}
Memory::Block& Buffer<void, void>::Queues()
{
static Memory::Block queues;
return queues;
};
}
| 19.461538
| 71
| 0.608696
|
Matthew-Zimmer
|
bdc49488d0957d4292661a5c6aba0fad298a3a78
| 8,344
|
cpp
|
C++
|
Project/Source/Components/UI/ComponentText.cpp
|
TBD-org/TBD-Engine
|
8b45d5a2a92e26bd0ec034047b8188e871fab0f9
|
[
"MIT"
] | 7
|
2021-04-26T21:32:12.000Z
|
2022-02-14T13:48:53.000Z
|
Project/Source/Components/UI/ComponentText.cpp
|
TBD-org/RealBugEngine
|
0131fde0abc2d86137500acd6f63ed8f0fc2835f
|
[
"MIT"
] | 66
|
2021-04-24T10:08:07.000Z
|
2021-10-05T16:52:56.000Z
|
Project/Source/Components/UI/ComponentText.cpp
|
TBD-org/TBD-Engine
|
8b45d5a2a92e26bd0ec034047b8188e871fab0f9
|
[
"MIT"
] | 1
|
2021-07-13T21:26:13.000Z
|
2021-07-13T21:26:13.000Z
|
#include "ComponentText.h"
#include "Application.h"
#include "GameObject.h"
#include "Modules/ModulePrograms.h"
#include "Modules/ModuleCamera.h"
#include "Modules/ModuleRender.h"
#include "Modules/ModuleUserInterface.h"
#include "Modules/ModuleResources.h"
#include "Modules/ModuleEditor.h"
#include "ComponentTransform2D.h"
#include "Resources/ResourceTexture.h"
#include "Resources/ResourceFont.h"
#include "FileSystem/JsonValue.h"
#include "Utils/ImGuiUtils.h"
#include "GL/glew.h"
#include "Math/TransformOps.h"
#include "imgui_stdlib.h"
#include "Utils/Leaks.h"
#define JSON_TAG_TEXT_FONTID "FontID"
#define JSON_TAG_TEXT_FONTSIZE "FontSize"
#define JSON_TAG_TEXT_LINEHEIGHT "LineHeight"
#define JSON_TAG_TEXT_LETTER_SPACING "LetterSpacing"
#define JSON_TAG_TEXT_VALUE "Value"
#define JSON_TAG_TEXT_ALIGNMENT "Alignment"
#define JSON_TAG_COLOR "Color"
ComponentText::~ComponentText() {
App->resources->DecreaseReferenceCount(fontID);
glDeleteVertexArrays(1, &vao);
glDeleteBuffers(1, &vbo);
}
void ComponentText::Init() {
App->resources->IncreaseReferenceCount(fontID);
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
Invalidate();
}
void ComponentText::OnEditorUpdate() {
if (ImGui::Checkbox("Active", &active)) {
if (GetOwner().IsActive()) {
if (active) {
Enable();
} else {
Disable();
}
}
}
ImGui::Separator();
ImGuiInputTextFlags flags = ImGuiInputTextFlags_AllowTabInput;
bool mustRecalculateVertices = false;
if (ImGui::InputTextMultiline("Text input", &text, ImVec2(0.0f, ImGui::GetTextLineHeight() * 8), flags)) {
SetText(text);
}
UID oldFontID = fontID;
ImGui::ResourceSlot<ResourceFont>("Font", &fontID);
if (oldFontID != fontID) {
mustRecalculateVertices = true;
}
if (ImGui::DragFloat("Font Size", &fontSize, 2.0f, 0.0f, FLT_MAX)) {
mustRecalculateVertices = true;
}
if (ImGui::DragFloat("Line height", &lineHeight, 2.0f, -FLT_MAX, FLT_MAX)) {
mustRecalculateVertices = true;
}
if (ImGui::DragFloat("Letter spacing", &letterSpacing, 0.1f, -FLT_MAX, FLT_MAX)) {
mustRecalculateVertices = true;
}
mustRecalculateVertices |= ImGui::RadioButton("Left", &textAlignment, 0);
ImGui::SameLine();
mustRecalculateVertices |= ImGui::RadioButton("Center", &textAlignment, 1);
ImGui::SameLine();
mustRecalculateVertices |= ImGui::RadioButton("Right", &textAlignment, 2);
ImGui::ColorEdit4("Color##", color.ptr());
if (mustRecalculateVertices) {
Invalidate();
}
}
void ComponentText::Save(JsonValue jComponent) const {
jComponent[JSON_TAG_TEXT_FONTID] = fontID;
jComponent[JSON_TAG_TEXT_FONTSIZE] = fontSize;
jComponent[JSON_TAG_TEXT_LINEHEIGHT] = lineHeight;
jComponent[JSON_TAG_TEXT_LETTER_SPACING] = letterSpacing;
jComponent[JSON_TAG_TEXT_ALIGNMENT] = textAlignment;
jComponent[JSON_TAG_TEXT_VALUE] = text.c_str();
JsonValue jColor = jComponent[JSON_TAG_COLOR];
jColor[0] = color.x;
jColor[1] = color.y;
jColor[2] = color.z;
jColor[3] = color.w;
}
void ComponentText::Load(JsonValue jComponent) {
fontID = jComponent[JSON_TAG_TEXT_FONTID];
fontSize = jComponent[JSON_TAG_TEXT_FONTSIZE];
lineHeight = jComponent[JSON_TAG_TEXT_LINEHEIGHT];
letterSpacing = jComponent[JSON_TAG_TEXT_LETTER_SPACING];
textAlignment = jComponent[JSON_TAG_TEXT_ALIGNMENT];
text = jComponent[JSON_TAG_TEXT_VALUE];
JsonValue jColor = jComponent[JSON_TAG_COLOR];
color.Set(jColor[0], jColor[1], jColor[2], jColor[3]);
}
void ComponentText::Draw(ComponentTransform2D* transform) {
if (fontID == 0) {
return;
}
ProgramTextUI* textUIProgram = App->programs->textUI;
if (textUIProgram == nullptr) return;
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glActiveTexture(GL_TEXTURE0);
glBindVertexArray(vao);
glUseProgram(textUIProgram->program);
float4x4 model = transform->GetGlobalMatrix();
float4x4& proj = App->camera->GetProjectionMatrix();
float4x4& view = App->camera->GetViewMatrix();
if (App->userInterface->IsUsing2D()) {
proj = float4x4::D3DOrthoProjLH(-1, 1, App->renderer->GetViewportSize().x, App->renderer->GetViewportSize().y); //near plane. far plane, screen width, screen height
view = float4x4::identity;
}
ComponentCanvasRenderer* canvasRenderer = GetOwner().GetComponent<ComponentCanvasRenderer>();
if (canvasRenderer != nullptr) {
float factor = canvasRenderer->GetCanvasScreenFactor();
view = view * float4x4::Scale(factor, factor, factor);
}
glUniformMatrix4fv(textUIProgram->viewLocation, 1, GL_TRUE, view.ptr());
glUniformMatrix4fv(textUIProgram->projLocation, 1, GL_TRUE, proj.ptr());
glUniformMatrix4fv(textUIProgram->modelLocation, 1, GL_TRUE, model.ptr());
glUniform4fv(textUIProgram->textColorLocation, 1, color.ptr());
RecalculateVertices();
for (size_t i = 0; i < text.size(); ++i) {
if (text.at(i) != '\n') {
Character character = App->userInterface->GetCharacter(fontID, text.at(i));
// render glyph texture over quad
glBindTexture(GL_TEXTURE_2D, character.textureID);
// update content of VBO memory
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(verticesText[i]), &verticesText[i].front());
glBindBuffer(GL_ARRAY_BUFFER, 0);
// render quad
glDrawArrays(GL_TRIANGLES, 0, 6);
}
}
glBindVertexArray(0);
glBindTexture(GL_TEXTURE_2D, 0);
glDisable(GL_BLEND);
}
void ComponentText::SetText(const std::string& newText) {
text = newText;
Invalidate();
}
void ComponentText::SetFontSize(float newfontSize) {
fontSize = newfontSize;
Invalidate();
}
void ComponentText::SetFontColor(const float4& newColor) {
color = newColor;
}
float4 ComponentText::GetFontColor() const {
return color;
}
void ComponentText::RecalculateVertices() {
if (!dirty) {
return;
}
if (fontID == 0) {
return;
}
verticesText.resize(text.size());
ComponentTransform2D* transform = GetOwner().GetComponent<ComponentTransform2D>();
float x = -transform->GetSize().x * 0.5f;
float y = 0;
float dy = 0; // additional y shifting
int j = 0; // index of row
// FontSize / size of imported font. 48 is due to FontImporter default PixelSize
float scale = (fontSize / 48);
for (size_t i = 0; i < text.size(); ++i) {
Character character = App->userInterface->GetCharacter(fontID, text.at(i));
float xpos = x + character.bearing.x * scale;
float ypos = y - (character.size.y - character.bearing.y) * scale;
float w = character.size.x * scale;
float h = character.size.y * scale;
switch (textAlignment) {
case TextAlignment::LEFT: {
// Default branch, could be deleted
break;
}
case TextAlignment::CENTER: {
xpos += (transform->GetSize().x - SubstringWidth(&text.c_str()[j], scale)) * 0.5f;
break;
}
case TextAlignment::RIGHT: {
xpos += transform->GetSize().x - SubstringWidth(&text.c_str()[j], scale);
break;
}
}
if (text.at(i) == '\n') {
dy += lineHeight; // shifts to next line
x = -transform->GetSize().x * 0.5f; // reset to initial position
j = i + 1; // updated j variable in order to get the substringwidth of the following line in the next iteration
}
// clang-format off
verticesText[i] = {
xpos, ypos + h - dy, 0.0f, 0.0f,
xpos, ypos - dy, 0.0f, 1.0f,
xpos + w, ypos - dy, 1.0f, 1.0f,
xpos, ypos + h - dy, 0.0f, 0.0f,
xpos + w, ypos - dy, 1.0f, 1.0f,
xpos + w, ypos + h - dy, 1.0f, 0.0f
};
// clang-format on
// now advance cursors for next glyph (note that advance is number of 1/64 pixels)
if (text.at(i) != '\n') {
x += ((character.advance >> 6) + letterSpacing) * scale; // bitshift by 6 to get value in pixels (2^6 = 64). Divides / 64
}
}
dirty = false;
}
void ComponentText::Invalidate() {
dirty = true;
}
float ComponentText::SubstringWidth(const char* substring, float scale) {
float subWidth = 0.f;
for (int i = 0; substring[i] != '\0' && substring[i] != '\n'; ++i) {
Character c = App->userInterface->GetCharacter(fontID, substring[i]);
subWidth += ((c.advance >> 6) + letterSpacing) * scale;
}
subWidth -= letterSpacing * scale;
return subWidth;
}
| 28.094276
| 166
| 0.71081
|
TBD-org
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.