blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 2
247
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
57
| license_type
stringclasses 2
values | repo_name
stringlengths 4
111
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringlengths 4
58
| visit_date
timestamp[ns]date 2015-07-25 18:16:41
2023-09-06 10:45:08
| revision_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| committer_date
timestamp[ns]date 1970-01-14 14:03:36
2023-09-06 06:22:19
| github_id
int64 3.89k
689M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 25
values | gha_event_created_at
timestamp[ns]date 2012-06-07 00:51:45
2023-09-14 21:58:52
⌀ | gha_created_at
timestamp[ns]date 2008-03-27 23:40:48
2023-08-24 19:49:39
⌀ | gha_language
stringclasses 159
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 7
10.5M
| extension
stringclasses 111
values | filename
stringlengths 1
195
| text
stringlengths 7
10.5M
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f2329fdd604661cfffa5337310df5b5cc9558ff4
|
d04b7ee933b9b0dd151aa6f5cd6967fe0adcbe92
|
/LeetCode_problems/Linked List Components/solution.cpp
|
5bff43a93a3c1cd4f31eca2f59a0fd93ff00a2c3
|
[
"MIT"
] |
permissive
|
deepak1214/CompetitiveCode
|
69e0e54c056ca7d360dac9f1099eaf018d202bd0
|
1e1449064dbe2c52269a6ac393da74f6571ebebc
|
refs/heads/main
| 2023-01-04T11:36:03.723271
| 2020-10-31T20:44:34
| 2020-10-31T20:44:34
| 308,840,332
| 4
| 0
|
MIT
| 2020-10-31T08:46:15
| 2020-10-31T08:46:14
| null |
UTF-8
|
C++
| false
| false
| 2,210
|
cpp
|
solution.cpp
|
#include<bits/stdc++.h>
using namespace std;
/*
-----------LOGIC-----------------------------------
In the question we are given a set G and a linked list
which may contain values which may or may not belong to G.
We need to find the nubmer of components present in that list.
A component here is defined as those nodes whcih are linked
in continuous chain and all of them are present in G form one component.
SO the problem is very similar to connected component in dfs.
We'll use a set to track values if are present in G.
Our approach will be like this .
Repeat till end of linked list
Move forward until we get a value present in G or we reach the end of LL
if we are not at the end then we get a component here
move forward the pointer till the values are continuously present in G
else
break
Other wise move to next pointer
You'll understand it better with an example
Say
Input - 0 , 1, 2, 3, 4
G = [0, 3, 1, 4]
Starting from 0 (present in G so we increment component count by 1 and start elimi
-nating the values linked to this)
from 0
1 (in G so move next)
2 (not in G so break)
Starting from 3 ((present in G so we increment component count by 1 and start elimi
-nating the values linked to this))
from 3
4 (in G so move next)
end (break)
Thus our component count is 2
*/
//=====================CODE==================
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int numComponents(ListNode* head, vector<int>& G) {
unordered_set<int> s(G.begin(),G.end());
ListNode* temp=head;
int c=0;
while(temp){
if(s.find(temp->val)!=s.end()){
c++;
while(temp and s.find(temp->val)!=s.end())
temp=temp->next;
continue;
}
temp=temp->next;
}
return c;
}
};
|
15d041d6dc4af892b4bb7d70f2454368d2aa74be
|
5c371843f2a8e99fbdaa81b1f25d924c5ef4074b
|
/lib/floor.h
|
608b47d078338f9b88a477d10810488894645136
|
[] |
no_license
|
alexn1st0r/the_lift
|
8cd9ce0cda21bef7d8983ced06c730de1dca0216
|
0f89ce48a5fc28fb14281a474645638a279a18c4
|
refs/heads/master
| 2022-06-08T15:32:07.382693
| 2020-05-06T19:06:46
| 2020-05-06T19:07:15
| 261,799,740
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,013
|
h
|
floor.h
|
#ifndef FLOOR_H_
#define FLOOR_H_
#include <iostream>
#include <vector>
#include "human.h"
class FloorQueue {
private:
std::vector<Human> m_humans;
std::vector<Human> m_humans_up;
std::vector<Human> m_humans_down;
int m_floor;
public:
FloorQueue (std::vector<int> humans, int floor);
~FloorQueue ();
inline bool all_up() { return !m_humans_up.empty() && m_humans_down.empty(); };
inline bool all_down() { return m_humans_up.empty() && !m_humans_down.empty(); };
inline bool is_up() { return !m_humans_up.empty(); };
inline bool is_down() { return !m_humans_down.empty(); };
inline int get_humans_queue_size() { return m_humans.size(); };
inline int get_humans_up_queue_size() { return m_humans_up.size(); };
inline int get_humans_down_queue_size() { return m_humans_down.size(); };
inline bool is_empty() const { return m_humans.empty(); };
std::vector<Human> get_human_queue(int nm);
std::vector<Human> get_human_queue_up(int nm);
std::vector<Human> get_human_queue_down(int nm);
};
#endif
|
3fd851fd2bded3ad7af624d3210e0f511c2afa26
|
8647138abceab67757e89d8f6332ac949946bc95
|
/3DMath/3DMath/3DMath/TriMesh.h
|
36266485ceda438a122f4ebff01896e9e8e8f1c4
|
[] |
no_license
|
skmioo/SkmiooStore
|
18ef8f4e329cd82a4a73d75f641145f5faf95fd9
|
2928f75aece1df56235ade83e1b5705a665a8e67
|
refs/heads/master
| 2023-07-02T01:24:24.788657
| 2023-06-14T07:33:14
| 2023-06-14T07:33:14
| 156,471,699
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 152
|
h
|
TriMesh.h
|
#pragma once
#include "EditTriMesh.h"
class TriMesh
{
public:
void fromEditMesh(const EditTriMesh &mesh);
void toEditMesh(EditTriMesh &mesh)const;
};
|
d3bcd3af06244ab6458a526ca8f9ff15ff3fab02
|
2e6ceacadfa7289cb085e749d8397fdc4c212080
|
/Assignment/userRole.h
|
32569cffa49dba16fedd6740560828e97085c27a
|
[] |
no_license
|
emerald84/Assignment-1
|
1b9b67d2470b2186bc9485d8a50ae296dfc17dfb
|
f21907744c31c006a5b7b40cbc9df505b213addd
|
refs/heads/main
| 2023-05-14T19:05:22.635408
| 2021-05-31T21:56:28
| 2021-05-31T21:56:28
| 372,636,743
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 243
|
h
|
userRole.h
|
#include <iostream>
#include <cstring>
#include "carddeck.h"
#include "cardgame.h"
#include "gameFunctions.h"
#ifndef _USER_ROLES_H
#define _USER_ROLES_H
using namespace std;
int menu(int DECKSIZE);
int displayCards();
#endif
|
4f433aea77714fcd3903025798c75702506741bd
|
c7272e93df5e9f68c36385308da28a944e300d9d
|
/29. Divide Two Integers.h
|
4c8b58b15569fcc46860c9d5ab3af16af3b75bd0
|
[
"MIT"
] |
permissive
|
Mids/LeetCode
|
368a941770bc7cb96a85a7b523d77446717a1f31
|
589b9e40acfde6e2dde37916fc1c69a3ac481070
|
refs/heads/master
| 2023-08-13T13:39:11.476092
| 2021-09-26T09:29:18
| 2021-09-26T09:29:18
| 326,600,963
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 851
|
h
|
29. Divide Two Integers.h
|
//
// Created by jin on 5/17/2021.
//
#ifndef LEETCODE_29_DIVIDE_TWO_INTEGERS_H
#define LEETCODE_29_DIVIDE_TWO_INTEGERS_H
using namespace std;
class Solution {
public:
int divide(int dividend, int divisor) {
if (dividend == 0 || divisor == 1) return dividend;
if (divisor == -1) {
if (dividend == INT_MIN) return INT_MAX;
return -dividend;
}
long long x = dividend;
long long y = divisor;
x = x > 0 ? x : -x;
y = y > 0 ? y : -y;
int offset = 1;
int result = 0;
long long temp = 1;
while (x >= y) {
y <<= 1, temp <<= 1, ++offset;
}
y >>= 1, temp >>= 1, --offset;
while (offset) {
x -= y;
if (x < 0) {
x += y;
} else {
result += temp;
}
y >>= 1, temp >>= 1, --offset;
}
return result * ((divisor < 0) ^ (dividend < 0) ? -1 : 1);
}
};
#endif //LEETCODE_29_DIVIDE_TWO_INTEGERS_H
|
97ef21299c66dc2e99873847426d87d1d3e9c43e
|
6f714dbab92f0507f13aa582fa992277e42c1777
|
/Plugin/openvas/OpenVasMgr.h
|
1edbd5cf1359e4d44da46508f3f4ce20c46082f0
|
[] |
no_license
|
sinzuo/bluedon-soc
|
90d72b966ace8d49b470dab791bd65f0d56d520e
|
809b59888de2f94b345b36ae33afacdbe103a1dd
|
refs/heads/master
| 2020-09-20T17:54:20.882559
| 2019-11-28T02:27:16
| 2019-11-28T02:27:16
| 224,552,658
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,473
|
h
|
OpenVasMgr.h
|
#ifndef _OPENVAS_MGR_H_
#define _OPENVAS_MGR_H_
#include "common/BDScModuleBase.h"
#include "config/BDOptions.h"
#include <time.h>
#include <stdarg.h>
#include <stdio.h>
#include "OpenVas.h"
//配置文件结构
typedef struct OpenVasConfigEx {
char chLog4File[100];
int nModuleId;
char chModuleName[20];
UInt16 wModuleVersion;
char chRecordSep[2]; //记录分隔符
char chFieldSep[2]; //字段分隔符
int nTaskNumPerThread; //每个线程处理的任务数
char sSubModule[128]; //支持的模块
char sUserName[64]; //用户名
char sPassWord[64]; //密码
} tag_OpenVas_config_t;
//线程池结构
typedef struct OpenVasThreadPoolEx {
pthread_t t_id;
unsigned int t_num;
bool b_state;
} tag_OpenVas_threadpool_t;
//Sar插件策略结构
typedef struct OpenVasPolicyEx {
OpenVasPolicyEx() {
vec_options.clear();
//为何和inspector插件中子任务序号保持一致,这里子任务序号不使用0
/*for (int i=0; i < num; i++) { // 1:cpu使用率 2:内存使用率 3:磁盘使用率 4:服务状态
m_mapFinished[i] = false;
m_mapResult[i] = "";
}*/
}
vector<string> vec_options; // 参数字符串
bool m_Finished; // 任务执行标志(细化至子任务)
string m_Result; // 任务结果字符串(细化至子任务)
} tag_OpenVas_policy_t;
class COpenVasMgr: public CScModuleBase {
public:
COpenVasMgr(const string& strConfigName);
virtual ~COpenVasMgr(void);
virtual bool Init(void); //初始化数据,先于Start被调用
virtual bool Start(void); //启动模块
virtual bool Stop(void); //停止模块
virtual bool IsRunning(void); //检查模块是否处于运行状态
virtual UInt32 GetModuleId(void);
virtual UInt16 GetModuleVersion(void);
virtual string GetModuleName(void);
virtual bool StartTask(const PModIntfDataType pDataType, const void* pData); //开始(下发)任务
virtual bool StopTask(const PModIntfDataType pDataType, const void* pData); //停止(取消)任务
virtual bool SetData(const PModIntfDataType pDataType, const void* pData, Poco::UInt32 dwLength); //调用方下发数据
virtual void* GetData(const PModIntfDataType pDataType, Poco::UInt32& dwRetLen); //调用方获取数据
virtual void FreeData(void* pData); //调用方释放获取到的内存
virtual void SetReportData(pFunc_ReportData pCbReport); //设置上报数据调用指针
virtual void SetFetchData(pFunc_FetchData pCbFetch); //设置获取数据调用指针
protected:
bool LoadConfig(void); //加载配置文件
void printConfig(); //打印配置信息
bool Load(void); //加载业务数据
bool ReportData(const PModIntfDataType pDataType, const void* pData, Poco::UInt32 dwLength); //上报数据(主要为监控日志)
const char* FetchData(const PModIntfDataType pDataType, Poco::UInt32& dwRetLen); //获取客户端系统参数
private:
static void* OnFetchHandle(void* arg); //Fetch Data 事件线程处理函数
static void* OnReportHandle(void* arg); //Report Data 事件线程处理函数
static void* OnOpenVasHandle(void* arg); //openvas命令
static void* OnTimeOut(void* arg); //超时处理
static string toBase64(string source);
private:
pFunc_ReportData m_pFuncReportData;
pFunc_FetchData m_pFuncFetchData;
string m_strConfigName;
bool m_bIsRunning;
Poco::FastMutex m_ModMutex;
pthread_t p_thread_report;
pthread_t p_thread_timeout;
//Poco::Mutex m_mutex_report;
vector<tag_OpenVas_policy_t> m_vecPolicy; // 策略(任务)队列
vector<tag_OpenVas_threadpool_t> m_vecThreadPool; // 线程池
list<tag_OpenVas_policy_t> m_listPolicy;
list<tag_OpenVas_policy_t> m_listReport;
int m_pthreadnum; // 线程池中预创建线程的数量
int m_pthreadnum_alive; // 线程池中活着的线程数量
bool m_bTimeOut;
bool m_bTimeOutStatus;
public:
tag_OpenVas_config_t m_OpenVasConfig;
COpenVasImpl* _pOpenvasImpl;
};
#endif //_OPENVAS_MGR_H_
|
707938a16eb0f4c1076c9627f60c51f923e873e1
|
5f183915dac91a5a89be52351a6b112a20d26ede
|
/Source/mediaOutputBase.cpp
|
4abb57ff9533e71ce544c01e47c737793ce22333
|
[] |
no_license
|
nameisshenlei/littlesurprise
|
aa1d2c7f4a6a9e1d2d2a5c8d2b22c2e3a4385396
|
7d8de018700b92341395d9e2f1e974ae43c12516
|
refs/heads/master
| 2021-01-19T21:40:38.892429
| 2017-04-19T01:23:32
| 2017-04-19T01:23:32
| 88,685,673
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 233
|
cpp
|
mediaOutputBase.cpp
|
#include "mediaOutputBase.h"
gstMediaoOutputBase::gstMediaoOutputBase()
{
}
gstMediaoOutputBase::~gstMediaoOutputBase()
{
}
bool gstMediaoOutputBase::createOutput()
{
return true;
}
void gstMediaoOutputBase::destroyOutput()
{
}
|
a2c5f9c055bec58b3f1419c0df09ba8dc364e90b
|
3dfc7473a0c86c745dcea6cbc203d72ae297c54a
|
/Correction/client/Player.h
|
b2cf92923bb4414ac83b6a4ff6cd8083f7dc9615
|
[] |
no_license
|
floriangomore/projetfinal
|
fae877d645f7a794f3da5e3f658613c7fe4490f5
|
ab1db5b461ab7a58fd741d968c460a1b4639fd65
|
refs/heads/master
| 2021-01-10T11:41:47.815690
| 2016-02-08T10:39:08
| 2016-02-08T10:39:08
| 50,998,636
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 251
|
h
|
Player.h
|
#ifndef PLAYER_H_
# define PLAYER_H_
#include <string>
class Player
{
private:
std::string m_name;
public:
Player();
~Player();
const std::string& getName(void) const { return (m_name); }
bool play(int *);
};
#endif // PLAYER_H_
|
a57853dc9b50aeb0d1c20ff7036d99b0c9db9a5b
|
664fe982b706d78af36fb3713f12f29e4cae36ce
|
/src/prerequisites.h
|
1c79fcea1e6a5bbcb4ce5db84319e6ff81277095
|
[
"MIT"
] |
permissive
|
k0zmo/evmc
|
2189de42bcf40ee49aacd247c186519f0744dc22
|
e5d87d5c2cccdf766db2ed90f324e5e14d786ca2
|
refs/heads/master
| 2020-12-02T00:58:57.438810
| 2017-01-27T21:39:42
| 2017-01-27T21:39:42
| 66,192,691
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,689
|
h
|
prerequisites.h
|
#pragma once
#include <algorithm>
#include <cstdint>
#include <ctime>
#include <fstream>
#include <iosfwd>
#include <memory>
#include <new>
#include <numeric>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
using byte = std::uint8_t;
using word = std::uint16_t;
using dword = std::uint32_t;
using qword = std::uint64_t;
using std::begin;
using std::end;
using std::vector;
using std::string;
using std::unique_ptr;
using std::pair;
constexpr inline byte operator"" _b(unsigned long long i)
{
return static_cast<byte>(i);
}
constexpr dword align(dword addr, dword alignment)
{
return (addr + (alignment - 1)) & ~(alignment - 1);
}
template <typename Enum, class = std::enable_if_t<std::is_enum<Enum>::value>>
constexpr auto underlying_cast(Enum e)
{
return static_cast<std::underlying_type_t<Enum>>(e);
}
template <typename T,
class = std::enable_if_t<std::is_standard_layout<T>::value>>
inline void write_bytes(std::ostream& os, const T& t)
{
os.write(reinterpret_cast<const char*>(&t), sizeof(t));
}
template <typename T,
class = std::enable_if_t<std::is_standard_layout<T>::value>>
inline void read_bytes(std::istream& os, T& t)
{
os.read(reinterpret_cast<char*>(&t), sizeof(t));
}
struct evm_header
{
byte magic[8];
dword code_size;
dword data_size;
dword initial_data_size;
};
enum class opcode : byte
{
nop = 32,
in = 40,
out = 41,
store = 48,
load = 49,
ldc = 50,
mov = 64,
add = 65,
sub = 66,
mul = 67,
div = 68,
mod = 69,
jz = 97,
jl = 98,
jump = 99,
call = 100,
ret = 101,
hlt = 126
};
enum { NUM_REGISTERS = 32 };
#pragma pack(push, 1)
struct bytecode_instr
{
opcode op;
byte dst;
byte src;
};
#pragma pack(pop)
static_assert(sizeof(bytecode_instr) == 3, "");
int16_t inline imm16(const bytecode_instr& i)
{
return static_cast<int16_t>((i.src << 8) | i.dst);
}
std::ostream& operator<<(std::ostream& os, const bytecode_instr& i);
std::ostream& operator<<(std::ostream& os, const vector<bytecode_instr>& is);
dword inline incr_check_overflow(dword base, dword offset)
{
if (base + offset < base)
throw std::runtime_error{"address overflow"};
return base + offset;
}
dword inline incr_check_overflow(dword base, qword offset)
{
const auto ret = base + offset;
if (ret < base || ret > (qword)0xFFFFFFFF)
throw std::runtime_error{"address overflow"};
return static_cast<dword>(ret);
}
dword inline decr_check_overflow(dword base, dword offset)
{
if (base - offset > base)
throw std::runtime_error{"address overflow"};
return base - offset;
}
|
001358dd56b9649d11f8fb27a3540a976d3794d1
|
558bae1119ce3752ba90733e898227baea82e8fc
|
/advantech/sample/Linux-x86/trek572/IMC_SUSI_IVCP_SAMPLE_CODE/sensor.cpp
|
46aefb7bd986d297e72dffc9595fa36044c42672
|
[] |
no_license
|
nanoadmin/nanotracker
|
8cefbcf9dbd1b2bf42da286522a04e7040da9a68
|
c6ab25a87b567467adf5ee5b86619ce3aff8e81e
|
refs/heads/master
| 2021-01-16T00:56:47.634547
| 2019-09-24T06:30:45
| 2019-09-24T06:30:45
| 99,987,309
| 1
| 1
| null | 2017-09-28T00:17:14
| 2017-08-11T03:21:25
|
Python
|
UTF-8
|
C++
| false
| false
| 2,419
|
cpp
|
sensor.cpp
|
#include <stdio.h>
#include "common.h"
#include "SUSI_IMC.h"
enum page_function{
SENSOR_READ_CPU1 = 1,
SENSOR_READ_CPU2,
SENSOR_READ_SYS
};
static void show_welcome_title(void)
{
printf("IVCP SDK Sample -- library version:%s\n", library_version);
printf(">> Psensor Control Menu\n\n");
}
static void page_menu()
{
printf("0) back\n");
printf("%d) Read CPU Core 1Temp\n", SENSOR_READ_CPU1);
printf("%d) Read CPU Core 2Temp\n", SENSOR_READ_CPU2);
printf("%d) Read Sys1 Temp\n", SENSOR_READ_SYS);
printf("\nEnter your choice: ");
}
void read_cpu_temp(int core)
{
USHORT result;
BYTE temp;
if(core == 1)
{
if( (result = SUSI_IMC_TEMPERATURESENSOR_GetCPUCore1Temperature( &temp )) != IMC_ERR_NO_ERROR )
{
printf("SUSI_IMC_TEMPERATURESENSOR_GetCPUCore1Temperature fail. error code=0x%04x\n", result);
return;
}
}
else
{
if( (result = SUSI_IMC_TEMPERATURESENSOR_GetCPUCore2Temperature( &temp )) != IMC_ERR_NO_ERROR )
{
printf("SUSI_IMC_TEMPERATURESENSOR_GetCPUCore2Temperature fail. error code=0x%04x\n", result);
return;
}
}
printf("The CPU Temp. is %d C\n", temp);
}
void read_sys1_temp()
{
USHORT result;
BYTE temp;
if( (result = SUSI_IMC_TEMPERATURESENSOR_GetSystem1Temperature( &temp )) != IMC_ERR_NO_ERROR )
{
printf("SUSI_IMC_TEMPERATURESENSOR_GetSystem1Temperature fail. error code=0x%04x\n", result);
return;
}
printf("The Sys Temp. is %d C\n", temp);
}
void sensor_main()
{
USHORT result;
int op;
if( (result = SUSI_IMC_TEMPERATURESENSOR_Initialize()) != IMC_ERR_NO_ERROR )
{
printf("SUSI_IMC_TEMPERATURESENSOR_Initialize fail. error code=0x%04x\n", result);
printf("\nPress ENTER to continue. ");
WAIT_ENTER();
return;
}
while(true)
{
CLEAR_SCREEN();
show_welcome_title();
page_menu();
if( SCANF("%d", &op) <=0 )
op = -1;
WAIT_ENTER();
if(op == 0)
break;
switch(op)
{
case SENSOR_READ_CPU1:
read_cpu_temp(1);
break;
case SENSOR_READ_CPU2:
read_cpu_temp(2);
break;
case SENSOR_READ_SYS:
read_sys1_temp();
break;
default:
printf("Unknown choice!\n");
break;
}
printf("\nPress ENTER to continue. ");
WAIT_ENTER();
}
if( (result = SUSI_IMC_TEMPERATURESENSOR_Deinitialize()) != IMC_ERR_NO_ERROR )
{
printf("SUSI_IMC_TEMPERATURESENSOR_Deinitialize. error code=0x%04x\n", result);
printf("\nPress ENTER to continue. ");
WAIT_ENTER();
}
}
|
4143b56e9b4d17de3a70421ab5da66510efeb2bf
|
bd69e970435c511cfba7ec572715e881b5120994
|
/unp_work/udp.cpp
|
36d57f9164e7458460f9bc8946b2f1c4169d8eb7
|
[] |
no_license
|
jamnix/mywork
|
c8c605437dd5344aeb3c4a265171eae57a998252
|
7c2b6a75772e91578c997d6838c40e1697549cf3
|
refs/heads/master
| 2021-01-23T13:35:28.114450
| 2014-05-18T17:10:33
| 2014-05-18T17:10:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 800
|
cpp
|
udp.cpp
|
#include "stdio.h"
#include "stdlib.h"
#include "sys/socket.h"
#include "string.h"
#include "unistd.h"
#include "arpa/inet.h"
short SERV_PORT = 8080;
int MAXLINE = 128;
void dg_echo(int sockfd, sockaddr* cliaddr, socklen_t clilen)
{
int n;
socklen_t len;
char msg[MAXLINE];
for(;;)
{
len = clilen;
n = recvfrom(sockfd, msg, sizeof(msg), 0, cliaddr, &len);
sendto(sockfd, msg, n, 0, cliaddr, len);
}
}
int main()
{
int sockfd;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
struct sockaddr_in servaddr, cliaddr;
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(SERV_PORT);
bind(sockfd, (sockaddr*)&servaddr, sizeof(servaddr));
dg_echo(sockfd, (sockaddr*)&cliaddr, sizeof(cliaddr));
}
|
9ae7afde6f3343ebc8691f01cff1670d701d9ad2
|
e8d05dc3622c2aa60d9610548c7a671f11b6227e
|
/utils/src/stuff/stack.h
|
c3ef285e8d73a9ecb04acc4fdd4feaeaff06c944
|
[
"MIT"
] |
permissive
|
yarkeeb/rdo_studio
|
b69ec5a1e506e97dbd08f6233e298c5f0799e9ba
|
c7e21aa144bc2620d36b1c6c11eb8a99f64574ab
|
refs/heads/master
| 2021-05-27T03:00:41.858923
| 2014-04-03T16:28:19
| 2014-04-03T16:28:19
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 910
|
h
|
stack.h
|
/*!
\copyright (c) RDO-Team, 2011
\file utils/stack.h
\author Урусов Андрей (rdo@rk9.bmstu.ru)
\date 12.02.2010
\brief
\indent 4T
*/
#ifndef _RDO_COMMON_STACK_H_
#define _RDO_COMMON_STACK_H_
// ----------------------------------------------------------------------- INCLUDES
#include <list>
// ----------------------------------------------------------------------- SYNOPSIS
#include "utils/src/common/rdocommon.h"
// --------------------------------------------------------------------------------
namespace rdo {
template<class T>
class stack
{
public:
void push (CREF(T) item);
void pop ();
rbool empty () const;
ruint size () const;
CREF(T) top () const;
REF(T) top ();
private:
typedef std::list<T> Container;
Container m_container;
};
} // namespace rdo
#include "utils/src/stuff/stack.inl"
#endif // _RDO_COMMON_STACK_H_
|
6e942519e195881fa291fea147f0b14829098b9f
|
37ada4f3b5cbd3a93bce52e8a09cbac88cdb9f70
|
/Board.cpp
|
f690e378e8cc263299fe20582b43ee4c81ed9e81
|
[] |
no_license
|
mronfire/BuncoGame
|
76c0e8f30cda3418619df7c0078def4db6042c08
|
d301bd6539e2c22aa8bb5de3906c8634b4be08dd
|
refs/heads/master
| 2020-04-06T03:54:53.082653
| 2017-02-25T21:22:02
| 2017-02-25T21:22:02
| 83,163,456
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,833
|
cpp
|
Board.cpp
|
//
// Board.cpp
// Bunco
//
// Created by Howard Stahl on 1/27/17.
// Copyright © 2017 Howard Stahl. All rights reserved.
//
/***********************************************************
* PROGRAMMED BY : Mario Rodriguez
* STUDENT ID : 1596508
* CLASS : CS20A->T - 6 : 45pm
* PROJECT #1 : Bunco Game
***********************************************************/
#include "Board.h"
namespace cs31
{
/*************************************************************************
* Default Constructor
*------------------------------------------------------------------------
* Purpose = This method will initialize the board and set the round for the
* board row
* Parameters = No parameters.
* Return Values = It returns nothing.
* Input = No input from user.
* Output = No output.
************************************************************************/
Board::Board() : mRound( 0 )
{
// initialize each BoardRow
for (int i = 1; i <= 6; i++)
{
mBoardRow[ i ].setRound( i );
}
}
/*************************************************************************
* setCurrentRound method
*------------------------------------------------------------------------
* Purpose = This method will set the current round being played
* Parameters = round - the current round in play
* Return Values = It returns nothing.
* Input = No input from user.
* Output = No output.
************************************************************************/
void Board::setCurrentRound( int round )
{
// unset the current board row
if (mRound >= 0 && mRound <= 6)
{
mBoardRow[mRound].setCurrentRound(false);
}
mRound = round; //--> assigns new round
// set the current board row
if (mRound >= 0 && mRound <= 6)
{
mBoardRow[mRound].setCurrentRound(true);
}
}
// TODO: set the human player to have won this current BoardRow
/*************************************************************************
* markHumanAsWinner method
*------------------------------------------------------------------------
* Purpose = This method will set the human player as the winner for the round
* Parameters = No parameters.
* Return Values = It returns nothing.
* Input = No input from user.
* Output = No output.
************************************************************************/
void Board::markHumanAsWinner()
{
mBoardRow[mRound].setHumanAsWinner();
}
// TODO: set the computer player to have won this current BoardRow
/*************************************************************************
* markComputerAsWinner method
*------------------------------------------------------------------------
* Purpose = This method will set the computer player as the winner for
* the round
* Parameters = No parameters.
* Return Values = It returns nothing.
* Input = No input from user.
* Output = No output.
************************************************************************/
void Board::markComputerAsWinner()
{
mBoardRow[mRound].setComputerAsWinner();
}
/*************************************************************************
* display method
*------------------------------------------------------------------------
* Purpose = This method will output the board itself, and display if there
* was a winner on the round or not decided yet.
* Parameters = No parameters.
* Return Values = It returns a string with all desired data.
* Input = No input from user.
* Output = No output.
************************************************************************/
std::string Board::display( ) const
{
std::string s = "\t\t Bunco Game\n\tHuman\t\t\tComputer\n";
for( int i = 1; i <= 6; i++)
{
s += mBoardRow[ i ].display() + "\n";
}
return( s );
}
// TODO: how many rounds has the human player won?
/*************************************************************************
* countUpHumanRoundWins method
*------------------------------------------------------------------------
* Purpose = This method will count the number of won rounds by the human
* player and then return it.
* Parameters = No parameters.
* Return Values = It returns nthe number of rounds won.
* Input = No input from user.
* Output = No output.
************************************************************************/
int Board::countUpHumanRoundWins( ) const
{
int numOfWins = 0; //variable to hold number of wins
//for-loop - This will loop through each board row checking for the
// round winner and update the number of wins.
for (int i = 0; i <= 6; i++)
{
if (mBoardRow[ i ].didHumanWin())
{
numOfWins += 1;
}
}
return(numOfWins);
}
// TODO: how many rounds has the computer player won?
/*************************************************************************
* countUpComputerRoundWins method
*------------------------------------------------------------------------
* Purpose = This method will count the number of won rounds by the computer
* player and then return it.
* Parameters = No parameters.
* Return Values = It returns nthe number of rounds won.
* Input = No input from user.
* Output = No output.
************************************************************************/
int Board::countUpComputerRoundWins( ) const
{
int numOfWins = 0; //variable to hold number of wins
//for-loop - This will loop through each board row checking for the
// round winner and update the number of wins.
for (int i = 0; i <= 6; i++)
{
if (mBoardRow[i].didComputerWin())
{
numOfWins += 1;
}
}
return(numOfWins);
}
}
|
46266eb9e94d8a7ff89079b7548e4c2ae2b0fbd1
|
b89713d68097057a25b2810936c215c260418794
|
/include/camp/list/list.hpp
|
a65dccfa442d2c68cdd6f2f20769615c17156923
|
[
"BSD-3-Clause"
] |
permissive
|
resslerruntime/RAJA
|
692cebc2bf598bc5ed35446aefbd8a41640a4844
|
df7ca1fa892b6ac4147c614d2d739d5022f63fc7
|
refs/heads/master
| 2020-08-02T03:36:43.901036
| 2019-07-25T18:52:01
| 2019-07-25T18:52:01
| 211,222,428
| 1
| 0
|
NOASSERTION
| 2019-09-27T02:45:36
| 2019-09-27T02:45:35
| null |
UTF-8
|
C++
| false
| false
| 1,253
|
hpp
|
list.hpp
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) 2016-19, Lawrence Livermore National Security, LLC
// and RAJA project contributors. See the RAJA/COPYRIGHT file for details.
//
// SPDX-License-Identifier: (BSD-3-Clause)
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
#ifndef CAMP_LIST_LIST_HPP
#define CAMP_LIST_LIST_HPP
#include "camp/number.hpp"
#include "camp/size.hpp"
namespace camp
{
// TODO: document
template <typename... Ts>
struct list {
using type = list;
};
namespace detail
{
template <typename T>
struct _as_list;
template <template <typename...> class T, typename... Args>
struct _as_list<T<Args...>> {
using type = list<Args...>;
};
template <typename T, T... Args>
struct _as_list<int_seq<T, Args...>> {
using type = list<integral_constant<T, Args>...>;
};
} // namespace detail
template <typename T>
struct as_list_s : detail::_as_list<T>::type {
};
template <typename T>
using as_list = typename as_list_s<T>::type;
template <typename... Args>
struct size<list<Args...>> {
constexpr static idx_t value{sizeof...(Args)};
using type = num<sizeof...(Args)>;
};
} // namespace camp
#endif /* CAMP_LIST_LIST_HPP */
|
98116e1ec2b3b3005bb5a2a04ba047b773dd64f8
|
66d18e8302467c600c3a5a7b1dd4ab7f33566df1
|
/Calibration.h
|
a500e8f3c0d27f69863e8a3e48aa8c1f9bcfe361
|
[] |
no_license
|
gedemagt/bachelor
|
b1cef5faafd7ccaaee8bc82eb4f57f5d52a2d913
|
1385a5845801c423ce6be108d75a57564ae28201
|
refs/heads/master
| 2020-05-31T17:12:50.550322
| 2014-08-10T11:19:32
| 2014-08-10T11:19:32
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 804
|
h
|
Calibration.h
|
#include"Selector.h"
#include"CalibrationClass.h"
#ifndef CALIBRATION_H
#define CALIBRATION_H
class Calib {
public:
Calibration Mg_Calib;
Calib(int state) {
ts = state;
Mg_Calib.LoadCalib();
};
~Calib();
void calibrate(Selector *s) {
Mg_Calib.Calibrate(s->Epad, s->E1, s->Ef, s->Nsfe, s->Nfe, s->Eb, s->Nsbe, s->Nbe);
if (ts == 1) {
Egas = s->Egas;
E1 = s->E1;
}
else if (ts == 2) {
Double_t a = 1.40822;
Double_t b = -100.146;
Egas = s->Egas;
E1 = s->E1 * a + b;
}
else if (ts == 3) {
Egas = s->Egas;
E1 = Mg_Calib.E1_calib;
}
};
char* getCalibration() {
switch (ts) {
case 1:
return "No calibration";
case 2:
return "My Calibration";
case 3:
return "Mortens Calibration";
}
}
Double_t Egas, E1;
private:
int ts = 1;
};
#endif
|
50067d5eefa2b5f0e3c600ef44707e8782777c85
|
ddb4faa321302addbd08d9cdd7f98da3181b4ab4
|
/mp4stream.cpp
|
ebcde6d60a1293e79e390f87336ffc3925309b01
|
[
"MIT"
] |
permissive
|
eachowu/windows-mp4_date
|
bdcfb6ed207c589de60d160cd88a8ca1c3ac47d8
|
496ea1cc00dd9a981410460a2445d8586aa1b1b5
|
refs/heads/master
| 2021-12-05T10:16:29.134552
| 2015-06-22T00:30:07
| 2015-06-22T00:30:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,880
|
cpp
|
mp4stream.cpp
|
/* mp4stream.cpp : network byte order layer on top of fstream for use with mp4 files
* Coert Vonk, in part based on
* https://github.com/macmade/MP4Parse
* for license see block below
*
* (c) Copyright 2015 by Coert Vonk - coertvonk.com
* Boost Sofware License 1.0, see below
* All rights reserved. Use of copyright notice does not imply publication.
*/
/*******************************************************************************
*
* Copyright (c) 2011, Jean-David Gadina - www.xs-labs.com
* Distributed under the Boost Software License, Version 1.0.
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
******************************************************************************/
/* $Id$ */
#include "stdafx.h"
#include <stdint.h>
#include <fstream>
#include <iostream>
#include "mp4stream.h"
mp4StreamException::mp4StreamException( void )
{
this->code = -1;
}
mp4StreamException::mp4StreamException( unsigned int c )
{
this->code = c;
}
const char *
mp4StreamException::what( void ) const throw()
{
switch ( this->code ) {
case mp4StreamException::NoFileName:
return "No input file";
case mp4StreamException::OpenError:
return "File open error";
}
return "Unknown exception";
}
mp4Stream::mp4Stream( void )
{
mp4StreamException e = mp4StreamException( mp4StreamException::NoFileName );
throw e;
}
mp4Stream::mp4Stream( char * filename )
{
this->stream.open( filename, std::ios::binary | std::ios::in | std::ios::out );
if ( this->stream.is_open() == false || this->stream.good() == false ) {
mp4StreamException e = mp4StreamException( mp4StreamException::OpenError );
throw e;
}
}
mp4Stream::~mp4Stream( void )
{
if ( this->stream.is_open() ) {
this->stream.close();
}
}
uint8_t
mp4Stream::readUint8( void )
{
uint8_t n;
this->read( (char *)&n, 1 );
return n;
}
uint32_t
mp4Stream::readUint16( void )
{
uint8_t c[2];
this->read( (char *)c, 2 );
uint16_t const n = (uint16_t)c[0] << 8 |
(uint16_t)c[1];
return n;
}
uint32_t
mp4Stream::readUint32( void )
{
uint8_t c[4];
this->read( (char *)c, 4 );
uint32_t const n = (uint32_t)c[0] << 24 |
(uint32_t)c[1] << 16 |
(uint32_t)c[2] << 8 |
(uint32_t)c[3];
return n;
}
uint64_t
mp4Stream::readUint64( void )
{
uint8_t c[8];
uint64_t n;
this->read( (char *)c, 8 );
n = (uint64_t)c[0] << 56 |
(uint64_t)c[1] << 48 |
(uint64_t)c[2] << 40 |
(uint64_t)c[3] << 32 |
(uint64_t)c[4] << 24 |
(uint64_t)c[5] << 16 |
(uint64_t)c[6] << 8 |
(uint64_t)c[7];
return n;
}
std::ostream &
mp4Stream::writeUint8( uint8_t const value )
{
return this->write( (char *)value, 1 );
}
std::ostream &
mp4Stream::writeUint16( uint16_t const value )
{
uint8_t c[2];
c[0] = (uint8_t)((value & 0xFF00U) >> 8);
c[1] = (uint8_t)((value & 0x00FFU) >> 0);
return this->write( (char *)c, 2 );
}
std::ostream &
mp4Stream::writeUint32( uint32_t const value )
{
uint8_t c[4];
c[0] = (uint8_t)((value & 0xFF000000U) >> 24);
c[1] = (uint8_t)((value & 0x00FF0000U) >> 16);
c[2] = (uint8_t)((value & 0x0000FF00U) >> 8);
c[3] = (uint8_t)((value & 0x000000FFU) >> 0);
return this->write( (char *)c, 4 );
}
std::ostream &
mp4Stream::writeUint64( uint64_t const value )
{
uint8_t c[8];
c[0] = (uint8_t)((value & 0xFF00000000000000LU) >> 56);
c[1] = (uint8_t)((value & 0x00FF000000000000LU) >> 48);
c[2] = (uint8_t)((value & 0x0000FF0000000000LU) >> 40);
c[3] = (uint8_t)((value & 0x000000FF00000000LU) >> 32);
c[4] = (uint8_t)((value & 0x00000000FF000000LU) >> 24);
c[5] = (uint8_t)((value & 0x0000000000FF0000LU) >> 16);
c[6] = (uint8_t)((value & 0x000000000000FF00LU) >> 8);
c[7] = (uint8_t)((value & 0x00000000000000FFLU) >> 0);
return this->write( (char *)c, 8 );
}
bool
mp4Stream::good( void ) const
{
return stream.good();
}
bool
mp4Stream::eof( void ) const
{
return stream.eof();
}
bool
mp4Stream::fail( void ) const
{
return stream.fail();
}
bool
mp4Stream::bad( void ) const
{
return stream.bad();
}
int
mp4Stream::peek( void )
{
return stream.peek();
}
int
mp4Stream::get( void )
{
return stream.get();
}
int
mp4Stream::sync( void )
{
return stream.sync();
}
std::streampos
mp4Stream::tellg( void )
{
return stream.tellg();
}
std::streampos
mp4Stream::tellp( void )
{
return stream.tellp();
}
std::istream &
mp4Stream::ignore( std::streamsize n, int delim )
{
return stream.ignore( n, delim );
}
std::istream &
mp4Stream::read( char * s, std::streamsize n )
{
return stream.read( s, n );
}
std::istream &
mp4Stream::putback( char c )
{
return stream.putback( c );
}
std::istream &
mp4Stream::unget( void )
{
return stream.unget();
}
std::istream &
mp4Stream::seekg( std::streampos pos )
{
return stream.seekg( pos );
}
std::istream &
mp4Stream::seekg( std::streamoff off, std::ios_base::seekdir dir )
{
return stream.seekg( off, dir );
}
std::ostream &
mp4Stream::seekp( std::streampos pos )
{
return stream.seekp( pos );
}
std::ostream &
mp4Stream::seekp( std::streamoff off, std::ios_base::seekdir dir )
{
return stream.seekp( off, dir );
}
std::ostream &
mp4Stream::write( char * s, std::streamsize n )
{
return stream.write( s, n );
}
|
af602b04e9c0f3b2ffcf757f3e469a523135845a
|
cb6137c290a7b938d26a90618c0a2e199eb28ba7
|
/Source/AttackRPG/RPGGameMode.cpp
|
b26e1d316974758d19b197002c84de1ba73919f4
|
[] |
no_license
|
q846236037/AttackRPG
|
b4554059f47bbb3039f07f88a6f379f70460fe40
|
00582ed7611fab17120cd5240e8b1ed5c47e1640
|
refs/heads/main
| 2023-03-26T23:21:28.886088
| 2021-04-01T11:53:09
| 2021-04-01T11:53:09
| 352,627,676
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 622
|
cpp
|
RPGGameMode.cpp
|
// Fill out your copyright notice in the Description page of Project Settings.
#include "RPGGameMode.h"
#include "GenericTeamAgentInterface.h"
#include "AttackRPG.h"
ARPGGameMode::ARPGGameMode()
{
}
void ARPGGameMode::BeginPlay()
{
//修改阵营比较关系
FGenericTeamId::SetAttitudeSolver([](FGenericTeamId A, FGenericTeamId B) {
if (A == RPGTEAM::NeutralTeam || B == RPGTEAM::NeutralTeam)
{
return ETeamAttitude::Neutral;
}
if (A != B)
{
return ETeamAttitude::Hostile;
}
if (A == B)
{
return ETeamAttitude::Friendly;
}
return ETeamAttitude::Neutral;
});//使用匿名函数
}
|
ee1303c753db1b0ad41cd8b0adbc69ae51c7dc79
|
90844f85fa32e83fec1e16fbe5eaf148cd18fa20
|
/zoj-1041.cpp
|
411aef7fc5ae9f177bd49e8fc03882d42a993564
|
[] |
no_license
|
kohn/kohn-zoj-sol
|
517d871a771d49a3abb9ed76e440522df44c4b91
|
551b86db35d0f8c01f3d8a3a4676129cee3cdbcb
|
refs/heads/master
| 2021-01-18T15:14:48.277509
| 2015-06-13T07:15:06
| 2015-06-13T07:15:06
| 36,655,559
| 1
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,220
|
cpp
|
zoj-1041.cpp
|
//1041 gougou WA
#include <iostream>
#include <string.h>
#include <math.h>
#include <vector>
#include <algorithm>
#define PRE 0.000001
using namespace std;
vector< pair<int,int> >point;
vector< pair<int,int> >valid;
int x,y;
double r;
bool isContained(int i,int j)
{
//求叉积?是干嘛的?
int k=(valid[i].first-x)*(valid[j].second-y) - (valid[i].second-y)*(valid[j].first-x);
return k<=0;
}
double dist(int a,int b)
{
return sqrt( pow(x-a,2) + pow(y-b,2) );
}
int fun(int n)
{
valid.clear();
for(int i=0;i<point.size();i++)
if(dist(point[i].first,point[i].second) <= r+PRE)
valid.push_back(point[i]);
int max=0;
for(int i=0;i<valid.size();i++) //扫描各个合法点
{
int num=1;
for(int j=0;j<valid.size();j++)
{
if(i==j)
continue;
if(isContained(i,j))
num++;
}
if(num>max) //若优于全局最优解,更新全局最优解
max=num;
}
return max;
}
int main()
{
cin>>x>>y>>r;
while(r>0)
{
int n;
cin>>n;
point.clear();
for(int i=0;i<n;i++)
{
int a,b;
cin>>a>>b;
point.push_back(make_pair(a,b));
}
cout<<fun(n)<<endl;
cin>>x>>y>>r;
}
return 0;
}
|
188f9127cc675c407362091900ef6fba92ffd468
|
a60ba5157b24f4060fa59e3aaf19c6cdc55bfb76
|
/TAGGL/ARCEmu/tlb.h
|
8ba70cd8543c44bbb09031134fdd3894d93d5a34
|
[] |
no_license
|
martinpiper/TAGGL
|
88fddd5276803b572f5ad26a0161d444ab1dd6a5
|
2cbeb55567aa15f4a3aa302a436c4ad2d201a4b7
|
refs/heads/master
| 2021-05-24T00:53:25.132646
| 2021-03-18T15:58:59
| 2021-03-18T15:58:59
| 6,575,802
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,064
|
h
|
tlb.h
|
/*************************************************************************
Copyright (C) 2002 - 2007 Wei Qin
See file COPYING for more information.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
*************************************************************************/
#ifndef SIMIT_TLB_H
#define SIMIT_TLB_H
//#define RECORD_TLB_MISS
#include "misc.h"
namespace simit {
typedef enum tlb_mapping_t
{
TLB_INVALID = 0,
TLB_SMALLPAGE = 1,
TLB_LARGEPAGE = 2,
TLB_SECTION = 3,
TLB_ESMALLPAGE = 4,
TLB_TINYPAGE = 5
} tlb_mapping_t;
/* Permissions bits in a TLB entry:
*
* 31 12 11 10 9 8 7 6 5 4 3 2 1 0
* +-------------+-----+-----+-----+-----+---+---+-------+
* Page: | | ap3 | ap2 | ap1 | ap0 | C | B | |
* +-------------+-----+-----+-----+-----+---+---+-------+
*
* 31 12 11 10 9 4 3 2 1 0
* +-------------+-----+-----------------+---+---+-------+
* Section: | | AP | | C | B | |
* +-------------+-----+-----------------+---+---+-------+
*/
/*
section:
section base address [31:20]
AP - table 8-2, page 8-8
domain
C,B
page:
page base address [31:16] or [31:12]
ap[3:0]
domain (from L1)
C,B
*/
//#define DEBUG_TLB
/* FS[3:0] in the fault status register: */
typedef enum mmu_fault_t
{
NO_FAULT = 0x0,
ALIGNMENT_FAULT = 0x1,
SECTION_TRANSLATION_FAULT = 0x5,
PAGE_TRANSLATION_FAULT = 0x7,
SECTION_DOMAIN_FAULT = 0x9,
PAGE_DOMAIN_FAULT = 0xB,
SECTION_PERMISSION_FAULT = 0xD,
SUBPAGE_PERMISSION_FAULT = 0xF,
/* this is for speed up checking access permisssion */
SLOW_ACCESS_CHECKING = 0x3,
/* this is for jit self-mofifying code check*/
JIT_ALARM_FAULT = 0xff,
} mmu_fault_t;
class tlb_entry_t
{
public:
word_t virt_addr;
word_t phys_addr;
word_t perms;
word_t domain;
word_t mask;
word_t nmask;
tlb_mapping_t mapping;
mmu_fault_t read_fault;
mmu_fault_t write_fault;
};
template <unsigned num> class tlb {
public:
/* constructor, num is number of entries */
tlb () {
reset();
}
/* destructor */
~tlb() {
#ifdef RECORD_TLB_MISS
printf("tlb miss = %u \n",miss_count);
#endif
}
/* reset */
void reset() {
miss_count = 0;
invalidate_all();
}
void invalidate_all () {
for (unsigned i= 0; i < num; i++) {
entries[i].mapping = TLB_INVALID;
entries[i].mask = 0xFFFFFFFF;
entries[i].virt_addr = 0xFFFFFFFF;
}
last_e= &entries[0];
cycle = 0;
}
void invalidate_entry (word_t addr) {
tlb_entry_t *e;
e = search (addr);
if (e) {
e->mapping = TLB_INVALID;
e->mask = 0xFFFFFFFF;
e->virt_addr = 0xFFFFFFFF;
}
}
/* search for an entry */
tlb_entry_t *search (word_t virt_addr) {
for (unsigned i = 0; i <num; i++) {
if (entries[i].mapping != TLB_INVALID &&
((virt_addr & entries[i].mask) ==
(entries[i].virt_addr & entries[i].mask))) {
return &entries[i];
}
}
#ifdef RECORD_TLB_MISS
miss_count++;
#endif
return NULL;
}
/* update RB */
tlb_entry_t *next () {
last_e = entries + cycle;
cycle = (cycle+1) % num;
return last_e;
}
tlb_entry_t *get_entry(int index){
return entries + index;
}
private:
tlb_entry_t entries[num];
tlb_entry_t *last_e;
int cycle; /* current tlb cycle, state for round robin policy */
uint64_t miss_count; /* miss count */
};
#define tlb_c_flag(tlb) \
((tlb)->perms & 0x8)
#define tlb_b_flag(tlb) \
((tlb)->perms & 0x4)
}
#endif /*SIMIT_TLB_H*/
|
a723e3c96c05708fb761ea0aaaab8c6d14f1080f
|
7b095c258340c02139d9a9b55d95bde6c90a40b0
|
/Chapter 8/8_7.cpp
|
af145d4a30685fc1d12bfed55e1517ac8096d83f
|
[] |
no_license
|
PhoenixDD/Cracking-the-Coding-Interview-6th-Ed
|
3a5b6eb85b82331cb19a853b338af884cdb87ae3
|
c58273feeb4de1145306c3839e0930107a599ccf
|
refs/heads/master
| 2021-01-19T06:18:39.443174
| 2017-08-17T19:01:58
| 2017-08-17T19:01:58
| 100,635,161
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 399
|
cpp
|
8_7.cpp
|
#include<iostream>
#include<string>
using namespace std;
string store;
void Permute(int start,string input)
{
if(start==input.length())
{
cout<<input<<endl;
return;
}
for (int i=start;i<input.length();i++)
{
swap(input[i], input[start]);
Permute(start + 1, input);
swap(input[i],input[start]);
}
}
int main()
{
Permute(0,"abc");
}
|
886a791c066fe19b2fdbcf99845df3363e4d1ca5
|
970da6ca9414b505832a09840ef5e7bb652843e6
|
/src/main.cpp
|
e73d9616753fcb5740b3f38d0fe06580ccad0310
|
[
"MIT"
] |
permissive
|
neonoia/Protoshop
|
fd9110bc515cc146679530970ea655172fc833cf
|
66fb204554822e6da6416f495622a2b7d5be73ec
|
refs/heads/master
| 2023-06-08T03:24:08.396180
| 2019-11-30T03:14:28
| 2019-11-30T03:14:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,349
|
cpp
|
main.cpp
|
#include <iostream>
#include "ui/imageviewer.hpp"
#include <QApplication>
#include <QCommandLineParser>
// #include "image/image.hpp"
// #include "image/exception.hpp"
// #include "adjustment/adjustment.hpp"
int main(int argc, char *argv[]) {
// try {
// // Image* img_lena = Image::load("./res/lena.bmp");
// // Image* img_baboon = Image::load("./res/lena.bmp");
// // Image* img = *img_lena + *img_baboon;
// // img->show();
// Image* img = Image::load("./res/lena.bmp");
// // AdjustmentTranslate::apply(img, 30, 25);
// AdjustmentRotate::rotate90CCW(img);
// img->show();
// // Image* img2 = *img + *img;
// // img2->show();
// } catch (ImageLoadException e) {
// std::cout << e.get_message() << std::endl;
// }
QApplication app(argc, argv);
QGuiApplication::setApplicationDisplayName(ImageViewer::tr("Image Viewer"));
QCommandLineParser commandLineParser;
commandLineParser.addHelpOption();
commandLineParser.addPositionalArgument(ImageViewer::tr("[file]"), ImageViewer::tr("Image file to open."));
commandLineParser.process(QCoreApplication::arguments());
ImageViewer imageViewer;
if (!commandLineParser.positionalArguments().isEmpty()
&& !imageViewer.loadFile(commandLineParser.positionalArguments().front())) {
return -1;
}
imageViewer.show();
return app.exec();
}
|
f68877862c71f3a3c2253b7fb7fb66b20f139950
|
d864aee02bc9e3588d8e70c708448374fb2387aa
|
/Contest/Duo/2017/2/C.cpp
|
aa9e2bcdb1c4120b7b8d63b4281758eba0b27320
|
[] |
no_license
|
BanSheeGun/Gun
|
075ebf62891a0ab4db6ff5ca13e1ae0644248119
|
8a046a9c3eb56fb5e87897343f383253b1736694
|
refs/heads/master
| 2021-01-17T00:18:41.834830
| 2018-03-18T06:32:04
| 2018-03-18T06:32:04
| 44,953,535
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,478
|
cpp
|
C.cpp
|
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const ll mod = 1e9 + 7;
long long ans;
int N;
int b[250010];
int n, i, k;
inline bool cmp(int a, int b) {
return a < b;
}
int tree[4000000];
int change(int now, int l, int r, int k, int x) {
if (l == r) {
tree[now] = x;
return 0;
}
int mid = (l + r) / 2;
if (k <= mid)
change(now*2, l, mid, k, x);
else
change(now*2+1, mid+1, r, k, x);
tree[now] = max(tree[now*2], tree[now*2+1]);
return 0;
}
int find(int now, int l, int r, int ll, int rr) {
if (ll <= l && r <= rr)
return tree[now];
int mid = (l + r) / 2;
int ans = 0;
if (ll <= mid)
ans = max(ans, find(now*2, l, mid, ll, rr));
if (rr > mid)
ans = max(ans, find(now*2+1, mid+1, r, ll, rr));
return ans;
}
int main() {
while (~scanf("%d", &n)) {
N = n * 2;
memset(tree, 0, sizeof(tree));
ans = 0;
for (i = 1; i <= n; ++i) {
scanf("%d", &k);
change(1, 1, N, i, k-i);
}
ans = 0;
for (i = 1; i <= n; ++i)
scanf("%d", &b[i]);
sort(b+1, b+1+n, cmp);
for (i = n+1; i <= N; ++i) {
int tmp = find(1, 1, N, b[i-n], i-1);
ans = (ans + tmp) % mod;
change(1, 1, N, i, tmp-i);
}
printf("%lld\n", ans);
}
return 0;
}
|
5e7e9b794dacc5c389dc4033b847f373da4cdae9
|
9f1ca205ac37aeff004e5c4847b5c7d6e6973899
|
/cplusplus/design_pattern/IteratorProj/bak/MyObject.cpp
|
3ca70bda159ef550317ce86d4106974ad8dfc420
|
[
"MIT"
] |
permissive
|
ppddflyme/Design-Pattern
|
68a7f80bdf6636daaccc4ffef041b4342a01b002
|
160741b81bc8a63bff0e3301394e6c3b3a526ae3
|
refs/heads/master
| 2021-06-24T20:41:56.681690
| 2020-09-30T03:11:36
| 2020-09-30T03:11:36
| 132,299,704
| 0
| 0
| null | 2020-09-30T03:11:37
| 2018-05-06T02:19:00
|
C++
|
UTF-8
|
C++
| false
| false
| 177
|
cpp
|
MyObject.cpp
|
#include "stdafx.h"
#include "MyObject.h"
MyObject::MyObject()
{
}
MyObject::~MyObject()
{
}
void MyObject::sayHi()
{
std::cout << "MyObject::sayHi()" << std::endl;
}
|
170ae9321e1dbdf0bcf1039fc8f0271f4d443836
|
b395562252d598cef36dde4c6405c13b476d6e0e
|
/Stage.cpp
|
c967f75ba68de040e5728533b72954adc64d52b6
|
[] |
no_license
|
DragonChestnut/RPGGame-caster-_v0.36
|
02b59e3e869fe5644d6222c0a86f38959e29a48b
|
2379fe607be1f93d3638adcd0abc048ccf434598
|
refs/heads/master
| 2020-03-21T14:39:49.396554
| 2018-06-26T01:48:33
| 2018-06-26T01:48:33
| 138,668,866
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,856
|
cpp
|
Stage.cpp
|
#include "Game.h"
#include "Xmodel.h"
#include "meshfield.h"
#include "camera.h"
#include "character.h"
#include "Billboard.h"
#include "scene.h"
#include "wall.h"
#include "input.h"
#include "shadow.h"
#include "GameUI.h"
#include "effect.h"
#include "Fade.h"
#include "Stage.h"
#include "Clock.h"
#include "sound.h"
static bool FadeSwitch;
void InitStage(void)
{
ResetCamera();
//
D3DXVECTOR3 characterpos = GetBillboardPos(BILL_CHARACTER);
SetShadowPos(SHADOW_CHARACTER, characterpos.x, characterpos.y, characterpos.z);
SetShadowScaling(SHADOW_CHARACTER, 0.12f, 0.05f, 0.05f);
InitCharacter();
SetISCharacterTrain(false);
InitGameUI();
InitEffect();
SetMeshFildTexNum(2);
CreateBillboardWHN(BILL_BACKGROUND_01, 128.f, 15.f, 1);
SetBillboardISTexNum(BILL_BACKGROUND_01, TEX_BACKGROUND_SHIRO_01);
SetBillboardPos(BILL_BACKGROUND_01, -30.f, -2.f, 12.f);
FadeSwitch = false;
CreateSound(SOUND_BGM_BATTLE);
}
void UninitStage(void)
{
UninitCharacter();
UninitGameUI();
UninitEffect();
DestroyBillboard(BILL_BACKGROUND_01);
DestroySound(SOUND_BGM_BATTLE);
}
void UpdateStage(void)
{
//
D3DXVECTOR3 characterpos = GetBillboardPos(BILL_CHARACTER);
SetShadowPos(SHADOW_CHARACTER, characterpos.x, characterpos.y, characterpos.z);
//
UpdateWall();
UpdateCamera();
UpdateMeshField();
UpdateCharacter();
UpdateShadow();
UpdateGameUI();
UpdateEffect();
UpdateBillboard();
UpdateClock();
//test
if (GetKeyboardPress(DIK_9))
{
StartFade(Out, White);
FadeSwitch = true;
}
if (FadeSwitch)
{
if (GetState() == After)
{
StartFade(In, White);
ChangeScene(SCENE_RESULT);
}
}
//
}
void DrawStage(void)
{
DrawWall();
DrawMeshField();
DrawCharacter();
DrawBillboard();
DrawShadow();
DrawGameUI();
DrawClock();
}
|
5a92e4a2025bf39757dcbadb4d7b3b30c52ca00c
|
90bd5ba5c2aa314c6a167f2955eff0d6ad8482dd
|
/Codeforces/CF608/C.cpp
|
ec14f54bc347dc7bbdc045709e7176b283f94971
|
[] |
no_license
|
Charly52830/Practice
|
d446811437a28ab915e4250a322734c28dd5ab33
|
8083542c60d055f0a9af2426c33ee17015e222f4
|
refs/heads/master
| 2021-07-05T10:53:48.083819
| 2020-12-15T01:06:22
| 2020-12-15T01:06:22
| 211,193,096
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 563
|
cpp
|
C.cpp
|
//https://codeforces.com/contest/1271/problem/C
#include<iostream>
using namespace std;
int main() {
int n,s_x,s_y,b,x,y,c1=0,c2=0,c3=0,c4=0;
scanf("%d %d %d",&n,&s_x,&s_y);
for(int i=0;i<n;i++) {
scanf("%d %d",&x,&y);
c1+=y>s_y;
c3+=y<s_y;
c2+=x>s_x;
c4+=x<s_x;
}
if(c1>= c2 && c1>=c3 && c1>=c4)
printf("%d\n%d %d\n",c1,s_x,s_y+1);
else if(c2>=c1 && c2>=c3 && c2>=c4)
printf("%d\n%d %d\n",c2,s_x+1,s_y);
else if(c3>= c1 && c3>=c2 && c3>=c4)
printf("%d\n%d %d\n",c3,s_x,s_y-1);
else
printf("%d\n%d %d\n",c4,s_x-1,s_y);
return 0;
}
|
770d25115aba620088fa198d77ec5f458a691a32
|
84a9cf5fd65066cd6c32b4fc885925985231ecde
|
/GDS2/Plugins/src/SceneEditor/Hierarchy.h
|
df509bd0a9a7618d2f3506e67df5b8567ee52087
|
[] |
no_license
|
acemon33/ElementalEngine2
|
f3239a608e8eb3f0ffb53a74a33fa5e2a38e4891
|
e30d691ed95e3811c68e748c703734688a801891
|
refs/heads/master
| 2020-09-22T06:17:42.037960
| 2013-02-11T21:08:07
| 2013-02-11T21:08:07
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,286
|
h
|
Hierarchy.h
|
///============================================================================
/// \note Elemental Engine
/// Copyright (c) 2005-2008 Signature Devices, Inc.
///
/// This code is redistributable under the terms of the EE License.
///
/// This code is distributed without warranty or implied warranty of
/// merchantability or fitness for a particular purpose. See the
/// EE License for more details.
///
/// You should have received a copy of the EE License along with this
/// code; If not, write to Signature Devices, Inc.,
/// 3200 Bridge Parkway Suite 102, Redwood City, CA 94086 USA.
///============================================================================
#if !defined(AFX_HIERARCHY_H__DE30104A_F977_488A_B91A_DBF0E9B6E33D__INCLUDED_)
#define AFX_HIERARCHY_H__DE30104A_F977_488A_B91A_DBF0E9B6E33D__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Hierarchy.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CHierarchy dialog
typedef list<struct HIERARCHYINFO *> LISTHINFO;
typedef struct HIERARCHYINFO
{
HIERARCHYINFO()
: objectName(NULL)
, compType(NULL)
, hItem(NULL)
{
}
~HIERARCHYINFO()
{
delete objectName;
delete compType;
}
StdString name; // the label for the item
IHashString *objectName; // the name of the object
IHashString *compType; // user data for the item
HTREEITEM hItem; // handle to tree item for this hierarchy item.
} HIERARCHYINFO;
struct HIERARCHYTREESTATE;
class CHierarchy : public CPropertyPage
{
typedef vector< pair<StdString, StdString> > MacrosList;
// Construction
public:
CHierarchy(CWnd* pParent = NULL); // standard constructor
// Dialog Data
enum { IDD = IDD_HIERARCHY };
void ClearHierarchy();
void CollapseItem( HTREEITEM Item )
{
ExpandItem( Item, TVE_COLLAPSE );
}
void ExpandItem( HTREEITEM Item, UINT nCode = TVE_EXPAND );
BOOL AddHierarchyItem(HTREEITEM parent, HIERARCHYINFO *child);
BOOL RemoveHierarchyItem(HIERARCHYINFO *child);
HIERARCHYINFO *GetItemData(HTREEITEM item);
void SelectItem(HTREEITEM item);
void DeselectItem(HTREEITEM item);
HTREEITEM GetParentItem();
bool IsItemChecked(HTREEITEM item);
void RenameItem(HTREEITEM item, IHashString *pNewName);
HIERARCHYINFO* GetNextItem(HIERARCHYINFO *hi, UINT nCode);
/// \brief return CHashString with text of the item
/// \param item - HTREEITEM from the tree
/// \return CHashString with text of the item
CHashString GetItemName(HTREEITEM item);
/// \brief select passed object in the EE
/// \param hi - pointer to hierarchy item info
void SelectObject(HIERARCHYINFO *hi);
UINT GetItemState(HTREEITEM item, UINT stateMask);
/// \brief save current hierarchy tree state (expand/collapse and selection)
/// \return pointer to structure with hierarchy tree state
HIERARCHYTREESTATE *SaveState();
/// \brief restore hierarchy tree state (expand/collapse and selection)
/// \param pState - pointer to structure with previously saved state
void RestoreState(const HIERARCHYTREESTATE *pState);
/// \brief release data for structure with previously saved state
/// \param pState - pointer to structure
void DeleteState(HIERARCHYTREESTATE *pState);
void CollapseScene();
void ExpandScene();
void SetItemText(HTREEITEM item, LPCTSTR text)
{
m_HierarchyControl.SetItemText(item, text);
}
void setUnderUpdateFlag( bool underUpdate ) { isUnderUpdate = underUpdate; };
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CHierarchy)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
virtual BOOL PreTranslateMessage(MSG* pMsg);
//}}AFX_VIRTUAL
// Implementation
// Generated message map functions
//{{AFX_MSG(CHierarchy)
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnKeeplocal();
afx_msg void OnKeepglobal();
afx_msg LRESULT OnDropMessage(WPARAM wParam, LPARAM lParam);
afx_msg void OnSelChangedTree(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnClickTree(NMHDR *pnhm, LRESULT *result);
afx_msg void OnDblClickTree(NMHDR *pnhm, LRESULT* result);
afx_msg void OnBeginLabelEdit(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnEndLabelEdit(NMHDR *pNMHDR, LRESULT *pResult);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
private:
bool ChangeObjectParentName(IHashString *name, IHashString *comp, IHashString *newParent);
list<DWORD> GetLinkableObjects(IHashString *componentType) const;
StdString GetFileSpawnerPath(LPCTSTR szResourcePath) const;
IXMLArchive *OpenXMLArchive(LPCTSTR szFilePath) const;
IXMLArchive *GetFileSpawner(LPCTSTR szResourcePath) const;
bool IsLinkAllowed(IHashString *componentType, IXMLArchive *pSpawnerArchive) const;
static void FillMacroses(LPCTSTR szResourcePath, MacrosList ¯oses);
static StdString ApplyMacroses(const StdString &value, const MacrosList ¯oses);
/// \brief helper function for recursive tree state processing
/// \param item - currently processed tree item
/// \param pState - pointer to structure with hierarchy state
void SaveState(HTREEITEM item, HIERARCHYTREESTATE *pState);
/// \brief helper function for recursive tree state restore
/// \param item - currently processed tree item
/// \param pState - pointer to structure with hierarchy state
void RestoreState(HTREEITEM item, const HIERARCHYTREESTATE *pState);
private:
CTreeCtrlEx m_HierarchyControl;
// cached names that get altered after a menu item is selected
CHashString m_hsDragObjectName;
CHashString m_hsDragObjectComp;
CHashString m_hsDragObjectNewParent;
StdString m_szOldName;
CImageList m_Icons;
IToolBox *m_pToolBox;
bool isUnderUpdate;
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_HIERARCHY_H__DE30104A_F977_488A_B91A_DBF0E9B6E33D__INCLUDED_)
|
67e5f96eccf9cf7f9dfabeb1ab7e021315a52cdd
|
991529a2e04b3dfc58eeafcb1fddbad8f7b6b6b0
|
/Oscilloscope/Channel/ChannelList/ChannelAttributes/attributes.h
|
7611d6d61e0bfcea9c3dda953ec654589ce94710
|
[] |
no_license
|
YegorR/Oscilloscope
|
92ccd4e37a986ceddde1759427d156859bdbc838
|
ff5a73afeab61a1d524e55c33c2b56efcc635093
|
refs/heads/master
| 2020-06-11T02:48:32.284805
| 2019-07-05T05:06:25
| 2019-07-05T05:06:25
| 193,830,284
| 0
| 2
| null | 2019-07-01T04:58:14
| 2019-06-26T04:37:09
|
C++
|
UTF-8
|
C++
| false
| false
| 246
|
h
|
attributes.h
|
#ifndef ATTRIBUTES_H
#define ATTRIBUTES_H
#include <QColor>
namespace oscilloscope
{
struct Attributes
{
QColor _collor = QColor(0,0,0,0);
int _lineType = 0;
int _lineWidth = 0;
};
}
#endif // ATTRIBUTES_H
|
c3403bb10e00abe00a7ede9f3d3b6feae264dce4
|
eca634ce6477e5680987dfc6536f6fdd93c58db6
|
/DeferredClient/CelSphere.cpp
|
a340a3a5e5f4f90c151bf67d87368e8e5b1c7c73
|
[] |
no_license
|
tectronics/surface-physics
|
ba2ed585406f9e9955aeabc6d343cedeb41c2f61
|
f5f2af539aee7483ae28f4edec4b7b62edfa2d61
|
refs/heads/master
| 2018-01-11T15:03:08.166454
| 2014-10-02T19:44:33
| 2014-10-02T19:44:33
| 45,230,360
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,088
|
cpp
|
CelSphere.cpp
|
#include "D3D11Client.h"
#include "CelSphere.h"
CelSphere::CelSphere() : D3D11Effect() {
Stars = NULL;
ConstLines = LatGrid = LngGrid = NULL;
sphere_r = 1e6f;
InitCelSphereEffect();
LoadStars();
LoadConstLines();
CreateGrid();
}
CelSphere::~CelSphere() {
for( DWORD j = 0; j < nbuf; j++ )
REL( Stars[j] );
REL( ConstLines );
REL( LatGrid );
REL( LngGrid );
REL( cb_VS_Star_Line );
REL( cb_PS_Line );
REL( IL_CVertex );
REL( VS_Star_Line );
REL( PS_Star );
REL( PS_Line );
}
void CelSphere::LoadStars() {
const DWORD bsize = 8;
double a, b, xz;
StarRenderPrm *prm = (StarRenderPrm*)gc->GetConfigParam( CFGPRM_STARRENDERPRM );
if( prm->mag_lo > prm->mag_hi ) {
if( prm->map_log )
a = -log( prm->brt_min )/(prm->mag_lo - prm->mag_hi);
else {
a = (1.0 - prm->brt_min)/(prm->mag_hi - prm->mag_lo);
b = prm->brt_min - prm->mag_lo*a;
}
}
else
oapiWriteLog( "Inconsistent magnitude limits for background stars" );
// float c;
int lvl, plvl = 256;
StarRec *data = new StarRec [MAXSTARVERTEX];
STARVERTEX *idata = new STARVERTEX [MAXSTARVERTEX];
FILE *file;
DWORD j, k, nvtx, idx = 0;
D3D11_BUFFER_DESC desc;
D3D11_SUBRESOURCE_DATA sdata;
nbuf = 0;
Stars = NULL;
// Stars[0] = NULL;
if( !(file = fopen( "Star.bin", "rb" )) )
return;
nsvtx = 0;
while( nvtx = fread( data, sizeof(StarRec), MAXSTARVERTEX, file ) ) {
for( j = 0; j < nvtx; j++ )
if( data[j].mag > prm->mag_lo ) {
nvtx = j;
break;
}
if( nvtx ) {
ID3D11Buffer **tmp = new ID3D11Buffer *[nbuf+1];
if( Stars ) {
memcpy( tmp, Stars, sizeof(ID3D11Buffer*)*nbuf );
delete [ ] Stars;
}
Stars = tmp;
nbuf++;
Stars[nbuf-1] = NULL;
for( j = 0; j < nvtx; j++ ) {
StarRec &rec = data[j];
STARVERTEX &v = idata[j];
xz = sphere_r*cos(rec.lat);
v.pos.x = (float)(xz*cos(rec.lng));
v.pos.y = (float)(xz*sin(rec.lng));
v.pos.z = (float)(sphere_r*sin(rec.lat));
if( prm->map_log ) v.col = (float)min( 1.0, max( prm->brt_min, exp( -(rec.mag - prm->mag_hi)*a ) ) );
else v.col = (float)min( 1.0, max( prm->brt_min, a*rec.mag + b ) );
lvl = (int)(v.col*256.0*0.5);
lvl = (lvl > 255 ? 255 : lvl);
for( k = lvl; k < (DWORD)plvl; k++ )
lvlid[k] = idx;
plvl = lvl;
idx++;
}
ZeroMemory( &desc, sizeof(desc) );
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.ByteWidth = 16*nvtx;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
desc.Usage = D3D11_USAGE_IMMUTABLE;
ZeroMemory( &sdata, sizeof(sdata) );
sdata.pSysMem = idata;
HR( Dev->CreateBuffer( &desc, &sdata, &Stars[nbuf-1] ) );
nsvtx += nvtx;
}
if( nvtx < MAXSTARVERTEX )
break;
}
fclose( file );
delete [ ] data;
delete [ ] idata;
for( j = 0; j < (DWORD)plvl; j++ )
lvlid[j] = idx;
}
void CelSphere::LoadConstLines() {
const DWORD maxline = 1000; // plenty for default data base, but check with custom data bases!
oapi::GraphicsClient::ConstRec *cline = new oapi::GraphicsClient::ConstRec [maxline];
ncline = gc->LoadConstellationLines( maxline, cline );
if( ncline ) {
D3DXVECTOR4 *data = new D3DXVECTOR4 [ncline*2];
DWORD j;
double xz;
for( j = 0; j < ncline; j++ ) {
oapi::GraphicsClient::ConstRec *rec = cline+j;
xz = sphere_r*cos( rec->lat1 );
data[j*2].x = (float)(xz*cos( rec->lng1 ));
data[j*2].z = (float)(xz*sin( rec->lng1 ));
data[j*2].y = (float)(sphere_r*sin( rec->lat1 ));
data[j*2].w = 1.0f;
xz = sphere_r*cos( rec->lat2 );
data[j*2+1].x = (float)(xz*cos( rec->lng2 ));
data[j*2+1].z = (float)(xz*sin( rec->lng2 ));
data[j*2+1].y = (float)(sphere_r*sin( rec->lat2 ));
data[j*2+1].w = 1.0f;
}
D3D11_BUFFER_DESC desc;
ZeroMemory( &desc, sizeof(desc) );
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.ByteWidth = ncline*2*16;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
desc.Usage = D3D11_USAGE_IMMUTABLE;
D3D11_SUBRESOURCE_DATA sdata;
ZeroMemory( &sdata, sizeof(sdata) );
sdata.pSysMem = data;
HR( Dev->CreateBuffer( &desc, &sdata, &ConstLines ) );
delete [ ] data;
}
delete [ ] cline;
}
void CelSphere::CreateGrid() {
DWORD j, i, idx;
double lat, lng, xz, y;
D3DXVECTOR4 *buf = new D3DXVECTOR4 [12*(NSEG+1)];
D3D11_BUFFER_DESC desc;
D3D11_SUBRESOURCE_DATA sdata;
for( j = idx = 0; j <= 10; j++ ) {
lat = (j-5)*15.0*RAD;
xz = sphere_r*cos( lat );
y = sphere_r*sin( lat );
for( i = 0; i <= NSEG; i++ ) {
lng = PI2*(double)i/(double)NSEG;
buf[idx].x = (float)(xz*cos( lng ));
buf[idx].z = (float)(xz*sin( lng ));
buf[idx].y = (float)y;
buf[idx].w = 1.0f;
idx++;
}
}
ZeroMemory( &desc, sizeof(desc) );
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.ByteWidth = 16*(NSEG+1)*11;//idx;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
desc.Usage = D3D11_USAGE_IMMUTABLE;
ZeroMemory( &sdata, sizeof(sdata) );
sdata.pSysMem = buf;
HR( Dev->CreateBuffer( &desc, &sdata, &LngGrid ) );
for( j = idx = 0; j < 12; j++ ) {
lng = j*15.0*RAD;
for( i = 0; i <= NSEG; i++ ) {
lat = PI2*(double)i/(double)NSEG;
xz = sphere_r*cos( lat );
y = sphere_r*sin( lat );
buf[idx].x = (float)(xz*cos( lng ));
buf[idx].z = (float)(xz*sin( lng ));
buf[idx].y = (float)y;
buf[idx].w = 1.0f;
idx++;
}
}
ZeroMemory( &desc, sizeof(desc) );
desc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
desc.ByteWidth = 16*(NSEG+1)*12;//idx;
desc.CPUAccessFlags = 0;
desc.MiscFlags = 0;
desc.StructureByteStride = 0;
desc.Usage = D3D11_USAGE_IMMUTABLE;
ZeroMemory( &sdata, sizeof(sdata) );
sdata.pSysMem = buf;
HR( Dev->CreateBuffer( &desc, &sdata, &LatGrid ) );
delete [ ] buf;
}
void CelSphere::RenderCelestialSphere( D3DXMATRIX *VP, float skybrt, const D3DXVECTOR3 *bgcol ) {
/*
Renders stars, constellations, labels.
*/
// static const D3DXCOLOR EGColor = D3DXCOLOR( 0.0f, 0.0f, 0.4f, 1.0f ), EColor = D3DXCOLOR( 0.0f, 0.0f, 0.8f, 1.0f );
dCtx->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP );
dCtx->VSSetConstantBuffers( 0, 1, &cb_VS_Star_Line );
dCtx->IASetInputLayout( IL_CVertex );
dCtx->VSSetShader( VS_Star_Line, NULL, NULL );
DWORD PMode = SC->GetPlanetariumFlag();
if( PMode & PLN_ENABLE ) {
float linebrt = 1.0f - skybrt;
dCtx->PSSetShader( PS_Line, NULL, NULL );
dCtx->PSSetConstantBuffers( 1, 1, &cb_PS_Line );
dCtx->UpdateSubresource( cb_VS_Star_Line, 0, NULL, SC->GetVP(), 0, 0 );
//ecliptic grid
if( PMode & PLN_EGRID ) {
D3DXVECTOR4 vColor( 0.0f, 0.0f, 0.4f*linebrt, 1.0f );
dCtx->UpdateSubresource( cb_PS_Line, 0, NULL, &vColor, 0, 0 );
RenderGrid( !(PMode & PLN_ECL) );
}
if( PMode & PLN_ECL ) {
D3DXVECTOR4 vColor( 0.0f, 0.0f, 0.8f*linebrt, 1.0f );
dCtx->UpdateSubresource( cb_PS_Line, 0, NULL, &vColor, 0, 0 );
RenderGreatCircle();
}
//celestial grid
if( PMode & (PLN_CGRID | PLN_EQU) ) {
static const double obliquity = 0.4092797095927;
double coso = cos(obliquity), sino = sin(obliquity);
D3DXMATRIX rot( 1.0f, 0.0f, 0.0f, 0.0f,
0.0f, (float)coso, (float)sino, 0.0f,
0.0f, -(float)sino, (float)coso, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f );
D3DXMatrixMultiply( &rot, &rot, SC->GetVP() );
dCtx->UpdateSubresource( cb_VS_Star_Line, 0, NULL, &rot, 0, 0 );
if( PMode & PLN_CGRID ) {
D3DXVECTOR4 vColor( 0.35f*linebrt, 0.0f, 0.35f*linebrt, 1.0f );
dCtx->UpdateSubresource( cb_PS_Line, 0, NULL, &vColor, 0, 0 );
RenderGrid( !(PMode & PLN_EQU) );
}
if( PMode & PLN_EQU ) {
D3DXVECTOR4 vColor( 0.7f*linebrt, 0.0f, 0.7f*linebrt, 1.0f );
dCtx->UpdateSubresource( cb_PS_Line, 0, NULL, &vColor, 0, 0 );
RenderGreatCircle();
}
}
//constellation lines
dCtx->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_LINELIST );
if( PMode & PLN_CONST ) {
D3DXVECTOR4 vColor( 0.4f*linebrt, 0.3f*linebrt, 0.2f*linebrt, 1.0f );
dCtx->UpdateSubresource( cb_PS_Line, 0, NULL, &vColor, 0, 0 );
RenderConstellations();
}
}
//stars
dCtx->UpdateSubresource( cb_VS_Star_Line, 0, NULL, SC->GetVP(), 0, 0 );
dCtx->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_POINTLIST );
dCtx->PSSetShader( PS_Star, NULL, NULL );
RenderStars( bgcol );
const oapi::GraphicsClient::LABELLIST *cmlist;
DWORD x = gc->GetCelestialMarkers( &cmlist );
x = x;
RenderCelestialMarkers( VP );
}
void CelSphere::RenderCelestialMarkers( D3DXMATRIX *VP ) {
/* todo */
}
void CelSphere::RenderStars( const D3DXVECTOR3 *bgcol ) {
//nmax = -1;
DWORD j, i, nmax = nsvtx;
const UINT CVertexStride = 16, Offset = 0;
if( bgcol ) {
int bglvl = min( 255, (int)((min( bgcol->x, 1.0f ) + min( bgcol->y, 1.0f ) + min( bgcol->z, 1.0f ))*128.0f));
nmax = min( nmax, (DWORD)lvlid[bglvl] );
}
for( i = j = 0; i < nmax; i += MAXSTARVERTEX, j++ ) {
dCtx->IASetVertexBuffers( 0, 1, &Stars[j], &CVertexStride, &Offset );
dCtx->Draw( min( nmax-i, MAXSTARVERTEX ), 0 );
}
}
void CelSphere::RenderConstellations() {
const UINT CVertexStride = 16, VBOffset = 0;
dCtx->IASetVertexBuffers( 0, 1, &ConstLines, &CVertexStride, &VBOffset );
dCtx->Draw( ncline*2, 0 );
}
void CelSphere::RenderGrid( bool eqline ) {
const UINT CVertexStride = 16, VBOffset = 0;
DWORD j;
dCtx->IASetVertexBuffers( 0, 1, &LngGrid, &CVertexStride, &VBOffset );
for( j = 0; j <= 10; j++ )
if( eqline || j != 5 )
dCtx->Draw( NSEG+1, j*(NSEG+1) );
dCtx->IASetVertexBuffers( 0, 1, &LatGrid, &CVertexStride, &VBOffset );
for( j = 0; j < 12; j++ )
dCtx->Draw( NSEG+1, j*(NSEG+1) );
}
void CelSphere::RenderGreatCircle() {
const UINT CVertexStride = 16, VBOffset = 0;
dCtx->IASetVertexBuffers( 0, 1, &LngGrid, &CVertexStride, &VBOffset );
dCtx->Draw( (NSEG+1), 5*(NSEG+1) );
}
|
97233775e969abc9c2c12ee69f27b34846928a39
|
6d9d0e262b045b1e889e0a45dfc247b067c9dad0
|
/ofxLowLevelEventsExample/src/ofApp.cpp
|
f0ed2d255b4cfca21805c13a9ce17118a3c4f5b7
|
[] |
no_license
|
oxillo/ofxLowLevelEvents
|
32451a3dc33f09becd150184f87a8267dd893bc5
|
a69c7313a76aabd364b9328c9694f6ddd9c32f18
|
refs/heads/master
| 2021-01-09T20:33:03.734617
| 2016-05-28T20:44:53
| 2016-05-28T20:44:53
| 59,914,144
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,273
|
cpp
|
ofApp.cpp
|
#include "ofApp.h"
#include "ofxLowLevelEvents.h"
//--------------------------------------------------------------
void ofApp::setup(){
// Center the window on the screen
screenSize.x = ofGetScreenWidth();
screenSize.y = ofGetScreenHeight();
windowSize.x = ofGetWidth();
windowSize.y = ofGetHeight();
windowCenter = screenSize * 0.5;
ofPoint topLeftCorner = windowCenter - (windowSize * 0.5);
ofSetWindowPosition(topLeftCorner.x, topLeftCorner.y);
ofSetWindowTitle("Cat assistant / Mouse finder");
ofLowLevelEvents().enable();
ofAddListener(ofLowLevelEvents().mouseMoved, this, &ofApp::mouseMovedLL);
//ofBackground(40, 40, 40);
mouseDirection = 0;
//
}
//--------------------------------------------------------------
void ofApp::update(){
// Update the center in update as there is no event for window position
windowCenter.x = ofGetWindowPositionX() + (0.5 * windowSize.x);
windowCenter.y = ofGetWindowPositionY() + (0.5 * windowSize.y);
circleSize = 0.5 * min(windowSize.x, windowSize.y); // Biggest circle that fits in the window
triangleSize = 0.8 * circleSize; // 80% of the circle size
ofVec3f yAxis(0,1,0);
mouseDirection = yAxis.angle(mousePosition - windowCenter);
// angle is unsigned so we set the sign depending on which side of the y-Axis the mouse is
if(mousePosition.x >= windowCenter.x){
mouseDirection = -mouseDirection;
}
// Increase circle resolution for smoother circles
ofSetCircleResolution(50);
}
//--------------------------------------------------------------
void ofApp::draw(){
ofSetColor(255,0,0);
ofFill();
//ofTranslate(240,240,0);
ofTranslate(windowSize * 0.5);
ofDrawCircle(0,0,circleSize);
ofSetColor(100,100,100);
ofDrawCircle(0,0,triangleSize);
ofPushMatrix();
ofRotate(mouseDirection);
ofSetColor(255,0,0);
ofDrawTriangle(-triangleSize * 0.3 , 0, 0, triangleSize, triangleSize * 0.3, 0.0);
ofPopMatrix();
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
void ofApp::mouseMovedLL(ofMouseEventArgs & event){
mousePosition.x = event.x;
mousePosition.y = event.y;
}
void ofApp::windowResized(int w, int h){
windowSize.x = w;
windowSize.y = h;
}
|
bfdfa23459c80d9dfc38274c665f1f0e24d7b535
|
f32e5ba53a1777081c2bb6f041dc07f811c0b35d
|
/silvercreek/Faces.cpp
|
a17916757627a2d7f8dae07c90e4f4f25f1d8b6b
|
[] |
no_license
|
terrymah/silvercreek
|
fd136c677cb5d270b8ea00d0373baecaa9895f01
|
ccc7e96308e5f9fea6f0eb152e22adaf34e683bb
|
refs/heads/master
| 2020-12-31T00:18:08.510139
| 2017-01-15T02:51:49
| 2017-01-15T02:51:49
| 45,081,617
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,035
|
cpp
|
Faces.cpp
|
#include "Faces.h"
FaceDetector::FaceDetector() :
m_source(nullptr),
m_videoHandle(0),
m_active(false)
{
if (!m_cs.load("haarcascade_frontalface_alt.xml"))
throw std::runtime_error("Couldn't load haarcascade_frontalface_alt.xml");
}
FaceDetector::~FaceDetector()
{
if (m_active)
m_task.wait();
}
void FaceDetector::SetVideoSource(VideoSource * source)
{
if (m_source) {
m_source->NewFrame -= m_videoHandle;
m_source = nullptr;
m_videoHandle = 0;
}
if (source) {
m_source = source;
m_videoHandle = m_source->NewFrame += [&](std::shared_ptr<cv::Mat> frame) {
OnNewFrame(frame);
};
}
}
int Face::Score(cv::Rect& rect)
{
int widthDelta = abs(rect.width - m_lastPosition.width);
int heightDelta = abs(rect.height - m_lastPosition.height);
int xDelta = abs(rect.x - m_lastPosition.x);
int yDelta = abs(rect.y - m_lastPosition.y);
int total = widthDelta + heightDelta + xDelta + yDelta;
if (widthDelta > MAX_SIZE_CHANGE)
return 0;
if (heightDelta > MAX_SIZE_CHANGE)
return 0;
if (xDelta > MAX_DIST_CHANGE)
return 0;
if (yDelta > MAX_DIST_CHANGE)
return 0;
// Higher is better
return TOTAL_CHANGE - total;
}
struct ScoreResult
{
int score;
Face* face;
cv::Rect* rect;
};
void FaceDetector::OnNewFrame(std::shared_ptr<cv::Mat> frame)
{
if (m_active && !m_task.is_done())
return;
m_active = true;
m_task = concurrency::create_task([=] {
cv::Mat frame_gray;
cv::cvtColor(*frame, frame_gray, CV_BGR2GRAY);
cv::equalizeHist(frame_gray, frame_gray);
std::vector<cv::Rect> faceRects;
m_cs.detectMultiScale(frame_gray, faceRects, 1.1, 2, CV_HAAR_SCALE_IMAGE, cv::Size(30, 30));
// Time to match
std::lock_guard<std::mutex> lock(m_faceLock);
for (auto& face : m_faces) {
face->matched = false;
}
// Score each rect against each face
std::vector<ScoreResult> scores;
for (auto& rect : faceRects) {
for (auto& face : m_faces) {
int score = face->Score(rect);
if (score) {
scores.push_back({ score, face.get(), &rect });
}
}
}
std::sort(begin(scores), end(scores), [](auto& left, auto& right) {
return left.score > right.score;
});
// For each candidate rect/face, match them up in decending score
for (auto& score : scores) {
if (!score.face->matched && (score.rect->x != score.rect->y)) {
bool update = !score.face->visible || score.face->m_lastPosition != *score.rect;
score.face->matched = true;
score.face->visible = true;
score.face->m_lastPosition = *score.rect;
score.rect->x = score.rect->y; // x == y will be our "matched" flag for the rect
if (update)
UpdatedFace.Fire(score.face);
}
}
// Set any unmatched faces to not visible
for (auto& face : m_faces) {
if (!face->matched && face->visible) {
face->visible = false;
UpdatedFace.Fire(face.get());
}
}
// Create a new face for any unmatched rect
for (auto& rect : faceRects) {
if (rect.x != rect.y) {
Face* f = new Face;
f->matched = true;
f->visible = true;
f->m_lastPosition = rect;
m_faces.push_back(std::unique_ptr<Face>(f));
NewFace.Fire(f);
}
}
});
}
size_t FaceDetector::GetCurrentFaceCount()
{
std::lock_guard<std::mutex> lock(m_faceLock);
return m_faces.size();
}
const Face * FaceDetector::GetFace(int i)
{
std::lock_guard<std::mutex> lock(m_faceLock);
return m_faces[i].get();
}
|
f47cde80f2a98aacf907e4bf6637a8ecd707b27b
|
475897accc433baa4ab4b681b40193fa80276d6f
|
/Assignment-10/p39_temp/Source.cpp
|
6a2b2169c737dd66cb3ad7dcfae2e6902a92c904
|
[] |
no_license
|
DangNguyen146/WeCode
|
aa1a136408df33510a4f3c677bbce629d557048a
|
08f8fbe03f046aa3af29477af81a42a295dde557
|
refs/heads/master
| 2022-11-18T22:15:51.598818
| 2020-07-07T17:32:12
| 2020-07-07T17:32:12
| 277,856,916
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,238
|
cpp
|
Source.cpp
|
#include<iostream>
using namespace std;
struct TNode
{
float Key;
struct TNode* pLeft;
struct TNode* pRight;
};
typedef TNode* Tree;
int insertNode(Tree& T, int x)
{
if (T)
{
if (T->Key > x)
return insertNode(T->pLeft, x);
if(T->Key<x)
return insertNode(T->pRight, x);
}
T = new TNode;
T->Key = x;
T->pLeft = T->pRight = NULL;
return 1;
}
//
//TNode* SearchNode(Tree T, float x)
//{
// if (T != NULL)
// {
// if (T->Key == x)
// return T;
// else
// {
// if (x > T->Key)
// return SearchNode(T->pRight, x);
// else
// return SearchNode(T->pLeft, x);
// }
// }
// return NULL;
//}
void RLN(Tree T)
{
if (T != NULL) {
RLN(T->pRight);
RLN(T->pLeft);
cout << T->Key << " ";
}
}
//TNode* SearchNode(Tree T, int x)
//{
// if (T != NULL)
// {
// if (T->Key == x)
// return T;
// else
// {
// if (x > T->Key)
// return SearchNode(T->pRight, x);
// else
// return SearchNode(T->pLeft, x);
// }
// }
// return NULL;
//}
int main()
{
Tree T = NULL;
//float tb=0;
int n;
while(1)
{
cin >> n;
if (n == 0)
break;
//tb =tb+ temp;
insertNode(T, n);
}
//tb /= 8;
//if (SearchNode(T, tb) != NULL)
// cout << 1;
//else
// cout << 0;
//cout << endl;
RLN(T);
return 0;
}
|
ae821559b77bfe2ce0e3d3119d4fdb21286e2060
|
bef7d0477a5cac485b4b3921a718394d5c2cf700
|
/ic2005/src/demo/wallz/ODEMarshal.h
|
4abf31d7665771218b75193c8ec818b75f4de34e
|
[
"MIT"
] |
permissive
|
TomLeeLive/aras-p-dingus
|
ed91127790a604e0813cd4704acba742d3485400
|
22ef90c2bf01afd53c0b5b045f4dd0b59fe83009
|
refs/heads/master
| 2023-04-19T20:45:14.410448
| 2011-10-04T10:51:13
| 2011-10-04T10:51:13
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,379
|
h
|
ODEMarshal.h
|
#ifndef __ODE_MARSHAL_H
#define __ODE_MARSHAL_H
//
// Data conversion between dingus and ODE
//
#include <ode/ode.h>
#include <dingus/math/Vector3.h>
#include <dingus/math/Matrix4x4.h>
#include <dingus/math/Quaternion.h>
typedef dBodyID TPhysBodyID;
typedef dJointGroupID TPhysJointGroupID;
typedef dJointID TPhysJointID;
typedef dWorldID TPhysWorldID;
typedef dGeomID TCollidableID;
typedef dSpaceID TCollidableContainerID;
namespace odemarshal {
struct SODEVector3 {
dVector3 v;
};
// --------------------------------------------------------------------------
inline void matrixFromMatrix3( const dMatrix3 rot, SMatrix4x4& out )
{
out._11 = float(rot[0]); out._21 = float(rot[1]); out._31 = float(rot[2]);
out._12 = float(rot[4]); out._22 = float(rot[5]); out._32 = float(rot[6]);
out._13 = float(rot[8]); out._23 = float(rot[9]); out._33 = float(rot[10]);
out._41 = 0.0f; out._42 = 0.0f; out._43 = 0.0f;
out._14 = 0.0f; out._24 = 0.0f; out._34 = 0.0f; out._44 = 1.0f;
}
inline void matrixToMatrix3( const SMatrix4x4& mat, dMatrix3 rot )
{
rot[0] = mat._11;
rot[1] = mat._21;
rot[2] = mat._31;
rot[3] = 0;
rot[4] = mat._12;
rot[5] = mat._22;
rot[6] = mat._32;
rot[7] = 0;
rot[8] = mat._13;
rot[9] = mat._23;
rot[10] = mat._33;
rot[11] = 0;
}
// --------------------------------------------------------------------------
inline void quatFromQuat( const dQuaternion src, SQuaternion& dst )
{
// TBD: are you sure?
dst.set( float(src[1]), float(src[2]), float(src[3]), float(src[0]) );
}
inline void quatFromQuat( const SQuaternion& src, dQuaternion dst )
{
// TBD: are you sure?
dst[0] = src.w;
dst[1] = src.x;
dst[2] = src.y;
dst[3] = src.z;
}
// --------------------------------------------------------------------------
inline SVector3 vec3FromVector3( const dVector3 in )
{
return SVector3( float(in[0]), float(in[1]), float(in[2]) );
}
inline void vec3FromVector3( const dVector3 in, SVector3& out )
{
out.set( float(in[0]), float(in[1]), float(in[2]) );
}
inline void vec3ToVector3( const SVector3& in, dVector3 out )
{
out[0] = in.x;
out[1] = in.y;
out[2] = in.z;
}
inline SODEVector3 vec3ToVector3( const SVector3& in )
{
SODEVector3 v;
v.v[0] = in.x;
v.v[1] = in.y;
v.v[2] = in.z;
return v;
}
inline void vec4FromVector4( const dVector4 in, SVector4& out )
{
out.set( float(in[0]), float(in[1]), float(in[2]), float(in[3]) );
}
inline void vec4ToVector4( const SVector4& in, dVector4 out )
{
out[0] = in.x;
out[1] = in.y;
out[2] = in.z;
out[3] = in.w;
}
// --------------------------------------------------------------------------
inline SVector3 vec3FromPtr( const dReal* in )
{
return SVector3( float(in[0]), float(in[1]), float(in[2]) );
}
inline void vec3FromPtr( const dReal* in, SVector3& out )
{
out.set( float(in[0]), float(in[1]), float(in[2]) );
}
inline SQuaternion quatFromPtr( const dReal* in )
{
const dQuaternion& quat = *(const dQuaternion*)in;
SQuaternion out;
odemarshal::quatFromQuat( quat, out );
return out;
}
inline void quatFromPtr( const dReal* in, SQuaternion& out )
{
const dQuaternion& quat = *(const dQuaternion*)in;
odemarshal::quatFromQuat( quat, out );
}
}; // namespace odemarshal
#endif
|
83dbb50211f95bcd8a3aa7735650d90c5dcf48e3
|
a2135aba714109fe1e85633cd8e8e5e1f38b350a
|
/Test 3/Inherit/main.cpp
|
c82ff063a67bc24dfcf2a1aceb735cdd499b5853
|
[
"MIT"
] |
permissive
|
RPG-NJU/NJU-AdvancedProgramming
|
b353a8a83102fbcd39126abb48a7510c9f9edd8c
|
6e680a384cac2b8a2404a1d9e6ab21ffe3c48877
|
refs/heads/master
| 2021-09-28T20:28:36.501102
| 2018-11-20T08:04:35
| 2018-11-20T08:04:35
| 154,761,388
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 297
|
cpp
|
main.cpp
|
#include "Body.h"
#include "Cylinder.h"
#include "ThreePrism.h"
#include "Cone.h"
int main()
{
Cylinder test1(4.0, 5.0);
test1.getArea();
test1.getVolume();
test1.printHeight();
Cylinder test2(4.0, 3.75);
test2.getArea();
test2.getVolume();
test2.printHeight();
return 0;
}
|
bdafcc1fb3d70746acabbb427994bc3ca5e89e2d
|
4829d700aef14cb58d588f93ad1f46e93b32becc
|
/AVulkan.cpp
|
e94a5e582c50e4e2a18a5fd302ff4f52e1eee449
|
[] |
no_license
|
Garciaj007/AVulkan
|
465938ab1af010c6fa8af9904465f4c72b0f02e3
|
2bc317f958bb10538d2b52cb90cbe1456a0aba31
|
refs/heads/main
| 2023-01-22T13:38:43.108152
| 2020-11-16T18:00:26
| 2020-11-16T18:00:26
| 313,385,314
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 39,262
|
cpp
|
AVulkan.cpp
|
#include <SDL.h>
#include <SDL_vulkan.h>
#include <vulkan/vulkan.h>
#include <optional>
#include <vector>
#include <string>
#include <iostream>
#include <sstream>
#include <fstream>
#include <set>
#include <assert.h>
// Global Settings
const char APPNAME[] = "VulkanDemo";
const char ENGINENAME[] = "VulkanDemoEngine";
int WIDTH = 1280;
int HEIGHT = 720;
VkPresentModeKHR vkPresentMode = VK_PRESENT_MODE_FIFO_RELAXED_KHR;
VkSurfaceTransformFlagBitsKHR vkTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
VkFormat vkFormat = VK_FORMAT_B8G8R8A8_SRGB;
VkColorSpaceKHR vkColorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
VkImageUsageFlags vkImageUsageFlags = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
const int MAX_FRAMES_IN_FLIGHT = 2;
#define STRINGIFY( name ) #name
#define Print(...) { printf(__VA_ARGS__); printf("\n"); }
template<typename T>
T clamp(T value, T min, T max)
{
return value < min ? min : value > max ? max : value;
}
struct QueueFamilyIndices
{
std::optional<uint32_t> graphicsFamily;
std::optional<uint32_t> presentFamily;
bool isComplete() { return graphicsFamily.has_value() && presentFamily.has_value(); }
};
struct SwapChainSupportDetails
{
VkSurfaceCapabilitiesKHR capabilities;
std::vector<VkSurfaceFormatKHR> formats;
std::vector<VkPresentModeKHR> presentModes;
};
std::string StringifyVulkanVersion(uint32_t version)
{
if (version > VK_API_VERSION_1_2) return STRINGIFY(VK_VERSION_1_2);
if (version > VK_API_VERSION_1_1) return STRINGIFY(VK_VERSION_1_1);
if (version > VK_API_VERSION_1_0) return STRINGIFY(VK_VERSION_1_0);
return "VK_VERSION_UNKNOWN";
}
// Vulkan Debug Report Callback
VKAPI_ATTR VkBool32 VKAPI_CALL VulkanDebugReportCallback(VkDebugReportFlagsEXT flags, VkDebugReportObjectTypeEXT type,
uint64_t obj, size_t location, int32_t code, const char* layer,
const char* message, void* userParam)
{
if (flags >= VK_DEBUG_REPORT_ERROR_BIT_EXT)
Print("Vulkan DBG Report: %s - %s", layer, message)
else if (flags >= VK_DEBUG_REPORT_WARNING_BIT_EXT)
Print("Vulkan DBG Report: %s - %s", layer, message)
else
Print("Vulkan DBG Report: %s - %s", layer, message)
return VK_FALSE;
}
// Vulkan Debug Utils Messenger
VKAPI_ATTR VkBool32 VKAPI_CALL VulkanDebugUtilsMessager(VkDebugUtilsMessageSeverityFlagBitsEXT messageSeverity,
VkDebugUtilsMessageTypeFlagsEXT messageType,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData, void* pUserData)
{
if (messageSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT)
Print("Vulkan DBG Msg: %s", pCallbackData->pMessage)
else if (messageSeverity >= VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT)
Print("Vulkan DBG Msg: %s", pCallbackData->pMessage)
else
Print("Vulkan DBG Msg: %s", pCallbackData->pMessage)
return VK_FALSE;
}
VkResult _vkCreateDebugReportCallbackEXT(VkInstance instance, const VkDebugReportCallbackCreateInfoEXT* createInfo, const VkAllocationCallbacks* allocator, VkDebugReportCallbackEXT* callback)
{
auto func = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
if (func)
return func(instance, createInfo, allocator, callback);
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
void _vkDestroyDebugReportCallbackEXT(VkInstance instance, VkDebugReportCallbackEXT callback, const VkAllocationCallbacks* allocator)
{
auto func = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
if (func) func(instance, callback, allocator);
}
VkResult _vkCreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* createInfo, const VkAllocationCallbacks* allocator, VkDebugUtilsMessengerEXT* messenger) {
auto func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func)
return func(instance, createInfo, allocator, messenger);
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
void _vkDestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT messenger, const VkAllocationCallbacks* allocator) {
auto func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func) func(instance, messenger, allocator);
}
void GetAndCheckVulkanAPISupport(uint32_t& version) {
VkResult result = vkEnumerateInstanceVersion(&version);
if (result != VK_SUCCESS)
throw std::exception("Vulkan: API Not Supported");
}
void GetVulkanExtensions(SDL_Window* window, std::vector<const char*>& extensions)
{
extensions.clear();
uint32_t extensionCount;
SDL_Vulkan_GetInstanceExtensions(window, &extensionCount, nullptr);
extensions.resize(extensionCount);
SDL_Vulkan_GetInstanceExtensions(window, &extensionCount, extensions.data());
Print("Vulkan: Found %i Available Extensions", extensionCount);
for (const auto& extension : extensions) Print("Extension: %s", extension);
#if defined(RAD_DEBUG) || defined(RAD_OPTIMIZED)
extensions.emplace_back(VK_EXT_DEBUG_REPORT_EXTENSION_NAME);
extensions.emplace_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
#endif
}
void GetVulkanLayerSupport(std::vector<std::string>& enabledLayers)
{
std::vector<std::string> requestedLayers;
requestedLayers.push_back("VK_LAYER_KHRONOS_validation");
enabledLayers.clear();
if (requestedLayers.empty()) return;
uint32_t layerCount;
vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
std::vector<VkLayerProperties> availableLayers(layerCount);
vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
Print("Vulkan: Found %i Available Validation Layers", layerCount);
for (const auto& availableLayer : availableLayers)
{
Print("Vulkan - Layer: %s - %s", availableLayer.layerName, availableLayer.description);
if (std::find(requestedLayers.begin(), requestedLayers.end(), availableLayer.layerName) != requestedLayers.end())
enabledLayers.emplace_back(availableLayer.layerName);
}
for (const auto& layer : enabledLayers)
Print("Vulkan - Enabling Layer: %s", layer.c_str());
if (enabledLayers.size() != requestedLayers.size())
Print("Vulkan: Could not find all validation layers.");
}
void CreateVulkanInstance(VkInstance& instance, const uint32_t& apiVersion, const std::vector<const char*>& extensions, const std::vector<const char*>& layers)
{
VkApplicationInfo appInfo{ VK_STRUCTURE_TYPE_APPLICATION_INFO };
appInfo.pApplicationName = APPNAME;
appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.pEngineName = ENGINENAME;
appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0);
appInfo.apiVersion = apiVersion;
VkInstanceCreateInfo createInfo{ VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO };
createInfo.pApplicationInfo = &appInfo;
createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
createInfo.ppEnabledExtensionNames = extensions.data();
createInfo.enabledLayerCount = static_cast<uint32_t>(layers.size());
createInfo.ppEnabledLayerNames = layers.data();
VkResult result = vkCreateInstance(&createInfo, nullptr, &instance);
if (result != VK_SUCCESS)
{
std::string message = "Vulkan: Failed to create instance : ";
switch (result)
{
case VK_ERROR_INCOMPATIBLE_DRIVER: message += STRINGIFY(VK_ERROR_INCOMPATIBLE_DRIVER);
break;
case VK_ERROR_LAYER_NOT_PRESENT: message += STRINGIFY(VK_ERROR_LAYER_NOT_PRESENT);
break;
case VK_ERROR_EXTENSION_NOT_PRESENT: message += STRINGIFY(VK_ERROR_EXTENSION_NOT_PRESENT);
break;
default: message += STRINGIFY(VK_ERROR_UNKNOWN);
break;
}
throw std::exception(message.c_str());
}
std::stringstream ss;
ss << "Loaded Vulkan: " << StringifyVulkanVersion(apiVersion);
Print(ss.str().c_str());
}
void SetupVulkanDebugMessengerCallback(const VkInstance& instance, VkDebugUtilsMessengerEXT& debugMessenger)
{
// Debug Utils Message Callback
VkDebugUtilsMessengerCreateInfoEXT utilsMessangerInfo = { VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT };
utilsMessangerInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
utilsMessangerInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
utilsMessangerInfo.pfnUserCallback = VulkanDebugUtilsMessager;
if (_vkCreateDebugUtilsMessengerEXT(instance, &utilsMessangerInfo, nullptr, &debugMessenger) != VK_SUCCESS)
Print("Vulkan: Unable to create debug utils messenger extension");
}
QueueFamilyIndices GetVulkanQueueFamilies(const VkPhysicalDevice& device, const VkSurfaceKHR& surface)
{
QueueFamilyIndices indices;
uint32_t familyQueueCount;
vkGetPhysicalDeviceQueueFamilyProperties(device, &familyQueueCount, nullptr);
std::vector<VkQueueFamilyProperties> queueFamilyProps(familyQueueCount);
vkGetPhysicalDeviceQueueFamilyProperties(device, &familyQueueCount, queueFamilyProps.data());
// Make sure the family of commands contains an option to issue graphical commands.
for (uint32_t i = 0; i < familyQueueCount; i++)
{
if (queueFamilyProps[i].queueCount > 0 && queueFamilyProps[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
indices.graphicsFamily = i;
VkBool32 presentSupport;
vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
if (presentSupport)
indices.presentFamily = i;
if (indices.isComplete())
break;
}
return indices;
}
bool IsVulkanDeviceCompatible(const VkPhysicalDevice& device, const VkSurfaceKHR& surface)
{
QueueFamilyIndices indices = GetVulkanQueueFamilies(device, surface);
return indices.isComplete();
}
void GetVulkanPhysicalDevice(const VkInstance& instance, const VkSurfaceKHR& surface, VkPhysicalDevice& outDevice)
{
uint32_t physicalDeviceCount;
vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, nullptr);
if (physicalDeviceCount == 0)
throw std::exception("Vulkan: No Physical Device (GPU) Found.");
std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
vkEnumeratePhysicalDevices(instance, &physicalDeviceCount, physicalDevices.data());
Print("Vulkan: Found %i Physical Devices", physicalDeviceCount);
for (const auto& physicalDevice : physicalDevices)
{
VkPhysicalDeviceProperties deviceProps;
vkGetPhysicalDeviceProperties(physicalDevice, &deviceProps);
Print("Vulkan - Physical Device: %s", deviceProps.deviceName);
}
for (const auto& physicalDevice : physicalDevices)
{
if (IsVulkanDeviceCompatible(physicalDevice, surface))
{
outDevice = physicalDevice; break;
}
}
if (outDevice == VK_NULL_HANDLE)
throw std::exception("Vulkan: Unable to fin a compatible GPU");
}
void CreateVulkanLogicalDevice(VkPhysicalDevice& physicalDevice, const VkSurfaceKHR& surface, const std::vector<const char*>& layers, VkDevice& outLogicalDevice, VkQueue& outGraphicsQueue, VkQueue& outPresentQueue)
{
QueueFamilyIndices indices = GetVulkanQueueFamilies(physicalDevice, surface);
// Create queue information structure used by device based on the previously fetched queue information from the physical device
// We create one command processing queue for graphics
std::vector<float> queuePriority = { 1.0f };
std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
uint32_t devicePropertiesCount;
if (vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &devicePropertiesCount, nullptr) != VK_SUCCESS)
throw std::exception("Vulkan: Unable to acquire device extension property count");
Print("Vulkan: Found %i Device extension properties", devicePropertiesCount);
std::vector<VkExtensionProperties> deviceProperties(devicePropertiesCount);
if (vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &devicePropertiesCount, deviceProperties.data()) != VK_SUCCESS)
throw std::exception("Vulkan: Unable to acquire device extension properties");
std::vector<const char*> devicePropertiesNames;
std::set<std::string> requestedExtensions{ VK_KHR_SWAPCHAIN_EXTENSION_NAME };
for (const auto& extensionProperty : deviceProperties)
{
auto it = requestedExtensions.find(std::string(extensionProperty.extensionName));
if (it != requestedExtensions.end())
devicePropertiesNames.emplace_back(extensionProperty.extensionName);
}
if (requestedExtensions.size() != devicePropertiesNames.size())
Print("Vulkan: Could not find all validation layers.");
for (const auto& devicePropertyName : devicePropertiesNames)
Print("Vulkan - Enabling Device Extension Property: %s", devicePropertyName);
for (uint32_t queueFamily : uniqueQueueFamilies)
{
VkDeviceQueueCreateInfo queueCreateInfo{ VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO };
queueCreateInfo.queueFamilyIndex = queueFamily;
queueCreateInfo.queueCount = 1;
queueCreateInfo.pQueuePriorities = queuePriority.data();
queueCreateInfos.push_back(queueCreateInfo);
}
// Device creation information
VkDeviceCreateInfo deviceCreateInfo{ VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO };
deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
deviceCreateInfo.pQueueCreateInfos = queueCreateInfos.data();
deviceCreateInfo.ppEnabledLayerNames = layers.data();
deviceCreateInfo.enabledLayerCount = static_cast<uint32_t>(layers.size());
deviceCreateInfo.ppEnabledExtensionNames = devicePropertiesNames.data();
deviceCreateInfo.enabledExtensionCount = static_cast<uint32_t>(devicePropertiesNames.size());
if (vkCreateDevice(physicalDevice, &deviceCreateInfo, nullptr, &outLogicalDevice) != VK_SUCCESS)
throw std::exception("Vulkan: Failed To create logical device");
vkGetDeviceQueue(outLogicalDevice, indices.graphicsFamily.value(), 0, &outGraphicsQueue);
vkGetDeviceQueue(outLogicalDevice, indices.presentFamily.value(), 0, &outPresentQueue);
}
void CreateVulkanSurface(SDL_Window* window, VkInstance instance, VkSurfaceKHR& outSurface)
{
if (!SDL_Vulkan_CreateSurface(window, instance, &outSurface))
{
std::string temp("Vulkan: Failed To create surface. \nReason: ");
temp.append(SDL_GetError());
throw std::exception(temp.c_str());
}
}
void GetVulkanPresentationMode(const VkSurfaceKHR& surface, const VkPhysicalDevice& physicalDevice, VkPresentModeKHR& outMode)
{
uint32_t modeCount;
if (vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &modeCount, nullptr) != VK_SUCCESS)
throw std::exception("Vulkan: Unable to query present mode count from physical device.");
std::vector<VkPresentModeKHR> availableModes(modeCount);
if (vkGetPhysicalDeviceSurfacePresentModesKHR(physicalDevice, surface, &modeCount, availableModes.data()) != VK_SUCCESS)
throw std::exception("Vulkan: Unable to query present modes from physical device.");
for (const auto& mode : availableModes)
if (mode == outMode)
return;
Print("Vulkan: unable to use perfered display mode, Falling back to FIFO");
outMode = VK_PRESENT_MODE_FIFO_KHR;
}
void GetVulkanImageFormat(const VkPhysicalDevice& device, const VkSurfaceKHR& surface, VkSurfaceFormatKHR& outFormat)
{
uint32_t count;
if (vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &count, nullptr) != VK_SUCCESS)
throw std::exception("Vulkan: Failed to get Physical Device Surface Formats Count");
std::vector<VkSurfaceFormatKHR> foundFormats(count);
if (vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &count, foundFormats.data()) != VK_SUCCESS)
throw std::exception("Vulkan: Failed to get Physical Devices Surface Formats");
if (foundFormats.size() == 1 && foundFormats[0].format == VK_FORMAT_UNDEFINED)
{
outFormat.format = VK_FORMAT_B8G8R8A8_SRGB;
outFormat.colorSpace = VK_COLOR_SPACE_SRGB_NONLINEAR_KHR;
return;
}
for (const auto& outerFormat : foundFormats)
{
if (outerFormat.format == VK_FORMAT_B8G8R8A8_SRGB)
{
outFormat.format = outerFormat.format;
for (const auto& innerFormat : foundFormats)
{
if (innerFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR)
{
outFormat.colorSpace = innerFormat.colorSpace;
return;
}
}
Print("Vulkan: No matching color space found, picking first available one!");
outFormat.colorSpace = foundFormats[0].colorSpace;
return;
}
}
Print("Vulkan: no matching color format found, picking first available one!");
outFormat = foundFormats[0];
}
void CreateVulkanSwapchain(const VkSurfaceKHR& surface, const VkPhysicalDevice& physicalDevice, const VkDevice& device, VkSwapchainKHR& outSwapchain, VkSurfaceFormatKHR& outSurfaceFormat, VkExtent2D& outExtent)
{
VkSurfaceCapabilitiesKHR surfaceCapabilities;
if (vkGetPhysicalDeviceSurfaceCapabilitiesKHR(physicalDevice, surface, &surfaceCapabilities) != VK_SUCCESS)
throw std::exception("Vulkan: Unable to acquire surface capabilities");
VkPresentModeKHR presentMode = VK_PRESENT_MODE_FIFO_RELAXED_KHR;
GetVulkanPresentationMode(surface, physicalDevice, presentMode);
uint32_t swapImageCount = surfaceCapabilities.minImageCount + 1 > surfaceCapabilities.maxImageCount ? surfaceCapabilities.minImageCount : surfaceCapabilities.minImageCount + 1;
VkExtent2D size = { WIDTH, HEIGHT };
if (surfaceCapabilities.currentExtent.width == 0xFFFFFFF)
{
size.width = clamp<uint32_t>(size.width, surfaceCapabilities.minImageExtent.width, surfaceCapabilities.maxImageExtent.width);
size.height = clamp<uint32_t>(size.height, surfaceCapabilities.minImageExtent.height, surfaceCapabilities.maxImageExtent.height);
}
else
size = surfaceCapabilities.currentExtent;
VkImageUsageFlags usageFlags;
std::vector<VkImageUsageFlags> requestedUsages{ VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT };
assert(requestedUsages.size() > 0);
usageFlags = requestedUsages[0];
for (const auto& requestedUsage : requestedUsages)
{
VkImageUsageFlags imageUsage = requestedUsage & surfaceCapabilities.supportedUsageFlags;
if (imageUsage != requestedUsage)
throw std::exception("Vulkan: unsupported image usage flag:" + requestedUsage);
usageFlags |= requestedUsage;
}
VkSurfaceTransformFlagBitsKHR transform;
if (surfaceCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
transform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
else
{
Print("Vulkan: unsupported surface transform: %s", STRINGIFY(VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR));
transform = surfaceCapabilities.currentTransform;
}
VkSurfaceFormatKHR imageFormat;
GetVulkanImageFormat(physicalDevice, surface, imageFormat);
VkSwapchainKHR oldSwapchain = outSwapchain;
VkSwapchainCreateInfoKHR swapInfo{ VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR };
swapInfo.surface = surface;
swapInfo.minImageCount = swapImageCount;
swapInfo.imageFormat = imageFormat.format;
swapInfo.imageColorSpace = imageFormat.colorSpace;
swapInfo.imageExtent = size;
swapInfo.imageArrayLayers = 1;
swapInfo.imageUsage = usageFlags;
swapInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapInfo.queueFamilyIndexCount = 0;
swapInfo.pQueueFamilyIndices = nullptr;
swapInfo.preTransform = transform;
swapInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapInfo.presentMode = presentMode;
swapInfo.clipped = true;
swapInfo.oldSwapchain = nullptr;
if (oldSwapchain != VK_NULL_HANDLE)
{
vkDestroySwapchainKHR(device, oldSwapchain, nullptr);
oldSwapchain = VK_NULL_HANDLE;
}
if (vkCreateSwapchainKHR(device, &swapInfo, nullptr, &oldSwapchain) != VK_SUCCESS)
throw std::exception("Vulkan: Failed to create Swapchain");
outSwapchain = oldSwapchain;
outSurfaceFormat = imageFormat;
outExtent = size;
}
void GetVulkanSwapchainImageHandles(const VkDevice& device, const VkSwapchainKHR& chain, std::vector<VkImage>& outImageHandles)
{
uint32_t imageCount;
if (vkGetSwapchainImagesKHR(device, chain, &imageCount, nullptr) != VK_SUCCESS)
throw std::runtime_error("Vulkan: Failed to get Swapchain Images Count");
outImageHandles.clear();
outImageHandles.resize(imageCount);
if (vkGetSwapchainImagesKHR(device, chain, &imageCount, outImageHandles.data()) != VK_SUCCESS)
throw std::runtime_error("Vulkan: Failed to get Swapchain Images");
}
void CreateVulkanImageViews(const VkDevice& device, const VkSurfaceFormatKHR& swapchainFormat, const std::vector<VkImage>& swapchainImages, std::vector<VkImageView>& outSwapchainImageViews)
{
outSwapchainImageViews.clear();
outSwapchainImageViews.resize(swapchainImages.size());
for (size_t i = 0; i < swapchainImages.size(); i++)
{
VkImageViewCreateInfo createInfo{ VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO };
createInfo.image = swapchainImages[i];
createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
createInfo.format = swapchainFormat.format;
createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
createInfo.subresourceRange.baseMipLevel = 0;
createInfo.subresourceRange.levelCount = 1;
createInfo.subresourceRange.baseArrayLayer = 0;
createInfo.subresourceRange.layerCount = 1;
if (vkCreateImageView(device, &createInfo, nullptr, &outSwapchainImageViews[i]) != VK_SUCCESS) {
throw std::runtime_error("failed to create image views!");
}
}
}
VkShaderModule CreateVulkanShaderModule(const VkDevice& device, const std::vector<char>& code)
{
VkShaderModuleCreateInfo createInfo{ VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO };
createInfo.codeSize = code.size();
createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
VkShaderModule shaderModule;
if(vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS)
throw std::runtime_error("failed to create shader module!");
return shaderModule;
}
std::vector<char> ReadFile(const std::string& path)
{
std::ifstream file(path, std::ios::ate | std::ios::binary);
if (!file.is_open())
throw std::runtime_error("Failed to Open File!");
auto fileSize = (size_t) file.tellg();
std::vector<char> buffer(fileSize);
file.seekg(0);
file.read(buffer.data(),fileSize);
file.close();
return buffer;
}
void CreateVulkanGraphicsPipeline(const VkDevice& device, const VkExtent2D& swapchainExtent, const VkRenderPass& renderPass, VkPipelineLayout& outPipelineLayout, VkPipeline& outGraphicsPipeline)
{
auto vertShaderCode = ReadFile("Shaders/SPIR-V/vert.spv");
auto fragShaderCode = ReadFile("Shaders/SPIR-V/frag.spv");
auto vertShaderModule = CreateVulkanShaderModule(device, vertShaderCode);
auto fragShaderModule = CreateVulkanShaderModule(device, fragShaderCode);
VkPipelineShaderStageCreateInfo vertShaderStageInfo{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertShaderModule;
vertShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo fragShaderStageInfo{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO };
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragShaderModule;
fragShaderStageInfo.pName = "main";
VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
vertexInputInfo.vertexBindingDescriptionCount = 0;
vertexInputInfo.vertexAttributeDescriptionCount = 0;
VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
inputAssembly.primitiveRestartEnable = VK_FALSE;
VkViewport viewport{};
viewport.x = 0.0f;
viewport.y = 0.0f;
viewport.width = (float)swapchainExtent.width;
viewport.height = (float)swapchainExtent.height;
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor{};
scissor.offset = { 0, 0 };
scissor.extent = swapchainExtent;
VkPipelineViewportStateCreateInfo viewportState{};
viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
VkPipelineRasterizationStateCreateInfo rasterizer{};
rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
rasterizer.depthClampEnable = VK_FALSE;
rasterizer.rasterizerDiscardEnable = VK_FALSE;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
rasterizer.depthBiasEnable = VK_FALSE;
VkPipelineMultisampleStateCreateInfo multisampling{};
multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
multisampling.sampleShadingEnable = VK_FALSE;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
VkPipelineColorBlendAttachmentState colorBlendAttachment{};
colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = VK_FALSE;
VkPipelineColorBlendStateCreateInfo colorBlending{};
colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
colorBlending.logicOpEnable = VK_FALSE;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = 1;
colorBlending.pAttachments = &colorBlendAttachment;
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
pipelineLayoutInfo.setLayoutCount = 0;
pipelineLayoutInfo.pushConstantRangeCount = 0;
if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &outPipelineLayout) != VK_SUCCESS)
throw std::runtime_error("failed to create pipeline layout!");
VkGraphicsPipelineCreateInfo pipelineInfo{};
pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
pipelineInfo.stageCount = 2;
pipelineInfo.pStages = shaderStages;
pipelineInfo.pVertexInputState = &vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.layout = outPipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &outGraphicsPipeline) != VK_SUCCESS)
throw std::runtime_error("failed to create graphics pipeline!");
vkDestroyShaderModule(device, fragShaderModule, nullptr);
vkDestroyShaderModule(device, vertShaderModule, nullptr);
}
void CreateVulkanRenderPass(const VkDevice& device, const VkSurfaceFormatKHR& swapchainFormat, VkRenderPass& outRenderPass) {
VkAttachmentDescription colorAttachment{};
colorAttachment.format = swapchainFormat.format;
colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
VkAttachmentReference colorAttachmentRef{};
colorAttachmentRef.attachment = 0;
colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass{};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &colorAttachmentRef;
VkRenderPassCreateInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
renderPassInfo.attachmentCount = 1;
renderPassInfo.pAttachments = &colorAttachment;
renderPassInfo.subpassCount = 1;
renderPassInfo.pSubpasses = &subpass;
if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &outRenderPass) != VK_SUCCESS) {
throw std::runtime_error("failed to create render pass!");
}
}
void CreateVulkanFramebuffers(const VkDevice& device, const VkExtent2D& extents, const VkRenderPass& renderPass, const std::vector<VkImageView>& swapchainImageViews, std::vector<VkFramebuffer>& outSwapchainFramebuffers) {
outSwapchainFramebuffers.clear();
outSwapchainFramebuffers.resize(swapchainImageViews.size());
for (size_t i = 0; i < swapchainImageViews.size(); i++) {
VkImageView attachments[] = {
swapchainImageViews[i]
};
VkFramebufferCreateInfo framebufferInfo{};
framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
framebufferInfo.renderPass = renderPass;
framebufferInfo.attachmentCount = 1;
framebufferInfo.pAttachments = attachments;
framebufferInfo.width = extents.width;
framebufferInfo.height = extents.height;
framebufferInfo.layers = 1;
if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &outSwapchainFramebuffers[i]) != VK_SUCCESS) {
throw std::runtime_error("failed to create framebuffer!");
}
}
}
void CreateVulkanCommandPool(const VkPhysicalDevice& physicalDevice, const VkDevice& device, const VkSurfaceKHR& surface, VkCommandPool& outCmdPool) {
QueueFamilyIndices queueFamilyIndices = GetVulkanQueueFamilies(physicalDevice, surface);
VkCommandPoolCreateInfo poolInfo{};
poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
if (vkCreateCommandPool(device, &poolInfo, nullptr, &outCmdPool) != VK_SUCCESS)
throw std::runtime_error("failed to create command pool!");
}
void CreateVulkanCommandBuffers(const VkDevice& device, const VkCommandPool& cmdPool, const VkRenderPass& renderPass, const VkPipeline& gfxPipeline, const VkExtent2D extents, const std::vector<VkFramebuffer>& framebuffers, std::vector<VkCommandBuffer>& outCmdBuffers) {
outCmdBuffers.clear();
outCmdBuffers.resize(framebuffers.size());
VkCommandBufferAllocateInfo allocInfo{ VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO };
allocInfo.commandPool = cmdPool;
allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
allocInfo.commandBufferCount = (uint32_t)outCmdBuffers.size();
if (vkAllocateCommandBuffers(device, &allocInfo, outCmdBuffers.data()) != VK_SUCCESS)
throw std::runtime_error("failed to allocate command buffers!");
for (size_t i = 0; i < outCmdBuffers.size(); i++) {
VkCommandBufferBeginInfo beginInfo{};
beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
if (vkBeginCommandBuffer(outCmdBuffers[i], &beginInfo) != VK_SUCCESS)
throw std::runtime_error("failed to begin recording command buffer!");
VkRenderPassBeginInfo renderPassInfo{};
renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
renderPassInfo.renderPass = renderPass;
renderPassInfo.framebuffer = framebuffers[i];
renderPassInfo.renderArea.offset = { 0, 0 };
renderPassInfo.renderArea.extent = extents;
VkClearValue clearColor = { 0.0f, 0.0f, 0.0f, 1.0f };
renderPassInfo.clearValueCount = 1;
renderPassInfo.pClearValues = &clearColor;
vkCmdBeginRenderPass(outCmdBuffers[i], &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(outCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, gfxPipeline);
vkCmdDraw(outCmdBuffers[i], 3, 1, 0, 0);
vkCmdEndRenderPass(outCmdBuffers[i]);
if (vkEndCommandBuffer(outCmdBuffers[i]) != VK_SUCCESS)
throw std::runtime_error("failed to record command buffer!");
}
}
void CreateVulkanSyncObjects(const VkDevice& device, const std::vector<VkImage>& swapChainImages, std::vector<VkSemaphore>& outImageReadySemaphores, std::vector<VkSemaphore>& outRenderFinishedSemaphores, std::vector<VkFence>& outFlightFences, std::vector<VkFence>& outImagesInFlight)
{
outImageReadySemaphores.clear();
outRenderFinishedSemaphores.clear();
outFlightFences.clear();
outImagesInFlight.clear();
outImageReadySemaphores.resize(MAX_FRAMES_IN_FLIGHT);
outRenderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
outFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
outImagesInFlight.resize(swapChainImages.size(), VK_NULL_HANDLE);
VkSemaphoreCreateInfo semaphoreInfo{ VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO };
VkFenceCreateInfo fenceInfo{ VK_STRUCTURE_TYPE_FENCE_CREATE_INFO };
fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &outImageReadySemaphores[i]) != VK_SUCCESS ||
vkCreateSemaphore(device, &semaphoreInfo, nullptr, &outRenderFinishedSemaphores[i]) != VK_SUCCESS ||
vkCreateFence(device, &fenceInfo, nullptr, &outFlightFences[i]) != VK_SUCCESS)
throw std::runtime_error("failed to create synchronization objects for a frame!");
}
}
int main(int argc, char* args[])
{
// Local Variables
uint32_t apiVersion;
bool isRunning = true;
std::vector<const char*> extensions{};
std::vector<std::string> enabledLayers{};
std::vector<const char*> layers;
VkInstance vkInstance = VK_NULL_HANDLE;
VkDebugUtilsMessengerEXT vkDebugMessenger = VK_NULL_HANDLE;
VkSurfaceKHR surface = VK_NULL_HANDLE;
VkPhysicalDevice vkPhysicalDevice = VK_NULL_HANDLE;
VkDevice vkDevice = VK_NULL_HANDLE;
VkQueue vkGraphicsQueue, vkPresentQueue;
VkSwapchainKHR vkSwapchain = VK_NULL_HANDLE;
VkSurfaceFormatKHR vkSurfaceFormat;
VkExtent2D vkExtent;
VkRenderPass vkRenderPass = VK_NULL_HANDLE;
VkPipelineLayout vkPipelineLayout = VK_NULL_HANDLE;
VkPipeline vkPipeline = VK_NULL_HANDLE;
VkCommandPool vkCommandPool = VK_NULL_HANDLE;
std::vector<VkImage> vkChainImages;
std::vector<VkImageView> vkChainImageViews;
std::vector<VkFramebuffer> vkChainFramebuffers;
std::vector<VkCommandBuffer> vkCommandBuffers;
std::vector<VkSemaphore> vkImageAvailableSemaphores;
std::vector<VkSemaphore> vkRenderFinishedSemaphores;
std::vector<VkFence> vkInFlightFences;
std::vector<VkFence> vkImagesInFlight;
size_t currentFrame = 0;
// =============================================================
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS);
auto* sdlWindow = SDL_CreateWindow("Hello Vulkan", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_VULKAN);
try {
GetAndCheckVulkanAPISupport(apiVersion);
GetVulkanExtensions(sdlWindow, extensions);
GetVulkanLayerSupport(enabledLayers);
for (const auto& layer : enabledLayers)
layers.emplace_back(layer.c_str());
CreateVulkanInstance(vkInstance, apiVersion, extensions, layers);
SetupVulkanDebugMessengerCallback(vkInstance, vkDebugMessenger);
CreateVulkanSurface(sdlWindow, vkInstance, surface);
GetVulkanPhysicalDevice(vkInstance, surface, vkPhysicalDevice);
CreateVulkanLogicalDevice(vkPhysicalDevice, surface, layers, vkDevice, vkGraphicsQueue, vkPresentQueue);
CreateVulkanSwapchain(surface, vkPhysicalDevice, vkDevice, vkSwapchain, vkSurfaceFormat, vkExtent);
GetVulkanSwapchainImageHandles(vkDevice, vkSwapchain, vkChainImages);
CreateVulkanImageViews(vkDevice, vkSurfaceFormat, vkChainImages, vkChainImageViews);
CreateVulkanRenderPass(vkDevice, vkSurfaceFormat, vkRenderPass);
CreateVulkanGraphicsPipeline(vkDevice, vkExtent, vkRenderPass, vkPipelineLayout, vkPipeline);
CreateVulkanFramebuffers(vkDevice, vkExtent, vkRenderPass, vkChainImageViews, vkChainFramebuffers);
CreateVulkanCommandPool(vkPhysicalDevice, vkDevice, surface, vkCommandPool);
CreateVulkanCommandBuffers(vkDevice, vkCommandPool, vkRenderPass, vkPipeline, vkExtent, vkChainFramebuffers, vkCommandBuffers);
CreateVulkanSyncObjects(vkDevice, vkChainImages, vkImageAvailableSemaphores, vkRenderFinishedSemaphores, vkInFlightFences, vkImagesInFlight);
while (isRunning)
{
// Handle Events
SDL_Event e;
SDL_PollEvent(&e);
switch (e.type)
{
case SDL_QUIT: isRunning = false;
break;
default: break;
}
// Drawing Code
vkWaitForFences(vkDevice, 1, &vkInFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
uint32_t imageIndex;
vkAcquireNextImageKHR(vkDevice, vkSwapchain, UINT64_MAX, vkImageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
if (vkImagesInFlight[imageIndex] != VK_NULL_HANDLE) {
vkWaitForFences(vkDevice, 1, &vkImagesInFlight[imageIndex], VK_TRUE, UINT64_MAX);
}
vkImagesInFlight[imageIndex] = vkInFlightFences[currentFrame];
VkSubmitInfo submitInfo{};
submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
VkSemaphore waitSemaphores[] = { vkImageAvailableSemaphores[currentFrame] };
VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
submitInfo.waitSemaphoreCount = 1;
submitInfo.pWaitSemaphores = waitSemaphores;
submitInfo.pWaitDstStageMask = waitStages;
submitInfo.commandBufferCount = 1;
submitInfo.pCommandBuffers = &vkCommandBuffers[imageIndex];
VkSemaphore signalSemaphores[] = { vkRenderFinishedSemaphores[currentFrame] };
submitInfo.signalSemaphoreCount = 1;
submitInfo.pSignalSemaphores = signalSemaphores;
vkResetFences(vkDevice, 1, &vkInFlightFences[currentFrame]);
if (vkQueueSubmit(vkGraphicsQueue, 1, &submitInfo, vkInFlightFences[currentFrame]) != VK_SUCCESS) {
throw std::runtime_error("failed to submit draw command buffer!");
}
VkPresentInfoKHR presentInfo{};
presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
presentInfo.waitSemaphoreCount = 1;
presentInfo.pWaitSemaphores = signalSemaphores;
VkSwapchainKHR swapChains[] = { vkSwapchain };
presentInfo.swapchainCount = 1;
presentInfo.pSwapchains = swapChains;
presentInfo.pImageIndices = &imageIndex;
vkQueuePresentKHR(vkPresentQueue, &presentInfo);
currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
}
}
catch (std::exception e)
{
SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Exception Thrown", e.what(), nullptr);
}
for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
{
vkDestroySemaphore(vkDevice, vkRenderFinishedSemaphores[i], nullptr);
vkDestroySemaphore(vkDevice, vkImageAvailableSemaphores[i], nullptr);
vkDestroyFence(vkDevice, vkInFlightFences[i], nullptr);
}
vkDestroyCommandPool(vkDevice, vkCommandPool, nullptr);
for (auto framebuffer : vkChainFramebuffers)
vkDestroyFramebuffer(vkDevice, framebuffer, nullptr);
vkDestroyPipeline(vkDevice, vkPipeline, nullptr);
vkDestroyPipelineLayout(vkDevice, vkPipelineLayout, nullptr);
vkDestroyRenderPass(vkDevice, vkRenderPass, nullptr);
for (auto imageView : vkChainImageViews)
vkDestroyImageView(vkDevice, imageView, nullptr);
vkDestroySwapchainKHR(vkDevice, vkSwapchain, nullptr);
vkDestroyDevice(vkDevice, nullptr);
vkDestroySurfaceKHR(vkInstance, surface, nullptr);
_vkDestroyDebugUtilsMessengerEXT(vkInstance, vkDebugMessenger, nullptr);
vkDestroyInstance(vkInstance, nullptr);
return 0;
}
|
019736ed1f8f7cca12aabe047ca060329788ae51
|
297497957c531d81ba286bc91253fbbb78b4d8be
|
/third_party/libwebrtc/third_party/abseil-cpp/absl/debugging/internal/demangle.h
|
cf60f72f1d7faac421df4f04a51952650147c0b2
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] |
permissive
|
marco-c/gecko-dev-comments-removed
|
7a9dd34045b07e6b22f0c636c0a836b9e639f9d3
|
61942784fb157763e65608e5a29b3729b0aa66fa
|
refs/heads/master
| 2023-08-09T18:55:25.895853
| 2023-08-01T00:40:39
| 2023-08-01T00:40:39
| 211,297,481
| 0
| 0
|
NOASSERTION
| 2019-09-29T01:27:49
| 2019-09-27T10:44:24
|
C++
|
UTF-8
|
C++
| false
| false
| 344
|
h
|
demangle.h
|
#ifndef ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_
#define ABSL_DEBUGGING_INTERNAL_DEMANGLE_H_
#include "absl/base/config.h"
namespace absl {
ABSL_NAMESPACE_BEGIN
namespace debugging_internal {
bool Demangle(const char *mangled, char *out, int out_size);
}
ABSL_NAMESPACE_END
}
#endif
|
6db7a0f9b656997bf71e4fb42660babb46efb7c7
|
29396c66f6aae81537b25c3b9e8d22ec2fbd57a8
|
/Documentation/Software/RobotX-Simulation/vmrc_ws/src/vmrc/robotx_gazebo/src/light_buoy_controller.cc
|
13497ffa06ae9bb99a32e4fd2af933f110c5f7bc
|
[] |
no_license
|
riplaboratory/Kanaloa
|
49cbbafb7235e5d185bb4522c4deca8a3fd2c087
|
36650e2daff733a55c6546ffb0ff083b57c8c1b8
|
refs/heads/master
| 2022-12-11T03:00:30.284107
| 2021-12-10T07:57:00
| 2021-12-10T07:57:00
| 121,706,694
| 11
| 14
| null | 2022-12-09T16:56:36
| 2018-02-16T02:11:52
|
Jupyter Notebook
|
UTF-8
|
C++
| false
| false
| 4,717
|
cc
|
light_buoy_controller.cc
|
/*
* Copyright (C) 2018 Open Source Robotics Foundation
*
* 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 <ignition/math/Rand.hh>
#include "robotx_gazebo/light_buoy_controller.hh"
const std::array<LightBuoyController::Colors_t, 5> LightBuoyController::kColors
= {LightBuoyController::Colors_t(CreateColor(1.0, 0.0, 0.0, 1.0), "RED"),
LightBuoyController::Colors_t(CreateColor(0.0, 1.0, 0.0, 1.0), "GREEN"),
LightBuoyController::Colors_t(CreateColor(0.0, 0.0, 1.0, 1.0), "BLUE"),
LightBuoyController::Colors_t(CreateColor(1.0, 1.0, 0.0, 1.0), "YELLOW"),
LightBuoyController::Colors_t(CreateColor(0.0, 0.0, 0.0, 1.0), "OFF")};
//////////////////////////////////////////////////
std_msgs::ColorRGBA LightBuoyController::CreateColor(const double _r,
const double _g, const double _b, const double _a)
{
static std_msgs::ColorRGBA color;
color.r = _r;
color.g = _g;
color.b = _b;
color.a = _a;
return color;
}
//////////////////////////////////////////////////
void LightBuoyController::Load(gazebo::physics::ModelPtr _parent,
sdf::ElementPtr _sdf)
{
GZ_ASSERT(_parent != nullptr, "Received NULL model pointer");
// Quit if ros plugin was not loaded
if (!ros::isInitialized())
{
ROS_ERROR("ROS was not initialized.");
return;
}
std::string ns = "";
if (_sdf->HasElement("robotNamespace"))
ns = _sdf->GetElement("robotNamespace")->Get<std::string>();
else
{
ROS_INFO_NAMED("light_bouy_controller",
"missing <robotNamespace>, defaulting to %s", ns.c_str());
}
this->nh = ros::NodeHandle(ns);
// Create publisher to set color on each panel
this->panelPubs[0] = this->nh.advertise<std_msgs::ColorRGBA>("panel1", 1u);
this->panelPubs[1] = this->nh.advertise<std_msgs::ColorRGBA>("panel2", 1u);
this->panelPubs[2] = this->nh.advertise<std_msgs::ColorRGBA>("panel3", 1u);
// Generate random initial pattern
std::string initial;
this->ChangePattern(initial);
this->changePatternServer = this->nh.advertiseService(
"new_pattern", &LightBuoyController::ChangePattern, this);
this->timer = this->nh.createTimer(
ros::Duration(1.0), &LightBuoyController::IncrementState, this);
}
//////////////////////////////////////////////////
void LightBuoyController::IncrementState(const ros::TimerEvent &/*_event*/)
{
std::lock_guard<std::mutex> lock(this->mutex);
// Start over if at end of pattern
if (this->state > 3)
this->state = 0;
auto msg = this->kColors[this->pattern[this->state]].first;
// Publish current color to each panel
for (size_t i = 0; i < 3; ++i)
this->panelPubs[i].publish(msg);
// Increment index for next timer callback
++this->state;
}
//////////////////////////////////////////////////
bool LightBuoyController::ChangePattern(std_srvs::Trigger::Request &_req,
std_srvs::Trigger::Response &_res)
{
this->ChangePattern(_res.message);
_res.message = "New pattern: " + _res.message;
_res.success = true;
return _res.success;
}
//////////////////////////////////////////////////
void LightBuoyController::ChangePattern(std::string &_message)
{
Pattern_t newPattern;
// Last phase in pattern is always off
newPattern[3] = 4;
// Loop until random pattern is different from current one
do {
// Generate random sequence of 3 colors among RED, GREEN, BLUE, and YELLOW
for (size_t i = 0; i < 3; ++i)
newPattern[i] = ignition::math::Rand::IntUniform(0, 3);
// Ensure there is no CONSECUTIVE repeats
while (newPattern[0] == newPattern[1] || newPattern[1] == newPattern[2])
newPattern[1] = ignition::math::Rand::IntUniform(0, 3);
} while (newPattern == this->pattern);
std::lock_guard<std::mutex> lock(this->mutex);
// Copy newly generated pattern to pattern
this->pattern = newPattern;
// Start in OFF state so pattern restarts at beginning
this->state = 3;
// Generate string representing pattern, ex: "RGB"
for (size_t i = 0; i < 3; ++i)
_message += this->kColors[newPattern[i]].second[0];
// Log the new pattern
ROS_INFO_NAMED("light_bouy_controller", "Pattern is %s", _message.c_str());
}
// Register plugin with gazebo
GZ_REGISTER_MODEL_PLUGIN(LightBuoyController)
|
22d4796218a25dc84bf9337ec2d0f32695ef12b0
|
972623e5589ecdbe899090a8478623eec8ff8574
|
/JuCssUI/CssControl.h
|
f657877f2baa633806584dfe05519cfedcb599a9
|
[
"Apache-2.0"
] |
permissive
|
yangshaoguang/jucpp
|
65068a1b4b2d253e0d2a1c45c2aaee7b25d094cf
|
46c40369af6d5d5688b48335d0d6be75d872c03a
|
refs/heads/master
| 2020-07-17T10:38:39.345633
| 2016-06-16T05:39:40
| 2016-06-16T05:39:40
| 206,003,818
| 0
| 1
|
Apache-2.0
| 2019-09-03T06:23:20
| 2019-09-03T06:23:20
| null |
GB18030
|
C++
| false
| false
| 842
|
h
|
CssControl.h
|
#pragma once
namespace ju {
struct BorderParam : public _struct {
int Width,Style,Radius;
Color Color;
BorderParam() {
::ZeroMemory(this, sizeof(this));
}
};
struct Border : public _struct {
BorderParam Left, Top, Right, Bottom;
};
struct TextParam {
String Text,FontName;
int Style,FontStyle,FontSize;
TextParam():Style(0),FontStyle(0),FontSize(12){
}
};
class CssControl : public _class {
protected:
Color color,background;
Border border;
Rect rect,padding;
TextParam text;
void onDraw(ju::DC* dc, ju::View*);
public:
Delegate<Mouse*, IWnd*> OnMouse; //MouseEvent处理所有鼠标消息.
Delegate<Twin16, IWnd*> OnSize; //WM_SIZE消息,参数是客户区的大小。
Delegate<IWnd*> OnClick;
CssControl();
void Resize(int cx,int cy);
void Redraw(ju::DC* dc, ju::View*);
};
}
|
deb6bb8d758519230e869eb263e87b0261175ff7
|
7244a83f759e0bd8eb24d2a487d908d4220d9154
|
/10369 - Arctic Network.cpp
|
91a1c3ae3edb098cdb68b6f920e590c3c8a8c46f
|
[] |
no_license
|
SeyfertCode/SeyfertUvaCode
|
c92a435be637dc5e1d4bba01865acb2f43c9e95a
|
d8b44e30881a7847216053b20b8a2c5274439a7a
|
refs/heads/master
| 2021-01-18T22:35:13.562131
| 2016-04-22T15:57:06
| 2016-04-22T15:57:06
| 23,531,556
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 986
|
cpp
|
10369 - Arctic Network.cpp
|
#include<bits/stdc++.h>
#define MAX 505
using namespace std;
vector<int>v(MAX);
int find(int x){
return x==v[x]? x:find(v[x]);
}
void Union(int a, int b){
v[find(a)] = find(b);
}
struct Edge{
int x;
int y;
double d;
};
bool cmp(Edge a, Edge b){
return a.d<b.d;
}
int main(){
int c,s;
int N;
cin>>N;
while(N--){
while(cin>>c>>s){
for(int i=0;i<s;++i)v[i] = i;
vector<Edge> paths;
Edge aux;
vector<int>vx(s),vy(s);
for(int i = 0;i<s;++i)cin>>vx[i]>>vy[i];
for(int i = 0;i<s-1;++i){
for(int j = i+1;j<s;++j){
aux.x = i;
aux.y = j;
aux.d = sqrt((vx[i]-vx[j])*(vx[i]-vx[j]) + (vy[i]-vy[j])*(vy[i]-vy[j]));
paths.push_back(aux);
}
}
sort(paths.begin(),paths.end(),cmp);
vector<Edge>MST;
for(int i = 0;(int)MST.size()<s-1;++i){
if(find(paths[i].x)!=find(paths[i].y)){
Union(paths[i].x,paths[i].y);
MST.push_back(paths[i]);
}
}
printf("%.2f\n",MST[s-c-1].d);
}
}
return 0;
}
|
f45285b60a25dafb1190d0e7fea48d0b42881b2e
|
8cd51b4885680c073566f16236cd68d3f4296399
|
/skins/fluent2/QskFluent2Skin.cpp
|
1b90f73288c8ddc8f2fdae442af762c52459deab
|
[
"BSD-3-Clause"
] |
permissive
|
uwerat/qskinny
|
0e0c6552afa020382bfa08453a5636b19ae8ff49
|
bf2c2b981e3a6ea1187826645da4fab75723222c
|
refs/heads/master
| 2023-08-21T16:27:56.371179
| 2023-08-10T17:54:06
| 2023-08-10T17:54:06
| 97,966,439
| 1,074
| 226
|
BSD-3-Clause
| 2023-08-10T17:12:01
| 2017-07-21T16:16:18
|
C++
|
UTF-8
|
C++
| false
| false
| 66,072
|
cpp
|
QskFluent2Skin.cpp
|
/******************************************************************************
* QSkinny - Copyright (C) 2023 Edelhirsch Software GmbH
* SPDX-License-Identifier: BSD-3-Clause
*****************************************************************************/
/*
Definitions ( where possible ) taken from
https://www.figma.com/file/NAWMapFlXnoOb86Q2H5GKr/Windows-UI-(Community)
*/
/*
TODO:
- we have a lot of lines with 1 pixels. Unfortunately OpenGL does some sort
of antialiasing, when a line is not a pixel position. On screens with high
resolution usually no probem, but f.e on mine ...
- QskCheckBox::Error is not properly supported
- Pressed state is missing
- QskComboBox
- QskPageIndicator
- Hovered state is missing
- QskPageIndicator
- QskListView
- Indicator subcontrol might be better than using the border of the selection box
- cell padding unclear
- using qskDpToPixels ?
*/
/*
The palette is made of a specific configurable colors and
predefined semitransparent shades of gray. Both need to
be resolved to opaque colors with the base colors of the sections.
Resolving the colors can be done in 2 ways:
- render time
This actually means, that we do not create opaque colors and
create the scene graph nodes with semitransparent colors.
- definition time
We create opaque colors for the base colors of the sections
and set them as skin hints.
Resolving at render time sounds like the right solution as we
background colors set in application code will just work.
Unfortunately we have 2 different sets of grays for light/dark
base colors and when applications are setting a light color, where a
dark color ( or v.v ) is expected we might end up with unacceptable
results: ( white on light or black on dark ).
So there are pros and cons and we do not have a final opinion
about waht to do. For the moment we implement resolving at definition
time as an option to be able to play with both solutions.
*/
#include "QskFluent2Skin.h"
#include "QskFluent2Theme.h"
#include <QskSkinHintTableEditor.h>
#include <QskBox.h>
#include <QskCheckBox.h>
#include <QskComboBox.h>
#include <QskDialogButtonBox.h>
#include <QskDrawer.h>
#include <QskFocusIndicator.h>
#include <QskGraphicLabel.h>
#include <QskListView.h>
#include <QskMenu.h>
#include <QskPageIndicator.h>
#include <QskPushButton.h>
#include <QskProgressBar.h>
#include <QskProgressRing.h>
#include <QskRadioBox.h>
#include <QskScrollView.h>
#include <QskSegmentedBar.h>
#include <QskSeparator.h>
#include <QskShadowMetrics.h>
#include <QskSlider.h>
#include <QskSpinBox.h>
#include <QskStandardSymbol.h>
#include <QskSubWindow.h>
#include <QskSwitchButton.h>
#include <QskSwitchButtonSkinlet.h>
#include <QskTabBar.h>
#include <QskTabButton.h>
#include <QskTabView.h>
#include <QskTextInput.h>
#include <QskTextLabel.h>
#include <QskVirtualKeyboard.h>
#include <QskAnimationHint.h>
#include <QskAspect.h>
#include <QskBoxBorderColors.h>
#include <QskBoxBorderMetrics.h>
#include <QskBoxShapeMetrics.h>
#include <QskColorFilter.h>
#include <QskFunctions.h>
#include <QskGraphic.h>
#include <QskGraphicIO.h>
#include <QskMargins.h>
#include <QskRgbValue.h>
#include <QskNamespace.h>
#include <QskPlatform.h>
#include <QGuiApplication>
#include <QScreen>
namespace
{
inline QFont createFont( const QString& name, qreal lineHeight,
qreal size, qreal tracking, QFont::Weight weight )
{
QFont font( name, qRound( size ) );
font.setPixelSize( qRound( lineHeight ) );
if( !qskFuzzyCompare( tracking, 0.0 ) )
font.setLetterSpacing( QFont::AbsoluteSpacing, tracking );
font.setWeight( weight );
return font;
}
inline constexpr QRgb rgbGray( int value, qreal opacity = 1.0 )
{
return qRgba( value, value, value, qRound( opacity * 255 ) );
}
inline constexpr QRgb rgbFlattened( QRgb foreground, QRgb background )
{
//Q_ASSERT( qAlpha( background ) == 255 );
const auto r2 = qAlpha( foreground ) / 255.0;
const auto r1 = 1.0 - r2;
const auto r = qRound( r1 * qRed( background ) + r2 * qRed( foreground ) );
const auto g = qRound( r1 * qGreen( background ) + r2 * qGreen( foreground ) );
const auto b = qRound( r1 * qBlue( background ) + r2 * qBlue( foreground ) );
return qRgb( r, g, b );
}
inline constexpr QRgb rgbSolid( QRgb foreground, QRgb background )
{
/*
dummy method, so that we can compare the results with
or without resolving the foreground alpha value
*/
#if 0
return rgbFlattened( foreground, background );
#else
//Q_ASSERT( qAlpha( background ) == 255 );
Q_UNUSED( background );
return foreground;
#endif
}
class Editor : private QskSkinHintTableEditor
{
public:
Editor( QskSkinHintTable* table )
: QskSkinHintTableEditor( table )
{
}
void setupMetrics();
void setupColors( QskAspect::Section, const QskFluent2Theme& );
private:
void setupPopup( const QskFluent2Theme& );
void setupSubWindow( const QskFluent2Theme& );
void setupBoxMetrics();
void setupBoxColors( QskAspect::Section, const QskFluent2Theme& );
void setupCheckBoxMetrics();
void setupCheckBoxColors( QskAspect::Section, const QskFluent2Theme& );
void setupComboBoxMetrics();
void setupComboBoxColors( QskAspect::Section, const QskFluent2Theme& );
void setupDialogButtonBoxMetrics();
void setupDialogButtonBoxColors( QskAspect::Section, const QskFluent2Theme& );
void setupDrawerMetrics();
void setupDrawerColors( QskAspect::Section, const QskFluent2Theme& );
void setupFocusIndicatorMetrics();
void setupFocusIndicatorColors( QskAspect::Section, const QskFluent2Theme& );
void setupGraphicLabelMetrics();
void setupGraphicLabelColors( QskAspect::Section, const QskFluent2Theme& );
void setupListViewMetrics();
void setupListViewColors( QskAspect::Section, const QskFluent2Theme& );
void setupMenuMetrics();
void setupMenuColors( QskAspect::Section, const QskFluent2Theme& );
void setupPageIndicatorMetrics();
void setupPageIndicatorColors( QskAspect::Section, const QskFluent2Theme& );
void setupProgressBarMetrics();
void setupProgressBarColors( QskAspect::Section, const QskFluent2Theme& );
void setupProgressRingMetrics();
void setupProgressRingColors( QskAspect::Section, const QskFluent2Theme& );
void setupPushButtonMetrics();
void setupPushButtonColors( QskAspect::Section, const QskFluent2Theme& );
void setupRadioBoxMetrics();
void setupRadioBoxColors( QskAspect::Section, const QskFluent2Theme& );
void setupScrollViewMetrics();
void setupScrollViewColors( QskAspect::Section, const QskFluent2Theme& );
void setupSegmentedBarMetrics();
void setupSegmentedBarColors( QskAspect::Section, const QskFluent2Theme& );
void setupSeparatorMetrics();
void setupSeparatorColors( QskAspect::Section, const QskFluent2Theme& );
void setupSliderMetrics();
void setupSliderColors( QskAspect::Section, const QskFluent2Theme& );
void setupSpinBoxMetrics();
void setupSpinBoxColors( QskAspect::Section, const QskFluent2Theme& );
void setupSwitchButtonMetrics();
void setupSwitchButtonColors( QskAspect::Section, const QskFluent2Theme& );
void setupTabButtonMetrics();
void setupTabButtonColors( QskAspect::Section, const QskFluent2Theme& );
void setupTabBarMetrics();
void setupTabBarColors( QskAspect::Section, const QskFluent2Theme& );
void setupTabViewMetrics();
void setupTabViewColors( QskAspect::Section, const QskFluent2Theme& );
void setupTextInputMetrics();
void setupTextInputColors( QskAspect::Section, const QskFluent2Theme& );
void setupTextLabelMetrics();
void setupTextLabelColors( QskAspect::Section, const QskFluent2Theme& );
void setupVirtualKeyboardMetrics();
void setupVirtualKeyboardColors( QskAspect::Section, const QskFluent2Theme& );
inline QskGraphic symbol( const char* name ) const
{
const QString path = QStringLiteral( ":fluent2/icons/qvg/" )
+ name + QStringLiteral( ".qvg" );
return QskGraphicIO::read( path );
}
inline void setBoxBorderGradient( QskAspect aspect,
QRgb border1, QRgb border2, QRgb baseColor )
{
border1 = rgbFlattened( border1, baseColor );
border2 = rgbFlattened( border2, baseColor );
setBoxBorderColors( aspect, { border1, border1, border1, border2 } );
}
inline void setBoxBorderGradient( QskAspect aspect,
const QskFluent2Theme::BorderGradient& gradient, QRgb baseColor )
{
setBoxBorderGradient( aspect, gradient[ 0 ], gradient[ 1 ], baseColor );
}
};
}
void Editor::setupMetrics()
{
setupBoxMetrics();
setupCheckBoxMetrics();
setupComboBoxMetrics();
setupDialogButtonBoxMetrics();
setupDrawerMetrics();
setupFocusIndicatorMetrics();
setupGraphicLabelMetrics();
setupListViewMetrics();
setupMenuMetrics();
setupPageIndicatorMetrics();
setupProgressBarMetrics();
setupProgressRingMetrics();
setupPushButtonMetrics();
setupRadioBoxMetrics();
setupScrollViewMetrics();
setupSegmentedBarMetrics();
setupSeparatorMetrics();
setupSliderMetrics();
setupSpinBoxMetrics();
setupSwitchButtonMetrics();
setupTabButtonMetrics();
setupTabBarMetrics();
setupTabViewMetrics();
setupTextInputMetrics();
setupTextLabelMetrics();
setupVirtualKeyboardMetrics();
}
void Editor::setupColors( QskAspect::Section section, const QskFluent2Theme& theme )
{
if ( section == QskAspect::Body )
{
// TODO
setupPopup( theme );
setupSubWindow( theme );
}
setupBoxColors( section, theme );
setupCheckBoxColors( section, theme );
setupComboBoxColors( section, theme );
setupDialogButtonBoxColors( section, theme );
setupDrawerColors( section, theme );
setupFocusIndicatorColors( section, theme );
setupGraphicLabelColors( section, theme );
setupGraphicLabelMetrics();
setupListViewColors( section, theme );
setupMenuColors( section, theme );
setupPageIndicatorColors( section, theme );
setupProgressBarColors( section, theme );
setupProgressRingColors( section, theme );
setupPushButtonColors( section, theme );
setupRadioBoxColors( section, theme );
setupScrollViewColors( section, theme );
setupSegmentedBarColors( section, theme );
setupSeparatorColors( section, theme );
setupSliderColors( section, theme );
setupSwitchButtonColors( section, theme );
setupSpinBoxColors( section, theme );
setupTabButtonColors( section, theme );
setupTabBarColors( section, theme );
setupTabViewColors( section, theme );
setupTextInputColors( section, theme );
setupTextLabelColors( section, theme );
setupVirtualKeyboardColors( section, theme );
};
void Editor::setupBoxMetrics()
{
}
void Editor::setupBoxColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
setGradient( QskBox::Panel | section,
theme.palette.background.solid.base );
}
void Editor::setupCheckBoxMetrics()
{
using Q = QskCheckBox;
setStrutSize( Q::Panel, 126, 38 );
setSpacing( Q::Panel, 8 );
setStrutSize( Q::Box, { 20, 20 } ); // 18 + 2*1 border
setBoxShape( Q::Box, 4 ); // adapt to us taking the border into account
setBoxBorderMetrics( Q::Box, 1 );
setPadding( Q::Box, 5 ); // "icon size"
setFontRole( Q::Text, QskFluent2Skin::Body );
}
void Editor::setupCheckBoxColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskCheckBox;
using A = QskAspect;
const auto& pal = theme.palette;
const auto checkMark = symbol( "checkmark" );
for ( const auto state1 : { A::NoState, Q::Hovered, Q::Pressed, Q::Disabled } )
{
QRgb fillColor, borderColor, textColor;
for ( const auto state2 : { A::NoState, Q::Checked } )
{
const auto states = state1 | state2;
if ( states == A::NoState )
{
fillColor = pal.fillColor.controlAlt.secondary;
borderColor = pal.strokeColor.controlStrong.defaultColor;
textColor = pal.fillColor.text.primary;
}
else if ( states == Q::Hovered )
{
fillColor = pal.fillColor.controlAlt.tertiary;
borderColor = pal.strokeColor.controlStrong.defaultColor;
textColor = pal.fillColor.text.primary;
}
else if ( states == ( Q::Hovered | Q::Checked ) )
{
fillColor = pal.fillColor.accent.secondary;
borderColor = fillColor;
textColor = pal.fillColor.text.primary;
}
else if ( states == Q::Checked )
{
fillColor = pal.fillColor.accent.defaultColor;
borderColor = pal.fillColor.accent.defaultColor;
textColor = pal.fillColor.text.primary;
}
else if ( states == Q::Pressed )
{
fillColor = pal.fillColor.controlAlt.quaternary;
borderColor = pal.strokeColor.controlStrong.disabled;
textColor = pal.fillColor.text.primary;
}
else if ( states == ( Q::Pressed | Q::Checked ) )
{
fillColor = pal.fillColor.accent.tertiary;
borderColor = pal.fillColor.accent.tertiary;
textColor = pal.fillColor.text.primary;
setSymbol( Q::Indicator | states, checkMark );
}
else if ( states == Q::Disabled )
{
fillColor = pal.fillColor.controlAlt.disabled;
borderColor = pal.strokeColor.controlStrong.disabled;
textColor = pal.fillColor.text.disabled;
}
else if ( states == ( Q::Disabled | Q::Checked ) )
{
fillColor = pal.fillColor.accent.disabled;
borderColor = pal.fillColor.accent.disabled;
textColor = pal.fillColor.text.disabled;
}
/*
Support for QskCheckBox::Error is not properly defined.
Doing some basic definitions, so that we can at least
see the boxes with this state. TODO ...
*/
for ( const auto state3 : { A::NoState, Q::Error } )
{
const auto box = Q::Box | section | states | state3;
const auto text = Q::Text | section | states | state3;
const auto indicator = Q::Indicator | section | states | state3;
#if 1
if ( state3 == Q::Error && !( states & Q::Disabled ) )
{
borderColor = QskRgb::IndianRed;
if ( states & Q::Checked )
fillColor = QskRgb::DarkRed;
}
#endif
fillColor = rgbSolid( fillColor, pal.background.solid.base );
setGradient( box, fillColor );
borderColor = rgbSolid( borderColor, fillColor );
setBoxBorderColors( box, borderColor );
setColor( text, textColor );
if ( states & Q::Checked )
{
setGraphicRole( indicator, ( states & Q::Disabled )
? QskFluent2Skin::GraphicRoleFillColorTextOnAccentDisabled
: QskFluent2Skin::GraphicRoleFillColorTextOnAccentPrimary );
setSymbol( indicator, checkMark );
}
}
}
}
}
void Editor::setupComboBoxMetrics()
{
using Q = QskComboBox;
setStrutSize( Q::Panel, { -1, 32 } );
setBoxBorderMetrics( Q::Panel, 1 );
setBoxShape( Q::Panel, 3 );
setPadding( Q::Panel, { 11, 0, 11, 0 } );
setStrutSize( Q::Icon, 12, 12 );
setPadding( Q::Icon, { 0, 0, 8, 0 } );
setAlignment( Q::Text, Qt::AlignLeft | Qt::AlignVCenter );
setFontRole( Q::Text, QskFluent2Skin::Body );
setStrutSize( Q::StatusIndicator, 12, 12 );
setSymbol( Q::StatusIndicator, symbol( "spin-box-arrow-down" ) );
setSymbol( Q::StatusIndicator | Q::PopupOpen, symbol( "spin-box-arrow-up" ) );
// Using Focused (Pressed doesn't exist yet):
setBoxBorderMetrics( Q::Panel | Q::Focused, { 1, 1, 1, 2 } );
}
void Editor::setupComboBoxColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskComboBox;
using W = QskFluent2Skin;
const auto& pal = theme.palette;
for ( const auto state : { QskAspect::NoState, Q::Hovered, Q::Focused, Q::Pressed, Q::Disabled } )
{
QRgb panelColor, borderColor1, borderColor2, textColor;
if ( state == QskAspect::NoState )
{
panelColor = pal.fillColor.control.defaultColor;
borderColor1 = pal.elevation.control.border[0];
borderColor2 = pal.elevation.control.border[1];
textColor = pal.fillColor.text.primary;
}
else if ( state == Q::Hovered )
{
panelColor = pal.fillColor.control.secondary;
borderColor1 = pal.elevation.textControl.border[0];
borderColor2 = pal.elevation.textControl.border[1];
textColor = pal.fillColor.text.primary;
}
else if ( state == Q::Focused )
{
panelColor = pal.fillColor.control.inputActive;
borderColor1 = pal.elevation.textControl.border[0];
borderColor2 = pal.fillColor.accent.defaultColor;
textColor = pal.fillColor.text.primary;
}
else if ( state == Q::Pressed )
{
panelColor = pal.fillColor.control.inputActive;
borderColor1 = pal.elevation.textControl.border[0];
borderColor2 = pal.fillColor.accent.defaultColor;
textColor = pal.fillColor.text.secondary;
}
else if ( state == Q::Disabled )
{
panelColor = pal.fillColor.control.disabled;
borderColor2 = borderColor1 = pal.strokeColor.control.defaultColor;
textColor = pal.fillColor.text.disabled;
}
const auto panel = Q::Panel | section | state;
const auto text = Q::Text | section | state;
const auto icon = Q::Icon | section | state;
const auto indicator = Q::StatusIndicator | section | state;
panelColor = rgbSolid( panelColor, pal.background.solid.base );
setGradient( panel, panelColor );
setBoxBorderGradient( panel, borderColor1, borderColor2, panelColor );
setColor( text, textColor );
if ( state == Q::Disabled )
{
setGraphicRole( icon, W::GraphicRoleFillColorTextDisabled );
setGraphicRole( indicator, W::GraphicRoleFillColorTextDisabled );
}
else if( state == Q::Pressed )
{
setGraphicRole( icon, W::GraphicRoleFillColorTextSecondary );
setGraphicRole( indicator, W::GraphicRoleFillColorTextSecondary );
}
else
{
setGraphicRole( icon, W::GraphicRoleFillColorTextPrimary );
setGraphicRole( indicator, W::GraphicRoleFillColorTextSecondary );
}
}
}
void Editor::setupDialogButtonBoxMetrics()
{
setPadding( QskDialogButtonBox::Panel, 20 );
}
void Editor::setupDialogButtonBoxColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
setGradient( QskDialogButtonBox::Panel | section,
theme.palette.background.solid.base );
}
void Editor::setupDrawerMetrics()
{
using Q = QskDrawer;
setPadding( Q::Panel, 5 );
setHint( Q::Overlay | QskAspect::Style, false );
#if 1
setAnimation( Q::Panel | QskAspect::Position, 200 );
#endif
}
void Editor::setupDrawerColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskDrawer;
setGradient( Q::Panel | section, theme.palette.background.solid.base );
}
void Editor::setupFocusIndicatorMetrics()
{
using Q = QskFocusIndicator;
setBoxBorderMetrics( Q::Panel, 2 );
setPadding( Q::Panel, 3 );
setBoxShape( Q::Panel, 4 );
}
void Editor::setupFocusIndicatorColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskFocusIndicator;
const auto& pal = theme.palette;
setBoxBorderColors( Q::Panel | section, pal.strokeColor.focus.outer );
}
void Editor::setupListViewMetrics()
{
using Q = QskListView;
using A = QskAspect;
for ( auto state : { A::NoState, Q::Hovered, Q::Pressed } )
setBoxBorderMetrics( Q::Cell | state | Q::Selected, { 3, 0, 0, 0 } );
#if 1
// taken from M3 - what are the actual values, TODO ...
setPadding( Q::Cell, { 16, 12, 16, 12 } );
#endif
}
void Editor::setupListViewColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskListView;
using A = QskAspect;
const auto& pal = theme.palette;
for ( const auto state1 : { A::NoState, Q::Hovered, Q::Pressed, Q::Disabled } )
{
QRgb textColor, indicatorColor;
if ( state1 == Q::Disabled )
{
textColor = pal.fillColor.text.disabled;
indicatorColor = pal.fillColor.accent.disabled;
}
else if ( state1 == Q::Pressed )
{
textColor = pal.fillColor.text.secondary;
indicatorColor = pal.fillColor.accent.defaultColor;
}
else
{
textColor = pal.fillColor.text.primary;
indicatorColor = pal.fillColor.accent.defaultColor;
}
for ( const auto state2 : { A::NoState, Q::Selected } )
{
QRgb cellColor;
if ( state2 == A::NoState )
{
if ( state1 == Q::Hovered )
cellColor = pal.fillColor.subtle.secondary;
else if ( state1 == Q::Pressed )
cellColor = pal.fillColor.subtle.tertiary;
else
cellColor = Qt::transparent;
}
else
{
if ( state1 == Q::Hovered )
cellColor = pal.fillColor.subtle.tertiary;
else
cellColor = pal.fillColor.subtle.secondary;
}
const auto cell = Q::Cell | section | state1 | state2;
const auto text = Q::Text | section | state1 | state2;
setGradient( cell, cellColor );
{
/*
We are using a section of the left border to display a
bar indicating the selection. Maybe we should introduce a
subcontrol instead TODO ...
*/
const auto c1 = cellColor;
const auto c2 = indicatorColor;
const auto p1 = ( state1 == Q::Pressed ) ? 0.33 : 0.25;
const auto p2 = 1.0 - p1;
setBoxBorderColors( cell,
QskGradient( { { p1, c1 }, { p1, c2 }, { p2, c2 }, { p2, c1 } } ) );
}
setColor( text, textColor );
}
}
setAnimation( Q::Cell | A::Color, 100 );
setAnimation( Q::Text | A::Color, 100 );
}
void Editor::setupMenuMetrics()
{
using Q = QskMenu;
setPadding( Q::Panel, { 4, 6, 4, 6 } );
setBoxBorderMetrics( Q::Panel, 1 );
setBoxShape( Q::Panel, 7 );
setPadding( Q::Segment, { 0, 10, 10, 10 } );
setSpacing( Q::Segment, 15 );
setBoxBorderMetrics( Q::Segment | Q::Selected, { 3, 0, 0, 0 } );
setFontRole( Q::Text, QskFluent2Skin::Body );
setStrutSize( Q::Icon, 12, 12 );
setPadding( Q::Icon, { 8, 8, 0, 8 } );
}
void Editor::setupMenuColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
Q_UNUSED( section );
using Q = QskMenu;
#if 1
setShadowMetrics( Q::Panel, theme.shadow.flyout.metrics );
#endif
const auto& pal = theme.palette;
setBoxBorderColors( Q::Panel, pal.strokeColor.surface.flyout );
setGradient( Q::Panel, pal.background.flyout.defaultColor );
setShadowColor( Q::Panel, theme.shadow.flyout.color );
setGradient( Q::Segment | Q::Hovered, pal.fillColor.subtle.secondary );
setGradient( Q::Segment | Q::Selected | Q::Pressed, pal.fillColor.subtle.tertiary );
setGradient( Q::Segment | Q::Selected, pal.fillColor.subtle.secondary );
/*
We are using a section of the left border to display a
bar indicating the selection. Maybe we should introduce a
subcontrol instead TODO ...
*/
const auto c1 = pal.fillColor.subtle.secondary;
const auto c2 = pal.fillColor.accent.defaultColor;
setBoxBorderColors( Q::Segment | Q::Selected,
QskGradient( { { 0.25, c1 }, { 0.25, c2 }, { 0.75, c2 }, { 0.75, c1 } } ) );
setBoxBorderColors( Q::Segment | Q::Selected | Q::Pressed,
QskGradient( { { 0.33, c1 }, { 0.33, c2 }, { 0.67, c2 }, { 0.67, c1 } } ) );
setColor( Q::Text, pal.fillColor.text.primary );
setColor( Q::Text | Q::Selected | Q::Pressed, pal.fillColor.text.secondary );
setGraphicRole( Q::Icon, QskFluent2Skin::GraphicRoleFillColorTextPrimary );
setGraphicRole( Q::Icon | Q::Selected | Q::Pressed, QskFluent2Skin::GraphicRoleFillColorTextSecondary );
}
void Editor::setupPageIndicatorMetrics()
{
using Q = QskPageIndicator;
using A = QskAspect;
setPadding( Q::Panel, 5 );
setSpacing( Q::Panel, 6 );
// circles, without border
setBoxShape( Q::Bullet, 100, Qt::RelativeSize );
setBoxBorderMetrics( Q::Bullet, 0 );
/*
Pressed/Hovered are not yet implemented.
Sizes would be:
- Q::Pressed : 3
- Q::Pressed | Q::Selected : 5
- Q::Hovered : 5
- Q::Hovered | Q::Selected : 7
*/
setStrutSize( Q::Bullet, 6, 6 );
/*
Using the margin to adjust sizes is a weired type of implementation.
Needs to be changed TODO ...
*/
for ( auto state : { A::NoState, Q::Disabled } )
{
setMargin( Q::Bullet | state | Q::Selected, 0 );
setMargin( Q::Bullet | state, 1 );
}
}
void Editor::setupPageIndicatorColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskPageIndicator;
using A = QskAspect;
const auto& pal = theme.palette;
setGradient( Q::Panel, QskGradient() );
// Pressed/Hovered are missing - color for both would be pal.fillColor.text.secondary
for ( const auto state : { A::NoState, Q::Disabled } )
{
const auto color = ( state == A::NoState )
? pal.fillColor.controlStrong.defaultColor
: pal.fillColor.controlStrong.disabled;
const auto bullet = Q::Bullet | state | section;
setGradient( bullet, color );
setGradient( bullet | Q::Selected, color );
}
}
void Editor::setupPopup( const QskFluent2Theme& theme )
{
using Q = QskPopup;
const auto& pal = theme.palette;
setGradient( Q::Overlay, pal.background.overlay.defaultColor );
}
void Editor::setupProgressBarMetrics()
{
using Q = QskProgressBar;
using A = QskAspect;
setMetric( Q::Groove | A::Size, 1 );
setBoxShape( Q::Groove, 100, Qt::RelativeSize );
setMetric( Q::Fill | A::Size, 3 );
setBoxShape( Q::Fill, 100, Qt::RelativeSize );
}
void Editor::setupProgressBarColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskProgressBar;
const auto& pal = theme.palette;
setGradient( Q::Groove | section, pal.strokeColor.controlStrong.defaultColor );
setGradient( Q::Fill | section, pal.fillColor.accent.defaultColor );
}
void Editor::setupProgressRingMetrics()
{
using Q = QskProgressRing;
using A = QskAspect;
static constexpr QskAspect::Variation SmallSize = A::Small;
static constexpr QskAspect::Variation NormalSize = A::NoVariation;
static constexpr QskAspect::Variation LargeSize = A::Large;
setStrutSize( Q::Fill | SmallSize, { 16, 16 } );
setStrutSize( Q::Fill | NormalSize, { 32, 32 } );
setStrutSize( Q::Fill | LargeSize, { 64, 64 } );
const auto startAngle = 90, spanAngle = -360;
setArcMetrics( Q::Fill | SmallSize, startAngle, spanAngle, 1.5 );
setArcMetrics( Q::Fill | NormalSize, startAngle, spanAngle, 3 );
setArcMetrics( Q::Fill | LargeSize, startAngle, spanAngle, 6 );
}
void Editor::setupProgressRingColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskProgressRing;
const auto& pal = theme.palette;
setGradient( Q::Fill | section, pal.fillColor.accent.defaultColor );
}
void Editor::setupPushButtonMetrics()
{
using Q = QskPushButton;
using W = QskFluent2Skin;
setStrutSize( Q::Panel, { 120, 32 } );
setBoxShape( Q::Panel, 4 );
setBoxBorderMetrics( Q::Panel, 1 );
setBoxBorderMetrics( Q::Panel | W::Accent | Q::Disabled, 0 );
// Fluent buttons don't really have icons,
setStrutSize( Q::Icon, 12, 12 );
setPadding( Q::Icon, { 0, 0, 8, 0 } );
setFontRole( Q::Text, W::Body );
}
void Editor::setupPushButtonColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskPushButton;
using W = QskFluent2Skin;
const auto& pal = theme.palette;
for ( const auto variation : { QskAspect::NoVariation, W::Accent } )
{
const auto panel = Q::Panel | section | variation;
const auto text = Q::Text | section | variation;
const auto icon = Q::Icon | section | variation;
for ( const auto state : { QskAspect::NoState, Q::Hovered, Q::Pressed, Q::Disabled } )
{
QRgb panelColor, borderColor1, borderColor2, textColor;
int graphicRole;
if ( variation == W::Accent )
{
if ( state == Q::Hovered )
{
panelColor = pal.fillColor.accent.secondary;
borderColor1 = pal.elevation.accentControl.border[0];
borderColor2 = pal.elevation.accentControl.border[1];
textColor = pal.fillColor.textOnAccent.primary;
graphicRole = W::GraphicRoleFillColorTextOnAccentPrimary;
}
else if ( state == Q::Pressed )
{
panelColor = pal.fillColor.accent.tertiary;
borderColor1 = borderColor2 = pal.strokeColor.control.onAccentDefault;
textColor = pal.fillColor.textOnAccent.secondary;
graphicRole = W::GraphicRoleFillColorTextOnAccentSecondary;
}
else if ( state == Q::Disabled )
{
panelColor = pal.fillColor.accent.disabled;
borderColor1 = borderColor2 = panelColor; // irrelevant: width is 0
textColor = pal.fillColor.textOnAccent.disabled;
graphicRole = W::GraphicRoleFillColorTextOnAccentDisabled;
}
else
{
panelColor = pal.fillColor.accent.defaultColor;
borderColor1 = pal.elevation.accentControl.border[0];
borderColor2 = pal.elevation.accentControl.border[1];
textColor = pal.fillColor.textOnAccent.primary;
graphicRole = W::GraphicRoleFillColorTextOnAccentPrimary;
}
}
else
{
if ( state == Q::Hovered )
{
panelColor = pal.fillColor.control.secondary;
borderColor1 = pal.elevation.control.border[0];
borderColor2 = pal.elevation.control.border[1];
textColor = pal.fillColor.text.primary;
graphicRole = W::GraphicRoleFillColorTextPrimary;
}
else if ( state == Q::Pressed )
{
panelColor = pal.fillColor.control.tertiary;
borderColor1 = borderColor2 = pal.strokeColor.control.defaultColor;
textColor = pal.fillColor.text.secondary;
graphicRole = W::GraphicRoleFillColorTextSecondary;
}
else if ( state == Q::Disabled )
{
panelColor = pal.fillColor.control.disabled;
borderColor1 = borderColor2 = pal.strokeColor.control.defaultColor;
textColor = pal.fillColor.text.disabled;
graphicRole = W::GraphicRoleFillColorTextDisabled;
}
else
{
panelColor = pal.fillColor.control.defaultColor;
borderColor1 = pal.elevation.control.border[0];
borderColor2 = pal.elevation.control.border[0];
textColor = pal.fillColor.text.primary;
graphicRole = W::GraphicRoleFillColorTextPrimary;
}
}
panelColor = rgbSolid( panelColor, pal.background.solid.base );
setGradient( panel | state, panelColor );
setBoxBorderGradient( panel | state,
borderColor1, borderColor2, panelColor );
setColor( text | state, textColor );
setGraphicRole( icon | state, graphicRole );
}
}
}
void Editor::setupRadioBoxMetrics()
{
using Q = QskRadioBox;
setSpacing( Q::Button, 8 );
setStrutSize( Q::Button, { 115, 38 } );
/*
We do not have an indicator - states are indicated by the panel border
However the colors of the inner side of the border are not solid for
the selected states and we use a dummy indicator to get this done.
How to solve this in a better way, TODO ...
*/
setBoxShape( Q::CheckIndicator, 100, Qt::RelativeSize );
setBoxBorderMetrics( Q::CheckIndicator, 0 );
setBoxBorderMetrics( Q::CheckIndicator | Q::Selected, 1 );
setBoxBorderMetrics( Q::CheckIndicator | Q::Pressed | Q::Selected, 1 );
setBoxShape( Q::CheckIndicatorPanel, 100, Qt::RelativeSize );
setStrutSize( Q::CheckIndicatorPanel, { 20, 20 } );
setBoxBorderMetrics( Q::CheckIndicatorPanel, 1 );
setBoxBorderMetrics( Q::CheckIndicatorPanel | Q::Selected, 0 );
setPadding( Q::CheckIndicatorPanel | Q::Selected, { 5, 5 } ); // indicator "strut size"
setPadding( Q::CheckIndicatorPanel | Q::Hovered | Q::Selected, { 4, 4 } ); // indicator "strut size"
setPadding( Q::CheckIndicatorPanel | Q::Pressed, { 7, 7 } ); // indicator "strut size"
setBoxBorderMetrics( Q::CheckIndicatorPanel | Q::Pressed | Q::Selected, 0 );
setPadding( Q::CheckIndicatorPanel | Q::Pressed | Q::Selected, { 6, 6 } ); // indicator "strut size"
setBoxBorderMetrics( Q::CheckIndicatorPanel | Q::Disabled | Q::Selected, 0 );
setPadding( Q::CheckIndicatorPanel | Q::Disabled | Q::Selected, { 6, 6 } ); // indicator "strut size"
setFontRole( Q::Text, QskFluent2Skin::Body );
}
void Editor::setupRadioBoxColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskRadioBox;
using A = QskAspect;
const auto& pal = theme.palette;
for ( const auto state1 : { A::NoState, Q::Hovered, Q::Pressed, Q::Disabled } )
{
for ( const auto state2 : { A::NoState, Q::Selected } )
{
const auto states = state1 | state2;
auto indicatorColor = pal.fillColor.textOnAccent.primary;
if ( !( states & Q::Selected ) )
indicatorColor = QskRgb::toTransparent( indicatorColor, 0 );
auto textColor = pal.fillColor.text.primary;
if ( states & Q::Disabled )
textColor = pal.fillColor.text.disabled;
QRgb panelBorderColor;
if ( states & ( Q::Disabled | Q::Pressed ) )
panelBorderColor = pal.strokeColor.controlStrong.disabled;
else
panelBorderColor = pal.strokeColor.controlStrong.defaultColor;
auto panelColor = pal.fillColor.accent.defaultColor;
if ( states == A::NoState )
{
panelColor = pal.fillColor.controlAlt.secondary;
}
else if ( states == Q::Selected )
{
}
else if ( states == Q::Hovered )
{
panelColor = pal.fillColor.controlAlt.tertiary;
}
else if ( states == ( Q::Hovered | Q::Selected ) )
{
panelColor = pal.fillColor.accent.secondary;
}
else if ( states == Q::Pressed )
{
panelColor = pal.fillColor.controlAlt.quaternary;
}
else if ( states == ( Q::Pressed | Q::Selected ) )
{
panelColor = pal.fillColor.accent.tertiary;
}
else if ( states == Q::Disabled )
{
panelColor = pal.fillColor.controlAlt.disabled;
}
else if ( states == ( Q::Disabled | Q::Selected ) )
{
panelColor = pal.fillColor.accent.disabled;
}
const auto panel = Q::CheckIndicatorPanel | section | states;
const auto indicator = Q::CheckIndicator | section | states;
const auto text = Q::Text | section | states;
#if 0
// we have different colors when making colors solid early. TODO ...
panelColor = rgbSolid2( panelColor, pal.background.solid.base );
indicatorColor = rgbSolid2( indicatorColor, pal.background.solid.base );
#endif
setBoxBorderGradient( indicator, pal.elevation.circle.border, panelColor );
setGradient( panel, panelColor );
setBoxBorderColors( panel, panelBorderColor );
setGradient( indicator, indicatorColor );
setColor( text, textColor );
}
}
}
void Editor::setupScrollViewMetrics()
{
using A = QskAspect;
using Q = QskScrollView;
for ( auto subControl : { Q::HorizontalScrollBar, Q::VerticalScrollBar } )
{
setMetric( subControl | A::Size, 6 );
// The scrollbar is expanding, when being hovered/pressed
const qreal padding = 4;
if ( subControl == Q::HorizontalScrollBar )
setPadding( Q::HorizontalScrollBar, 0, padding, 0, 0 );
else
setPadding( Q::VerticalScrollBar, padding, 0, 0, 0 );
setPadding( subControl | Q::Hovered, 0 );
setPadding( subControl | Q::Pressed, 0 );
setBoxShape( subControl, 100, Qt::RelativeSize );
setAnimation( subControl | A::Metric, 100 );
}
/*
The scroll bars are actually above the viewport, what is not
supported by the skinlet. Do we want to have this. TODO ...
*/
// handles
setBoxShape( Q::HorizontalScrollHandle, 100, Qt::RelativeSize );
setBoxShape( Q::VerticalScrollHandle, 100, Qt::RelativeSize );
const auto handleExtent = 40.0;
setStrutSize( Q::HorizontalScrollHandle, handleExtent, 0.0 );
setStrutSize( Q::VerticalScrollHandle, 0.0, handleExtent );
}
void Editor::setupScrollViewColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using A = QskAspect;
using Q = QskScrollView;
const auto& pal = theme.palette;
{
const auto fillColor = pal.fillColor.controlStrong.defaultColor;
setGradient( Q::HorizontalScrollHandle | section, fillColor );
setGradient( Q::VerticalScrollHandle | section, fillColor );
}
for ( auto subControl : { Q::HorizontalScrollBar, Q::VerticalScrollBar } )
{
auto fillColor = pal.fillColor.acrylic.background;
#if 1
/*
With Fluent2 the scroll bar is supposed to be on top of scrollable
item. QskScrollViewSkinlet does not support this yet and we
always have the scrollbar on top of the panel. For the light
scheme this leads to white on white, so we better shade the scrollbar
for the moment: TODO ...
*/
const auto v = qBlue( fillColor );
if ( v > 250 )
{
if ( v == qRed( fillColor ) && v == qGreen( fillColor ) )
fillColor = qRgba( 240, 240, 240, qAlpha( fillColor ) );
}
#endif
setGradient( subControl, QskRgb::toTransparent( fillColor, 0 ) );
setGradient( subControl | Q::Hovered, fillColor );
setGradient( subControl | Q::Pressed, fillColor );
setAnimation( subControl | A::Color, 100 );
}
}
void Editor::setupSegmentedBarMetrics()
{
using Q = QskSegmentedBar;
using A = QskAspect;
const QSizeF segmentStrutSize( 120, 32 );
setBoxBorderMetrics( Q::Panel, 1 );
setBoxBorderMetrics( Q::Panel | Q::Selected | Q::Disabled, 0 );
setSpacing( Q::Panel, 8 );
setStrutSize( Q::Icon, { 12, 12 } );
setFontRole( Q::Text, QskFluent2Skin::Body );
setStrutSize( Q::Segment | A::Horizontal, segmentStrutSize );
setStrutSize( Q::Segment | A::Vertical, segmentStrutSize.transposed() );
setBoxShape( Q::Segment, 4 );
setPadding( Q::Segment, { 8, 0, 8, 0 } );
}
void Editor::setupSegmentedBarColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskSegmentedBar;
using A = QskAspect;
using W = QskFluent2Skin;
const auto& pal = theme.palette;
auto panelColor = pal.fillColor.control.defaultColor;
panelColor = rgbSolid( panelColor, pal.background.solid.base );
setGradient( Q::Panel, panelColor );
for ( const auto state1 : { A::NoState, Q::Hovered, Q::Disabled } )
{
for ( const auto state2 : { A::NoState, Q::Selected } )
{
const auto states = state1 | state2;
QRgb segmentColor, borderColor1, borderColor2, textColor;
int graphicRole;
if ( states == A::NoState )
{
segmentColor = pal.fillColor.control.defaultColor;
borderColor1 = pal.elevation.control.border[0];
borderColor2 = pal.elevation.control.border[1];
textColor = pal.fillColor.text.primary;
graphicRole = W::GraphicRoleFillColorTextPrimary;
}
else if ( states == Q::Hovered )
{
segmentColor = pal.fillColor.control.secondary;
borderColor1 = pal.elevation.control.border[0];
borderColor2 = pal.elevation.control.border[1];
textColor = pal.fillColor.text.primary;
graphicRole = W::GraphicRoleFillColorTextPrimary;
}
else if ( states == ( Q::Selected | Q::Disabled ) )
{
segmentColor = pal.fillColor.accent.disabled;
borderColor1 = borderColor2 = pal.strokeColor.control.defaultColor;
textColor = pal.fillColor.textOnAccent.disabled;
graphicRole = W::GraphicRoleFillColorTextOnAccentDisabled;
}
else if ( states & Q::Selected )
{
segmentColor = pal.fillColor.accent.defaultColor;
borderColor1 = pal.elevation.control.border[0];
borderColor2 = pal.elevation.control.border[1];
textColor = pal.fillColor.textOnAccent.primary;
graphicRole = W::GraphicRoleFillColorTextOnAccentPrimary;
}
else if ( states & Q::Disabled )
{
segmentColor = pal.fillColor.control.disabled;
borderColor1 = borderColor2 = pal.strokeColor.control.defaultColor;
textColor = pal.fillColor.text.disabled;
graphicRole = W::GraphicRoleFillColorTextDisabled;
}
const auto segment = Q::Segment | section | states;
const auto text = Q::Text | section | states;
const auto icon = Q::Icon | section | states;
segmentColor = rgbSolid( segmentColor, pal.background.solid.base );
setGradient( segment, segmentColor );
setBoxBorderGradient( segment, borderColor1, borderColor2, panelColor );
setColor( text, textColor );
setGraphicRole( icon, graphicRole );
}
}
}
void Editor::setupSeparatorMetrics()
{
using Q = QskSeparator;
using A = QskAspect;
setMetric( Q::Panel | A::Size, 1 );
setBoxShape( Q::Panel, 0 );
setBoxBorderMetrics( Q::Panel, 0 );
}
void Editor::setupSeparatorColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskSeparator;
const auto& pal = theme.palette;
setGradient( Q::Panel | section, pal.strokeColor.divider.defaultColor );
}
void Editor::setupSliderMetrics()
{
using Q = QskSlider;
using A = QskAspect;
const qreal extent = 22;
setMetric( Q::Panel | A::Size, extent );
setBoxShape( Q::Panel, 0 );
setBoxBorderMetrics( Q::Panel, 0 );
setPadding( Q::Panel | A::Horizontal, QskMargins( 0.5 * extent, 0 ) );
setPadding( Q::Panel | A::Vertical, QskMargins( 0, 0.5 * extent ) );
setMetric( Q::Groove | A::Size, 4 );
setBoxShape( Q::Groove, 100, Qt::RelativeSize );
setMetric( Q::Fill | A::Size, 4 );
setBoxShape( Q::Fill, 100, Qt::RelativeSize );
setStrutSize( Q::Handle, { 22, 22 } );
setBoxShape( Q::Handle, 100, Qt::RelativeSize );
setBoxBorderMetrics( Q::Handle, 1 );
setStrutSize( Q::Ripple, { 12, 12 } );
setBoxShape( Q::Ripple, 100, Qt::RelativeSize );
setStrutSize( Q::Ripple | Q::Hovered, { 14, 14 } );
setStrutSize( Q::Ripple | Q::Pressed, { 10, 10 } );
}
void Editor::setupSliderColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskSlider;
using A = QskAspect;
const auto& pal = theme.palette;
{
const auto handleColor = pal.fillColor.controlSolid.defaultColor;
setGradient( Q::Handle, handleColor );
setBoxBorderGradient( Q::Handle, pal.elevation.circle.border, handleColor );
}
for ( auto state : { A::NoState , Q::Pressed , Q::Disabled } )
{
QRgb grooveColor, fillColor, rippleColor;
if ( state == A::NoState )
{
grooveColor = pal.fillColor.controlStrong.defaultColor;
fillColor = pal.fillColor.accent.defaultColor;
rippleColor = fillColor;
}
else if ( state == Q::Pressed )
{
grooveColor = pal.fillColor.controlStrong.defaultColor;
fillColor = pal.fillColor.accent.defaultColor;
rippleColor = pal.fillColor.accent.tertiary;
}
else if ( state == Q::Disabled )
{
grooveColor = pal.fillColor.controlStrong.disabled;
fillColor = pal.fillColor.accent.disabled;
rippleColor = grooveColor;
}
grooveColor = rgbSolid( grooveColor, pal.background.solid.base );
setGradient( Q::Groove | section | state, grooveColor );
setGradient( Q::Fill | section | state, fillColor );
setGradient( Q::Ripple | section | state, rippleColor );
}
}
void Editor::setupSpinBoxMetrics()
{
using Q = QskSpinBox;
setHint( Q::Panel | QskAspect::Style, Q::ButtonsRight );
setStrutSize( Q::Panel, { -1, 32 } );
setBoxBorderMetrics( Q::Panel, 1 );
setBoxShape( Q::Panel, 3 );
setPadding( Q::Panel, { 11, 0, 11, 0 } );
setAlignment( Q::Text, Qt::AlignLeft );
setFontRole( Q::Text, QskFluent2Skin::Body );
setPadding( Q::TextPanel, { 11, 5, 0, 0 } );
setStrutSize( Q::UpPanel, 32, 20 );
setPadding( Q::UpPanel, { 11, 7, 11, 7 } );
setStrutSize( Q::DownPanel, 34, 20 );
setPadding( Q::DownPanel, { 11, 7, 13, 7 } );
setSymbol( Q::UpIndicator, symbol( "spin-box-arrow-up" ) );
setSymbol( Q::DownIndicator, symbol( "spin-box-arrow-down" ) );
// Focused (Pressed doesn't exist yet):
setBoxBorderMetrics( Q::Panel | Q::Focused, { 1, 1, 1, 2 } );
}
void Editor::setupSpinBoxColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskSpinBox;
using A = QskAspect;
const auto& pal = theme.palette;
for ( auto state : { A::NoState, Q::Hovered, Q::Focused, Q::Disabled } )
{
QRgb panelColor, borderColor1, borderColor2;
if ( state == A::NoState )
{
panelColor = pal.fillColor.control.defaultColor;
borderColor1 = pal.elevation.control.border[0];
borderColor2 = pal.elevation.control.border[1];
}
else if ( state == Q::Hovered )
{
panelColor = pal.fillColor.control.secondary;
borderColor1 = pal.elevation.textControl.border[0];
borderColor2 = pal.elevation.textControl.border[1];
}
else if ( state == Q::Focused )
{
// Focused (Pressed doesn't exist yet):
panelColor = pal.fillColor.control.inputActive;
borderColor1 = pal.elevation.textControl.border[0];
borderColor2 = pal.fillColor.accent.defaultColor;
}
else if ( state == Q::Disabled )
{
panelColor = pal.fillColor.control.disabled;
borderColor1 = borderColor2 = pal.strokeColor.control.defaultColor;
}
QRgb textColor;
int graphicRole;
if ( state != Q::Disabled )
{
textColor = pal.fillColor.text.primary;
graphicRole = QskFluent2Skin::GraphicRoleFillColorTextSecondary;
}
else
{
textColor = pal.fillColor.text.disabled;
graphicRole = QskFluent2Skin::GraphicRoleFillColorTextDisabled;
}
const auto panel = Q::Panel | section | state;
const auto text = Q::Text | section | state;
const auto upIndicator = Q::UpIndicator | section | state;
const auto downIndicator = Q::DownIndicator | section | state;
panelColor = rgbSolid( panelColor, pal.background.solid.base );
setGradient( panel, panelColor );
setBoxBorderGradient( panel, borderColor1, borderColor2, panelColor );
setColor( text, textColor );
setGraphicRole( upIndicator, graphicRole );
setGraphicRole( downIndicator, graphicRole );
}
}
void Editor::setupTabBarMetrics()
{
}
void Editor::setupTabBarColors( QskAspect::Section section, const QskFluent2Theme& theme )
{
setGradient( QskTabBar::Panel | section, theme.palette.background.solid.base );
}
void Editor::setupTabButtonMetrics()
{
using Q = QskTabButton;
setStrutSize( Q::Panel, { -1, 31 } );
setPadding( Q::Panel, { 7, 0, 7, 0 } );
setBoxShape( Q::Panel, { 7, 7, 0, 0 } );
setAlignment( Q::Text, Qt::AlignLeft | Qt::AlignVCenter );
setBoxBorderMetrics( Q::Panel, { 0, 0, 0, 1 } );
setBoxBorderMetrics( Q::Panel | Q::Checked, { 1, 1, 1, 0 } );
setFontRole( Q::Text, QskFluent2Skin::Body );
setFontRole( Q::Text | Q::Checked, QskFluent2Skin::BodyStrong );
}
void Editor::setupTabButtonColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskTabButton;
const auto& pal = theme.palette;
for ( const auto state : { QskAspect::NoState,
Q::Checked, Q::Hovered, Q::Pressed, Q::Disabled } )
{
QRgb panelColor, textColor;
if ( state == Q::Checked )
{
panelColor = pal.background.solid.secondary;
textColor = pal.fillColor.text.primary;
}
else if ( state == Q::Hovered )
{
panelColor = pal.fillColor.subtle.secondary;
textColor = pal.fillColor.text.secondary;
}
else if ( state == Q::Pressed )
{
panelColor = pal.fillColor.subtle.tertiary;
textColor = pal.fillColor.text.secondary;
}
else if ( state == Q::Disabled )
{
panelColor = pal.fillColor.control.disabled;
textColor = pal.fillColor.text.disabled;
}
else
{
panelColor = pal.fillColor.subtle.tertiary;
textColor = pal.fillColor.text.secondary;
}
const auto panel = Q::Panel | section | state;
const auto text = Q::Text | section | state;
panelColor = rgbSolid( panelColor, pal.background.solid.base );
setGradient( panel, panelColor );
const auto borderColor = rgbSolid(
pal.strokeColor.card.defaultColor, pal.background.solid.base );
setBoxBorderColors( panel, borderColor );
setColor( text, textColor );
}
}
void Editor::setupTabViewMetrics()
{
}
void Editor::setupTabViewColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskTabView;
setGradient( Q::Page | section, theme.palette.background.solid.secondary );
}
void Editor::setupGraphicLabelMetrics()
{
using Q = QskGraphicLabel;
setPadding( Q::Panel, 10 );
setBoxShape( Q::Panel, 3 );
setBoxBorderMetrics( Q::Panel, 1 );
}
void Editor::setupGraphicLabelColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskGraphicLabel;
const auto& pal = theme.palette;
#if 1
setColor( Q::Panel | section, pal.fillColor.subtle.secondary );
setBoxBorderColors( Q::Panel | section, pal.strokeColor.control.defaultColor );
#endif
}
void Editor::setupTextLabelMetrics()
{
using Q = QskTextLabel;
setPadding( Q::Panel, 10 );
setBoxShape( Q::Panel, 3 );
setBoxBorderMetrics( Q::Panel, 1 );
setFontRole( Q::Text, QskFluent2Skin::Body );
}
void Editor::setupTextLabelColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskTextLabel;
const auto& pal = theme.palette;
#if 1
setColor( Q::Panel | section, pal.fillColor.subtle.secondary );
setBoxBorderColors( Q::Panel | section, pal.strokeColor.control.defaultColor );
#endif
setColor( Q::Text | section, pal.fillColor.text.primary );
}
void Editor::setupTextInputMetrics()
{
using Q = QskTextInput;
setStrutSize( Q::Panel, { -1, 30 } );
setPadding( Q::Panel, { 11, 0, 11, 0 } );
setBoxBorderMetrics( Q::Panel, 1 );
for( const auto& state : { Q::Focused, Q::Editing } )
setBoxBorderMetrics( Q::Panel | state, { 1, 1, 1, 2 } );
setBoxShape( Q::Panel, 3 );
setAlignment( Q::Text, Qt::AlignLeft | Qt::AlignVCenter );
setFontRole( Q::Text, QskFluent2Skin::Body );
}
void Editor::setupTextInputColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskTextInput;
using A = QskAspect;
const auto& pal = theme.palette;
setColor( Q::PanelSelected, pal.fillColor.accent.selectedTextBackground );
setColor( Q::TextSelected, pal.fillColor.textOnAccent.selectedText );
for( const auto state : { A::NoState, Q::Hovered, Q::Focused, Q::Editing, Q::Disabled } )
{
QRgb panelColor, borderColor1, borderColor2, textColor;
if ( state == A::NoState )
{
panelColor = pal.fillColor.control.defaultColor;
borderColor1 = pal.elevation.textControl.border[0];
borderColor2 = pal.elevation.textControl.border[1];
textColor = pal.fillColor.text.secondary;
}
else if ( state == Q::Hovered )
{
panelColor = pal.fillColor.control.secondary;
borderColor1 = pal.elevation.textControl.border[0];
borderColor2 = pal.elevation.textControl.border[1];
textColor = pal.fillColor.text.secondary;
}
else if ( ( state == Q::Focused ) || ( state == Q::Editing ) )
{
panelColor = pal.fillColor.control.inputActive;
borderColor1 = pal.elevation.textControl.border[0];
borderColor2 = pal.fillColor.accent.defaultColor;
textColor = pal.fillColor.text.secondary;
}
else if ( state == Q::Disabled )
{
panelColor = pal.fillColor.control.disabled;
borderColor1 = borderColor2 = pal.strokeColor.control.defaultColor;
textColor = pal.fillColor.text.disabled;
}
const auto panel = Q::Panel | section | state;
const auto text = Q::Text | section | state;
panelColor = rgbSolid( panelColor, pal.background.solid.base );
setGradient( panel, panelColor );
setBoxBorderGradient( panel, borderColor1, borderColor2, panelColor );
setColor( text, textColor );
}
}
void Editor::setupSwitchButtonMetrics()
{
using Q = QskSwitchButton;
using A = QskAspect;
const QSizeF strutSize( 38, 18 );
setStrutSize( Q::Groove | A::Horizontal, strutSize );
setStrutSize( Q::Groove | A::Vertical, strutSize.transposed() );
setBoxShape( Q::Groove, 100, Qt::RelativeSize );
setBoxBorderMetrics( Q::Groove, 1 );
setBoxBorderMetrics( Q::Groove | Q::Checked, 0 );
setBoxShape( Q::Handle, 100, Qt::RelativeSize );
setPosition( Q::Handle, 0.1, { QskStateCombination::CombinationNoState, Q::Disabled } );
setPosition( Q::Handle | Q::Checked, 0.9,
{ QskStateCombination::CombinationNoState, Q::Disabled } );
setBoxBorderMetrics( Q::Handle, 0 );
setBoxBorderMetrics( Q::Handle | Q::Checked, 1 );
setBoxBorderMetrics( Q::Handle | Q::Disabled | Q::Checked, 0 );
setStrutSize( Q::Handle, 12, 12 );
setStrutSize( Q::Handle | Q::Hovered, 14, 14,
{ QskStateCombination::CombinationNoState, Q::Checked } );
const QSizeF pressedSize( 17, 14 );
setStrutSize( Q::Handle | Q::Pressed | A::Horizontal,
pressedSize, { QskStateCombination::CombinationNoState, Q::Checked } );
setStrutSize( Q::Handle | Q::Pressed | A::Vertical,
pressedSize.transposed(), { QskStateCombination::CombinationNoState, Q::Checked } );
setStrutSize( Q::Handle | Q::Disabled, 12, 12,
{ QskStateCombination::CombinationNoState, Q::Checked } );
setAnimation( Q::Handle | A::Metric, 100 );
}
void Editor::setupSwitchButtonColors(
QskAspect::Section section, const QskFluent2Theme& theme )
{
using Q = QskSwitchButton;
using A = QskAspect;
const auto& pal = theme.palette;
for ( const auto state1 : { A::NoState, Q::Hovered, Q::Pressed, Q::Disabled } )
{
for ( const auto state2 : { A::NoState, Q::Checked } )
{
const auto states = state1 | state2;
QRgb grooveColor, grooveBorderColor, handleColor;
if ( states == A::NoState )
{
grooveColor = pal.fillColor.controlAlt.secondary;
grooveBorderColor = pal.strokeColor.controlStrong.defaultColor;
handleColor = pal.strokeColor.controlStrong.defaultColor;
}
else if ( states == Q::Checked )
{
grooveColor = pal.fillColor.accent.defaultColor;
grooveBorderColor = pal.strokeColor.controlStrong.defaultColor;
handleColor = pal.fillColor.textOnAccent.primary;
}
else if ( states == Q::Hovered )
{
grooveColor = pal.fillColor.controlAlt.tertiary;
grooveBorderColor = pal.fillColor.text.secondary;
handleColor = pal.fillColor.text.secondary;
}
else if ( states == ( Q::Hovered | Q::Checked ) )
{
grooveColor = pal.fillColor.accent.secondary;
grooveBorderColor = pal.strokeColor.controlStrong.defaultColor;
handleColor = pal.fillColor.textOnAccent.primary;
//handleColor = pal.fillColor.accent.defaultColor;
}
else if ( states == Q::Pressed )
{
grooveColor = pal.fillColor.controlAlt.quaternary;
grooveBorderColor = pal.strokeColor.controlStrong.defaultColor;
handleColor = pal.strokeColor.controlStrong.defaultColor;
}
else if ( states == ( Q::Pressed | Q::Checked ) )
{
grooveColor = pal.fillColor.accent.tertiary;
grooveBorderColor = pal.strokeColor.controlStrong.defaultColor;
handleColor = pal.fillColor.textOnAccent.primary;
}
else if ( states == Q::Disabled )
{
grooveColor = pal.fillColor.controlAlt.disabled;
grooveBorderColor = pal.fillColor.text.disabled;
handleColor = pal.fillColor.text.disabled;
}
else if ( states == ( Q::Disabled | Q::Checked ) )
{
grooveColor = pal.fillColor.accent.disabled;
grooveBorderColor = pal.fillColor.accent.disabled;
handleColor = pal.fillColor.textOnAccent.disabled;
}
const auto groove = Q::Groove | section | states;
const auto handle = Q::Handle | section | states;
grooveColor = rgbSolid( grooveColor, pal.background.solid.base );
setGradient( groove, grooveColor );
setBoxBorderColors( groove, grooveBorderColor );
setGradient( handle, handleColor );
setBoxBorderGradient( handle, pal.elevation.circle.border, grooveColor );
}
}
}
void Editor::setupSubWindow( const QskFluent2Theme& theme )
{
using Q = QskSubWindow;
const auto& pal = theme.palette;
setPadding( Q::Panel, { 0, 31, 0, 0 } );
setBoxShape( Q::Panel, 7 );
setBoxBorderMetrics( Q::Panel, 1 );
setBoxBorderColors( Q::Panel, pal.strokeColor.surface.defaultColor );
setGradient( Q::Panel, pal.background.layer.alt );
setShadowMetrics( Q::Panel, theme.shadow.dialog.metrics );
setShadowColor( Q::Panel, theme.shadow.dialog.color );
setHint( Q::TitleBarPanel | QskAspect::Style, Q::TitleBar | Q::Title );
setPadding( Q::TitleBarPanel, { 24, 31, 24, 0 } );
setFontRole( Q::TitleBarText, QskFluent2Skin::Subtitle );
setColor( Q::TitleBarText, pal.fillColor.text.primary );
setAlignment( Q::TitleBarText, Qt::AlignLeft );
setTextOptions( Q::TitleBarText, Qt::ElideRight, QskTextOptions::NoWrap );
}
void Editor::setupVirtualKeyboardMetrics()
{
using Q = QskVirtualKeyboard;
setMargin( Q::ButtonPanel, 2 );
setFontRole( Q::ButtonText, QskFluent2Skin::BodyLarge );
setPadding( Q::Panel, 8 );
}
void Editor::setupVirtualKeyboardColors(
QskAspect::Section, const QskFluent2Theme& theme )
{
using Q = QskVirtualKeyboard;
const auto& pal = theme.palette;
setGradient( Q::ButtonPanel, pal.fillColor.control.defaultColor );
setGradient( Q::ButtonPanel | Q::Hovered, pal.fillColor.control.secondary );
setGradient( Q::ButtonPanel | QskPushButton::Pressed, pal.fillColor.control.tertiary );
setColor( Q::ButtonText, pal.fillColor.text.primary );
setColor( Q::ButtonText | QskPushButton::Pressed, pal.fillColor.text.secondary );
setGradient( Q::Panel, pal.background.solid.tertiary );
}
QskFluent2Skin::QskFluent2Skin( QObject* parent )
: Inherited( parent )
{
setupFonts();
Editor editor( &hintTable() );
editor.setupMetrics();
}
void QskFluent2Skin::addTheme( QskAspect::Section section, const QskFluent2Theme& theme )
{
if ( section == QskAspect::Body )
{
// design flaw: we can't have section sensitive filters. TODO ..
setupGraphicFilters( theme );
}
Editor editor( &hintTable() );
editor.setupColors( section, theme );
}
QskFluent2Skin::~QskFluent2Skin()
{
}
void QskFluent2Skin::setupFonts()
{
static QString fontName( QStringLiteral( "Segoe UI Variable" ) );
Inherited::setupFonts( fontName );
setFont( Caption, createFont( fontName, 12, 16, 0.0, QFont::Normal ) );
setFont( Body, createFont( fontName, 14, 20, 0.0, QFont::Normal ) );
setFont( BodyStrong, createFont( fontName, 14, 20, 0.0, QFont::DemiBold ) );
setFont( BodyLarge, createFont( fontName, 18, 24, 0.0, QFont::Medium ) );
setFont( Subtitle, createFont( fontName, 20, 28, 0.0, QFont::DemiBold ) );
setFont( Title, createFont( fontName, 28, 36, 0.0, QFont::DemiBold ) );
setFont( TitleLarge, createFont( fontName, 40, 52, 0.0, QFont::DemiBold ) );
setFont( Display, createFont( fontName, 68, 92, 0.0, QFont::DemiBold ) );
}
void QskFluent2Skin::setGraphicColor( GraphicRole role, QRgb rgb )
{
QskColorFilter colorFilter;
colorFilter.setMask( QskRgb::RGBAMask );
colorFilter.addColorSubstitution( QskRgb::Black, rgb );
setGraphicFilter( role, colorFilter );
}
void QskFluent2Skin::setupGraphicFilters( const QskFluent2Theme& theme )
{
const auto& colors = theme.palette.fillColor;
setGraphicColor( GraphicRoleFillColorTextDisabled, colors.text.disabled );
setGraphicColor( GraphicRoleFillColorTextOnAccentDisabled, colors.textOnAccent.disabled );
setGraphicColor( GraphicRoleFillColorTextOnAccentPrimary, colors.textOnAccent.primary );
setGraphicColor( GraphicRoleFillColorTextOnAccentSecondary, colors.textOnAccent.secondary );
setGraphicColor( GraphicRoleFillColorTextPrimary, colors.text.primary );
setGraphicColor( GraphicRoleFillColorTextSecondary, colors.text.secondary );
}
#include "moc_QskFluent2Skin.cpp"
|
438bef20acee56ca3382717563534c37409b0f83
|
d8effd075768aecbf0a590804e6c94127954d01c
|
/noz/src/noz/Editor/Nodes/UI/AssetEditor/SceneEditor.cpp
|
de21cd472853a3f2b732346346f31ee03d81df46
|
[] |
no_license
|
nozgames/noz-cpp
|
55c88e0ea92408433ca34399f31007418d46a063
|
0466c938f54edf846c01dd195ce870b366821e99
|
refs/heads/master
| 2022-11-24T04:20:51.348835
| 2020-07-30T21:42:48
| 2020-07-30T21:42:48
| 283,881,452
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,050
|
cpp
|
SceneEditor.cpp
|
///////////////////////////////////////////////////////////////////////////////
// NoZ Engine Framework
// Copyright (C) 2015 NoZ Games, LLC
// http://www.nozgames.com
///////////////////////////////////////////////////////////////////////////////
#include <noz.pch.h>
#include <noz/Serialization/JsonSerializer.h>
#include <noz/System/Process.h>
#include <noz/Nodes/UI/Button.h>
#include <noz/Nodes/UI/DropDownList.h>
#include <noz/Nodes/UI/DropDownListItem.h>
#include <noz/Components/Transform/LayoutTransform.h>
#include "SceneEditor.h"
using namespace noz;
using namespace noz::Editor;
SceneEditor::SceneEditor(void) {
playing_process_ = nullptr;
panning_ = false;
zoom_= 1.0f;
// Create a new inspector for scene editor.
if(!Application::IsInitializing()) {
// Create a new hierarchy for scene editor.
if(nullptr==hierarchy_) {
hierarchy_ = new Hierarchy;
SetHierarchy(hierarchy_);
}
}
}
SceneEditor::~SceneEditor(void) {
if(hierarchy_) hierarchy_->Destroy();
if(inspector_) inspector_->Destroy();
}
bool SceneEditor::OnApplyStyle (void) {
noz_assert(hierarchy_);
if(!AssetEditor::OnApplyStyle()) return false;
if(nullptr == scene_root_) return false;
if(scene_) {
hierarchy_->SetTarget(scene_->GetRootNode());;
scene_root_->AddChild(scene_->GetRootNode());
}
hierarchy_->SelectionChanged += SelectionChangedEventHandler::Delegate(this,&SceneEditor::OnHeirarchySelectionChanged);
if(resolution_) {
resolution_->SelectionChanged += SelectionChangedEventHandler::Delegate(this, &SceneEditor::OnResolutionSelected);
RefreshResolutions();
}
if(play_) play_->Click += ClickEventHandler::Delegate(this, &SceneEditor::OnPlay);
return true;
}
bool SceneEditor::Load (AssetFile* file) {
scene_ = AssetManager::LoadAsset<Scene>(file->GetGuid());
return true;
}
void SceneEditor::OnHeirarchySelectionChanged (UINode* sender) {
SetInspector(EditorFactory::CreateInspector(hierarchy_->GetSelected()));
// Find the animator that controls the selected node. The controlling animator is
// either the animator on the node itself or the first animator in the nodes ancestry.
Animator* animator = nullptr;
for(Node* node = hierarchy_->GetSelected(); !animator && node && node!=scene_root_; node = node->GetLogicalParent()) {
animator = node->GetComponent<Animator>();
}
// Set the new animation view source to the controlling animator
SetAnimationViewSource(animator);
}
void SceneEditor::RefreshResolutions (void) {
if(nullptr == resolution_) return;
for(noz_uint32 i=0,c=EditorSettings::GetResolutionCount(); i<c; i++) {
DropDownListItem* r = new DropDownListItem;
r->SetText(String::Format("%dx%d - %s", EditorSettings::GetResolution(i).GetWidth(), EditorSettings::GetResolution(i).GetHeight(), EditorSettings::GetResolution(i).GetName().ToCString()));
r->SetUserData((void*)i);
resolution_->AddChild(r);
}
resolution_->GetFirstChildItem()->Select();
}
void SceneEditor::OnResolutionSelected(UINode* sender) {
DropDownListItem* item = resolution_->GetSelectedItem();
if(nullptr == item) return;
noz_uint32 i = (noz_uint32)(noz_uint64)item->GetUserData();
if(i>=EditorSettings::GetResolutionCount()) i=0;
if(nullptr==scene_root_) return;
LayoutTransform* t = Cast<LayoutTransform>(scene_root_->GetTransform());
if(nullptr == t) {
t = new LayoutTransform;
t->SetMargin(LayoutLength(LayoutUnitType::Auto,0.0f));
t->SetPivot(Vector2::Zero);
scene_root_->SetTransform(t);
}
const Resolution& r = EditorSettings::GetResolution(i);
t->SetWidth((noz_float)r.GetWidth());
t->SetHeight((noz_float)r.GetHeight());
}
void SceneEditor::Save (void) {
FileStream fs;
if(!fs.Open(GetFile()->GetPath(),FileMode::Truncate)) {
Console::WriteError(this, "failed to save scene");
return;
}
JsonSerializer().Serialize(scene_,&fs);
SetModified(false);
}
void SceneEditor::OnActivate (void) {
AssetEditor::OnActivate();
}
void SceneEditor::OnPlay(UINode*) {
if(playing_process_ != nullptr) return;
play_->SetInteractive(false);
String size;
LayoutTransform* t = Cast<LayoutTransform>(scene_root_->GetTransform());
if(nullptr != t) {
size = String::Format("-width=%d -height=%d", (noz_int32)t->GetWidth().value_, (noz_int32)t->GetHeight().value_);
}
playing_process_ = Process::Start(
Environment::GetExecutablePath().ToCString(),
String::Format("-remote -scene=%s %s", scene_->GetGuid().ToString().ToCString(),size.ToCString()).ToCString()
);
}
void SceneEditor::Update (void) {
AssetEditor::Update();
if(playing_process_ && playing_process_->HasExited()) {
delete playing_process_;
playing_process_ = nullptr;
play_->SetInteractive(true);
}
}
void SceneEditor::OnMouseDown (SystemEvent* e) {
// Space being held starts a drag move
if(Input::GetKey(Keys::Space)) {
pan_start_ = e->GetPosition();
panning_ = true;
SetCapture();
e->SetHandled();
return;
}
Node* n = Node::HitTest(scene_->GetRootNode(), e->GetPosition());
if(n) {
hierarchy_->SetSelected(n);
}
}
void SceneEditor::OnMouseOver (SystemEvent* e) {
if(panning_) {
grid_node_->SetOffset(grid_node_->GetOffset() + (e->GetPosition()-pan_start_));
Vector2 pos = pan_node_->GetTransform()->GetLocalPosition();
pos += (e->GetPosition()-pan_start_);
pan_start_ = e->GetPosition();
pan_node_->GetTransform()->SetLocalPosition(pos);
}
}
void SceneEditor::OnMouseUp (SystemEvent* e) {
panning_ = false;
}
void SceneEditorRootNode::RenderOverride (RenderContext* rc) {
Node::RenderOverride(rc);
SceneEditor* editor = GetAncestor<SceneEditor>();
if(nullptr == editor) return;
rc->PushMatrix();
rc->MultiplyMatrix(GetLocalToViewport());
for(noz_uint32 i=0, c=editor->hierarchy_->GetSelectedItemCount(); i<c; i++) {
HierarchyItem* item = editor->hierarchy_->GetSelectedItem(i);
Node* n = item->GetTarget();
if(n->IsViewport() || n->IsSceneRoot()) continue;
Rect r = n->LocalToWindow(n->GetRectangle());
Vector2 tl = WindowToLocal(r.GetTopLeft());
Vector2 br = WindowToLocal(r.GetBottomRight());
Vector2 tr(br.x,tl.y);
Vector2 bl(tl.x,br.y);
rc->DrawDebugLine(tl,tr,Color::White);
rc->DrawDebugLine(tr,br,Color::White);
rc->DrawDebugLine(br,bl,Color::White);
rc->DrawDebugLine(bl,tl,Color::White);
}
rc->PopMatrix();
}
void SceneEditor::OnMouseWheel (SystemEvent* e) {
AssetEditor::OnMouseWheel(e);
// Is the mouse over the grid?
if(grid_node_ && grid_node_->HitTest(e->GetPosition()) == HitTestResult::Rect) {
// If the mouse if over the node then zoom
if(e->GetDelta().y > 0.0f) {
SetZoom(zoom_ * 1.1f);
} else {
SetZoom(zoom_ * (1/1.1f));
}
e->SetHandled();
}
}
void SceneEditor::SetZoom (noz_float zoom) {
zoom = Math::Clamp(zoom,0.01f,40.0f);
if(zoom == zoom_) return;
zoom_ = zoom;
zoom_node_->GetTransform()->SetScale(zoom_);
grid_node_->SetScale(zoom_);
}
|
c0ed9e369a4da74efbf783f8da12c8fc4c8cfc13
|
0550a6655187cc7f2e23270782b29af786f2711d
|
/server/backends/sciBE/sciBE.cpp
|
14f1872177c63e6c89a21afcb48d245d22d2c9bb
|
[] |
no_license
|
SCIInstitute/dSpaceX
|
01135cf2d034660de1c4a796b65244bbadac2a5b
|
8176401859315824d278b642038032b99208fb53
|
refs/heads/master
| 2023-01-11T16:17:44.716002
| 2021-02-14T00:02:57
| 2021-02-14T00:02:57
| 101,233,360
| 5
| 2
| null | 2022-12-29T09:44:50
| 2017-08-23T23:28:24
|
C++
|
UTF-8
|
C++
| false
| false
| 5,006
|
cpp
|
sciBE.cpp
|
/*
* dSpaceX - sample dynamicly loaded back-end
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef WIN32
#define getcwd _getcwd
#define snprintf _snprintf
#define PATH_MAX _MAX_PATH
#else
#include <unistd.h>
#include <limits.h>
#endif
#include <vector>
#include "util/DenseVectorSample.h";
#include "Precision.h"
#include "Linalg.h"
#include "LinalgIO.h"
#include "DenseMatrix.h"
#include "DenseVector.h"
/* NOTE: This needs to be removed and the data read moved to Initialize */
std::vector<DenseVectorSample*> samples;
FortranLinalg::DenseVector<Precision> y;
/* image file reader */
extern "C" int dsx_getThumbNail( const char *Name, int *Width, int *Height,
unsigned char **Image );
/* storage location for everything we allocate
we must free the memory -- Windows DLL! */
typedef struct {
int nParam;
int nQoI;
double *cases;
double *qois;
char **pNames;
char **qNames;
unsigned char *thumb;
char currentPath[PATH_MAX];
} BEstorage;
static BEstorage save;
static int first = -1;
/* function that gets invoked to return the data for the design setting */
extern "C" int dsxInitialize( int *nCases, int *nParams, double **params,
char ***PNames, int *nQoI, double **QoIs,
char ***QNames)
{
int i, j, m, n, len;
double *cases, *qois;
char text[133], **pNames, **qNames;
FILE *fp;
if (first == -1) {
save.nParam = 0;
save.nQoI = 0;
save.cases = NULL;
save.qois = NULL;
save.pNames = NULL;
save.qNames = NULL;
save.thumb = NULL;
}
*nCases = *nParams = *nQoI = 0;
*params = *QoIs = NULL;
*PNames = *QNames = NULL;
// fp = fopen("aeroDB_ALL.dat", "r");
// if (fp == NULL) return -1;
// fscanf(fp, "%d %d %d", nParams, nQoI, nCases);
*nCases = y.N(); // samples.size();
*nQoI = 1;
*nParams = 1;
len = *nCases;
cases = (double *) malloc(*nParams*len*sizeof(double));
qois = (double *) malloc(*nQoI* len*sizeof(double));
pNames = (char **) malloc(*nParams *sizeof(char *));
qNames = (char **) malloc(*nQoI *sizeof(char *));
if ((cases == NULL) || (qois == NULL) ||
(pNames == NULL) || (qNames == NULL)) {
if (cases != NULL) free(cases);
if (qois != NULL) free(qois);
if (pNames != NULL) free(pNames);
if (qNames != NULL) free(qNames);
return -2;
}
for (i = 0; i < *nParams; i++) {
// fscanf(fp, " \"%[^\"]\"", text);
strcpy(text, "parameters\0");
len = strlen(text)+1;
pNames[i] = (char*)malloc(len*sizeof(char));
if (pNames[i] == NULL) continue;
for (j = 0; j < len; j++) pNames[i][j] = text[j];
}
for (i = 0; i < *nQoI; i++) {
// fscanf(fp, " \"%[^\"]\"", text);
strcpy(text, "qoi\0");
len = strlen(text)+1;
qNames[i] = (char*)malloc(len*sizeof(char));
if (qNames[i] == NULL) continue;
for (j = 0; j < len; j++) qNames[i][j] = text[j];
}
for (m = n = j = 0; j < *nCases; j++) {
for (i = 0; i < *nParams; i++, m++) {
// fscanf(fp, "%lf", &cases[m]);
cases[n] = 0;
}
for (i = 0; i < *nQoI; i++, n++) {
// fscanf(fp, "%lf", &qois[n]);
qois[n] = y(j);
}
}
// fclose(fp);
/* get our current location */
(void) getcwd(save.currentPath, PATH_MAX);
printf("Path = %s\n", save.currentPath);
save.nParam = *nParams;
save.nQoI = *nQoI;
save.cases = cases;
save.qois = qois;
save.pNames = pNames;
save.qNames = qNames;
*params = cases;
*QoIs = qois;
*PNames = pNames;
*QNames = qNames;
first++;
return 0;
}
/* function that returns a thumbnail of the specified case */
extern "C" int dsxThumbNail(int caseIndex, int *width, int *height,
unsigned char **image)
{
int stat = 0;
char filename[129];
*width = *height = 0;
*image = NULL;
if (save.thumb != NULL) free(save.thumb);
save.thumb = NULL;
#ifdef WIN32
snprintf(filename, 128, "ThumbNails\\%d.png", caseIndex);
#else
snprintf(filename, 128, "ThumbNails/%d.png", caseIndex);
#endif
stat = dsx_getThumbNail(filename, width, height, image);
if (stat == 0) save.thumb = *image;
return stat;
}
/* computes distance between the 2 specified cases */
extern "C" int dsxDistance(/*@unused@*/ int case1, /*@unused@*/ int case2, double *distance)
{
*distance = 0.0;
return 0;
}
/* cleans up any allocated memory */
extern "C" void dsxCleanup()
{
int i;
if (save.thumb != NULL) free(save.thumb);
if (save.cases != NULL) free(save.cases);
if (save.qois != NULL) free(save.qois);
if (save.pNames != NULL) {
for (i = 0; i < save.nParam; i++)
if (save.pNames[i] != NULL) free(save.pNames[i]);
free(save.pNames);
}
if (save.qNames != NULL) {
for (i = 0; i < save.nQoI; i++)
if (save.qNames[i] != NULL) free(save.qNames[i]);
free(save.qNames);
}
}
|
349bca67a2518edeb723d2e643cc095e3ab19195
|
b0e1e913b04dd5fc519e79b29f99a0d90a0367b5
|
/dijkstra/display.cpp
|
a08e5cebd32698ff401d5e9d060ab6f18eaf2a07
|
[] |
no_license
|
WillH97/visual-algorithms
|
48d3d3d6f38380a33bb10abd6645ac7f5d1b2593
|
830114628bcfd5519306bc6e246b279fb58699d6
|
refs/heads/main
| 2023-01-05T13:23:23.938911
| 2020-11-03T22:56:25
| 2020-11-03T22:56:25
| 307,209,025
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,999
|
cpp
|
display.cpp
|
#include "includes.h"
#include "globals.h"
#include "structs.h"
void display( )
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0, 0, 0);
// draw a box for each wall point
for (int i = 0; i < pts.size(); i++) {
if ( pts[i].wall ) {
// draw box
glColor3f(0,0,0);
glBegin(GL_POLYGON);
glVertex2i( (pts[i].x)*h, (pts[i].y)*h);
glVertex2i( (pts[i].x * h) + h, (pts[i].y)*h);
glVertex2i( (pts[i].x * h) + h, (pts[i].y*h) + h);
glVertex2i( (pts[i].x)*h, (pts[i].y * h) + h);
glEnd();
} else if ( pts[i].visited ) {
glColor3f(0.5, 0.5, 0.5);
glBegin(GL_POLYGON);
glVertex2i( (pts[i].x)*h, (pts[i].y)*h);
glVertex2i( (pts[i].x * h) + h, (pts[i].y)*h);
glVertex2i( (pts[i].x * h) + h, (pts[i].y*h) + h);
glVertex2i( (pts[i].x)*h, (pts[i].y * h) + h);
glEnd();
}
}
// draw srcPt and endPt
if ( clickCount > 0 ) {
glColor3f(0, 0.8, 0);
glBegin(GL_POLYGON);
glVertex2i(pts[source].x*h, pts[source].y*h);
glVertex2i((pts[source].x*h)+h, pts[source].y*h);
glVertex2i((pts[source].x*h)+h, (pts[source].y*h)+h);
glVertex2i(pts[source].x*h, (pts[source].y*h)+h);
glEnd();
}
if ( clickCount > 1 ) {
glColor3f(0.8, 0, 0);
glBegin(GL_POLYGON);
glVertex2i(pts[end].x*h, pts[end].y*h);
glVertex2i((pts[end].x*h)+h, pts[end].y*h);
glVertex2i((pts[end].x*h)+h, (pts[end].y*h)+h);
glVertex2i(pts[end].x*h, (pts[end].y*h)+h);
glEnd();
}
glColor3f(0, 0.8, 0);
int index = current;
while ( pts[index].parent != -1 ) {
glBegin(GL_POLYGON);
glVertex2i(pts[index].x*h, pts[index].y*h);
glVertex2i((pts[index].x*h)+h, pts[index].y*h);
glVertex2i((pts[index].x*h)+h, (pts[index].y*h)+h);
glVertex2i(pts[index].x*h, (pts[index].y*h)+h);
glEnd();
index = pts[index].parent;
}
glColor3f(0,0,0);
// drawing vertical grid lines
for (int i = 0; i < wsize; i += h) {
glBegin(GL_LINES);
glVertex2i(0, i);
glVertex2i(wsize, i);
glEnd();
}
// drawing horizontal grid lines
for (int i = 0; i < wsize; i += h) {
glBegin(GL_LINES);
glVertex2i(i, 0);
glVertex2i(i, wsize);
glEnd();
}
/*
// draw path
if ( drawPath ) {
glColor3f(0, 0.8, 0);
int index = end;
while ( pts[index].parent != -1 ) {
glBegin(GL_POLYGON);
glVertex2i(pts[index].x*h, pts[index].y*h);
glVertex2i((pts[index].x*h)+h, pts[index].y*h);
glVertex2i((pts[index].x*h)+h, (pts[index].y*h)+h);
glVertex2i(pts[index].x*h, (pts[index].y*h)+h);
glEnd();
index = pts[index].parent;
}
}
*/
glFlush();
}
void displayPath( )
{
glClear(GL_COLOR_BUFFER_BIT);
glColor3f(0, 0.8, 0);
int index = end;
while ( pts[index].parent != -1 ) {
glBegin(GL_POLYGON);
glVertex2i(pts[index].x*h, pts[index].y*h);
glVertex2i((pts[index].x*h)+h, pts[index].y*h);
glVertex2i((pts[index].x*h)+h, (pts[index].y*h)+h);
glVertex2i(pts[index].x*h, (pts[index].y*h)+h);
glEnd();
index = pts[index].parent;
}
glFlush();
}
|
3b3428ebb5dfebb7958d887cc7564830d4e4078d
|
6bbcea857ff801abafc83a3cd8cf164f4cea15ae
|
/Libraries/Rendering/Caustic/Texture.cpp
|
9fa2db1339f4ccfc12e78fc9ee73426d25e8a9c7
|
[
"MIT"
] |
permissive
|
pat-sweeney/Caustic
|
3259d0bfd816c338902f1cfde9f9abc196fb8c11
|
683761c5e44964ee0cc726cebcf9feb9a95eee1c
|
refs/heads/master
| 2023-07-06T06:51:04.962968
| 2023-06-26T05:36:32
| 2023-06-26T05:36:32
| 144,092,641
| 2
| 0
|
MIT
| 2022-12-08T03:57:28
| 2018-08-09T02:44:59
|
C++
|
UTF-8
|
C++
| false
| false
| 14,318
|
cpp
|
Texture.cpp
|
//**********************************************************************
// Copyright Patrick Sweeney 2015-2023
// Licensed under the MIT license.
// See file LICENSE for details.
//**********************************************************************
module;
#include <memory>
#include <wincodec.h>
#include <objbase.h>
#include <map>
#include <d3d11.h>
#include <string>
#include <atlbase.h>
module Rendering.Caustic.Texture;
import Base.Core.Core;
import Base.Core.Error;
import Base.Core.RefCount;
import Base.Core.IRefCount;
import Imaging.Image.IImage;
import Imaging.Image.ImageIter;
import Rendering.Caustic.ITexture;
import Rendering.Caustic.IRenderer;
namespace Caustic
{
//**********************************************************************
// Function: CopyFromImage
// Copies an image's pixels into a texture
//
// Parameters:
// pRenderer - Renderer
// pImage - image to use
//**********************************************************************
void CTexture::CopyFromImage(IRenderer* pRenderer, IImage* pImage, bool generateMipMap /* = false */)
{
pRenderer->RunOnRenderer(
[&](IRenderer* pRenderer) {
DXGI_FORMAT format = DXGI_FORMAT_R8G8B8A8_UNORM;
bool fastCopy = false;
switch (pImage->GetBPP())
{
case 1:
format = DXGI_FORMAT::DXGI_FORMAT_R8_UNORM;
break;
case 8:
format = DXGI_FORMAT::DXGI_FORMAT_R8_UNORM;
fastCopy = true;
break;
case 16:
format = DXGI_FORMAT::DXGI_FORMAT_R16_UINT;
fastCopy = true;
break;
case 24:
format = (pImage->GetImageType() == EImageType::RGBA_32bpp) ?
DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM :
DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM;
break;
case 32:
format = (pImage->GetImageType() == EImageType::RGBA_32bpp) ?
DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM :
DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM;
fastCopy = true;
break;
case 128: // Image with 4 floats per pixel
format = DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT;
fastCopy = true;
break;
}
D3D11_MAPPED_SUBRESOURCE ms;
auto ctx = pRenderer->GetContext();
CT(ctx->Map(GetD3DTexture(), 0, D3D11_MAP_WRITE_DISCARD, 0, &ms));
if (fastCopy)
{
BYTE* pDst = reinterpret_cast<BYTE*>(ms.pData);
BYTE* pSrc = pImage->GetData();
int h = pImage->GetHeight();
int w = pImage->GetWidth();
int bps = w * pImage->GetBPP() / 8;
int stride = pImage->GetStride();
for (int y = 0; y < (int)h; y++)
{
memcpy(pDst, pSrc, bps);
pSrc += stride;
pDst += ms.RowPitch;
}
}
else
{
CImageIterGeneric srcRow(pImage, 0, 0);
BYTE* pr = reinterpret_cast<BYTE*>(ms.pData);
for (int y = 0; y < (int)pImage->GetHeight(); y++)
{
CImageIterGeneric srcCol = srcRow;
BYTE* pc = pr;
for (int x = 0; x < (int)pImage->GetWidth(); x++)
{
switch (format)
{
case DXGI_FORMAT::DXGI_FORMAT_R8_UNORM:
pc[0] = srcCol.GetRed();
pc++;
break;
case DXGI_FORMAT::DXGI_FORMAT_R16_UINT:
((uint16*)pc)[0] = (uint16)srcCol.GetGray();
pc += 2;
break;
case DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM:
pc[0] = srcCol.GetRed();
pc[1] = srcCol.GetGreen();
pc[2] = srcCol.GetBlue();
pc[3] = srcCol.GetAlpha();
pc += 4;
break;
case DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM:
pc[0] = srcCol.GetBlue();
pc[1] = srcCol.GetGreen();
pc[2] = srcCol.GetRed();
pc[3] = srcCol.GetAlpha();
pc += 4;
break;
case DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT:
break;
}
srcCol.Step(CImageIter::Right);
}
pr += ms.RowPitch;
srcRow.Step(CImageIter::Down);
}
}
ctx->Unmap(GetD3DTexture(), 0);
if (generateMipMap && format == DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM)
GenerateMips(pRenderer);
}, true);
}
void CTexture::CopyToImage(IRenderer* pRenderer, IImage* pImage)
{
pRenderer->RunOnRenderer(
[&](IRenderer* pRenderer) {
int bpp = 32;
switch (m_Format)
{
case DXGI_FORMAT::DXGI_FORMAT_R8_UNORM:
bpp = 8;
break;
case DXGI_FORMAT::DXGI_FORMAT_R16_UINT:
bpp = 16;
break;
case DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM:
case DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM:
bpp = 32;
break;
case DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT:
bpp = 128;
break;
}
CT((pImage->GetBPP() == bpp) ? S_OK : E_FAIL);
CT((pImage->GetWidth() == m_Width) ? S_OK : E_FAIL);
CT((pImage->GetHeight() == m_Height) ? S_OK : E_FAIL);
D3D11_MAPPED_SUBRESOURCE ms;
auto ctx = pRenderer->GetContext();
CComPtr<ID3D11Texture2D> spTex = GetD3DTexture();
CT(ctx->Map(spTex, 0, D3D11_MAP_READ, 0, &ms));
BYTE* pSrc = reinterpret_cast<BYTE*>(ms.pData);
BYTE* pDst = pImage->GetData();
int stride = pImage->GetStride();
if (ms.RowPitch == stride)
{
CopyMemory(pDst, pSrc, m_Height * stride);
}
else
{
for (int y = 0; y < (int)m_Height; y++)
{
memcpy(pDst, pSrc, m_Width * bpp / 8);
pSrc += ms.RowPitch;
pDst += stride;
}
}
ctx->Unmap(spTex, 0);
}, true);
}
//**********************************************************************
// Function: CopyToImage
// Copies an texture's pixels into an <IImage>
//
// Parameters:
// pRenderer - Renderer
//**********************************************************************
CRefObj<IImage> CTexture::CopyToImage(IRenderer* pRenderer)
{
EImageType imageType;
switch (m_Format)
{
case DXGI_FORMAT::DXGI_FORMAT_R8_UNORM:
imageType = EImageType::Gray_8bpp;
break;
case DXGI_FORMAT::DXGI_FORMAT_R16_UINT:
imageType = EImageType::Gray_16bpp;
break;
case DXGI_FORMAT::DXGI_FORMAT_R8G8B8A8_UNORM:
imageType = EImageType::RGBA_32bpp;
break;
case DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM:
imageType = EImageType::BGRA_32bpp;
break;
case DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT:
imageType = EImageType::Float4_128bpp;
break;
}
CRefObj<IImage> spImage = Caustic::CreateImage(m_Width, m_Height, imageType);
CopyToImage(pRenderer, spImage);
return spImage;
}
//**********************************************************************
// Function: Copy
// Copies a texture to another texture
//
// Parameters:
// pRenderer - Renderer
//**********************************************************************
void CTexture::Copy(IRenderer* pRenderer, ITexture* pDstTex)
{
pRenderer->RunOnRenderer(
[&](IRenderer* pRenderer) {
ID3D11Texture2D* pSrc = GetD3DTexture();
ID3D11Texture2D* pDst = pDstTex->GetD3DTexture();
pRenderer->GetContext()->CopyResource(pDst, pSrc);
}, true);
}
//**********************************************************************
// Function: GenerateMips
// Generates the MIPMAP chain for a texture
//
// Parameters:
// pRenderer - Renderer
//**********************************************************************
void CTexture::GenerateMips(IRenderer *pRenderer)
{
pRenderer->RunOnRenderer(
[&](IRenderer* pRenderer) {
CD3D11_TEXTURE2D_DESC desc(m_Format, m_Width, m_Height);
desc.Usage = D3D11_USAGE_DEFAULT;
desc.CPUAccessFlags = 0;
desc.MipLevels = 0;
desc.BindFlags = D3D11_BIND_SHADER_RESOURCE | D3D11_BIND_RENDER_TARGET;
desc.MiscFlags = D3D11_RESOURCE_MISC_GENERATE_MIPS;
CComPtr<ID3D11Texture2D> spTexture;
CT(pRenderer->GetDevice()->CreateTexture2D(&desc, nullptr, &spTexture));
pRenderer->GetContext()->CopySubresourceRegion(spTexture, 0, 0, 0, 0, m_spTexture, 0, NULL);
m_spTexture = spTexture;
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{};
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = (UINT)-1;
m_spTextureRV = nullptr;
CT(pRenderer->GetDevice()->CreateShaderResourceView(m_spTexture, &srvDesc, &m_spTextureRV));
pRenderer->GetContext()->GenerateMips(m_spTextureRV);
}, true);
}
//**********************************************************************
// Constructor: CTexture
// Ctor for our texture wrapper object
//
// Parameters:
// pRenderer - Graphics renderer
// width - Width of image in pixels
// height - Height of image in pixels
// format - Defines the pixel format for the image
// cpuFlags - Flags indicating allowed access to texture from CPU (see D3D11 documentation)
// bindFlags - bind flags (see D3D11 documentation)
//**********************************************************************
CTexture::CTexture(IRenderer *pRenderer, uint32 width, uint32 height, DXGI_FORMAT format, D3D11_CPU_ACCESS_FLAG cpuFlags, D3D11_BIND_FLAG bindFlags) :
m_Format(format),
m_Width(width),
m_Height(height)
{
CT(pRenderer->IsRenderThread() ? S_OK : E_FAIL);
CD3D11_TEXTURE2D_DESC desc(format, width, height);
if (cpuFlags & D3D11_CPU_ACCESS_READ)
desc.Usage = D3D11_USAGE_STAGING;
else if (cpuFlags & D3D11_CPU_ACCESS_WRITE)
desc.Usage = D3D11_USAGE_DYNAMIC;
else
desc.Usage = D3D11_USAGE_DEFAULT;
desc.CPUAccessFlags = cpuFlags;
desc.MipLevels = 1;
desc.BindFlags = bindFlags;
CT(pRenderer->GetDevice()->CreateTexture2D(&desc, nullptr, &m_spTexture));
if (desc.Usage == D3D11_USAGE_DYNAMIC || desc.Usage == D3D11_USAGE_DEFAULT)
{
D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc{};
srvDesc.Format = desc.Format;
srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
srvDesc.Texture2D.MipLevels = 1;
CT(pRenderer->GetDevice()->CreateShaderResourceView(m_spTexture, &srvDesc, &m_spTextureRV));
}
}
CTexture::CTexture(ID3D11Texture2D* pD3DTexture, ID3D11ShaderResourceView* pD3DRV)
{
m_spTextureRV = pD3DRV;
m_spTexture = pD3DTexture;
}
CTexture::~CTexture()
{
}
uint32 CTexture::GetWidth()
{
return m_Width;
}
uint32 CTexture::GetHeight()
{
return m_Height;
}
DXGI_FORMAT CTexture::GetFormat()
{
return m_Format;
}
void CTexture::Render(IRenderer* pRenderer, int slot, bool isPixelShader)
{
pRenderer->RunOnRenderer(
[&](IRenderer* pRenderer)
{
auto ctx = pRenderer->GetContext();
if (m_spTexture != nullptr)
{
CComPtr<ID3D11ShaderResourceView> spResource = m_spTextureRV;
if (isPixelShader)
ctx->PSSetShaderResources(slot, 1, &spResource.p);
else
ctx->VSSetShaderResources(slot, 1, &spResource.p);
}
else
{
// No valid texture?! Checkerboard it
CRefObj<ITexture> spTexture = CheckerboardTexture(pRenderer);
CComPtr<ID3D11ShaderResourceView> spResource = spTexture->GetD3DTextureRV();
if (isPixelShader)
ctx->PSSetShaderResources(slot, 1, &spResource.p);
else
ctx->VSSetShaderResources(slot, 1, &spResource.p);
}
});
return;
}
};
|
d3a93a0fd3cf6799f6236fc0bb7ba305715dce5a
|
c566110212dd54bd3b38db0dcc5c4a3e5a3fdef7
|
/arduino_sketchbook/out176_a2/out176_a2.ino
|
8ceb342744c28483ada46eedb619a918e2c558fc
|
[] |
no_license
|
pantonvich/HomeAutomation
|
b9dde8144b484d7dbd632222fbd497ec126f0297
|
8efdce6b6675b1adf01a52823dfc283157c81dcd
|
refs/heads/master
| 2020-12-24T07:24:09.360552
| 2016-08-05T23:13:50
| 2016-08-05T23:13:50
| 64,971,893
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 32,552
|
ino
|
out176_a2.ino
|
#include <SPI.h>
#include <Ethernet.h>
#include <avr/wdt.h>
//#define FREERAM
#define DEBUG
//#define TEST
#define IP176
#define VERSION_BUILD 3
//#define IP177
//#define VERSION_BUILD 0
//#define TEST
//#define IP178
//#define IP179
//#define VERSION_BUILD 0
//#define IP180
#define ALERT_NONE 0
#define ALERT_WATER 1
#define ALERT_BELL 2
#define ALERT_RAIN 3
int AlertType = ALERT_NONE; //0=none, 1=rain, 2=water, 3 = bell
long AlertValue = 0;
#ifdef DEBUG
#define DEBUG_PRINT(str0,str1) \
Serial.print(millis()); \
Serial.print(": "); \
Serial.print(__PRETTY_FUNCTION__); \
Serial.print(' '); \
Serial.print(__FILE__); \
Serial.print(':'); \
Serial.print(__LINE__); \
Serial.print(' '); \
Serial.print(str0); \
Serial.print(' '); \
Serial.println(str1);
#else
#define DEBUG_PRINT(str0,str1)
#endif
#define VERSION_MAJOR '_'
#define VERSION_MINOR 'a'
#ifdef IP176
#ifndef TEST
#define DEFINED_SEND_INTERVAL 300000
#define ip4 176
#define getURL F("GET /outbash.cgi?")
#endif
//#define POWER_APIN A0
#define RAIN_APIN A5
#define PYRANOMETER_APIN A2
//#define GAS_APIN A1
#define SD_CARD_DPIN 4
//#define WATER_DPIN 6
//#define INSIDE_ONEWIRE_DPIN 7
#define OUTSIDE_ONEWIRE_DPIN 8
//#define RESET_DPIN 9
#endif
#ifdef IP177
#ifndef TEST
#define DEFINED_SEND_INTERVAL 300000
#define ip4 177
#define getURL F("GET /ardbash.cgi?")
#endif
#define POWER_APIN A0
//#define RAIN_APIN A5
//#define PYRANOMETER_APIN A2
#define GAS_APIN A1
#define SD_CARD_DPIN 4
#define WATER_DPIN 6
#define INSIDE_ONEWIRE_DPIN 7
#define OUTSIDE_ONEWIRE_DPIN 8
#define RESET_DPIN 9
#endif
#ifdef IP179
#ifndef TEST
#define DEFINED_SEND_INTERVAL 120000
#define ip4 179
#define getURL F("GET /windbash.cgi?")
#endif
//#define POWER_APIN A0
//#define RAIN_APIN A5
//#define PYRANOMETER_APIN A2
//#define GAS_APIN A1
#define SD_CARD_DPIN 4
//#define WATER_DPIN 6
//#define INSIDE_ONEWIRE_DPIN 7
//#define OUTSIDE_ONEWIRE_DPIN 8
#define DHT_BASEMENT_PIN 2
#define DHT_BASEMENT_PIN1 3
//#define DHT_BASEMENT_PIN2 6
#define BELL_PIN 5
#define WD_PIN 8
#define WS_PIN 9
#define RESET_DPIN 14 //A0
#define WS_DEBOUNCE 2
#define BELL_DEBOUNCE 500
#include "DHT.h"
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
#ifdef DHT_BASEMENT_PIN
DHT dht(DHT_BASEMENT_PIN, DHTTYPE);
#endif
#ifdef DHT_BASEMENT_PIN1
DHT dht1(DHT_BASEMENT_PIN1, DHTTYPE);
#endif
#ifdef DHT_BASEMENT_PIN2
DHT dht2(DHT_BASEMENT_PIN2, DHTTYPE);
#endif
#define GUST_INTERVAL 10000
#endif
#ifdef TEST
// byte ip4 = 15
// #define getURL F("GET /tstbash.cgi?")
#define getURL "GET /testbash.cgi?"
#define ip4 179
#define DEFINED_SEND_INTERVAL 10000
#endif
byte mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, ip4};
byte ip[] = { 192, 168, 0, ip4};
byte gateway[] = { 192, 168, 0, 1 };
byte subnet[] = { 255, 255, 255, 0 };
byte rip[4];
#if defined(INSIDE_ONEWIRE_DPIN) || defined(OUTSIDE_ONEWIRE_DPIN)
unsigned long ONEWIRE_DELAY = 10;
#endif
unsigned long RESET_INTERVAL = 300000;
unsigned long SEND_INTERVAL = DEFINED_SEND_INTERVAL;
unsigned long currentMillis =0;
unsigned long lastConnectMillis=SEND_INTERVAL;
unsigned long ClientMillis=0;
unsigned long resetMillis=0;
unsigned long ctLoop = 0;
#ifdef RESET_DPIN
unsigned int resetSendCt = 0; //reboot hack
#endif
#define STRING_BUFFER_SIZE 400
char outbuffer[STRING_BUFFER_SIZE+2];
unsigned long outbufferIdx = 0;
#define STRING_GetBuffer_SIZE 20
char GetBuffer[STRING_GetBuffer_SIZE+2];
unsigned int GetBufferIdx=0;
//int lastday = 0;
EthernetServer server(80);
EthernetClient client;
void setup()
{
#ifdef RESET_DPIN
digitalWrite(RESET_DPIN, HIGH); //this is a hack!
wdt_disable();
pinMode(RESET_DPIN, OUTPUT);
#endif
Ethernet.begin(mac, ip, gateway, gateway, subnet);
server.begin();
#ifdef DEBUG
Serial.begin(115200);
DEBUG_PRINT("str","");
#endif
analogReference(DEFAULT);
#ifdef GAS_APIN
pinMode(GAS_APIN, INPUT);
#endif
#ifdef POWER_APIN
pinMode(POWER_APIN, INPUT);
#endif
#ifdef PYRANOMETER_APIN
pinMode(PYRANOMETER_APIN, INPUT);
#endif
#ifdef RAIN_APIN
pinMode(RAIN_APIN, INPUT);
#endif
#ifdef WATER_DPIN
pinMode(WATER_DPIN, INPUT);
//waterLastRead = digitalRead(WATER_DPIN);
//for(int x = 0;x<5;x++) water5[x] = 0;
digitalWrite(WATER_DPIN,HIGH);
#endif
#ifdef SD_CARD_DPIN
//disable SD card
pinMode(SD_CARD_DPIN, OUTPUT);
digitalWrite(SD_CARD_DPIN, HIGH);
#endif
#ifdef BELL_PIN
pinMode(BELL_PIN, INPUT);
digitalWrite(BELL_PIN,HIGH);
#endif
#ifdef WS_PIN
pinMode(WS_PIN, INPUT);
pinMode(WD_PIN, INPUT);
digitalWrite(WS_PIN,HIGH);
digitalWrite(WD_PIN,HIGH);
#endif
#ifdef RESET_DPIN
//wdt_enable(WDTO_8S);
// clear various "reset" flags
MCUSR = 0;
// allow changes, disable reset
WDTCSR = bit (WDCE) | bit (WDE);
// set interrupt mode and an interval
WDTCSR = bit (WDIE) | bit (WDP3) | bit (WDP0); // set WDIE, and 8 seconds delay
#endif
outbuffer[outbufferIdx++] = '*';
}
void runLoops()
{
#ifdef RESET_DPIN
wdt_reset();
#endif
currentMillis = millis();
#ifdef POWER_APIN
PowerLoop();
#endif
#ifdef GAS_APIN
GasLoop();
#endif
#ifdef WATER_DPIN
WaterLoop();
#endif
#ifdef PYRANOMETER_APIN
PyranometerRead();
#endif
#ifdef RAIN_APIN
RainRead();
#endif
#ifdef BELL_PIN
BellLoop();
#endif
#ifdef WS_PIN
WindLoop();
#endif
ctLoop++;
}
void runDelayLoops(int milliseconds)
{
static unsigned long holdMillis;
holdMillis = currentMillis;
while (holdMillis - currentMillis < milliseconds)
{
runLoops();
}
}
void loop()
{
runLoops();
ServerMode();
if (currentMillis - lastConnectMillis > SEND_INTERVAL ) //|| outbuffer[1] == '*'
{
ClientMode();
resetAll();
lastConnectMillis = currentMillis;
//TimeAdj();
#ifdef WS_PIN
SetLastDay();
#endif
//we got a connect so reset or add one to reset count
#ifdef RESET_DPIN
if(GetBufferIdx>13) {resetSendCt = 0;} else {resetSendCt++; }
DEBUG_PRINT("resetSendCt",resetSendCt);
DEBUG_PRINT("GetBufferIdx",GetBufferIdx);
//reboot hack
if (resetSendCt > 3) { digitalWrite(RESET_DPIN, LOW); }
#endif
}
}
#ifdef RESET_DPIN
ISR (WDT_vect)
{
DEBUG_PRINT("ISR","");
wdt_disable();
delay(5000);
digitalWrite(RESET_DPIN, LOW);
}
#endif
void ServerMode()
{
char c;
int flag = 0;
unsigned long connectLoop = 0;
client = server.available();
if (client) {
// an http request ends with a blank line
boolean current_line_is_blank = true;
GetBufferIdx = 0;
while (client.connected()) {
unsigned long startTime = millis();
while ((!client.available()) && ((millis() - startTime ) < 5000)){
runLoops();
};
if (client.available()) {
if (connectLoop++ > 10000) break;
c = client.read();
if (flag<2 && GetBufferIdx < STRING_GetBuffer_SIZE )
{
if (flag==1 && c==' ')
flag=2;
if (flag==1) {
GetBuffer[GetBufferIdx++] = c;
}
if (flag==0 && c == '/')
flag = 1;
}
// if we've gotten to the end of the line (received a newline
// character) and the line is blank, the http request has ended,
// so we can send a reply
if (c == '\n' && current_line_is_blank) {
client.println(F("HTTP/1.1 200 OK"));
client.println(F("Content-Type: text/html"));
client.println(F("Connection: close"));
client.println();
client.print(F("<!DOCTYPE html><html><head><link rel=""icon"" type=""image/png"" href=""data:image/png;base64,iVBORw0KGgo=""></head><body>"));
BuildOutput();
client.print(outbuffer);
DEBUG_PRINT(F("outbuffer"), outbuffer);
client.println(F("</body></html>"));
client.println();
break;
}
if (c == '\n') {
// we're starting a new line
current_line_is_blank = true;
} else if (c != '\r') {
// we've gotten a character on the current line
current_line_is_blank = false;
}
}
if (connectLoop++ > 10000) break;
}
DEBUG_PRINT(F("connectLoop"),connectLoop);
// give the web browser time to receive the data
runDelayLoops(2);
client.flush();
client.stop();
GetBuffer[GetBufferIdx]='\0';
//DEBUG_PRINT(GetBuffer);
}
}
#if defined(INSIDE_ONEWIRE_DPIN) || defined(OUTSIDE_ONEWIRE_DPIN)
#include <OneWire.h>
void GetOneWireTemps(int pinToRead) {
int HighByte, LowByte, TReading, SignBit, Tc_100, Whole, Fract, Tf_100;
OneWire ds(pinToRead);
byte i;
byte present = 0;
byte data[12];
byte addr[8];
int ct = 0;
while (ct != -1) {
if ( !ds.search(addr)) {
ds.reset_search();
return;
}
if ( OneWire::crc8( addr, 7) != addr[7]) {
//DEBUG_PRINT("CRC is not valid!\n");
return;
}
if ( addr[0] == 0x28) {
// The DallasTemperature library can do all this work for you!
ds.reset();
ds.select(addr);
ds.write(0x44,0); // start conversion, with parasite power on at the end
runDelayLoops(ONEWIRE_DELAY);
//delay(1000); // maybe 750ms is enough, maybe not
// we might do a ds.depower() here, but the reset will take care of it.
present = ds.reset();
ds.select(addr);
ds.write(0xBE); // Read Scratchpad
for ( i = 0; i < 9; i++) { // we need 9 bytes
data[i] = ds.read();
}
runDelayLoops(10);
LowByte = data[0];
HighByte = data[1];
TReading = (HighByte << 8) + LowByte;
SignBit = TReading & 0x8000; // test most sig bit
if (SignBit) // negative
{
TReading = (TReading ^ 0xffff) + 1; // 2's comp
}
Tc_100 = (6 * TReading) + TReading / 4; // multiply by (100 * 0.0625) or 6.25
//Tf_100 = (9/5)*Tc_100+32;
//Whole = ((9 * Tc_100 / 5) + 3200) / 100; // separate off the whole and fractional portions
//Fract = ((9 * Tc_100 / 5) + 3200) % 100;
int W100, W10, W1, F1, F10;
char temp[6];
itoa(addr[7],temp,16);
bTitle(temp[0],temp[1]);
W100 = Tc_100 / 10000;
W10 = Tc_100 / 1000 - W100 * 10;
W1 = Tc_100 / 100 - W10 * 10 - W100 * 100;
F1 = Tc_100 / 10 - W1 *10 - W10 * 100 - W100 * 1000;
F10 = Tc_100 - F1 * 10 - W1 * 100 - W10 * 1000 - W100 * 10000;
if (SignBit) {
outbuffer[outbufferIdx++] = '-';
}
//buffer[outbufferIdx++] = 48+W100;
outbuffer[outbufferIdx++] = 48+W10;
outbuffer[outbufferIdx++] = 48+W1;
outbuffer[outbufferIdx++] = '.';
outbuffer[outbufferIdx++] = 48+F1;
outbuffer[outbufferIdx++] = 48+F10;
}
}
}
#endif
#ifdef POWER_APIN
float powerTripLow = .90;
float powerTripHigh = 1.008;
unsigned long powerCount = 0;
unsigned long powerCountLast = 0;
unsigned long powerLastBlink = 0;
unsigned long powerK5count =0;
unsigned long powerW1=0;
unsigned long powerW2=0;
unsigned long powerW3=0;
unsigned long powerW4=0;
unsigned long powerW5=0;
//unsigned long powerW6=0;
float powerBlinkLength = 80;
float powerBlinkRate = 200;
int powerBlinkFlag = 1;
float powerRatio = 1.0;
float powerFilterH = 600;
float powerFilterC = 600;
float powerMaxL = 1;
float powerMaxH = 0;
int powerReading = 0;
void PowerLoop() {
powerReading = analogRead(POWER_APIN);
powerFilterH += .01 * (powerReading-powerFilterH);
powerFilterC += .9 * (powerReading-powerFilterC);
powerRatio = powerFilterC/powerFilterH;
if (powerRatio < powerMaxL) powerMaxL = powerRatio;
if (powerRatio > powerMaxH) powerMaxH = powerRatio;
if ((powerRatio < powerTripLow && powerBlinkFlag ==1 && currentMillis-powerLastBlink > 50) )
{
powerBlinkFlag = 0;
powerCount++;
float rate = currentMillis-powerLastBlink;
if(rate>0) powerBlinkRate += .05 *(rate-powerBlinkRate);
powerLastBlink = currentMillis;
}
else if (powerRatio > powerTripHigh && powerBlinkFlag == 0)
{
if ( currentMillis-powerLastBlink > 30 ){
float rate = currentMillis-powerLastBlink;
if (rate>0) powerBlinkLength += .05*(rate-powerBlinkLength);
powerBlinkFlag = 1;
}
}
unsigned long w = currentMillis - lastConnectMillis;
if ( w < 60000) { powerW1 = powerCount; }
else if (w < 120000) { powerW2 = powerCount; }
else if (w < 180000) { powerW3 = powerCount; }
else if (w < 240000) { powerW4 = powerCount; }
//else if (w < 300000) { powerW5 = powerCount; }
else { powerW5 = powerCount;}
}
void bPrintPower(char c1, char c2, unsigned long p1, unsigned long p0)
{
if(p1 == 0 )
bPrint(c1,c2,0,100);
else
bPrint(c1,c2,p1-p0,100);
}
#endif
#ifdef GAS_APIN
int gasTripOffset = 15; //75;
unsigned long gasTotalCount = 0;
unsigned long gasLastCount = 0;
unsigned long gaslastMillis = 0;
unsigned long gasReading = 0;
unsigned int gasFlag = 0;
unsigned long gasTripHigh = 0;
unsigned long gasTripLow = 1023;
float gasFilterL = 900;
unsigned long gasLowLow = 1023;
unsigned long gasMaxMax = 0;
void GasLoop()
{
gasReading = analogRead(GAS_APIN);
gasFilterL += .01 * (gasReading-gasFilterL);
gasReading = gasFilterL;
if (gasReading>gasTripHigh) {
if (gasFlag == 1){
gasFlag =0;
gasTotalCount++;
}
gasTripLow = gasReading - gasTripOffset;
gasTripHigh = gasReading;
}
if (gasReading<gasTripLow) {
gasFlag = 1;
gasTripHigh = gasReading + gasTripOffset;
gasTripLow = gasReading;
}
if(gasReading<gasLowLow) gasLowLow=gasReading;
if(gasReading>gasMaxMax) gasMaxMax=gasReading;
}
#endif
#ifdef WATER_DPIN
unsigned long waterTotal = 0;
int waterLastRead = LOW;
unsigned long waterHitMillis = 0;
unsigned int water5[6];
unsigned long WATER_DEBOUNCE = 10;
void WaterLoop()
{
if (digitalRead(WATER_DPIN) != waterLastRead && (currentMillis - waterHitMillis > WATER_DEBOUNCE) ) {
waterHitMillis = currentMillis;
AlertType = ALERT_WATER;
waterLastRead = !waterLastRead;
waterTotal++; //if(waterLastRead == LOW)
ClientMode();
//AlertType = ALERT_NONE;
}
unsigned long w = currentMillis - lastConnectMillis;
if ( w < 60000) { water5[1] = waterTotal; }
else if (w < 120000) { water5[2] = waterTotal; }
else if (w < 180000) { water5[3] = waterTotal; }
else if (w < 240000) { water5[4] = waterTotal; }
water5[5] = waterTotal;
}
#endif
#ifdef PYRANOMETER_APIN
// pyranometer
// ------+-----------A
// |
// 10K
// |
// +-----+-----------gnd
//
#define PYRANOMETER_INTERVAL 1000
unsigned int PyranometerReading = 0;
unsigned long LastPyranometerMillis=PYRANOMETER_INTERVAL;
float PyranometerFilter = 0.0;
void PyranometerRead(){
if (currentMillis - LastPyranometerMillis > PYRANOMETER_INTERVAL )
{
PyranometerReading = analogRead(PYRANOMETER_APIN);
PyranometerFilter += .01 * ((float)PyranometerReading-PyranometerFilter);
LastPyranometerMillis = currentMillis;
}
}
#endif
#ifdef RAIN_APIN
// rain_detector
// +-----------A
// |
// ||----+----100K---5+
// +-----------------gnd
//
#define RAIN_INTERVAL 1000
//3hours
#define RAIN_ALERT_INTERVAL 10800000
unsigned long rainLow = 1024;
unsigned long rainHigh = 0;
float rainFilter = 0.0;
float rainFilterLast = 0.0;
unsigned long LastRainMillis = 0;
unsigned long LastRainAlertMillis800 = RAIN_ALERT_INTERVAL;
unsigned long LastRainAlertMillis700 = RAIN_ALERT_INTERVAL;
unsigned long LastRainAlertMillis600 = RAIN_ALERT_INTERVAL;
unsigned long LastRainAlertMillis500 = RAIN_ALERT_INTERVAL;
unsigned long LastRainAlertMillis400 = RAIN_ALERT_INTERVAL;
unsigned int rainRead;
void RainRead() {
if (currentMillis - LastRainMillis > RAIN_INTERVAL )
{
LastRainMillis = currentMillis;
rainRead = analogRead(RAIN_APIN);
if (rainRead < rainLow) rainLow = rainRead;
if (rainRead > rainHigh) rainHigh = rainRead;
rainFilter += .01 * ((float)rainRead-rainFilter);
if (rainFilter < 800 && (currentMillis - LastRainAlertMillis800 > RAIN_ALERT_INTERVAL)) {
AlertType = ALERT_RAIN;
LastRainAlertMillis800=currentMillis;
}
if (rainFilter < 700 && (currentMillis - LastRainAlertMillis700 > RAIN_ALERT_INTERVAL)) {
AlertType = ALERT_RAIN;
LastRainAlertMillis700=currentMillis;
}
if (rainFilter < 600 && (currentMillis - LastRainAlertMillis600 > RAIN_ALERT_INTERVAL)) {
AlertType = ALERT_RAIN;
LastRainAlertMillis600=currentMillis;
}
if (rainFilter < 500 && (currentMillis - LastRainAlertMillis500 > RAIN_ALERT_INTERVAL)) {
AlertType = ALERT_RAIN;
LastRainAlertMillis500=currentMillis;
}
if (rainFilter < 400 && (currentMillis - LastRainAlertMillis400 > RAIN_ALERT_INTERVAL)) {
AlertType = ALERT_RAIN;
LastRainAlertMillis400=currentMillis;
}
//DEBUG_PRINT("AlertType",AlertType);
if (AlertType != ALERT_NONE ) {
DEBUG_PRINT("ClientMode","AlertType");
ClientMode();
//Reset AlertType = ALERT_NONE;
ClientMode();
}
}
}
#endif
#ifdef BELL_PIN
int bellLastRead = LOW;
unsigned long bellHitMillis=0;
unsigned long bellTotal = 0;
unsigned int bell2Min = 0;
void BellLoop()
{
int bellRead =digitalRead(BELL_PIN);
if (bellRead == HIGH && bellLastRead==LOW && (currentMillis - bellHitMillis > BELL_DEBOUNCE))
{
bellTotal++;
bell2Min++;
bellHitMillis=currentMillis;
AlertType = ALERT_BELL;
ClientMode();
}
bellLastRead=bellRead;
}
#endif
#ifdef WS_PIN
int wsLastRead = LOW;
unsigned long wsCt = 0;
unsigned long wsSendCt = 0;
unsigned long wsInterval=0;
unsigned long wsTime;
unsigned long wsHitMillis = 0;
unsigned long wgMaxSendCt = 0;
unsigned long wgNextIntervalMillis = 0;
unsigned long wgMaxTodayCt=0;
unsigned long wgMaxYesterdayCt = 0; //yesterdays max wind
int wdLastRead=LOW;
unsigned long wdInterval;
int wdFlag=LOW;
float wd;
void WindLoop()
{
int wsRead=digitalRead(WS_PIN);
int wdRead=digitalRead(WD_PIN);
if (wsRead==HIGH && wsLastRead==LOW && (currentMillis - wsHitMillis > WS_DEBOUNCE)) {
wsHitMillis=currentMillis;
wsPulse();
wsCt++;
wsSendCt++;
}
if (wdRead==HIGH && wdLastRead==LOW && wdFlag==HIGH ) {
wdPulse();
}
//check 10s gust
//filter 2min wind
if (currentMillis - wgNextIntervalMillis > GUST_INTERVAL)
{
if (wgMaxTodayCt<wsCt) wgMaxTodayCt=wsCt;
//ws2 = ws2 * .91667 + (float)wsCt;
//ws2 += .15 * (wsCt - ws2);
if (wsCt > wgMaxSendCt) wgMaxSendCt = wsCt;
wsCt=0;
//DEBUG_PRINT(bellTotal);
//DEBUG_PRINT(" ");
//DEBUG_PRINTLN(bellLastRead);
wgNextIntervalMillis=currentMillis;
}
wsLastRead=wsRead;
wdLastRead=wdRead;
}
//Use Pulse_A_Interval to calculate wind speed. Use Pulse_B_Interval*360.0/Pulse_A_Interval to get direction of wind.
//http://code.ohloh.net/file?fid=plfSM3O7RAnLnqzfqC-IfeGTw3g&cid=LIfw5qQ_Ip0&s=&fp=490510&mp=&projSelected=true#L0
// * In ULTIMETER Weather Stations, speed is determined by measuring the time interval between
// * two successive closures of the speed reed. Calibration is done as follows (RPS = revolutions
// * per second):
// * 0.010 < RPS < 3.229 (approximately 0.2 < MPH < 8.2):
// * windSpeedDur<309693
// * MPH = -0.1095(RPS2) + 2.9318(RPS) 0.1412
// * KNTS = -0.09515(RPS2) + 2.5476(RPS) 0.1226
// *
// * 3.230 < RPS < 54.362 (approximately 8.2 < MPH < 136.0):
// * windSpeedDur < 18395
/// * MPH = 0.0052(RPS2) + 2.1980(RPS) + 1.1091
// * KNTS = 0.0045(RPS2) + 1.9099(RPS) + 0.9638
// *
// * 54.363 < RPS < 66.332 (approximately 136.0 < MPH < 181.5):
// *
// * MPH = 0.1104(RPS2) - 9.5685(RPS) + 329.87
// * KNTS = 0.09593(RPS2) - 8.3147(RPS) + 286.65
// *
// * Conversions used are: mph * 0.86897 = knots; mph * 1.6094 = kmph; mph * 0.48037 = m/s
int getMPH(float r, float s)
{
if (s<=0 || r <= 0 || r == 4294967295) return 0;
float rps = r/s;
if (rps<.05) return 0;
if (rps< 3.230) return rps * rps * -11 + rps * 293 - 14;
//0.0052(RPS2) + 2.1980(RPS) + 1.1091
if (rps< 54.362) return rps * rps * .52 + rps * 220 + 111;
// * MPH = 0.1104(RPS2) - 9.5685(RPS) + 329.87
return rps * rps * 11 - rps * 957 + 32987;
}
void wsPulse() {
unsigned long currentTime = micros();
wsInterval = currentTime - wsTime;
wsTime = currentTime;
//if (wsInterval>wgMax) wgMax=wsInterval;
wdFlag=HIGH;
}
void wdPulse() {
unsigned long currentTime = micros();
wdInterval = currentTime - wsTime;
if (wsInterval >= wdInterval)
{
wd = wdInterval*360.0/wsInterval;
wdFlag=LOW;
}
}
#endif
#ifdef DHTTYPE
void PrintHum() {
float humidity;
float temperature;
#ifdef DHT_BASEMENT_PIN
humidity = dht.readHumidity();
temperature = dht.readTemperature();
bPrint('0','H',humidity*10,100);
bPrint('0','T',temperature*10,100);
humidity = dht1.readHumidity();
#endif
#ifdef DHT_BASEMENT_PIN1
humidity = dht1.readHumidity();
temperature = dht1.readTemperature();
bPrint('1','H',humidity*10,100);
bPrint('1','T',temperature*10,100);
#endif
#ifdef DHT_BASEMENT_PIN2
humidity = dht2.readHumidity();
temperature = dht2.readTemperature();
bPrint('2','H',humidity*10,100);
bPrint('2','T',temperature*10,100);
#endif
}
#endif
void BuildOutput() {
DEBUG_PRINT(F("BuildOutput"),"");
if (AlertType==ALERT_WATER) {
#ifdef WATER_DPIN
outbuffer[outbufferIdx++] = 'W';
outbuffer[outbufferIdx++] = 'A';
outbuffer[outbufferIdx++] = 'T';
outbuffer[outbufferIdx++] = 'E';
outbuffer[outbufferIdx++] = 'R';
outbuffer[outbufferIdx++] = '0'+waterLastRead;
#endif
} else if (AlertType==ALERT_RAIN) {
#ifdef RAIN_APIN
outbuffer[outbufferIdx++] = 'R';
outbuffer[outbufferIdx++] = 'A';
outbuffer[outbufferIdx++] = 'I';
outbuffer[outbufferIdx++] = 'N';
bPrint('R','f',rainFilter,100);
#endif
} else if (AlertType==ALERT_BELL) {
#ifdef BELL_PIN
outbuffer[outbufferIdx++] = 'B';
outbuffer[outbufferIdx++] = 'E';
outbuffer[outbufferIdx++] = 'L';
outbuffer[outbufferIdx++] = 'L';
#endif
}else {
#ifdef INSIDE_ONEWIRE_DPIN
GetOneWireTemps(INSIDE_ONEWIRE_DPIN);
#endif
#ifdef OUTSIDE_ONEWIRE_DPIN
GetOneWireTemps(OUTSIDE_ONEWIRE_DPIN);
#endif
Print();
}
AlertType=ALERT_NONE;
outbuffer[outbufferIdx] = '\0';
outbufferIdx=0;
}
void Print() {
DEBUG_PRINT(F("Print"),"");
#ifdef POWER_APIN
bPrint('K','0',powerCount,10000);
bPrintPower('w','1', powerW1, powerCountLast);
bPrintPower('w','2', powerW2, powerW1);
bPrintPower('w','3', powerW3, powerW2);
bPrintPower('w','4', powerW4, powerW3);
bPrintPower('w','5', powerW5, powerW4);
bPrint('K','5',powerCount - powerCountLast ,1000);
DEBUG_PRINT(F("K0"),"");
#endif
#ifdef WATER_DPIN
bPrint('H','0',waterTotal,100);
DEBUG_PRINT(F("H0"),waterTotal);
bPrint('H','5',waterTotal-water5[0],1);
DEBUG_PRINT(F("Hw0"),water5[0]);
DEBUG_PRINT(F("Hw1"),water5[1]);
DEBUG_PRINT(F("Hw2"),water5[2]);
DEBUG_PRINT(F("Hw3"),water5[3]);
DEBUG_PRINT(F("Hw4"),water5[4]);
DEBUG_PRINT(F("Hw5"),water5[5]);
for(int x = 1;x<6;x++) {
int t = 0;
DEBUG_PRINT(F("Hw"),water5[x]);
if (water5[x] <= water5[5]) t=water5[x]-water5[x-1];
DEBUG_PRINT(F("t"),t);
if (t<0) t=0;
bPrint('h','0' + x,t,1);
}
DEBUG_PRINT(F("H0"),"");
#endif
#ifdef PYRANOMETER_APIN
bPrint('P','r',PyranometerReading,100);
bPrint('P','f',PyranometerFilter*10,100);
#endif
#ifdef RAIN_APIN
bPrint('R','r',rainRead,1000);
bPrint('R','f',rainFilter,1000);
bPrint('R','L',rainLow,1000);
bPrint('R','H',rainHigh,1000);
#endif
#ifdef POWER_APIN
//bPrint('f','H',powerFilterH,1000);
//bPrint('f','C',powerFilterC,1000);
bPrint('B','L',powerBlinkLength,1000);
bPrint('B','R',powerBlinkRate,1000);
bPrint('M','H',powerMaxH*1000,1000);
bPrint('M','h',powerTripHigh*1000,1000);
bPrint('M','L',powerMaxL*1000,100);
bPrint('M','l',powerTripLow*1000,100);
DEBUG_PRINT(F("BL"),"");
#endif
#ifdef GAS_APIN
bPrint('G','0',gasTotalCount,1000);
bPrint('G','5', gasTotalCount - gasLastCount,1);
//bPrint('G','o', gasMaxMax - gasLowLow,10);
bPrint('G','r',gasReading,1000);
bPrint('G','f',gasFilterL,1000);
bPrint('G','l',gasLowLow,1000);
bPrint('G','h',gasMaxMax,1000);
bPrint('G','d', gasMaxMax - gasLowLow,10);
bPrint('G','t',gasTripOffset,10);
DEBUG_PRINT(F("G0"),"");
#endif
#ifdef WS_PIN
bPrint('W','D',wd,100);
bPrint('W','S',getMPH(wsSendCt,SEND_INTERVAL/1000),1000);
bPrint('W','G',getMPH(wgMaxSendCt,GUST_INTERVAL/1000),1000);
bPrint('w','2',wsSendCt,100);
bPrint('g','m',wgMaxTodayCt,100);
bPrint('g','y',wgMaxYesterdayCt,100);
DEBUG_PRINT(F("WD"),"");
#endif
#ifdef DHTTYPE
PrintHum();
DEBUG_PRINT(F("Hum"),"");
#endif
#ifdef BELL_PIN
bPrint('B','0',bellTotal,1);
bPrint('B','2',bell2Min,1);
#endif
bPrint('C','l',ctLoop,1000);
#ifdef FREERAM
bPrint('F','r',freeRam(),10000);
DEBUG_PRINT(F("Fr"),"");
#endif
//bPrint(' ','v',ip[3],100);
bPrint(VERSION_MAJOR,VERSION_MINOR,VERSION_BUILD,1);
bPrint('m','e',ip[3],100);
//bPrint('v','6',ONEWIRE_DELAY,100);
}
void resetAll()
{
#ifdef WATER_DPIN
water5[0]=waterTotal;
#endif
#ifdef POWER_APIN
powerCountLast = powerCount;
powerMaxH = 0;
powerMaxL = 1;
powerW1=0;powerW2=0;powerW3=0;powerW4=0;powerW5=0;
#endif
#ifdef GAS_APIN
gasLastCount = gasTotalCount;
gasLowLow = 1023;
gasMaxMax = 0;
#endif
#ifdef RAIN_APIN
rainLow=1024;
rainHigh=0;
rainFilterLast = rainFilter;
#endif
#ifdef BELL_PIN
bell2Min=0;
#endif
#ifdef WS_PIN
wsSendCt=0;
wgMaxSendCt = 0;
#endif
ctLoop=0;
}
void bTitle(char c1, char c2) {
if ((outbufferIdx + 4) > STRING_BUFFER_SIZE) return;
outbuffer[outbufferIdx++] = '[';
outbuffer[outbufferIdx++] = c1;
outbuffer[outbufferIdx++] = c2;
outbuffer[outbufferIdx++] = ']';
}
void bPrint(char c1, char c2, unsigned long reading,unsigned long i){
bTitle(c1,c2);
//if ((outbufferIdx + i) > STRING_BUFFER_SIZE) return;
BufferPrint(reading,i);
}
void BufferPrint(unsigned long reading,unsigned long i) {
unsigned long temp;
unsigned int iCount = 0;
while (i*10 <= reading){
i*=10;
iCount++;
}
if ((outbufferIdx + iCount) > STRING_BUFFER_SIZE) return;
while (i>0){
temp = reading/i;
reading -= temp * i;
outbuffer[outbufferIdx++] = 48+temp;
i/=10;
}
}
//void buf_add_char(unsigned char *str,unsigned int strsz)
//{
// if ((outbufferIdx + strsz) > STRING_BUFFER_SIZE) return;
// unsigned int i;
// for (i = 0; i < strsz; i++)
// {
// outbuffer[outbufferIdx++] =str[i];
// }
//}
#ifdef FREERAM
int freeRam () {
extern int __heap_start, *__brkval;
int v;
return (int) &v - (__brkval == 0 ? (int) &__heap_start : (int) __brkval);
}
#endif
//void serialPrint()
//{
//if(false){
// if(outbufferIdx<(OUT_SIZE-10)){
// if(powerReading>999){
// OutBufferPrint(powerReading,1000);
// }
// else if(powerReading>99){
// OutBufferPrint(powerReading,100);
// }
// else{ OutBufferPrint(powerReading,10);}
// }}
//return;
//DEBUG_PRINT(rArg);
//DEBUG_PRINT("");
//DEBUG_PRINT(counter);
//DEBUG_PRINT(" ");
//DEBUG_PRINT(powerReading);
// DEBUG_PRINT(" ");
//DEBUG_PRINT(powerFilterC/powerFilterH);
//DEBUG_PRINT(" ");
//DEBUG_PRINT(topLow);
//DEBUG_PRINT(" ");
//DEBUG_PRINT(powerBlinkFlag);
//DEBUG_PRINTLN(" ");
//return;
//}
void ClientMode()
{
#define INVALUE_MAX 7
IPAddress nasServerIP(192,168,0,77);
unsigned long connectLoop = 0;
unsigned long inValue[INVALUE_MAX];
int inPos = -1;
inValue[0] = 0; inValue[1] = 0; inValue[2] = 0; inValue[3] = 0; inValue[4] = 0; inValue[5] = 0; inValue[6] = 0;
if (client.connect(nasServerIP,80)) {
} else {
Ethernet.begin(mac, ip, gateway, gateway, subnet);
runDelayLoops(100);
client.connect(nasServerIP,80);
}
if (client.connected()) {
DEBUG_PRINT("getURL",getURL);
client.print(getURL); //"GET /webtest.cgi?n=123 HTTP/1.0");
BuildOutput();
DEBUG_PRINT("outbuffer ",outbuffer);
client.println(outbuffer);
client.print(F(" HTTP/1.0"));
client.println();
}
while(client.connected() && !client.available()) {
runLoops(); //waits for data
if (connectLoop++ > 10000) break;
}
GetBufferIdx = 0;
DEBUG_PRINT(F("geting"),F("GetBuffer"));
while (client.connected()) {
while( client.available()) { //connected or data available
char c = client.read();
//GetBuffer[GetBufferIdx++] = c;
if (c >= '0' && c <= '9' && GetBufferIdx < STRING_GetBuffer_SIZE)
{
//just get the date
if (inPos == -1) GetBuffer[GetBufferIdx++] = c;
if (inPos > -1 && c != '|' && inPos < INVALUE_MAX ) inValue[inPos] = inValue[inPos] * 10 + (c - '0');
}
else if (c=='|') {inPos++;}
if (connectLoop++ > 10000) break;
}
if (connectLoop++ > 10000) break;
}
DEBUG_PRINT(F("connectLoop"),connectLoop);
client.stop();
GetBuffer[GetBufferIdx] = '\0';
DEBUG_PRINT("GetBufferIdx ",GetBufferIdx);
DEBUG_PRINT("GetBuffer ",GetBuffer);
DEBUG_PRINT("inPos ",inPos);
if (inPos > 4) {
#ifdef POWER_APIN
if(inValue[0] > 0) powerTripLow = (float)inValue[0]/1000.0;
if(inValue[1] > 0) powerTripHigh = (float)inValue[1]/1000.0;
#endif
#ifdef GAS_APIN
if(inValue[2] > 0) gasTripOffset = inValue[2];
#endif
if(inValue[3] > 0) SEND_INTERVAL = inValue[3];
if(inValue[4] > 0) RESET_INTERVAL = inValue[4];
#ifdef WATER_DPIN
if(inValue[5] > 0) WATER_DEBOUNCE = inValue[5];
#endif
#if defined(INSIDE_ONEWIRE_DPIN) || defined(OUTSIDE_ONEWIRE_DPIN)
if(inValue[6] > 0) ONEWIRE_DELAY = inValue[6];
#endif
}
}
void SetLastDay(){
static int lastDay = 0;
int day;
if(GetBufferIdx>13) {
//resetSendCt = 0; //we got a connect so reset
day = (GetBuffer[6] - '0') * 10 + (GetBuffer[7] - '0');
if (day != lastDay)
{
lastDay = day;
#ifdef WS_PIN
wgMaxYesterdayCt = wgMaxTodayCt;
wgMaxTodayCt = 0;
#endif
}
}
/*
DEBUG_PRINT("GetBufferIdx",GetBufferIdx);
if(GetBufferIdx>13) {
//resetSendCt = 0; //we got a connect so reset
int day = (GetBuffer[6] - '0') * 10 + (GetBuffer[7] - '0');
long year = (GetBuffer[0] - '0') * 1000 + (GetBuffer[1] - '0') * 100 + (GetBuffer[2] - '0') * 10 + (GetBuffer[3] - '0');
int month = (GetBuffer[4] - '0') * 10 + (GetBuffer[5] - '0');
DEBUG_PRINT("dd",day);
DEBUG_PRINT("MM",month);
DEBUG_PRINT("yyyy",year);
}
*/
}
/*
void TimeAdj()
{
if(GetBufferIdx>18)
{
resetSendCt = 0; //we got a time so reset reboot hack
long adj = GetBuffer[16] - '0';
if (adj > 4) adj -= 5;
adj *= 6;
//DEBUG_PRINTLN(adj);
adj = ((adj * 60000) + ((((GetBuffer[17] - '0') * 10) + (GetBuffer[18] - '0')) * 1000));
adj += (GetBuffer[17] - '0');
//DEBUG_PRINTLN(adj);
adj *= 10;
adj += (GetBuffer[18] - '0');
//DEBUG_PRINTLN(adj);
adj *= 1000;
//4 minutes adj up and make negitive
//if (adj > RESET_INTERVAL - 5000) adj -= RESET_INTERVAL; //300000;
DEBUG_PRINT(F("adj "));
DEBUG_PRINT(adj);
DEBUG_PRINT(F(" "));
DEBUG_PRINT(resetMillis);
if (abs(adj) > 1000 && resetMillis > abs(adj) && abs(adj) < RESET_INTERVAL ) {
resetMillis -= adj;
nextConnect -= adj;
}
DEBUG_PRINT(F(" "));
DEBUG_PRINTLN(resetMillis);
}
}
*/
|
5d786ad677b5bae1d6e1ded3729584b2ccba2fd2
|
26f3130ff66b93fa7328cdfbafb80686133ff695
|
/Les 3/Boeken Stack/Boeken/Boeken.h
|
39d467ec8bff114d795fa3e77b0bc56dd1f0841d
|
[] |
no_license
|
LMichelle/Intro-OOP
|
95f7eec5d6129ccd155a87d8bd451262634b1659
|
e9e66f3c606d9515f442a087f15327f4b0f4bb2a
|
refs/heads/master
| 2021-07-22T22:56:22.432299
| 2017-11-01T07:51:24
| 2017-11-01T07:51:24
| 103,917,298
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 141
|
h
|
Boeken.h
|
#pragma once
#include <string>
class Boeken
{
public:
Boeken();
Boeken(std::string type);
std::string _type = "onbekend";
~Boeken();
};
|
e1e128c215b89398476d6d7583bcfe09c20dd1ed
|
780fb7751adb628c7f598fc3dfc4bf422911b987
|
/ch04/thread_safe_que.cpp
|
c6b03ad1677b4d0c52c780ea030b38e4ec9d8e81
|
[] |
no_license
|
Aperjump/Notes-on-C-Concurrency
|
1b2cabeec6e3bda44751b83d81a4e0a896cec07a
|
05faa13c0206b1d61bac98f965a4299396cdfb8d
|
refs/heads/master
| 2020-12-25T18:42:50.918173
| 2017-06-25T12:44:30
| 2017-06-25T12:44:30
| 93,979,029
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,677
|
cpp
|
thread_safe_que.cpp
|
/***
thread_safe_que
@C++ Concurrency in Action
***/
#include <memory>
#include <mutex>
#include <queue>
#include <condition_variable>
using namespace std;
template<typename T>
class thread_safe_que
{
public:
thread_safe_que()
{
}
thread_safe_que(const thread_safe_que& other)
{
lock_guard<mutex> lk(other.mut);
data_que = other.data_que;
}
thread_safe_que& operator=(
const thread_safe_que&) = delete;
void push(T new_value)
{
lock_guard<mutex> lk(mut);
data_que.push(new_value);
data_cond.notify_one();
}
/***
bool try_pop(T& new_value) will store the retrived value
in the referenced variable, so it can use the return value
for status
***/
bool try_pop(T& new_value)
{
lock_guard<mutex> lk(mut);
if (data_que.empty())
return false;
value = data_que.front();
data_que.pop();
return true;
}
std::shared_ptr<T> try_pop()
{
lock_guard<mutex> lk(mut);
if (data_que.empty())
return shared_ptr<T>>();
shared_ptr<T> res(make_shared<T>(data_que.front()));
data_que.pop();
return res;
}
void wait_and_pop(T& value)
{
unique_lock<mutex> lk(mut);
data_cond.wait(lk, [this]{return !data_que.empty();});
value = data_que.front();
data_que.pop();
}
std::shared_ptr<T> wait_and_pop()
{
unique_lock<mutex> lk(mut);
data_cond.wait(lk,[this]{return !data_que.empty();});
shared_ptr<T> res(make_shared<T>(data_que.front()));
data_que.pop();
return res;
}
bool empty() const
{
lock_guard<mutex> lk(mut);
return data_que.empty();
}
private:
mutex mut;
queue<T> data_que;
condition_variable data_cond;
}
|
2ba7e3dce775207e5f182e6942ea8395d9cb6288
|
79f1cb095cc7623469bf2e11145e6972f0095be9
|
/Sorting/3PartitionQuickSort.cpp
|
d3cbef106564196fe8fe82014abe35bea01559cb
|
[] |
no_license
|
Shubhamrawat5/DSA
|
161b9bb8138e6bead2709d343759aff39bbb3350
|
4d1fb52ae9f7cc568b4194b9caa8cf06a7b6d687
|
refs/heads/master
| 2023-01-03T05:03:55.373958
| 2020-10-30T19:45:26
| 2020-10-30T19:45:26
| 278,144,595
| 2
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 808
|
cpp
|
3PartitionQuickSort.cpp
|
#include<iostream>
using namespace std;
//swap function
void swap(int *x,int *y)
{
int temp=*x;
*x=*y;
*y=temp;
}
//taking 1st element as pivot then moving smaller value to left side of m1 and greater value to right side of m2 and equal element btw m1 & m2
int Partition(int a[],int l,int r,int &m1,int &m2)
{
int pivot=l;
m1=l,m2=l+1;
while(m2<=r)
{
if(a[pivot]==a[m2]){
++m2;
}
if(a[pivot]>a[j]) {
swap(&a[m1],&a[m2]);
}
else{
swap(&a[m2],&a[r]);
--r;
}
}
}
//3 partition quick sort
int quicksort(int a[],int l,int r)
{
if(l<r){
int m1,m2;
Partition(a,l,r,m1,m2);
quicksort(a,l,m1-1);
quicksort(a,m2+1,r);
}
return 0;
}
int main()
{
int a[]={2,7,2,9,2,1,8};
int n=sizeof(a)/sizeof(a[0]);
quicksort(a,0,n-1);
for(int i=0;i<n;++i)
cout<<a[i]<<" ";
}
|
a8f1e1ee95868e893a52f0c3ae20012fd7585982
|
a2e990761661bf454cf1887760d344971fdfca73
|
/Bob/Attiny85/SoftSerialExample/SoftSerialExample.ino
|
2b234d8da09647daafa8f8b5dd15e6d0f18e86ee
|
[] |
no_license
|
Bob0505/sketchbook_1.6.8
|
c0ca9e29383f966756662f56625ec7cc5ca6873f
|
b6d80b514fcef5afe9cb6951a4fd2f6a56e9c4e6
|
refs/heads/master
| 2020-05-21T04:33:26.648979
| 2017-01-07T03:55:47
| 2017-01-07T03:55:47
| 61,954,503
| 2
| 1
| null | 2017-01-11T00:08:26
| 2016-06-25T17:39:19
|
C
|
UTF-8
|
C++
| false
| false
| 2,100
|
ino
|
SoftSerialExample.ino
|
/*
Software serial multiple serial test
Receives from the hardware serial, sends to software serial.
Receives from software serial, sends to hardware serial.
The circuit:
* RX is digital pin 2 (connect to TX of other device)
* TX is digital pin 3 (connect to RX of other device)
created back in the mists of time
modified 9 Apr 2012
by Tom Igoe
based on Mikal Hart's example
This example code is in the public domain.
<SoftSerial> adapted from <SoftwareSerial> for <TinyPinChange> library which allows sharing the Pin Change Interrupt Vector.
Single difference with <SoftwareSerial>: add #include <TinyPinChange.h> at the top of your sketch.
RC Navy (2012): http://p.loussouarn.free.fr
*/
#include <TinyPinChange.h> /* Ne pas oublier d'inclure la librairie <TinyPinChange> qui est utilisee par la librairie <RcSeq> */
#include <SoftSerial.h> /* Allows Pin Change Interrupt Vector Sharing */
#define ledPin 1
#define RX1_pin 2
#define TX1_pin 3
#define RX2_pin 4
#define TX2_pin 5
SoftSerial portOne(RX1_pin, TX1_pin);
//portTwo need to check
//SoftSerial portTwo(RX2_pin, TX2_pin);
void setup()
{
// Open serial communications and wait for port to open:
// set the data rate for the SoftwareSerial port
portOne.begin(9600); //19200 4800
portOne.println("Hello, world!!!");
/*
portTwo.begin(9600); //19200 4800
portTwo.println("World, hello!!!");
*/
}
void loop() // run over and over
{
portOne.print("Bob Love Kara~!!!");
// portTwo.print("Kara Love Bob~!!!");
// fade in from min to max in increments of 5 points:
for(int fadeValue = 0 ; 255>= fadeValue; fadeValue +=51) {
// sets the value (range from 0 to 255):
analogWrite(ledPin, fadeValue);
// wait for 30 milliseconds to see the dimming effect
for(int index=0;index<10;index++)
{
if (portOne.available())
portOne.write(portOne.read());
portOne.print(index);
/*
if (portTwo.available())
portTwo.write(portTwo.read()+1);
portTwo.println(' '); portTwo.print(index); portTwo.println(' ');
*/
delay(50);
}
}
}
|
bdac8637b36bf732bccbd32a0c9a1e0afd9bd589
|
26ded7fd94d8a2281fd3c42100b82d5736014430
|
/PYO/Other/i18n/mainLoad.cpp
|
e2f784b56631b6f3cf9e47dcccad9606a0d900b4
|
[
"MIT"
] |
permissive
|
danyow/PYO
|
9192b2d017ea0b826ffaf7caf6eed1584ab3bc81
|
64b64020820cfef689123a69002c9252ade0306e
|
refs/heads/master
| 2021-08-31T06:24:57.472135
| 2017-12-20T14:42:14
| 2017-12-20T14:42:14
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,755
|
cpp
|
mainLoad.cpp
|
//
// Created by kaishiqi on 14-8-5.
// Copyright (c) 2014 kaishiqi. All rights reserved.
//
#include <iostream>
#include "I18nUtils.h"
USING_NS_I18N;
inline void output(std::string str) {
std::cout << str << std::endl;
}
int mainLoad()
{
const char MO_FILE_ZH_HANS[] = "/Users/imagons/Desktop/GitHub/PYO/res/zh_Hans.mo";
const char MO_FILE_ZH_HANT[] = "/Users/imagons/Desktop/GitHub/PYO/res/zh_Hant.mo";
const char MO_FILE_JA[] = "/Users/imagons/Desktop/GitHub/PYO/res/ja.mo";
const char MO_FILE_KO[] = "/Users/imagons/Desktop/GitHub/PYO/res/ko.mo";
const char MO_FILE_FR[] = "/Users/imagons/Desktop/GitHub/PYO/res/fr.mo";
const char MO_FILE_DE[] = "/Users/imagons/Desktop/GitHub/PYO/res/de.mo";
const char MO_FILE_RU[] = "/Users/imagons/Desktop/GitHub/PYO/res/ru.mo";
/**
*
* i18n translate usage:
*
*/
output("\t-- i18n translate usage --");
auto showText = [](){
// general text
output(__("Hello world!"));
// context text
output(_x("post", "A post."));
output(_x("post", "To post."));
// plural text
output(_n("There is a comment.", "There are comments.", 1));
output(_n("There is a comment.", "There are comments.", 3));
// plural + context
output(_nx("This apple belongs to them.", "These apples belong to them.", 30, "male"));
output(_nx("This apple belongs to them.", "These apples belong to them.", 7, "female"));
output(_nx("This apple belongs to them.", "These apples belong to them.", 1, "animal"));
// noop text (don't translate them now)
std::vector<NoopEntry> messages {
_n_noop("hero", "heroes"),
_n_noop("book", "books"),
_n_noop("child", "children"),
_n_noop("knife", "knives"),
_n_noop("mouse", "mice"),
_nx_noop("he", "they", "male"),
_nx_noop("she", "they", "female"),
_nx_noop("it", "they", "object")
};
// translate noop (when using translation)
auto mo = I18nUtils::getInstance()->getMO();
output("noops:");
for (int i = 0; i < messages.size(); i++) {
auto isSingular = (mo.onPluralExpression(i) == 0);
std::string prestr;
#if (IS_ENABLE_FORMAT_MATCH_ARGS_INDEX == FORMAT_MATCH_ENABLE)
prestr = i18nFormatStr(__("\ti=%d1 is %8s2: "), i, (isSingular ? __("singular").c_str() : __("plural").c_str()));
#else
prestr = i18nFormatStr(__("\ti=%d is %8s: "), i, (isSingular ? __("singular").c_str() : __("plural").c_str()));
#endif
output(prestr + t_nooped(messages.at(i), i));
}
// use arguments
output(i18nFormatStr(__("You have chosen the %s1 hat."), __("red").c_str()));
output(i18nFormatStr(__("You have chosen the %s1 hat."), __("blue").c_str()));
output(i18nFormatStr(__("You have chosen the %s1 hat."), __("yellow").c_str()));
// repeated use arguments
std::string heroName("xxx");
output(i18nFormatStr(__("Hi %s1! Welcome to %s1's city."), heroName.c_str()));
/**
* Sometimes the arguments' index in the translation is very important, such as grammatical inverted.
* e.g.,
* english: There are birds singing in the tree.
* chinese: 小鸟在树上唱歌。
*
* original text: There are birds [%s1] in the [%s2].
* translation text: 小鸟在[%s2]上[%s1]。
*/
output(i18nFormatStr(__("There are birds %s1 in the %s2."), __("singing").c_str(), __("tree").c_str()));
};
/**
* Note: onPluralExpression and nplurals,
* need to keep consistent with *.po file Plural-Forms setting.
*/
// English Plural-Forms: nplurals=2; plural=(n!=1);
output("[Engilish] Original Text");
showText();
// Chinese Plural-Forms: nplurals=1; plural=0;
output("\n[Chinese (Simplified)]");
I18nUtils::getInstance()->addMO(MO_FILE_ZH_HANS, [](int){return 0;}, 1);
showText();
// Chinese Plural-Forms: nplurals=1; plural=0;
output("\n[Chinese (Traditional)]");
I18nUtils::getInstance()->addMO(MO_FILE_ZH_HANT, [](int){return 0;}, 1);
showText();
// Japanese Plural-Forms: nplurals=1; plural=0;
output("\n[Japanese");
I18nUtils::getInstance()->addMO(MO_FILE_JA, [](int){return 0;}, 1);
showText();
// Korean Plural-Forms: nplurals=1; plural=0;
output("\n[Korean]");
I18nUtils::getInstance()->addMO(MO_FILE_KO, [](int){return 0;}, 1);
showText();
// French Plural-Forms: nplurals=2; plural=(n > 1);
output("\n[French]");
I18nUtils::getInstance()->addMO(MO_FILE_FR, [](int n){return n>1;}, 2);
showText();
// Germen Plural-Forms: nplurals=2; plural=(n != 1);
output("\n[Germen]");
I18nUtils::getInstance()->addMO(MO_FILE_DE, [](int n){return (n!=1);}, 2);
showText();
// Russian Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);
output("\n[Russian]");
auto russianExpression = [](int n){
return n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2;
};
I18nUtils::getInstance()->addMO(MO_FILE_RU, russianExpression, 3);
showText();
//...
output("");
/** Cocos2d-x 3.x usage */
//Data moData = FileUtils::getInstance()->getDataFromFile(MO_FILE_ZH_HANS);
//I18nUtils::getInstance()->addMO(moData.getBytes(), [](int){return 0;}, 1);
/**
*
* domain argument usage:
* e.g., multiple module project.
*
*/
output("\t-- domain usage --");
output("[load modules...]");
I18nUtils::getInstance()->addMO(MO_FILE_ZH_HANS, [](int){return 0;}, 1, "game1");
I18nUtils::getInstance()->addMO(MO_FILE_JA, [](int){return 0;}, 1, "game2");
I18nUtils::getInstance()->addMO(MO_FILE_KO, [](int){return 0;}, 1, "game3");
I18nUtils::getInstance()->addMO(MO_FILE_FR, [](int n){return n>1;}, 2, "game4");
I18nUtils::getInstance()->addMO(MO_FILE_DE, [](int n){return (n!=1);}, 2, "game5");
output(__("Hello world!", "game1"));
output(__("Hello world!", "game2"));
output(__("Hello world!", "game3"));
output(__("Hello world!", "game4"));
output(__("Hello world!", "game5"));
output("[unload modules...]");
I18nUtils::getInstance()->removeAllMO();
output(__("Hello world!", "game1"));
output(__("Hello world!", "game2"));
output(__("Hello world!", "game3"));
output(__("Hello world!", "game4"));
output(__("Hello world!", "game5"));
output("");
/**
*
* i18nFormat usage:
*
*/
output("\t-- i18nFormat usage --");
#if (IS_ENABLE_FORMAT_MATCH_ARGS_INDEX == FORMAT_MATCH_ENABLE)
/** Same as use printf, but format % character can append arguments' index(from to 1 start). */
output(i18nFormat("[enable] c:%c1 d:%d2 f:%.2f3 s:%s4 %:%", '@', 30, 3.1415, "str"));
//output([enable] c:@ d:30 f:3.14 s:str %:%)
output(i18nFormat("[enable] %s1.a = %s1.b = %s1.c = %s1.d = %d2", "foo", 7));
//output([enable] foo.a = foo.b = foo.c = foo.d = 18)
output(i18nFormat("[enable] %d1 < %d2; %d2 > %d3; %d3 > %d1", 1, 3, 2));
//output([enable] 1 < 3; 3 > 2; 2 > 1)
#else
/** Same as use printf, but returned std:string. */
output(i18nFormat("[unable] c:%c d:%d f:%.2f s:%s %%:%%", '@', 30, 3.1415, "str"));
//output([unable] c:@ d:30 f:3.14 s:str %:%)
#endif
output("");
return 0;
}
|
f3a9d3e0dc0bba9c80812fc1600805e57176da1e
|
d8cabb3e0df24ac70ed78a7828291532c25fec55
|
/UVA_1/r_167 - The Sultan s Successors(11).cc
|
056c1cd210155da836549903e339d75fce3d6cd9
|
[] |
no_license
|
Bekon0700/Competitive_Programming
|
207bb28418d49a2223efb917c7ddf07dfdf4f284
|
ff93fdb2ada1bafabca13431bec7a78a9754e1b8
|
refs/heads/master
| 2022-10-16T09:38:13.865274
| 2020-06-08T13:12:34
| 2020-06-08T13:12:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,395
|
cc
|
r_167 - The Sultan s Successors(11).cc
|
#include<stdio.h>
#include<math.h>
int pos[100][10],NO;
void MAIN()
{
int i,j,x,t,max,input[10][10];
scanf("%d",&t);
while(t--)
{
for(i=1;i<9;i++)
for(j=1;j<9;j++)
scanf("%d",&input[i][j]);
i = 1 ;
max = input[1][pos[i][1]] +input[2][pos[i][2]] +input[3][pos[i][3]] +input[4][pos[i][4]] +input[5][pos[i][5]] +input[6][pos[i][6]] + input[7][pos[i][7]] +input[8][pos[i][8]] ; ;
for(i=2;i<93;i++)
{
x = input[1][pos[i][1]] +input[2][pos[i][2]] +input[3][pos[i][3]] +input[4][pos[i][4]] +input[5][pos[i][5]] +input[6][pos[i][6]] + input[7][pos[i][7]] +input[8][pos[i][8]] ;
if(x>max)
max = x;
}
printf("%5d\n",max);
}
}
int CC(int k,int cur[],int can[])
{
int i, c, x ;
bool f[10] ;
for(i=1; i < 9 ;i++)
f[i] = true;
for(i=1; i < k ;i++)
{
f[cur[i]] = false;
x = k -i;
if(cur[i] - x > 0)
f[ cur[i] - x ] = false;
if(cur[i] + x < 9)
f[ cur[i] + x ] = false;
}
c = 0 ;
for(i=1; i < 9 ;i++)
if( f[i] )
can[c++] = i;
return c ;
}
void BT(int k,int cur[])
{
int i, candidate;
if(k==9)
{
for(i = 1;i<9;i++)
pos[NO][i] = cur[i] ;
NO++;
return ;
}
else
{
int can[10];
candidate = CC(k,cur,can);
for(i=0;i < candidate; i++)
{
cur[k] = can[i];
BT(k+1,cur);
}
return ;
}
}
void GENARET()
{
int cur[10];
NO = 1 ;
BT(1,cur) ;
}
int main()
{
GENARET();
MAIN();
return 0;
}
|
e2fb3c52f11f4fe285bf1e04b347170ab879abd2
|
4c214a64016cc838700025aebb9fddab1fbacf55
|
/Il2Native.Logic/NativeImplementations/System.Private.CoreLib/System/Reflection/Emit/AssemblyBuilder.cpp
|
9e861143619d27ea25e2d1623b86d39dc461b94c
|
[
"MIT"
] |
permissive
|
Moxicution/cs2cpp
|
73b5fe4a4cdbf1dcec0efcd8cae28ff2d0527664
|
d07d3206fb57edb959df8536562909a4d516e359
|
refs/heads/master
| 2023-07-03T00:57:59.383603
| 2017-08-03T09:05:03
| 2017-08-03T09:05:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,160
|
cpp
|
AssemblyBuilder.cpp
|
#include "System.Private.CoreLib.h"
namespace CoreLib { namespace System { namespace Reflection { namespace Emit {
namespace _ = ::CoreLib::System::Reflection::Emit;
// Method : System.Reflection.Emit.AssemblyBuilder.GetInMemoryAssemblyModule(System.Reflection.RuntimeAssembly)
::CoreLib::System::Reflection::RuntimeModule* AssemblyBuilder::GetInMemoryAssemblyModule(::CoreLib::System::Reflection::RuntimeAssembly* assembly)
{
throw 3221274624U;
}
// Method : System.Reflection.Emit.AssemblyBuilder.nCreateDynamicAssembly(System.AppDomain, System.Reflection.AssemblyName, ref System.Threading.StackCrawlMark, System.Reflection.Emit.AssemblyBuilderAccess)
::CoreLib::System::Reflection::Assembly* AssemblyBuilder::nCreateDynamicAssembly_Ref(::CoreLib::System::AppDomain* domain, ::CoreLib::System::Reflection::AssemblyName* name, ::CoreLib::System::Threading::StackCrawlMark__enum& stackMark, _::AssemblyBuilderAccess__enum access)
{
throw 3221274624U;
}
}}}}
namespace CoreLib { namespace System { namespace Reflection { namespace Emit {
namespace _ = ::CoreLib::System::Reflection::Emit;
}}}}
|
cf83a93cce909e997adea14dac34d642eb0f7cc7
|
f92e96888be9d8569e29d05c7a329ee2dfbe53e6
|
/src/pldensity.cpp
|
c37b8216e24dac7af3674b76e2876cc5ab746332
|
[
"MIT"
] |
permissive
|
nzunigag/pldensity
|
66392736b4eb3fae9061bce3d337eedb6825435e
|
d4a0f6871bb2df9e7b6372505ac1eab30fc4ca51
|
refs/heads/master
| 2021-08-30T08:00:59.683241
| 2017-12-16T22:53:47
| 2017-12-16T22:53:47
| 113,084,792
| 0
| 0
| null | 2017-12-04T19:21:33
| 2017-12-04T19:21:33
| null |
UTF-8
|
C++
| false
| false
| 11,605
|
cpp
|
pldensity.cpp
|
#define ARMA_64BIT_WORD 1
#define _USE_MATH_DEFINES
#include <RcppArmadillo.h>
#include <cmath>
using namespace Rcpp;
using namespace arma;
using namespace std;
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::plugins(cpp11)]]
// // This inline function creates one sample of multivariate t-distribution
// // [[Rcpp::export]]
// inline arma::vec rSt(
// const arma::vec& mu,
// const arma::mat& Sigma,
// const double df) {
//
// int d = mu.size();
// vec normal = chol(Sigma).t() * randn(d);
// double chi2 = rchisq(1, df)[0];
// return mu + normal / sqrt(chi2 / df);
// }
// This inline function evaluates the density of t distribution
inline double dst(
const arma::vec& x,
const arma::vec& mu,
const arma::mat& Sigma, // Sigma^{-1}
const double df) {
int d = mu.n_elem;
vec xcentered = x - mu;
double innerterm = - 0.5 * (df + d) *
log(1.0 + as_scalar(xcentered.t() * inv_sympd(Sigma) * xcentered) / df);
double ldet;
double sign;
log_det(ldet, sign, Sigma); // compute and store the logarithm of determinant
double extterm = log(tgamma(0.5 * (df + d))) - log(tgamma(0.5 * df)) - 0.5 * d * log(df * M_PI) - 0.5 * ldet;
double density = exp(extterm + innerterm);
return !isnan(density) ? density : 0.0;
}
// Samples from a multivariate categorical variable
inline arma::uvec resample(int N, vec prob) {
vec probsum = cumsum(prob) / sum(prob);
uvec out(N);
for (int i = 0; i < N; i++) {
double u = unif_rand();
int j = 0;
while (u > probsum[j]) {j++;}
out[i] = j;
}
return out;
}
// Defines a particle, which carries a essensial state
struct Particle {
int m; // Total clusters
vec n; // Observations per cluster
mat mu; // Mean (dim1) per cluster
cube S; // SS (dim1, dim2) per cluster
Particle (int m_, arma::vec& n_, arma::mat& mu_, arma::cube& S_)
: m(m_), n(n_), mu(mu_), S(S_) {};
Particle (const arma::vec& x) {
m = 1;
n.resize(1);
n[0] = 1;
mu.resize(x.n_elem, 1);
mu.col(0) = x;
S.resize(x.n_elem, x.n_elem, 1);
S.slice(0).fill(0.0);
}
Particle (const Particle& z) { // copy constructor
m = z.m;
n = z.n;
mu = z.mu;
S = z.S;
};
Particle () {};
};
// Defines the prior, to avoid passing along all the parameters
struct DPNormalPrior { // mu ~ N(lambda, S / kappa), S^-1 ~ W(Omega, nu)
const double alpha;
const arma::vec& lambda;
const double kappa;
const double nu;
const arma::mat& Omega;
DPNormalPrior(
const double a_,
const arma::vec& l_,
const double k_,
double n_,
const arma::mat& O_)
: alpha(a_), lambda(l_), kappa(k_), nu(n_), Omega(O_) {}
};
// Evaluate contricution to predictive of cluster, j == z.m is the prior
inline arma::vec predictive(
const arma::vec& x,
const Particle& z,
const DPNormalPrior& p
) {
// Initialize
double d = x.n_elem;
vec dpred(z.m + 1);
// Cluster contribution
for (int j = 0; j < z.m; j++) {
vec aj = (p.kappa * p.lambda + z.n[j] * z.mu.col(j)) / (p.kappa + z.n[j]);
mat Dj = z.S.slice(j) + p.kappa * z.n[j] /
(p.kappa + z.n[j]) * (p.lambda - z.mu.col(j)) * (p.lambda - z.mu.col(j)).t();
double cj = 2 * p.nu + z.n[j] - d + 1.0;
mat Bj = 2.0 * (p.kappa + z.n[j] + 1.0) / (p.kappa + z.n[j]) /
cj * (p.Omega + 0.5 * Dj);
dpred[j] = z.n[j] * dst(x, aj, Bj, cj);
}
// Prior contribution
vec a0 = p.lambda;
double c0 = 2.0 * p.nu - d + 1.0;
const mat& B0 = 2.0 * (p.kappa + 1.0) / p.kappa / c0 * p.Omega;
dpred[z.m] = p.alpha * dst(x, a0, B0, c0);
return dpred;
}
// Evaluates the density of a new point given a particle
inline Particle propagate(
const arma::vec& xnew,
const Particle& z,
const DPNormalPrior& p // iteration timestamp
) {
// Initialize output
Particle out(z);
// Propagate allocation
vec cp = predictive(xnew, z, p);
int k = resample(1, cp)[0];
// If new cluster
if (k == z.m) {
out.n.insert_rows(out.m, 1);
out.mu.insert_cols(out.m, xnew);
out.S.insert_slices(out.m, 1);
out.m += 1;
out.n[k] += 1;
} else {
out.n[k] += 1;
out.mu.col(k) = (z.n[k] * z.mu.col(k) + xnew) / out.n[k];
out.S.slice(k) += (xnew * xnew.t()) + z.n[k] * (z.mu.col(k) * z.mu.col(k).t()) -
out.n[k] * (out.mu.col(k) * out.mu.col(k).t());
}
return out;
}
//' @title Dirichlet Process Normal Mixture Kernel Density Estimation
//' @description Bla Bla
//' @param x a matrix of observations
//' @param alpha concentration parameter of Dirichlett process
//' @export
// [[Rcpp::export]]
Rcpp::List dp_normal_mix(
const arma::mat& x,
const int N,
const double alpha,
const arma::vec& lambda,
const double kappa,
const double nu,
const arma::mat& Omega
) {
// Total observations
const int T = x.n_rows;
const int d = x.n_cols;
// Save prior in structure
const DPNormalPrior prior(alpha, lambda, kappa, nu, Omega);
// Initialize N particles
std::vector<Particle> particle(N);
for (int i = 0; i < N; i++) {
vec randstart(d);
for (int j = 0; j < d; j++) {
randstart[j] = unif_rand();
}
particle[i] = Particle(randstart);
}
// Update every particle
for (int t = 1; t < T; t++) {
// Resample
vec weight(N);
for (int i = 0; i < N; i++) {
weight[i] = sum(predictive(x.row(t).t(), particle[i], prior));
}
uvec new_idx = resample(N, weight);
// Propagate
std::vector<Particle> temp_particle(particle);
for (int i = 0; i < N; i++) {
particle[i] = propagate(x.row(t).t(), temp_particle[new_idx[i]], prior);
}
}
// Wrap all the output in lists for R
Rcpp::List param = Rcpp::List::create(
Named("alpha") = alpha,
Named("lambda") = wrap(lambda),
Named("kappa") = wrap(kappa),
Named("nu") = nu,
Named("Omega") = wrap(Omega)
);
Rcpp::List particle_list;
for (int i = 0; i < N; i++) {
Rcpp::List particlei = Rcpp::List::create(
Named("m") = particle[i].m,
Named("n") = wrap(particle[i].n),
Named("mu") = wrap(particle[i].mu),
Named("S") = wrap(particle[i].S));
particle_list.push_back(particlei);
}
Rcpp::List out = Rcpp::List::create(
Named("N") = N,
Named("param") = param,
Named("particle_list") = particle_list
);
out.attr("class") = "PL";
return out;
}
//' @title Eval Point Density
//' @description Bla Bla
//' @export
// [[Rcpp::export]]
arma::vec dp_normal_deval(
const Rcpp::List& model,
const arma::mat& xnew,
const int nparticles = 50
) {
// Check list is of appropriate type
if (!Rf_inherits(model, "PL")) throw "List must be a PL object";
// Allocate space
const uword K = xnew.n_rows;
vec density(K, fill::zeros);
// Prior structure
const int N = model["N"];
Rcpp::List param = model["param"];
vec lambda = param["lambda"];
mat Omega = param["Omega"];
double alpha = param["alpha"], kappa = param["kappa"], nu = param["nu"];
const DPNormalPrior prior(alpha, lambda, kappa, nu, Omega);
const int N0 = min(N, nparticles);
Rcpp::List particle_list = model["particle_list"];
for (int i = 0; i < N0; i++) {
Rcpp::List particle_param = particle_list[i];
int m = particle_param["m"];
vec n = particle_param["n"];
mat mu = particle_param["mu"];
cube S = particle_param["S"];
Particle z(m, n, mu, S);
for (uword k = 0; k < K; k++) {
density(k) += sum(predictive(xnew.row(k).t(), z, prior)) / N0;
}
}
return density;
}
//' @title Take marginals
//' @description Bla Bla
//' @export
// [[Rcpp::export]]
Rcpp::List dp_normal_marginal(
const Rcpp::List& model,
const arma::uvec& dims
) {
// Check list is of appropriate type
if (!Rf_inherits(model, "PL")) throw "List must be a PL object";
const uvec dims_ = dims - 1;
// Parameters
const int N = model["N"];
Rcpp::List param_full = model["param"];
const double alpha = param_full["alpha"], kappa = param_full["kappa"], nu = param_full["nu"];
vec lambda = param_full["lambda"];
vec lambdanew = lambda.elem(dims_);
mat Omega = param_full["Omega"];
mat Omeganew = Omega.submat(dims_, dims_);
Rcpp::List param_reduced = Rcpp::List::create(
Named("alpha") = alpha,
Named("lambda") = wrap(lambdanew),
Named("kappa") = kappa,
Named("nu") = nu,
Named("Omega") = wrap(Omeganew)
);
// Copy only selected dimensions
Rcpp::List particle_list_reduced;
Rcpp::List particle_list_full = model["particle_list"];
for (int i = 0; i < N; i++) {
Rcpp::List particle = particle_list_full[i];
int m = particle["m"];
vec n = particle["n"];
mat mu = particle["mu"];
mat munew = mu.rows(dims_);
cube S = particle["S"];
cube Snew(dims_.n_elem, dims_.n_elem, m);
for (int k = 0; k < m; k++) {
Snew.slice(k) = S.slice(k).submat(dims_, dims_);
}
Rcpp::List particlei = Rcpp::List::create(
Named("m") = m,
Named("n") = n,
Named("mu") = wrap(munew),
Named("S") = wrap(Snew));
particle_list_reduced.push_back(particlei);
}
Rcpp::List model_reduced = Rcpp::List::create(
Named("N") = N,
Named("param") = param_reduced,
Named("particle_list") = particle_list_reduced
);
model_reduced.attr("class") = "PL";
return model_reduced;
}
//' @title Eval Point Conditional density
//' @description Bla Bla
//' @export
// [[Rcpp::export]]
arma::mat dp_normal_deval_conditional(
const Rcpp::List& model,
const arma::mat& xnew,
const arma::uvec& eval_dims,
const arma::uvec& condition_dims,
const arma::mat& condition_values,
const int nparticles = 50
) {
// Check list is of appropriate type
if (!Rf_inherits(model, "PL"))
throw "List must be a PL object";
// Allocate space
const uvec edims = eval_dims - 1;
const uvec cdims = condition_dims - 1;
const int total_dims = edims.n_elem + cdims.n_elem;
const uword K = xnew.n_rows, L = condition_values.n_rows;
mat density(K, L, fill::zeros);
// Marginal model
Rcpp::List marginal = dp_normal_marginal(model, cdims + 1);
// Priors
Rcpp::List param = model["param"];
vec lambda = param["lambda"];
vec mlambda = lambda(cdims);
mat Omega = param["Omega"];
mat mOmega = Omega.submat(cdims, cdims);
const DPNormalPrior prior((double) param["alpha"], lambda, (double) param["kappa"], (double) param["nu"], Omega);
const DPNormalPrior mprior((double) param["alpha"], mlambda, (double) param["kappa"], (double) param["nu"], mOmega);
// Eval conditional densities
const int N0 = min((int) model["N"], nparticles);
Rcpp::List particle_list = model["particle_list"];
Rcpp::List mparticle_list = marginal["particle_list"];
for (int i = 0; i < N0; i++) {
Rcpp::List particle_param = particle_list[i];
Rcpp::List mparticle_param = mparticle_list[i];
int m = particle_param["m"];
vec n = particle_param["n"];
mat mu = particle_param["mu"];
mat mmu = mparticle_param["mu"];
cube S = particle_param["S"];
cube mS = mparticle_param["S"];
Particle zfull(m, n, mu, S);
Particle zmarginal(m, n, mmu, mS);
for (uword l = 0; l < L; l++) {
for (uword k = 0; k < K; k++) {
vec xfull(total_dims, fill::zeros);
xfull(edims) = xnew.row(k).t();
xfull(cdims) = condition_values.row(l).t();
double djoint = sum(predictive(xfull, zfull, prior));
double dmarginal = sum(predictive(condition_values.row(l).t(), zmarginal, mprior));
density(k, l) += djoint / dmarginal / N0;
}
}
}
return density;
}
|
b95136459ea0ae9d9b6b87ea7be531bccff064b5
|
838f063e516b979364bdddb7a8604f9c3ff405d8
|
/backend/actions/context.h
|
3062c54d44e9290d1ee82437ad9f767c1915e135
|
[
"Apache-2.0"
] |
permissive
|
GoogleCloudPlatform/cloud-spanner-emulator
|
d205193c7c3c265a47a822e1df574271c8522759
|
53eaa404d303fb2dc03f3b444553aa9bb24c3786
|
refs/heads/master
| 2023-08-29T12:33:41.780107
| 2023-08-11T08:15:10
| 2023-08-11T08:15:10
| 251,420,886
| 236
| 38
|
Apache-2.0
| 2023-09-07T12:35:45
| 2020-03-30T20:28:25
|
C++
|
UTF-8
|
C++
| false
| false
| 5,814
|
h
|
context.h
|
//
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#ifndef THIRD_PARTY_CLOUD_SPANNER_EMULATOR_BACKEND_ACTIONS_CONTEXT_H_
#define THIRD_PARTY_CLOUD_SPANNER_EMULATOR_BACKEND_ACTIONS_CONTEXT_H_
#include <memory>
#include <utility>
#include <vector>
#include "zetasql/public/value.h"
#include "absl/status/statusor.h"
#include "absl/types/span.h"
#include "backend/actions/ops.h"
#include "backend/datamodel/key.h"
#include "backend/datamodel/key_range.h"
#include "backend/schema/catalog/column.h"
#include "backend/schema/catalog/table.h"
#include "backend/storage/iterator.h"
#include "common/clock.h"
namespace google {
namespace spanner {
namespace emulator {
namespace backend {
// EffectsBuffer abstracts the mutation environment in which an action lives.
//
// Actions don't directly mutate underlying storage (via Write/Delete), but
// instead specify the row operation they would like to apply to storage. These
// row operations get buffered to the list of row operations that the
// transaction needs to apply. Within a statement, for a given row operation,
// all effects resulting from the row operation (including cascading effects)
// are processed before the next row mutation in the statement is processed.
class EffectsBuffer {
public:
virtual ~EffectsBuffer() = default;
// Adds an insert operation to the effects buffer.
virtual void Insert(const Table* table, const Key& key,
absl::Span<const Column* const> columns,
const std::vector<zetasql::Value>& values) = 0;
// Adds an update operation to the effects buffer.
virtual void Update(const Table* table, const Key& key,
absl::Span<const Column* const> columns,
const std::vector<zetasql::Value>& values) = 0;
// Adds a delete operation to the effects buffer.
virtual void Delete(const Table* table, const Key& key) = 0;
};
// TODO: Remove ChangeStreamEffectsBuffer.
class ChangeStreamEffectsBuffer {
public:
virtual ~ChangeStreamEffectsBuffer() = default;
// Adds an insert operation to the effects buffer.
virtual void Insert(zetasql::Value partition_token_str,
const ChangeStream* change_stream,
const InsertOp& op) = 0;
// Adds an update operation to the effects buffer.
virtual void Update(zetasql::Value partition_token_str,
const ChangeStream* change_stream,
const UpdateOp& op) = 0;
// Adds a delete operation to the effects buffer.
virtual void Delete(zetasql::Value partition_token_str,
const ChangeStream* change_stream,
const DeleteOp& op) = 0;
virtual void BuildMutation() = 0;
virtual std::vector<WriteOp> GetWriteOps() = 0;
};
// ReadOnlyStore abstracts the storage environment in which an action lives.
//
// The contents of the storage presented to the action depends on when the
// action runs. Examples:
//
// - Actions which modify the row operation (like DEFAULT) will run before the
// row operation has been applied to the storage and will see the contents of
// the storage without the effect of the row operation.
//
// - Actions which verify statements (like index uniqueness verification) will
// run after the row operation (in fact after all row operations in the
// statement) has (have) been applied and will see the effect of the row
// operation.
class ReadOnlyStore {
public:
virtual ~ReadOnlyStore() = default;
// Returns true if the given key exist, false if it does not.
virtual absl::StatusOr<bool> Exists(const Table* table,
const Key& key) const = 0;
// Returns true if a row with the given key prefix exist, false if it does
// not.
virtual absl::StatusOr<bool> PrefixExists(const Table* table,
const Key& prefix_key) const = 0;
// Reads the given key range from the store.
virtual absl::StatusOr<std::unique_ptr<StorageIterator>> Read(
const Table* table, const KeyRange& key_range,
absl::Span<const Column* const> columns) const = 0;
};
// ActionContext contains the context in which an action operates.
class ActionContext {
public:
ActionContext(
std::unique_ptr<ReadOnlyStore> store,
std::unique_ptr<EffectsBuffer> effects,
std::unique_ptr<ChangeStreamEffectsBuffer> change_stream_effects,
Clock* clock)
: store_(std::move(store)),
effects_(std::move(effects)),
change_stream_effects_(std::move(change_stream_effects)),
clock_(clock) {}
// Accessors.
ReadOnlyStore* store() const { return store_.get(); }
EffectsBuffer* effects() const { return effects_.get(); }
ChangeStreamEffectsBuffer* change_stream_effects() const {
return change_stream_effects_.get();
}
Clock* clock() const { return clock_; }
private:
std::unique_ptr<ReadOnlyStore> store_;
std::unique_ptr<EffectsBuffer> effects_;
std::unique_ptr<ChangeStreamEffectsBuffer> change_stream_effects_;
// System-wide monotonic clock.
Clock* clock_;
};
} // namespace backend
} // namespace emulator
} // namespace spanner
} // namespace google
#endif // THIRD_PARTY_CLOUD_SPANNER_EMULATOR_BACKEND_ACTION_CONTEXT_H_
|
ebab0736a1d04f0ac2a84563e1f37daf9daf1273
|
5a6fef4990838748dcc75153ec796e5067bffd8f
|
/TouchGFX/gui/src/model/Model.cpp
|
2efc7e69cfa1e23358311a6f5fa827ffee9c5227
|
[] |
no_license
|
AdrianBesciak/STM32WeatherStation
|
b094035ee3cd74cf7f62e0e1fa21b890ab588682
|
51434a1c962f5c1cc47813993d6ef903b2e19e80
|
refs/heads/master
| 2023-05-06T09:19:07.511455
| 2021-05-27T19:03:26
| 2021-05-27T19:03:26
| 348,804,324
| 7
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,100
|
cpp
|
Model.cpp
|
#include <gui/model/Model.hpp>
#include <gui/model/ModelListener.hpp>
#include "ds18b20.hpp"
#include "weather.hpp"
Model::Model() : modelListener(nullptr), tick_count(0) {
}
void mockData() {
weatherForecast.status = static_cast<Weather_t>((weatherForecast.status + 1) % 5);
weatherForecast.temperature += 0.1;
weatherForecast.feels_like += 0.2;
weatherForecast.humidity = (weatherForecast.humidity + 1) % 100;
weatherForecast.pressure++;
weatherForecast.wind_speed += 0.1;
weatherForecast.sunset += 2137;
weatherForecast.sunrise += 1337;
weatherForecast.visibility += 0.1;
// weatherForecast.error = static_cast<Weather_Error_t>((weatherForecast.error + 1) % (RECV_EMPTY + 1));
}
void Model::tick() {
if (tick_count % 60 == 0) {
const auto &t = thermometers[0];
if (t.isValid()) {
auto temp = t.getTemperature();
modelListener->temperatureChanged(temp);
}
}
if (tick_count % 60 == 0) {
// mockData();
modelListener->weatherChanged(&weatherForecast);
}
tick_count++;
}
|
1a0d0a862cf02a96c252d2254a20075b73821d05
|
2193e470633936c4fc65e11644d343d6ca1b0161
|
/BullCowGame-starter-kit/Source/BullCowGame/BullCowCartridge.cpp
|
b7fc624469ad46da2f271c1dabe7c3f614caaf83
|
[] |
no_license
|
kamelCased/unreal-cpp
|
6996f4aa26d6f0fad180a5cc466d977720314bdb
|
9410e12509726f824eebed45940f38e5d84e9aa4
|
refs/heads/main
| 2023-08-17T18:22:14.569250
| 2021-10-22T19:24:11
| 2021-10-22T19:24:11
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,892
|
cpp
|
BullCowCartridge.cpp
|
#include "BullCowCartridge.h"
// Start game
void UBullCowCartridge::BeginPlay()
{
if (FirstGame) {
Super::BeginPlay();
// load in words
loadWords();
}
// Set word and lives
SetGameParams();
// Instructions
PrintWelcomeMessage();
PrintLives();
PrintHiddenWordLength();
// Start playing
}
// After a player guess
void UBullCowCartridge::OnInput(const FString& Input)
{
// During gameplay
if (Lives > 0 && !WonGame)
{
ClearScreen();
ProcessGuess(Input);
}
// Outside gameplay
else
{
PlayAgain();
}
}
void UBullCowCartridge::SetGameParams()
{
WonGame = false;
// Select hidden word
do
{
HiddenWord = HiddenWordOptions[FMath::RandRange(0, HiddenWordOptions.Num())];
}
while(HiddenWord.Len() < 4 || !IsIsogram(HiddenWord));
// Debug line
// PrintLine(HiddenWord);
// Set number of lives
Lives = HiddenWord.Len();
}
void UBullCowCartridge::PrintWelcomeMessage() const
{
PrintLine(TEXT("Welcome to the bull cow game!"));
}
void UBullCowCartridge::PrintLives() const
{
PrintLine(FString::Printf(TEXT("+ You have %i lives left."), Lives));
}
void UBullCowCartridge::PrintHiddenWordLength() const
{
PrintLine(FString::Printf(TEXT("+ Guess the %i letter isogram..."), HiddenWord.Len()));
}
void UBullCowCartridge::PrintExitMessage() const
{
PrintLine(TEXT("We hope you enjoyed playing the Bull & Cow game! Press enter to play again..."));
}
void UBullCowCartridge::ProcessGuess(const FString& Guess)
{
// Guess is right
if (Guess == HiddenWord)
{
WonGame = true;
GameOver();
}
// Guess has incorrect length
else if (Guess.Len() != HiddenWord.Len())
{
PrintLine(TEXT("Wrong answer. Your guess is a %i letter word. \nThe hidden word is a %i letter isogram."), Guess.Len(), HiddenWord.Len());
}
// Guess has correct length but is not an isogram
else if (!IsIsogram(Guess))
{
PrintLine(TEXT("Wrong answer. Your guess is not an isogram. \nThe hidden word is a %i letter isogram: it has no repeated letters."), HiddenWord.Len());
}
// Guess is correct length but wrong word
else
{
// lose a life
--Lives;
// Remaining lives
if (Lives > 0)
{
// count bulls and cows
CountBullsCows(Guess);
// show lives left
PrintLives();
}
else {
GameOver();
}
}
}
bool UBullCowCartridge::IsIsogram(const FString& Word) const
{
for (int32 LetterPos = 0; LetterPos < Word.Len(); LetterPos++)
{
for (int32 OtherLetterPos = LetterPos + 1; OtherLetterPos < Word.Len(); OtherLetterPos++)
{
// same letter found twice
if (Word[LetterPos] == Word[OtherLetterPos])
{
// word is not isogram
return false;
}
}
}
// no repeated letters, word is isogram
return true;
}
void UBullCowCartridge::CountBullsCows(const FString& Guess) const
{
// count bulls (same letter at same index) and cows (same letter at different index)
int32 Bulls = 0, Cows = 0;
for (int GuessIndex = 0; GuessIndex < Guess.Len(); GuessIndex++)
{
// Same letter at same index
if (Guess[GuessIndex] == HiddenWord[GuessIndex])
{
Bulls++;
}
// Different letter at same index
else
{
// Check rest of HiddenWord for same letter
for (int HiddenWordIndex = 0; HiddenWordIndex < HiddenWord.Len(); HiddenWordIndex++)
{
// Same letter at different index
if (Guess[GuessIndex] == HiddenWord[HiddenWordIndex])
{
Cows++;
break;
}
}
}
}
// Print result
PrintLine(FString::Printf(TEXT("You had %i bull(s) and %i cow(s)."), Bulls, Cows));
}
void UBullCowCartridge::GameOver()
{
// Game won
if (WonGame)
{
PrintLine(TEXT("You won the game!"));
}
// Game lost
else
{
PrintLine(TEXT("You lost the game!"));
PrintLine(FString::Printf(TEXT("The word was: %s"), *HiddenWord));
}
// Game ended
PrintExitMessage();
}
void UBullCowCartridge::PlayAgain()
{
// New game
ClearScreen();
FirstGame = false;
BeginPlay();
}
void UBullCowCartridge::loadWords() {
const FString WordListPath = FPaths::ProjectContentDir() / TEXT("WordList/HiddenWordList.txt");
FFileHelper::LoadFileToStringArray(HiddenWordOptions, *WordListPath);
}
|
8ddeaca3e4040210835c17b7ced55914e5c3e818
|
5687fe3f0f9a8b81fdef8d309b34665ad95ae969
|
/Threads/assignment4.cpp
|
21aaf981608e2b6cce22b51ed41e1c5380981ddc
|
[] |
no_license
|
asifrasheed6/CMP310
|
b608e72e564102e6c58f890158bbb9ea087b99d2
|
3e8c4769da1c397419ea22786ddca73d8017e9cd
|
refs/heads/master
| 2023-01-11T23:40:57.259889
| 2020-11-12T19:59:42
| 2020-11-12T19:59:42
| 299,400,618
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,102
|
cpp
|
assignment4.cpp
|
#include<stdio.h>
#include<stdlib.h>
#include<QThread>
#include<QMutex>
#include<QSemaphore>
/*
Program to solve the Jurassic Park Problem.
The program accpets the number of visitors and number of cars as command line parameters.
The program runs multiple visitor and car threads.
Number of visitor threads are equal to the number of visitors and the number of car threads are equal to the number of cars.
Each visitor thread and car thread would have reference to a buffer from which cars retrieve waiting passenger, reference to the QSemaphore cars which represents the available cars and reference to the QSemaphore passengers which represents the passangers wating for a car.
Written by Abdullah Siddiqui (00075201) and Asif Rasheed (00073877).
*/
class Visitor : public QThread{
private:
Visitor **buffer;
int id, buffer_size;
QSemaphore *cars, *passengers;
public:
/*
The static attributes:
index represents the next index of the buffer to write to.
COUNT represents the number of Visitor objects.
mutex used to synchronize writing to the buffer.
*/
static int index, COUNT;
static QMutex mutex;
Visitor(Visitor **buffer, int buffer_size, QSemaphore *cars, QSemaphore *passengers) : buffer(buffer), id(COUNT++), buffer_size(buffer_size), cars(cars), passengers(passengers) {}
int getID(){
return id;
}
/*
Each visitor would sleep for upto 5 seconds.
Each visitor would wait if no cars are available and once a car is available will write to the buffer.
It would acquire the QSemaphore cars decreasing the number of available cars and release the QSemaphore passengers increasing the number of passengers.
*/
void run(){
sleep(rand() % 6);
printf("Visitor %d is waiting for a car\n", id);
cars->acquire();
mutex.lock();
buffer[index++] = this;
index %= buffer_size;
mutex.unlock();
passengers->release();
}
/*
Destructor is called by a Car thread once "the car drops off the passenger".
It would decrement COUNT by 1. Once count is zero, would write NULL to all buffer indexes.
*/
~Visitor(){
--COUNT;
printf("Visitor %d left the park\n", id);
for(int i=0; COUNT == 0 && i<buffer_size; i++){
cars->acquire();
mutex.lock();
buffer[index++] = NULL;
index %= buffer_size;
mutex.unlock();
passengers->release();
}
}
};
int Visitor::index = 0;
int Visitor::COUNT = 0;
QMutex Visitor::mutex;
class Car : public QThread{
private:
Visitor **buffer;
int id, buffer_size;
QSemaphore *cars, *passengers;
public:
/*
The static attributes:
index represents the next index of the buffer to read from.
COUNT represents the number of Car objects.
mutex used to synchronize reading from the buffer.
*/
static int index, COUNT;
static QMutex mutex;
Car(Visitor **buffer, int buffer_size, QSemaphore *cars, QSemaphore *passengers) : buffer(buffer), id(COUNT++), buffer_size(buffer_size), cars(cars), passengers(passengers) {}
/*
If there are no passengers available, the threads would wait. Once there is a visitor available, it would acquire the passenger reducing the number of available passengers, read the visitor from buffer and sleeps for upto 3 seconds. Once woken up, it would release the semaphore cars increasing the number of available cars and deallocate the visitor (drops off the passenger).
*/
void run(){
while(1){
passengers->acquire();
mutex.lock();
Visitor *visitor = buffer[index++];
index %= buffer_size;
mutex.unlock();
if(visitor == NULL)
break;
printf("Car %d got visitor %d as a passenger\n", id, visitor->getID());
sleep(rand() % 4);
printf("Car %d returned\n", id);
cars->release();
delete visitor;
}
}
};
int Car::index = 0;
int Car::COUNT = 0;
QMutex Car::mutex;
int main(int argc, char** argv){
if(argc < 3){
printf("Usage: %s NUM_VISITORS NUM_CARS\n", argv[0]);
return 1;
}
const int NUM_VISITORS = atoi(argv[1]);
const int NUM_CARS = atoi(argv[2]);
Visitor *buffer[NUM_CARS];
QSemaphore cars(NUM_CARS), passengers;
Visitor *visitor[NUM_VISITORS];
Car *car[NUM_CARS];
for(int i=0; i<NUM_CARS; i++){
car[i] = new Car(buffer, NUM_CARS, &cars, &passengers);
car[i]->start();
}
for(int i=0; i<NUM_VISITORS; i++){
visitor[i] = new Visitor(buffer, NUM_CARS, &cars, &passengers);
visitor[i]->start();
}
// Doesn't need to wait for the Visitor threads as all the visitor threads are deallocated by the Car threads.
for(int i=0; i<NUM_CARS; i++){
car[i]->wait();
delete car[i];
}
return 0;
}
|
72a120125e854ec631189dfa891bba40cf9be32b
|
379883bdfa84528741a56a2f02a946989b539c65
|
/CPP.Part_2/week_1/helpers/nmspace_test/file1.cpp
|
92b8ce3831f40796c026671019e0c2e063174986
|
[
"Unlicense"
] |
permissive
|
DGolgovsky/Courses
|
3bcaac3dc32d8ee84b02e1aafad0709ae4a6bd41
|
01e2dedc06f677bcdb1cbfd02ccc08a89cc932a0
|
refs/heads/master
| 2022-12-31T14:27:10.668181
| 2020-10-26T08:10:19
| 2020-10-26T08:10:19
| 111,097,533
| 5
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 194
|
cpp
|
file1.cpp
|
#include "header.hpp"
/*
void file1()
{
std::cout << "File1:\n";
std::cout << size_t(&foo) << '\n';
std::cout << size_t(&bar) << '\n';
std::cout << size_t(&foobar) << '\n';
}
*/
|
8c52a399004630cc4fa6c665946981ba1242fcbd
|
41778ded99c3d573661983be345a325f1ec1115a
|
/cal/correctPosCsI.cpp
|
81ad37419ecf4ff087cfb5cbcfc398af78d5bd8e
|
[] |
no_license
|
ChronoBro/sort_7Li
|
f27f600c9876f7ac79cb665394b3949d68312401
|
5fb4338b5c9fdf690e0d6582eff953ca2956a11a
|
refs/heads/master
| 2021-01-20T21:11:47.498108
| 2019-08-12T17:09:01
| 2019-08-12T17:09:01
| 60,623,927
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,690
|
cpp
|
correctPosCsI.cpp
|
#include <iostream>
#include <fstream>
#include "TGraph.h"
using namespace std;
void correctPosCsI ()
{
int no=0;
ostringstream outstring;
string name;
//making this just change Russian calibrations for now
//never mind previous comment, found mistake in energy calibrations....
//never mind never mind
//never mind never mind never mind
for(no=0;no<32;no++)
{
outstring.str("");
outstring << "/home/lithium7/unpacker/cal/blockCalCsid"<<no;
name = outstring.str();
name = name +".cal";
ofstream ofile0(name.c_str());
if(!ofile0.is_open()){cout << "ERROR opening " << name << endl;}
outstring.str("");
outstring << "/home/lithium7/unpacker/cal/posCorrectCal/channels_energy" << no;
name = outstring.str();
name = name + ".cal";
ifstream ifile0(name.c_str());
if(!ifile0.is_open())cout << "ERROR opening " << name << endl;
int i;
int j;
int k;
int n=4; //number of peaks
int cycles=8; //number of blocks
float channel[128];
float energy[128];
float use1[4];
float use2[4];
TGraph * gr;
TF1 * fit;
float slope;
float intercept;
float quad;
for (i=0;i<32;i++)
{
ifile0 >> channel[i]>> energy [i] ;
}
//cout << channel[0] << endl;
//cout << energy[0]<< endl;;
i=0;
for(j=1;j<=cycles;j++)
{
for(k=0;i<j*n;i++)
{
use1[k]=channel[i];
use2[k]=energy[i];
k++;
cout << "i = " << i << endl;
cout << "k = " << k << endl;
cout << "channel = " << channel[i] <<endl;
cout << "energy = " << energy[i] << endl;
}
gr = new TGraph(n,use1,use2);
gr->Fit("pol1");
fit = gr->GetFunction("pol1");
// quad = fit->GetParameter(2);
slope = fit->GetParameter(1);
intercept = fit->GetParameter(0);
ofile0 << slope << "\t" << intercept << endl;
}
ifile0.close();
ofile0.close();
}
for(no=0;no<32;no++)
{
outstring.str("");
outstring << "/home/lithium7/unpacker/cal/blockCalCsiA"<<no;
name = outstring.str();
name = name +".cal";
ofstream ofile0(name.c_str());
if(!ofile0.is_open()){cout << "ERROR opening " << name << endl;}
outstring.str("");
outstring << "/home/lithium7/unpacker/cal/posCorrectCal/channels_energy" << no;
name = outstring.str();
name = name + "_a.cal";
ifstream ifile0(name.c_str());
if(!ifile0.is_open())cout << "ERROR opening " << name << endl;
int i;
int j;
int k;
int n=3; //number of peaks
int cycles=8; //number of blocks
float channel[128];
float energy[128];
float use1[4];
float use2[4];
TGraph * gr;
TF1 * fit;
float slope;
float intercept;
float quad;
for (i=0;i<32;i++)
{
ifile0 >> channel[i]>> energy [i] ;
}
//cout << channel[0] << endl;
//cout << energy[0]<< endl;;
i=0;
for(j=1;j<=cycles;j++)
{
for(k=0;i<j*n;i++)
{
use1[k]=channel[i];
use2[k]=energy[i];
k++;
cout << "i = " << i << endl;
cout << "k = " << k << endl;
cout << "channel = " << channel[i] <<endl;
cout << "energy = " << energy[i] << endl;
}
gr = new TGraph(n,use1,use2);
gr->Fit("pol1");
fit = gr->GetFunction("pol1");
//quad = fit->GetParameter(2);
slope = fit->GetParameter(1);
intercept = fit->GetParameter(0);
ofile0 << slope << "\t" << intercept << endl;
}
ifile0.close();
ofile0.close();
}
}
|
c879ab4eb367d1cb4deb0d299fafdc72a6af1858
|
1fe0b84836f9ab6a44694e81447329608ceb9fc4
|
/suma/suma.cpp
|
41862b5c6bf526b2ef8294d99f3b96006b7f9103
|
[] |
no_license
|
carlitosColonSalva/c-plus-plus-samples
|
9be1f19919c10edf818966010ba58203481a79e5
|
ea69944e489c443aa8c82712c70c7d912127aa77
|
refs/heads/main
| 2023-06-20T06:37:07.266209
| 2021-07-18T01:43:19
| 2021-07-18T01:43:19
| 385,975,128
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 286
|
cpp
|
suma.cpp
|
#include <iostream>
using namespace std;
#include <string>
int sumar();
void main()
{
int num0;
num0 = sumar();
cout << num0;
system("pause");
}
int sumar()
{
int num1, num2, num3;
num1 = 1;
num2 = 2;
num3 = num1 + num2;
return num3;
}
|
4c77891d1ac4566a76e5f52c9b8e8acc813e1f53
|
96a330b0069bf008457d7a9201fc8eba83ff86c6
|
/src/services/pcn-dynmon/src/extractor/MapExtractor.cpp
|
729666463adcfbe21419ee01f5765f671527d8f4
|
[
"Apache-2.0"
] |
permissive
|
polycube-network/polycube
|
0ef845cb7043a47c37f2f2073d5aaf818da6da46
|
a143e3c0325400dad7b9ff3406848f5a953ed3d1
|
refs/heads/master
| 2023-03-20T01:08:32.534908
| 2022-06-30T12:45:40
| 2022-06-30T12:45:40
| 161,432,392
| 463
| 107
|
Apache-2.0
| 2023-03-07T01:11:30
| 2018-12-12T04:23:33
|
C++
|
UTF-8
|
C++
| false
| false
| 20,571
|
cpp
|
MapExtractor.cpp
|
#include "MapExtractor.h"
#include <functional>
#include <string>
#include <linux/bpf.h>
#include "polycube/services/table_desc.h"
#define INT "int"
#define CHAR "char"
#define SHORT "short"
#define LONG "long"
#define FLOAT "float"
#define DOUBLE "double"
#define LONG_LONG "long long"
#define LONG_DOUBLE "long double"
#define SIGNED_CHAR "signed char"
#define UNSIGNED_INT "unsigned int"
#define UNSIGNED_CHAR "unsigned char"
#define UNSIGNED_LONG "unsigned long"
#define UNSIGNED_SHORT "unsigned short"
#define UNSIGNED_LONG_LONG "unsigned long long"
using std::ostringstream;
using std::runtime_error;
using namespace polycube::service;
using json = nlohmann::json;
using value_type = json::object_t::value_type;
#pragma region compiletime_string_hashing
/**
* This region of code exports the hash method which is used at compile time to
* transform a string into uint64_t value by hashing it; this permits to use
* the switch statement on strings.
*/
namespace StringHash {
constexpr uint64_t _(uint64_t h, const char *s) {
return (*s == 0)
? h
: _((h * 1099511628211ull) ^ static_cast<uint64_t>(*s), s + 1);
}
constexpr uint64_t hash(const char *s) {
return StringHash::_(14695981039346656037ull, s);
}
uint64_t hash(const std::string &s) {
return StringHash::_(14695981039346656037ull, s.data());
}
} // namespace StringHash
#pragma endregion
using namespace StringHash;
#define ENUM hash("enum")
#define UNION hash("union")
#define STRUCT hash("struct")
#define STRUCT_PACKED hash("struct_packed")
#define PADDING "__pad_"
typedef enum {
Property,
ArrayProperty,
Value,
Struct,
Union,
Enum,
} objectType;
/**
* Recognizes the type of a node object contained in a TableDesc's leaf_desc tree
*
* @param[object] the object to be recognized
*
* @throw std::runtime_error if the object cannot be recognized
*
* @returns a objectType
*/
objectType identifyObject(json object) {
if (object.is_string())
return Value;
if (object.is_array()) {
if (object.size() == 2)
return Property;
if (object.size() == 3) {
if (object[2].is_string()) {
switch (hash(object[2])) {
case STRUCT:
case STRUCT_PACKED:
return Struct;
case UNION:
return Union;
case ENUM:
return Enum;
default:
throw runtime_error("Unknown type" + object[3].get<string>());
}
} else if (object[2].is_array())
return ArrayProperty;
else if (object[2].is_number() && object[1].is_string())
return Property;
throw runtime_error("Unknown element" + object[0].get<string>());
}
}
throw runtime_error("Unable to identifyObject " + object.dump());
}
json MapExtractor::extractFromArrayMap(const TableDesc &desc, RawTable table,
std::shared_ptr<ExtractionOptions> &extractionOptions) {
auto value_desc = json::parse(string{desc.leaf_desc});
json j_entries;
MapEntry batch(desc.max_entries * desc.key_size,
desc.max_entries * desc.leaf_size);
unsigned int count = desc.max_entries;
//Trying to retrieve values using batch operations
if(table.get_batch(batch.getKey(), batch.getValue(), &count) == 0 || errno == ENOENT) {
//Batch retrieval ok, checking if need to empty
if(count > 0 && extractionOptions->getEmptyOnRead()) {
MapEntry reset(0, desc.max_entries * desc.leaf_size);
table.update_batch(batch.getKey(), reset.getValue(), &count);
}
for(int i=0; i<count; i++) {
int offset = 0;
auto value = recExtract(value_desc, static_cast<char*>(batch.getValue()) + i*desc.leaf_size, offset);
j_entries.push_back(value);
}
return j_entries;
}
// Retrieving values using old method
std::vector<std::shared_ptr<MapEntry>> entries;
MapEntry reset_value(0, desc.key_size);
void *last_key = nullptr;
//Getting all map values
while (true) {
MapEntry entry(desc.key_size, desc.leaf_size);
if (table.next(last_key, entry.getKey()) > -1) {
last_key = entry.getKey();
table.get(entry.getKey(), entry.getValue());
entries.push_back(std::make_shared<MapEntry>(entry));
if(extractionOptions->getEmptyOnRead())
table.set(last_key, reset_value.getValue());
}else
break;
}
//Parsing retrieved values
for(auto &entry: entries) {
int offset = 0;
auto j_entry = recExtract(value_desc, entry->getValue(), offset);
j_entries.push_back(j_entry);
}
return j_entries;
}
json MapExtractor::extractFromQueueStackMap(const TableDesc &desc, RawQueueStackTable table,
std::shared_ptr<ExtractionOptions> &extractionOptions) {
auto value_desc = json::parse(string{desc.leaf_desc});
std::vector<std::shared_ptr<MapEntry>> entries;
// Retrieving map entries iteratively, DOES NOT SUPPORT BATCH OPERATIONS
while(true) {
MapEntry entry(0, desc.leaf_size);
if (table.pop(entry.getValue()) != 0)
break;
entries.push_back(std::make_shared<MapEntry>(entry));
}
json j_entries;
for(auto &entry: entries) {
int offset = 0;
auto j_entry = recExtract(value_desc, entry->getValue(), offset);
j_entries.push_back(j_entry);
}
return j_entries;
}
json MapExtractor::extractFromHashMap(const TableDesc &desc, RawTable table,
std::shared_ptr<ExtractionOptions> &extractionOptions) {
// Getting both key_desc and leaf_desc objects which represents the structure of the map entry
auto value_desc = json::parse(string{desc.leaf_desc});
auto key_desc = json::parse(string{desc.key_desc});
json j_entries;
MapEntry batch(desc.max_entries * desc.key_size,
desc.max_entries * desc.leaf_size);
unsigned int count = desc.max_entries;
//Trying to retrieve values using batch operations
if((extractionOptions->getEmptyOnRead() && (table.get_and_delete_batch(batch.getKey(), batch.getValue(), &count) == 0 || errno == ENOENT)) ||
(!extractionOptions->getEmptyOnRead() && (table.get_batch(batch.getKey(), batch.getValue(), &count) == 0 || errno == ENOENT))) {
//Batch retrieval ok
for(int i=0; i<count; i++) {
int offset_key = 0, offset_value = 0;
json entry_obj;
entry_obj["key"] = recExtract(key_desc, static_cast<char*>(batch.getKey()) + i*desc.key_size, offset_key);
entry_obj["value"] = recExtract(value_desc, static_cast<char*>(batch.getValue()) + i*desc.leaf_size, offset_value);
j_entries.push_back(entry_obj);
}
return j_entries;
}
// Retrieving map entries with old method
std::vector<std::shared_ptr<MapEntry>> entries;
void *last_key = nullptr;
while (true) {
MapEntry entry(desc.key_size, desc.leaf_size);
if (table.next(last_key, entry.getKey()) > -1) {
last_key = entry.getKey();
table.get(entry.getKey(), entry.getValue());
entries.push_back(std::make_shared<MapEntry>(entry));
if(extractionOptions->getEmptyOnRead())
table.remove(last_key);
} else
break;
}
for (auto &entry : entries) {
int val_offset = 0, key_offset = 0;
json entry_obj;
entry_obj["key"] = recExtract(key_desc, entry->getKey(), key_offset);
entry_obj["value"] = recExtract(value_desc, entry->getValue(), val_offset);
j_entries.push_back(entry_obj);
}
return j_entries;
}
json MapExtractor::extractFromPerCPUMap(const TableDesc &desc, RawTable table,
std::shared_ptr<ExtractionOptions> &extractionOptions) {
// Getting the maximux cpu available
size_t n_cpus = polycube::get_possible_cpu_count();
size_t leaf_array_size = n_cpus * desc.leaf_size;
// Getting key and value description to parse correctly
auto value_desc = json::parse(string{desc.leaf_desc});
auto key_desc = json::parse(string{desc.key_desc});
json j_entries;
std::vector<std::shared_ptr<MapEntry>> entries;
MapEntry reset_value(0, leaf_array_size);
void *last_key = nullptr;
// Retrieving map entries with old method, DOES NOT SUPPORT BATCH OPERATION
while (true) {
MapEntry entry(desc.key_size, leaf_array_size);
if (table.next(last_key, entry.getKey()) > -1) {
last_key = entry.getKey();
table.get(entry.getKey(), entry.getValue());
entries.push_back(std::make_shared<MapEntry>(entry));
if(extractionOptions->getEmptyOnRead()) {
table.set(last_key, reset_value.getValue());
if(desc.type != BPF_MAP_TYPE_PERCPU_ARRAY) {
table.remove(last_key);
}
}
} else
break;
}
for(auto& entry : entries) {
int key_offset = 0;
json j_entry;
// Parse the current key and set the id of that entry
j_entry["key"] = recExtract(key_desc, entry->getKey(), key_offset);
json j_values;
// The leaf_size is the size of a single leaf value, but potentially there is an
// array of values! So the entry->getValue() pointer must be manually shifted to parse
// all the per_cpu values
for(int i=0, offset=0; i<n_cpus; i++, offset=0){
auto val = recExtract(value_desc, static_cast<char*>(entry->getValue()) + (i * desc.leaf_size), offset);
j_values.emplace_back(val);
}
j_entry["value"] = j_values;
j_entries.push_back(j_entry);
}
return j_entries;
}
json MapExtractor::extractFromMap(BaseCube &cube_ref, const string& map_name, int index,
ProgramType type, std::shared_ptr<ExtractionOptions> extractionOptions) {
// Getting the TableDesc object of the eBPF table
auto &desc = cube_ref.get_table_desc(map_name, index, type);
if(desc.type == BPF_MAP_TYPE_HASH || desc.type == BPF_MAP_TYPE_LRU_HASH)
return extractFromHashMap(desc, cube_ref.get_raw_table(map_name, index, type), extractionOptions);
else if(desc.type == BPF_MAP_TYPE_ARRAY)
return extractFromArrayMap(desc, cube_ref.get_raw_table(map_name, index, type), extractionOptions);
else if(desc.type == BPF_MAP_TYPE_QUEUE || desc.type == BPF_MAP_TYPE_STACK)
return extractFromQueueStackMap(desc, cube_ref.get_raw_queuestack_table(map_name, index, type), extractionOptions);
else if(desc.type == BPF_MAP_TYPE_PERCPU_HASH || desc.type == BPF_MAP_TYPE_PERCPU_ARRAY || desc.type == BPF_MAP_TYPE_LRU_PERCPU_HASH)
return extractFromPerCPUMap(desc, cube_ref.get_raw_table(map_name, index, type), extractionOptions);
else
// The map type is not supported yet by Dynmon
throw runtime_error("Unhandled Map Type " + std::to_string(desc.type) + " extraction.");
}
json MapExtractor::recExtract(json object_description, void *data, int &offset) {
// Identifying the object
auto objectType = identifyObject(object_description);
switch (objectType) {
case Property: { // the object describes a property of a C struct
auto propertyName = object_description[0].get<string>();
auto propertyType = object_description[1];
return propertyName, recExtract(propertyType, data, offset);
}
case ArrayProperty: { // the object describes a property of a C struct which is an array
auto propertyName = object_description[0].get<string>();
auto propertyType = object_description[1];
auto len = object_description[2][0].get<int>();
// array of primitive type
if (propertyType.is_string()) // this string is the name of the primitive type
return valueFromPrimitiveType(propertyType, data, offset, len);
// array of complex type
else {
json array;
for (int i = 0; i < len; i++)
array.push_back(recExtract(propertyType, data, offset));
return value_type(propertyName, array);
}
}
case Value: // the object describes a primitive type
return valueFromPrimitiveType(object_description.get<string>(), data,
offset);
case Struct: // the object describes a C struct
return valueFromStruct(object_description, data, offset);
case Union: // the object describes a C union
return valueFromUnion(object_description, data, offset);
case Enum: // the object describes a C enum
return valueFromEnum(object_description, data, offset);
}
throw runtime_error("Unhandled object type " + std::to_string(objectType) + " - recExtract()");
}
json MapExtractor::valueFromStruct(json struct_description, void *data,
int &offset) {
json array;
// Getting the name of the C struct
// auto structName = struct_description[0].get<string>();
// Getting the set of properties of the C struct
auto structProperties = struct_description[1];
// For each property
for (auto &property : structProperties) {
// Getting the property's name
auto propertyName = property[0].get<std::string>();
// Getting the property type object
// auto propertyType = property[1];
// If the property is an alignment padding -> skipp it increasing the offset
if (propertyName.rfind(PADDING, 0) == 0) {
auto paddingSize = property[2][0].get<int>();
offset += paddingSize;
} else
// Adding the property to the returning set extracting its value recursively
array.push_back(value_type(propertyName, recExtract(property, data, offset)));
}
return array;
}
json MapExtractor::valueFromUnion(json union_description, void *data,
int &offset) {
json array;
int oldOffset = offset;
int maxOffset = 0;
// Getting the name of the C union
// auto unionName = union_description[0].get<string>();
// Getting the set of properties of the C union
auto unionProperties = union_description[1];
// For each property
for (auto &property : unionProperties) {
// Getting the property's name
auto propertyName = property[0].get<std::string>();
// Getting the property type object
// auto propertyType = property[1];
// Adding the property to the returning set extracting its value recursively
array.push_back(value_type(propertyName, recExtract(property, data, offset)));
// Saving the offset in order to increase it to the maximum property size
if (offset > maxOffset)
maxOffset = offset;
// Restoring the previous offset before iterate to the next property
offset = oldOffset;
}
// Setting the offset to the maximum found so far
offset = maxOffset;
return array;
}
json MapExtractor::valueFromEnum(json enum_description, void *data,
int &offset) {
int index = *(int *)((char *)data + offset);
offset += sizeof(int);
return enum_description[1][index].get<string>();
}
json MapExtractor::valueFromPrimitiveType(const string& type_name, void *data,
int &offset, int len) {
char *address = ((char *)data + offset);
// Casting the memory pointed by *address to the corresponding C type
switch (hash(type_name)) {
case hash(INT): {
if (len == -1) {
int value = *(int *)address;
offset += sizeof(int);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
int value = *(int *)address;
offset += sizeof(int);
address += sizeof(int);
vec.push_back(value);
}
return vec;
}
}
case hash(CHAR): {
if (len == -1) {
char value = *address;
offset += sizeof(char);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
char value = *address;
offset += sizeof(char);
address += sizeof(char);
vec.push_back(value);
}
return vec;
}
}
case hash(SHORT): {
if (len == -1) {
short value = *(short *)address;
offset += sizeof(short);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
short value = *(short *)address;
offset += sizeof(short);
address += sizeof(short);
vec.push_back(value);
}
return vec;
}
}
case hash(LONG): {
if (len == -1) {
long value = *(long *)address;
offset += sizeof(long);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
long value = *(long *)address;
offset += sizeof(long);
address += sizeof(long);
vec.push_back(value);
}
return vec;
}
}
case hash(FLOAT): {
if (len == -1) {
float value = *(float *)address;
offset += sizeof(float);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
float value = *(float *)address;
offset += sizeof(float);
address += sizeof(float);
vec.push_back(value);
}
return vec;
}
}
case hash(DOUBLE): {
if (len == -1) {
double value = *(double *)address;
offset += sizeof(double);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
double value = *(double *)address;
offset += sizeof(double);
address += sizeof(double);
vec.push_back(value);
}
return vec;
}
}
case hash(LONG_LONG): {
if (len == -1) {
long long value = *(long long *)address;
offset += sizeof(long long);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
long long value = *(long long *)address;
offset += sizeof(long long);
address += sizeof(long long);
vec.push_back(value);
}
return vec;
}
}
case hash(LONG_DOUBLE): {
if (len == -1) {
long double value = *(long double *)address;
offset += sizeof(long double);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
long double value = *(long double *)address;
offset += sizeof(long double);
address += sizeof(long double);
vec.push_back(value);
}
return vec;
}
}
case hash(SIGNED_CHAR): {
if (len == -1) {
signed char value = *address;
offset += sizeof(signed char);
return value;
} else {
signed char *value = (signed char *)address;
offset += sizeof(signed char) * len;
return (char *)value;
}
}
case hash(UNSIGNED_INT): {
if (len == -1) {
unsigned int value = *(unsigned int *)address;
offset += sizeof(unsigned int);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
unsigned int value = *(unsigned int *)address;
offset += sizeof(unsigned int);
address += sizeof(unsigned int);
vec.push_back(value);
}
return vec;
}
}
case hash(UNSIGNED_CHAR): {
if (len == -1) {
unsigned char value = *address;
offset += sizeof(unsigned char);
return value;
} else {
unsigned char *value = (unsigned char *)address;
offset += sizeof(unsigned char) * len;
return (char *)value;
}
}
case hash(UNSIGNED_LONG): {
if (len == -1) {
unsigned long value = *(unsigned long *)address;
offset += sizeof(unsigned long);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
unsigned long value = *(unsigned long *)address;
offset += sizeof(unsigned long);
address += sizeof(unsigned long);
vec.push_back(value);
}
return vec;
}
}
case hash(UNSIGNED_SHORT): {
if (len == -1) {
unsigned short value = *(unsigned short *)address;
offset += sizeof(unsigned short);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
unsigned short value = *(unsigned short *)address;
offset += sizeof(unsigned short);
address += sizeof(unsigned short);
vec.push_back(value);
}
return vec;
}
}
case hash(UNSIGNED_LONG_LONG): {
if (len == -1) {
unsigned long long value = *(unsigned long long *)address;
offset += sizeof(unsigned long long);
return value;
} else {
json vec = json::array();
for (int i = 0; i < len; i++) {
unsigned long long value = *(unsigned long long *)address;
offset += sizeof(unsigned long long);
address += sizeof(unsigned long long);
vec.push_back(value);
}
return vec;
}
}
default:
throw runtime_error("ERROR: " + type_name + " not a valid type!");
}
}
|
5fd5377632578f6c461d9de24c7292e0517c5368
|
836c0526d4f3bcb00fac4ef1a72fab37d45a9f27
|
/src/ConnectionsManager.cpp
|
2fe835824621c60c03e3e5bb54dee627492384c9
|
[] |
no_license
|
unameit/yhttpd
|
6c63a0eef341bb1010a53a317fc33b227ba955a3
|
aa113ece568828fdb705f7c55d10e42598aa1d8c
|
refs/heads/master
| 2020-05-19T18:56:44.246897
| 2015-06-16T22:59:30
| 2015-06-16T22:59:30
| 37,553,831
| 1
| 0
| null | null | null | null |
ISO-8859-2
|
C++
| false
| false
| 3,133
|
cpp
|
ConnectionsManager.cpp
|
#include <sys/time.h> // struct timeval dla ::select(..)
#include <sys/types.h> // uint
#include <unistd.h> // ::select(..)
#include "SystemException.h" // rzucamy wyjątkiem, gdy select zwróci -1
#include "AsyncConnection.h" // wcześniej była tylko deklaracja zapowiadająca, a my wywołujemy metody z tej klasy
#include "ConnectionsManager.h" // definicja tej klasy
void ConnectionsManager::add(AsyncConnection *c)
{
connections.add(c);
}
void ConnectionsManager::main()
{
fd_set rfds, wfds; // read and write file/socket descriptors
uint i, rfds_count = 0, wfds_count = 0;
int fd, max_fd = -1;
AsyncConnection *c;
while(connections.getCount() > 0) {
// nigdy się nie kończymy? normalnie nie, przynajmniej na razie.
FD_ZERO(&rfds);
FD_ZERO(&wfds);
update();
for(i = 0; i < connections.getCount(); ++i) { // przeleć wszystkie..
c = (AsyncConnection *) connections[i]; // weź i-te połączenie
fd = (int) *c; // weź jego deskryptor
if ( c->isReadNeeded() ) { // jesli to i-te połączenie chce czytać, to
FD_SET(fd, &rfds); // odnotuj to
rfds_count++; // i policz, ile ich jest (chcących czytać)
if (fd > max_fd) // pamiętaj maksymalny deskryptor - dla ::select(..)
max_fd = fd;
}
if ( c->isWriteNeeded() ) { // analogicznie, jesli chce zapisywać...
FD_SET(fd, &wfds);
wfds_count++;
if (fd > max_fd)
max_fd = fd;
}
}
// nie sprawdzamy, czy jest sens wchodzić do select'a (tzn. czy jest
// chociaż jedno połączenie, które chce zapisywać lub odczytywać),
// gdyż wiemy, że tym conajmniej jednym połączeniem będzie gniazdo w
// dziedzinie UNIXa - czyli kanał komunikacjyny z procesem-rodzicem.
int rc = select(max_fd + 1, (rfds_count > 0? &rfds: NULL), (wfds_count > 0? &wfds: NULL), NULL, NULL);
if (-1 == rc)
throw SystemException("select() failed!");
update();
if (rfds_count > 0) { // były jakieś do zapisu?
for(i = 0; i < connections.getCount(); ++i) { // to sprawdźmy je
c = (AsyncConnection *) connections[i]; // weź i-te połączenie
fd = (int) *c; // weź jego deskryptor
if (FD_ISSET(fd, &rfds)) // można czytać?
c->onReadable(); // wywołaj obsługę tej sytuacji
}
}
update();
if (wfds_count > 0) { // były jakies do zapisu?
for(i = 0; i < connections.getCount(); ++i) { // to sprawdźmy je
c = (AsyncConnection *) connections[i]; // weź i-te połączenie
fd = (int) *c; // weź jego deskryptor
if (FD_ISSET(fd, &wfds)) // można pisać?
c->onWriteable(); // wywołaj obsługę tej sytuacji
}
}
}
}
void ConnectionsManager::update()
{
AsyncConnection *c;
for(uint i = 0; i < connections.getCount(); ++i) { // przeleć wszystkie..
c = (AsyncConnection *) connections[i]; // weź i-te połączenie
if (-1 == (int) *c) { // jeśli już nieaktywne, to
c->finalize(); // wywołaj pseudo-desktrukor, czyli niech obiekt wie, że już zauważylismy zakończenie połączenia
connections.remove(i--); // usuń go z tablicy
}
}
}
|
5fd4a910c61e554d79d8fa79416b31141c139217
|
8c4790265d5e6a7bc011b68b2476573d1adc2824
|
/CampionatDeKarate/addorganizatie.cpp
|
56fb46a6274b7cfa642e200a39b78bcd3a6e7993
|
[] |
no_license
|
Adrriana/proiecte
|
5e247c0e0ae5cfd3975a95e112f9e7d638fd83f9
|
d8e884b7ca11e04e796c4525c39f691958080b03
|
refs/heads/master
| 2020-12-02T21:03:20.421172
| 2018-12-06T16:33:55
| 2018-12-06T16:33:55
| 96,248,809
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,484
|
cpp
|
addorganizatie.cpp
|
#include "addorganizatie.h"
#include "ui_addorganizatie.h"
#include <QMessageBox>
AddOrganizatie::AddOrganizatie(QWidget *parent) :
QDialog(parent),
ui(new Ui::AddOrganizatie),
m_type(AddOrganizatie::AddType::ADD_PERSON)
{
ui->setupUi(this);
}
AddOrganizatie::~AddOrganizatie()
{
delete ui;
}
void AddOrganizatie::setData(const QString &id_organizatie, const QString &denumire, const QString &adresa)
{
ui->id_organizatie->setText(id_organizatie);
ui->denumire->setText(denumire);
ui->adresa->setText(adresa);
}
void AddOrganizatie::data(QString &id_organizatie, QString &denumire, QString &adresa)
{
id_organizatie = ui->id_organizatie->text();
denumire = ui->denumire->text();
adresa = ui->adresa->text();
}
void AddOrganizatie::accept()
{
bool ok = true;
if(m_type == AddType::ADD_PERSON)
{
ui->id_organizatie->text().toInt(&ok);
if(!ok)
{
QMessageBox::warning(this, tr("Add Item Error"), tr("Id should be a number"));
}
else
{
QDialog::accept();
}
}
}
void AddOrganizatie::showEvent(QShowEvent *)
{
if(m_type == AddType::ADD_PERSON)
{
setData("", "", "");
ui->id_organizatie->setEnabled(true);
ui->denumire->setEnabled(true);
ui->adresa->setEnabled(true);
}
}
void AddOrganizatie::setType(AddType type)
{
m_type = type;
}
|
cae5f419e34608170aff748891ce12b0cb5c1a4c
|
cefd6c17774b5c94240d57adccef57d9bba4a2e9
|
/WebKit/Source/WebCore/dom/LiveNodeList.cpp
|
5a0dc22ad4d8c8b27928f12e5fb8a38ed2e257f3
|
[
"BSL-1.0",
"BSD-2-Clause",
"LGPL-2.0-only",
"LGPL-2.1-only"
] |
permissive
|
adzhou/oragle
|
9c054c25b24ff0a65cb9639bafd02aac2bcdce8b
|
5442d418b87d0da161429ffa5cb83777e9b38e4d
|
refs/heads/master
| 2022-11-01T05:04:59.368831
| 2014-03-12T15:50:08
| 2014-03-12T15:50:08
| 17,238,063
| 0
| 1
|
BSL-1.0
| 2022-10-18T04:23:53
| 2014-02-27T05:39:44
|
C++
|
UTF-8
|
C++
| false
| false
| 6,215
|
cpp
|
LiveNodeList.cpp
|
/*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2006, 2007, 2008, 2010, 2013 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "LiveNodeList.h"
#include "ClassNodeList.h"
#include "Element.h"
#include "ElementTraversal.h"
#include "HTMLCollection.h"
#include "TagNodeList.h"
namespace WebCore {
ContainerNode& LiveNodeList::rootNode() const
{
if (isRootedAtDocument() && ownerNode().inDocument())
return ownerNode().document();
return ownerNode();
}
template <class NodeListType>
inline bool isMatchingElement(const NodeListType*, Element*);
template <> inline bool isMatchingElement(const LiveNodeList* nodeList, Element* element)
{
return nodeList->nodeMatches(element);
}
template <> inline bool isMatchingElement(const HTMLTagNodeList* nodeList, Element* element)
{
return nodeList->nodeMatchesInlined(element);
}
template <> inline bool isMatchingElement(const ClassNodeList* nodeList, Element* element)
{
return nodeList->nodeMatchesInlined(element);
}
ALWAYS_INLINE Element* LiveNodeList::iterateForPreviousElement(Element* current) const
{
ContainerNode& rootNode = this->rootNode();
for (; current; current = ElementTraversal::previous(current, &rootNode)) {
if (isMatchingElement(static_cast<const LiveNodeList*>(this), current))
return current;
}
return 0;
}
template <class NodeListType>
inline Element* firstMatchingElement(const NodeListType* nodeList, ContainerNode& root)
{
Element* element = ElementTraversal::firstWithin(&root);
while (element && !isMatchingElement(nodeList, element))
element = ElementTraversal::next(element, &root);
return element;
}
template <class NodeListType>
inline Element* nextMatchingElement(const NodeListType* nodeList, Element* current, ContainerNode& root)
{
do {
current = ElementTraversal::next(current, &root);
} while (current && !isMatchingElement(nodeList, current));
return current;
}
template <class NodeListType>
inline Element* traverseMatchingElementsForward(const NodeListType* nodeList, Element& current, unsigned count, unsigned& traversedCount, ContainerNode& root)
{
Element* element = ¤t;
for (traversedCount = 0; traversedCount < count; ++traversedCount) {
element = nextMatchingElement(nodeList, element, root);
if (!element)
return nullptr;
}
return element;
}
Element* LiveNodeList::collectionFirst() const
{
auto& root = rootNode();
if (type() == Type::HTMLTagNodeListType)
return firstMatchingElement(static_cast<const HTMLTagNodeList*>(this), root);
if (type() == Type::ClassNodeListType)
return firstMatchingElement(static_cast<const ClassNodeList*>(this), root);
return firstMatchingElement(static_cast<const LiveNodeList*>(this), root);
}
Element* LiveNodeList::collectionLast() const
{
// FIXME: This should be optimized similarly to the forward case.
return iterateForPreviousElement(ElementTraversal::lastWithin(&rootNode()));
}
Element* LiveNodeList::collectionTraverseForward(Element& current, unsigned count, unsigned& traversedCount) const
{
auto& root = rootNode();
if (type() == Type::HTMLTagNodeListType)
return traverseMatchingElementsForward(static_cast<const HTMLTagNodeList*>(this), current, count, traversedCount, root);
if (type() == Type::ClassNodeListType)
return traverseMatchingElementsForward(static_cast<const ClassNodeList*>(this), current, count, traversedCount, root);
return traverseMatchingElementsForward(static_cast<const LiveNodeList*>(this), current, count, traversedCount, root);
}
Element* LiveNodeList::collectionTraverseBackward(Element& current, unsigned count) const
{
// FIXME: This should be optimized similarly to the forward case.
auto& root = rootNode();
Element* element = ¤t;
for (; count && element ; --count)
element = iterateForPreviousElement(ElementTraversal::previous(element, &root));
return element;
}
unsigned LiveNodeList::length() const
{
return m_indexCache.nodeCount(*this);
}
Node* LiveNodeList::item(unsigned offset) const
{
return m_indexCache.nodeAt(*this, offset);
}
void LiveNodeList::invalidateCache() const
{
m_indexCache.invalidate();
}
Node* LiveNodeList::namedItem(const AtomicString& elementId) const
{
// FIXME: Why doesn't this look into the name attribute like HTMLCollection::namedItem does?
Node& rootNode = this->rootNode();
if (rootNode.inDocument()) {
Element* element = rootNode.treeScope().getElementById(elementId);
if (element && nodeMatches(element) && element->isDescendantOf(&rootNode))
return element;
if (!element)
return 0;
// In the case of multiple nodes with the same name, just fall through.
}
unsigned length = this->length();
for (unsigned i = 0; i < length; i++) {
Node* node = item(i);
if (!node->isElementNode())
continue;
Element* element = toElement(node);
// FIXME: This should probably be using getIdAttribute instead of idForStyleResolution.
if (element->hasID() && element->idForStyleResolution() == elementId)
return node;
}
return 0;
}
} // namespace WebCore
|
bd3425f419ea8aa484b6dab348f8957ac5d7ed86
|
2b4d34bfc16ef7b694ec3b994fd7e7b69560a479
|
/q10.cpp
|
69427a1ca82e25b064d842b0d109344697de038d
|
[] |
no_license
|
learner0101/DAA-assignment-3-Section-B
|
e33b091bcf5d17a8b8c4b7280b1f06e63bc5ea82
|
82b01267e9a2e0e474969edd30719baf5ce35bd3
|
refs/heads/master
| 2020-04-07T06:01:04.204547
| 2018-11-18T19:31:02
| 2018-11-18T19:31:02
| 158,119,229
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,228
|
cpp
|
q10.cpp
|
/*
Assignment : 3 section B
question : 10
Submitted by: vashudev(41)
*/
#include<iostream>
using namespace std;
bool **a_mat;
bool *isPotential;
int countknown(int n, int person_x)
{
/*
objective: To calculates number of people that a person_x knows.
Input variables: n- size of array isPotential, person_x - person for which number of his/ her acquaintances has to be calculated.
Return value: no of people that person_x knows
*/
int count=0;
for(int i=1; i<=n; i++){
// test whether person i is a potenital invitee and also if person i and person_x know each other
if(isPotential[i] && a_mat[i][person_x])
count++;
}
return count;
}
void plan_party(int n){
/*
objective: To computes all persons who can be invitated for a party out of n people based on following conditions:
Input variable: n - number of people to choose from
Return value: none
*/
int potential_count = n;
for(int j=1; j<=n; j++)
{
//stores the number of people j knows
int known = countknown(n,j);
//stores the number of people j does not know
int unknown = potential_count - known - 1;
//if a potenital invitee disqualifies any of condition 1 or 2, make him invalid and start checking from person 1 again
if( isPotential[j] && (known < 5 || unknown < 5) )
{
isPotential[j]=false;
potential_count--;
j = 0;
//if number of potenital invitee become less than 11, there is no way we can find a person who know 5 person and does not know 5 person
if(potential_count < 11){
for(int i=1;i<=n;i++)
isPotential[i] = false;
break;
}
}
}//the loop ends when every potential invitee satisfy both condition 1 and 2 or everyone become impotential
}
void print_invitees(int n){
/*Description
-----------
objective: To print the final invitees and the count of invitees.
*/
int count = 0;
cout<<"\n\nAlice can invite following people\n\n";
for(int i=1; i<=n; i++){
if(isPotential[i]){
cout<<i<<"\t";
count++;
}
}
if(count == 0)
cout<<"\n\nNo one can be invited.";
else
cout<<"\n\nMaximum number of people who can be invited is : "<<count;
}
// main function
int main()
{
int n;
while(true){
cout<<"\nEnter value of n: ";
cin>>n;
if(n>=11)
break;
}
a_mat = new bool*[n+1];
for(int i=0;i<=n;i++)
a_mat[i] = new bool[n+1];
isPotential = new bool[n+1];
for(int i=1; i<=n; i++)
{
isPotential[i] = true;
for(int j=1; j<=n; j++)
{
a_mat[i][j] = false;
}
}
char choice;
//input pairs
while(true)
{
int x, y;
cout<<"\nEnter pair (x,y) who know each other \n";
cout<<"\n Person x : ";
cin>>x;
if(x<1 || x>n){
cout<<"\nInvald pair!Enter again!\n";
continue;
}
cout<<"\n Person y : ";
cin>>y;
if(y<1 || y>n || y == x){
cout<<"\nInvald pair!Enter again!\n";
continue;
}
//update adjacency matrix
a_mat[x][y] = true;
a_mat[y][x] = true;
cout<<"\nAre there any more pairs who know each other?(y/n): ";
cin>>choice;
if(choice=='n')
break;
x++;
y++;
}
plan_party(n);
print_invitees(n);
return 0;
}
|
236b06fbac577617de3f5b6450eeccac23ab0a93
|
48757d2216e4f79970a0d4bb98db076a7da6b209
|
/Packet_TS.h
|
d79ef2f1e88211ba3d79fffc95b74ea5455acbeb
|
[] |
no_license
|
MtDesert/libTsPackets
|
232a043e233d8c10b7050912c47bc8ba1f1a3403
|
a7b0507fcbdc6ceb9a848110948d400b0cef37a7
|
refs/heads/master
| 2021-01-20T08:19:09.446873
| 2014-09-25T16:47:08
| 2014-09-25T16:47:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,339
|
h
|
Packet_TS.h
|
#ifndef PACKET_TS_H
#define PACKET_TS_H
#include"DataBlock.h"
class DataBlock_TsHeader:public DataBlock
{
public:
unsigned parseData(uchar *pointer, unsigned length, unsigned offset=0);
DATABLOCK_CUSTOM_ATTRIBUTE_BIGENDIAN(SyncByte,uint8,0)
DATABLOCK_BOOL_BIGENDIAN(TransportErrorIndicator,1,0)
DATABLOCK_BOOL_BIGENDIAN(PayloadUnitStartIndicator,1,1)
DATABLOCK_BOOL_BIGENDIAN(TransportPriority,1,2)
DATABLOCK_BITS_VALUE_BIGENDIAN(Pid,1,3,13)
DATABLOCK_BOOL_BIGENDIAN(TransportScramblingControl_0,3,0)
DATABLOCK_BOOL_BIGENDIAN(TransportScramblingControl_1,3,1)
DATABLOCK_BOOL_BIGENDIAN(AdaptationFieldControl_adaptationField,3,2)
DATABLOCK_BOOL_BIGENDIAN(AdaptationFieldControl_payload,3,3)
DATABLOCK_BITS_VALUE_BIGENDIAN(ContinuityCounter,3,4,4)
};
class DataBlock_AdaptionField:public DataBlock
{
public:
unsigned parseData(uchar *pointer, unsigned length, unsigned offset);
DATABLOCK_BITS_VALUE_BIGENDIAN(AdaptationFieldLength,0,0,8)
DATABLOCK_BOOL_BIGENDIAN(DiscontinuityIndicator,1,0)
DATABLOCK_BOOL_BIGENDIAN(RandomAccessIndicator,1,1)
DATABLOCK_BOOL_BIGENDIAN(ElementaryStreamPriorityIndicator,1,2)
DATABLOCK_BOOL_BIGENDIAN(PcrFlag,1,3)
DATABLOCK_BOOL_BIGENDIAN(OpcrFlag,1,4)
DATABLOCK_BOOL_BIGENDIAN(SplicingPointFlag,1,5)
DATABLOCK_BOOL_BIGENDIAN(TransportPrivateDataFlag,1,6)
DATABLOCK_BOOL_BIGENDIAN(AdaptationFieldExtentionFlag,1,7)
};
class Packet_TS:public DataBlock
{
public:
Packet_TS();
unsigned parseData(uchar *pointer, unsigned length, unsigned offset=0);
uint8 adaptation_field_length()const;
//flag
bool discontinuity_indicator()const;
bool random_access_indicator()const;
bool elementary_stream_priority_indicator()const;
bool PCR_flag()const;
bool OPCR_flag()const;
bool splicing_point_flag()const;
bool transport_private_data_flag()const;
bool adaptation_field_extension_flag()const;
//pcr_flag
uint64 program_clock_reference_base()const;
uint16 program_clock_reference_extension()const;
uint64 pcrValue()const;
//opcr_flag
uint64 original_program_clock_reference_base()const;
uint16 original_program_clock_reference_extension()const;
uint64 opcrValue()const;
//splicing_point_flag
uint8 splice_countdown()const;
//transport_private_data_flag
uint8 transport_private_data_length()const;
uchar *private_data_byte;
//adaptation_field_extension_flag
uint8 adaptation_field_extension_length()const;
uint8 ltw_flag()const;
uint8 piecewise_rate_flag()const;
uint8 seamless_splice_flag()const;
//ltw_flag
uint8 ltw_valid_flag()const;
uint16 ltw_offset()const;
//piecewise_rate_flag;
uint32 piecewise_rate()const;
//seamless_splice_flag
uint8 splice_type()const;
uint64 DTS_next_AU()const;
private:
DataBlock_TsHeader header;
DataBlock_AdaptionField adaptionField;
DataBlock payload;//Maybe it will be stuff byte
uchar *adaptation_field;//xxxOffset()
uchar *pcrVal;
uchar *opcrVal;
uchar *splice;
uchar *transport_private_data_len;
uchar *adaptation_field_extension;
uchar *ltw;
uchar *piecewiseRate;
uchar *seamless_splice;
uchar *stuffing_byte;
//uchar *payload;
};
class PacketTS:public Packet_TS
{
public:
unsigned parseData(const uchar* data,unsigned len);
private:
uchar rawData[1024];
};
#endif // PACKET_TS_H
|
542e7f7b83c3303241d39788c49be898d48f863c
|
9939aab9b0bd1dcf8f37d4ec315ded474076b322
|
/examples/nqueen/server/nqueen.hpp
|
30c15c3a5f0b8842cbc978a47515087257a067e6
|
[
"BSL-1.0",
"LicenseRef-scancode-free-unknown"
] |
permissive
|
STEllAR-GROUP/hpx
|
1068d7c3c4a941c74d9c548d217fb82702053379
|
c435525b4631c5028a9cb085fc0d27012adaab8c
|
refs/heads/master
| 2023-08-30T00:46:26.910504
| 2023-08-29T14:59:39
| 2023-08-29T14:59:39
| 4,455,628
| 2,244
| 500
|
BSL-1.0
| 2023-09-14T13:54:12
| 2012-05-26T15:02:39
|
C++
|
UTF-8
|
C++
| false
| false
| 4,835
|
hpp
|
nqueen.hpp
|
// Copyright (c) 2011 Vinay C Amatya
// Copyright (c) 2011 Bryce Lelbach
//
// SPDX-License-Identifier: BSL-1.0
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <hpx/config.hpp>
#if !defined(HPX_COMPUTE_DEVICE_CODE)
#include <hpx/hpx.hpp>
#include <hpx/include/actions.hpp>
#include <hpx/include/components.hpp>
#include <cstddef>
#include <vector>
namespace nqueen {
typedef std::vector<std::size_t> list_type;
namespace server {
class board : public hpx::components::component_base<board>
{
private:
list_type list_;
std::size_t count_;
// here board is a component
// friend class hpx::serialization::access;
// template <class Archive>
// void serialize(Archive& ar, const unsigned int version)
// {
// ar & size_;
// ar & list_;
// ar & level_;
// ar & count_;
// }
public:
board()
: list_(0)
, count_(0)
{
}
board(list_type const& list, std::size_t, std::size_t)
: list_(list)
, count_(0)
{
}
~board() = default;
void init_board(std::size_t size)
{
std::size_t i = 0;
while (i != size)
{
list_.push_back(size);
++i;
}
}
bool check_board(list_type const& list, std::size_t level)
{
for (std::size_t i = 0; i < level; ++i)
{
if ((list.at(i) == list.at(level)) ||
(list.at(level) - list.at(i) == level - i) ||
(list.at(i) - list.at(level) == level - i))
{
return false;
}
}
return true;
}
list_type access_board()
{
return list_;
}
void update_board(std::size_t pos, std::size_t val)
{
list_.at(pos) = val;
}
void clear_board()
{
board::list_.clear();
}
std::size_t solve_board(list_type const& list, std::size_t size,
std::size_t level, std::size_t col)
{
board b(list, size, level);
if (level == size)
{
return 1;
}
else if (level == 0)
{
b.update_board(level, col);
if (b.check_board(b.access_board(), level))
{
b.count_ +=
solve_board(b.access_board(), size, level + 1, col);
}
}
else
{
for (std::size_t i = 0; i < size; ++i)
{
b.update_board(level, i);
if (b.check_board(b.access_board(), level))
{
b.count_ += solve_board(
b.access_board(), size, level + 1, col);
}
}
}
return b.count_;
}
HPX_DEFINE_COMPONENT_ACTION(board, init_board, init_action)
HPX_DEFINE_COMPONENT_ACTION(board, access_board, access_action)
HPX_DEFINE_COMPONENT_ACTION(board, update_board, update_action)
HPX_DEFINE_COMPONENT_ACTION(board, check_board, check_action)
HPX_DEFINE_COMPONENT_ACTION(board, solve_board, solve_action)
HPX_DEFINE_COMPONENT_ACTION(board, clear_board, clear_action)
};
} // namespace server
} // namespace nqueen
// Declaration of serialization support for the board actions
HPX_REGISTER_ACTION_DECLARATION(
nqueen::server::board::init_action, board_init_action)
HPX_REGISTER_ACTION_DECLARATION(
nqueen::server::board::check_action, board_check_action)
HPX_REGISTER_ACTION_DECLARATION(
nqueen::server::board::access_action, board_access_action)
HPX_REGISTER_ACTION_DECLARATION(
nqueen::server::board::update_action, board_update_action)
HPX_REGISTER_ACTION_DECLARATION(
nqueen::server::board::solve_action, board_solve_action)
HPX_REGISTER_ACTION_DECLARATION(
nqueen::server::board::clear_action, board_clear_action)
#endif
|
e2e7fee0aa30c1c5ac89741e5d06638774459039
|
c63caa816dcd3aedb239969d908c617aaef38fc6
|
/src/savegamegamebyro.h
|
bce080180d250e6a3bb900205edb71d0a2386abf
|
[] |
no_license
|
noc9109/modorganizer
|
d54773560a4e8f9f9ed4ab33a8c49bbfbebb2f0d
|
5adb3b377ecd50a75dd034a49582a1da91b67e1c
|
refs/heads/master
| 2020-12-24T21:21:40.809230
| 2015-12-21T14:12:22
| 2015-12-21T14:12:22
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,126
|
h
|
savegamegamebyro.h
|
/*
Copyright (C) 2012 Sebastian Herbord. All rights reserved.
This file is part of Mod Organizer.
Mod Organizer is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Mod Organizer 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 Mod Organizer. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SAVEGAMEGAMEBRYO_H
#define SAVEGAMEGAMEBRYO_H
#include "savegame.h"
#include <QMetaType>
#include <QObject>
#include <QString>
namespace MOBase { class IPluginGame; class ISaveGame; }
/**
* @brief represents a single save game
**/
class SaveGameGamebryo : public SaveGame {
Q_OBJECT
public:
/**
* @brief construct a save game and immediately read out information from the file
*
* @param filename absolute path of the save game file
**/
SaveGameGamebryo(QObject *parent, const QString &filename, MOBase::IPluginGame const *game);
/*
SaveGameGamebryo(const SaveGameGamebryo &reference);
SaveGameGamebryo &operator=(const SaveGameGamebryo &reference);
~SaveGameGamebryo();
*/
/**
* @return number of plugins that were enabled when the save game was created
**/
int numPlugins() const { return m_Plugins.size(); }
/**
* retrieve the name of one of the plugins that were enabled when the save game
* was created. valid indices are in the range between [0, numPlugins()[
* @param index plugin index
* @return name of the plugin
**/
const QString &plugin(int index) const { return m_Plugins.at(index); }
private:
QStringList m_Plugins;
//Note: This isn't owned by us so safe to copy
MOBase::ISaveGame const *m_Save;
};
#endif // SAVEGAMEGAMEBRYO_H
|
bf38b465f13c1603ec82c2bc8002fa1ec654bbd1
|
11496c1e672cca830ad70d738a5e55c27a82d2ef
|
/EJEMPLOS/FP01/temp (2).txt
|
3f4e83d4fcb6740047f206776b4ea22815de6a4b
|
[] |
no_license
|
nievesnu/FP2
|
7edad90d79f820404f888e1a409a35405022b962
|
402cf2a162afd7884e422f888eb62374fa711f78
|
refs/heads/main
| 2023-05-27T22:14:09.601814
| 2021-06-13T12:40:02
| 2021-06-13T12:40:02
| 357,543,791
| 0
| 0
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 1,579
|
txt
|
temp (2).txt
|
#include <iostream>
#include <fstream>
using namespace std;
#include <iomanip>
int main() {
const int MaxDias = 31;
const int MED = 2; // Nº de medidas
typedef double tTemp[MaxDias][MED]; // Día x mínima / máxima
tTemp temp;
double tMaxMedia = 0, tMinMedia = 0,
tMaxAbs = -100, tMinAbs = 100;
int dia = 0;
double max, min;
ifstream archivo;
archivo.open("temp.txt");
if(!archivo.is_open())
cout << "No se ha podido abrir el archivo." << endl;
else {
archivo >> min >> max;
while(!((min == -99) && (max == -99)) && (dia < MaxDias)) {
temp[dia][0] = min;
temp[dia][1] = max;
dia++;
archivo >> min >> max;
}
archivo.close();
for(int i = 0; i < dia; i++) {
tMinMedia = tMinMedia + temp[i][0];
if(temp[i][0] < tMinAbs) {
tMinAbs = temp[i][0];
}
tMaxMedia = tMaxMedia + temp[i][1];
if(temp[i][1] > tMaxAbs) {
tMaxAbs = temp[i][1];
}
}
tMinMedia = tMinMedia / dia;
tMaxMedia = tMaxMedia / dia;
cout << "Temperaturas minimas.-" << endl;
cout << " Media = " << fixed << setprecision(1)
<< tMinMedia << " C Minima absoluta = "
<< setprecision(1) << tMinAbs << " C" << endl;
cout << "Temperaturas maximas.-" << endl;
cout << " Media = " << fixed << setprecision(1)
<< tMaxMedia << " C Maxima absoluta = "
<< setprecision(1) << tMaxAbs << " C" << endl;
}
return 0;
}
|
9bb2a02446bd693f9cf328c82049c08969b417e9
|
42f701e352599fd402c1aa76691b1c1926da56cf
|
/main.cpp
|
74b5ae6ee8875ca04f383fb237b58882a4bcdaed
|
[] |
no_license
|
wuyuanyi135/clion-excessive-cpu
|
a90ac7ac177819dd5addbdce66ffb81dc56e5554
|
4ac15bed0f36950b69f7d8b52f068947762d4168
|
refs/heads/master
| 2020-08-01T21:26:33.666857
| 2019-09-26T15:45:52
| 2019-09-26T15:45:52
| 211,122,317
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 162
|
cpp
|
main.cpp
|
#include <iostream>
#include <xtensor/xarray.hpp>
#include <xtensor/xmath.hpp>
int main() {
auto a = xt::xarray<double>({1,2,3});
auto b = xt::prod(a);
}
|
a8a88fb969cd0c491a149c47aea4550e6a235dae
|
22e3f9e32c009aa83a3b9ba112be98243faa4707
|
/main.cpp
|
270c26725510737a5a85fccef6d30b43e23ef2ef
|
[] |
no_license
|
OlexandrPavliuk/cpplessons
|
d221285be3ebd6fc32e005a8a8e7091f77247104
|
fe7bfa2c74bff0daa6535049e9779878c298b6a4
|
refs/heads/master
| 2016-08-12T15:29:06.868841
| 2016-02-28T10:40:34
| 2016-02-28T10:40:34
| 50,688,595
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 677
|
cpp
|
main.cpp
|
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <getopt.h>
#include "httpserver.h"
#include <unistd.h>
int main(int argc, char **argv) {
int opt;
char ip[255] = "\0";
int port;
char directory[255] = "\0";
while ((opt = getopt(argc, argv, "h:p:d:")) != -1) {
switch (opt) {
case 'h':
strcpy(ip, optarg);
break;
case 'p':
port = atoi(optarg);
break;
case 'd':
strcpy(directory, optarg);
break;
default:
return 1;
}
}
daemon(1, 1);
HttpServer server(ip, (unsigned short)port, directory);
server.Start();
return 0;
}
|
fa62bd82626315601789e2bf28cbbe8a49666535
|
8d2ef01bfa0b7ed29cf840da33e8fa10f2a69076
|
/code/Shared/fxList.cpp
|
5f0ec8cb354a9e564926ecdad621fd7832e32c74
|
[] |
no_license
|
BackupTheBerlios/insane
|
fb4c5c6a933164630352295692bcb3e5163fc4bc
|
7dc07a4eb873d39917da61e0a21e6c4c843b2105
|
refs/heads/master
| 2016-09-05T11:28:43.517158
| 2001-01-31T20:46:38
| 2001-01-31T20:46:38
| 40,043,333
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,192
|
cpp
|
fxList.cpp
|
//---------------------------------------------------------------------------
#include "fxList.h"
#include <assert.h>
//---------------------------------------------------------------------------
void fxList::Clear(void)
{
if (PointerArray != NULL) free(PointerArray);
PointerArray = NULL;
Count = 0;
}
void fxList::Add(void * pointer)
{
Count++;
PointerArray = realloc(PointerArray, 4 * Count);
assert(PointerArray);
int * tp = (int*)PointerArray;
tp += Count-1;
*tp = (int)pointer;
}
void fxList::Remove(int index)
{
for (int i=index; i < Count - 1; i++)
{
int * tp1 = (int*)PointerArray;
tp1 += i;
int * tp2 = (int*)PointerArray;
tp2 += i+1;
*tp1 = *tp2;
}
Count--;
PointerArray = realloc(PointerArray, Count * 4);
assert(PointerArray);
}
void fxList::Delete(void * pointer)
{
int index = GetIndex(pointer);
if (index == -1) return;
Remove(index);
}
int fxList::GetIndex(void * pointer)
{
for (int i=0; i < Count; i++)
{
int * tp = (int*)PointerArray;
tp += i;
if (*tp == (int)pointer) return i;
}
return -1;
}
void * fxList::Get(int index)
{
int * tp = (int*)PointerArray;
tp += index;
return (void*)*tp;
}
|
c2c39f0e6791e8815e5eea84a9f46f8c64beccb4
|
3f213b81b2ea38e56f3098ccabe49ed5a71f9dd5
|
/topology_cut/geometry.h
|
a899cd1c08bb686d11c292122e50630f91568dd5
|
[] |
no_license
|
silverriver/topology_cut
|
0ba4f657bcd7ecfe55caab447c45ca74f97aa1d6
|
31bb4a767a8d62fcdb42e4fbf67a686a9b15ff10
|
refs/heads/master
| 2021-01-20T16:21:59.730095
| 2019-05-30T03:30:42
| 2019-05-30T03:30:42
| 90,832,713
| 5
| 1
| null | null | null | null |
GB18030
|
C++
| false
| false
| 27,258
|
h
|
geometry.h
|
#pragma once
#include <vector>
#include <cmath>
#include <utility>
#include <CGAL\Exact_predicates_exact_constructions_kernel.h>
#include <iostream>
#include <exception>
#include <algorithm>
#include <CGAL\Polygon_2.h>
#include <CGAL\Polygon_with_holes_2.h>
#include <CGAL\Polygon_set_2.h>
#include <CGAL\Bbox_3.h>
#include <CGAL\Bbox_2.h>
#define M_PI_2 6.28318530717958647693
#define M_PI 3.14159265358979323846
namespace TC //short for topology cut
{
typedef CGAL::Exact_predicates_exact_constructions_kernel K;
typedef K::Point_2 point_2;
typedef K::Point_3 point_3;
typedef K::Plane_3 plane_3;
typedef K::Vector_2 vector_2;
typedef K::Vector_3 vector_3;
typedef K::Segment_2 segment_2;
typedef K::Segment_3 segment_3;
typedef K::Triangle_3 triangle_3;
typedef K::Line_3 line_3;
typedef K::FT FT;
typedef CGAL::Bbox_3 bbox_3;
typedef CGAL::Bbox_2 bbox_2;
typedef CGAL::Polygon_2<K> polygon_2;
typedef CGAL::Polygon_with_holes_2<K> polygon_with_holes_2;
typedef CGAL::Polygon_set_2<K> polygon_set_2;
typedef std::vector<int> index_l;
bool operator == (const index_l &l1, const index_l &l2);
inline bool operator != (const index_l &l1, const index_l &l2)
{
return !(l1==l2);
}
inline bool is_simple (const index_l &l)
{
for (int i(0);i!=l.size ();++i)
for (int j(i+1);j<l.size ();++j)
if (l[i] == l[j])
return false;
return true;
}
struct loop
{
index_l vpi; //indices of points.vpi[0]不一定等于vpi[n]
index_l vei; //vei[i] 表示边(vpi[i], vpi[i+1])的索引
std::vector <bool> ve_ori; //为每个边分配一个flag,表示这个边的方向。ve_ori[i]=true: loop中这个边与边vei[i]方向相同
void reverse () {std::reverse (vpi.begin (),vpi.end ());std::reverse (vei.begin (),vei.end ()); std::reverse (ve_ori.begin (),ve_ori.end ());}
};
struct edge
{
int n[2];
bool operator== (const edge&e) const
{
if ((n[0] == e.n[0] && n[1] == e.n[1]) ||
(n[1] == e.n[0] && n[0] == e.n[1]))
return true;
else
return false;
}
bool operator != (const edge &e) const {return !(this->operator==(e));}
edge () {}
edge (const int&n1, const int &n2) {n[0] = n1; n[1] = n2;}
edge opposite () const {return edge(n[1],n[0]);}
void sort () {if (n[0] > n[1]) {int temp(n[1]); n[1] = n[0]; n[0] = temp;}}
};
struct face
{
std::vector<loop> vl; //indices of loops, vli[0]是外圈,其余为内圈,从pli的正向往下看,vli[0]应该是逆时针旋转,其余loop应该是顺时针旋转
//int vbi[2]; //index of the block that this face belongs to. a face belongs to at most 2 blocks.
//bool vft [2]; //vft[i] = true: the outer normal of this face on block vbi[i] is the positive direction of the plane that this face belongs to.
//vft[i] = false: the outer normal of this face on block vbi[i] is the negative direction of the plane that this face belongs to.
//vft[i] = false: vli中各个loop的实际顺序应该翻转一下
int pli; //the plane holding this face
face () { /*vbi[0]=vbi[1]=-1; */pli=-1;}
void revise_loops ()
{
for (int i(0);i!=vl.size ();++i)
std::reverse(vl[i].vpi.begin (),vl[i].vpi.end ());
}
bbox_3 init_bbox (const std::vector<point_3> &vp, double tol = 0.000001) const
{
using CGAL::to_double;
FT minx ((vp[vl[0].vpi[0]].x())),maxx((vp[vl[0].vpi[0]].x()));
FT miny ((vp[vl[0].vpi[0]].y())),maxy((vp[vl[0].vpi[0]].y()));
FT minz ((vp[vl[0].vpi[0]].z())),maxz((vp[vl[0].vpi[0]].z()));
for (int i(0);i!=vl.size ();++i)
{
for (int j(0);j!=vl[i].vpi.size ();++j)
{
const point_3 &p (vp[vl[i].vpi[j]]);
if (p.x () > maxx) maxx = p.x();
if (p.x () < minx) minx = p.x();
if (p.y() >maxy) maxy = p.y();
if (p.y() <miny) miny = p.y();
if (p.z() >maxz) maxz = p.z();
if (p.z() <minz) minz = p.z();
}
}
return bbox_3 (to_double(minx)-tol, to_double(miny) - tol, to_double(minz) -tol,
to_double (maxx)+tol, to_double (maxy) + tol, to_double (maxz) + tol);
}
int init_face (const std::vector<edge> &ve); //给vl_edge和vl_edge_ori赋值,trace block 之前做一些初始化
//void merge_loops ();
};
struct block
{
std::vector <std::pair <int,bool>> vfi; //indices of faces and direction of each face (true: the outer normal of this face on this block is the positive direction of plane that this face belongs to)
};
//记录一个截面
struct csection
{
std::vector<point_3> vp;
std::vector<index_l> vl;
void clear () {vp.clear(); vl.clear();}
};
struct stl_model
{
struct tri_3
{
int n[3];
tri_3 () {}
tri_3 (const int& n1, const int& n2, const int&n3) {n[0]=n1; n[1]=n2; n[2]=n3;}
int & operator[] (const int&i)
{
if (i<0 || i>=3)
throw std::range_error ("stl_model::tri_3()");
return n[i];
}
const int & operator[] (const int&i) const
{
if (i<0 || i>=3)
throw std::range_error ("stl_model::tri_3()");
return n[i];
}
};
std::vector <point_3> vp;
std::vector <tri_3> vt; //各个三角形旋转方向是朝外的,按照右手定则
std::vector <int> vpli; //为每个三角形分配一个整数
std::vector <bool> vtri_ori; //记录每个三角形的转向,其实可以通过vt计算得到,true:vt的外法线方向和平面vpli[i]一样
stl_model () {};
int init_stl (std::ifstream &infile);
vector_3 get_normal (const int & n1, const int &n2, const int &n3) const;
vector_3 get_normal (const tri_3 &tri) const {return get_normal (tri[0],tri[1],tri[2]);}
vector_3 get_normal (const int &i) const {return get_normal(vt[i]);}
plane_3 get_plane (const int &i) const {return plane_3 (vp[vt[i].n[0]],get_normal(i));}
bbox_3 init_bbox (const int&i, const double &tol=0.000000001) const
{
using CGAL::to_double;
FT minx (vp[vt[i].n[0]].x()), maxx (vp[vt[i].n[0]].x());
FT miny (vp[vt[i].n[0]].y()), maxy (vp[vt[i].n[0]].y());
FT minz (vp[vt[i].n[0]].z()), maxz (vp[vt[i].n[0]].z());
for (int j(0);j!=3;++j)
{
if (vp[vt[i].n[j]].x() > maxx) maxx = vp[vt[i].n[j]].x();
if (vp[vt[i].n[j]].x() < minx) minx = vp[vt[i].n[j]].x();
if (vp[vt[i].n[j]].y() > maxy) maxy = vp[vt[i].n[j]].y();
if (vp[vt[i].n[j]].y() < miny) miny = vp[vt[i].n[j]].y();
if (vp[vt[i].n[j]].z() > maxz) maxz = vp[vt[i].n[j]].z();
if (vp[vt[i].n[j]].z() < minz) minz = vp[vt[i].n[j]].z();
}
return bbox_3 (to_double(minx)-tol, to_double(miny) - tol, to_double(minz) -tol,
to_double (maxx)+tol, to_double (maxy) + tol, to_double (maxz) + tol);
}
//检查是否有外露边界和非流形边界。并且检查各个三角面的旋转方向是否一致。未来还可以加上修复各个面朝向的部分,
int check () const;
void clear () {vp.clear(); vt.clear(); vpli.clear ();}
//计算该结构与给定平面的交集。所生成的loop记录在vl中,并且loop的旋转方向是view against pl的正向,用单面切割,并且只计算在模型内部的点
//返回值是0:成功,否则弹出异常。如果没有交集,则vl和vp都是空的
int plane_intersect (const plane_3 & pl, std::vector <point_2> &vp, std::vector<index_l> &vl) const;
//vl中各个loop的方向为从pl的正向看下去的方向
int plane_intersect (const plane_3 & pl, std::vector <point_3> &vp, std::vector <index_l>&vl) const;
int plane_intersect (const plane_3 & pl, csection &sec)
{
return plane_intersect(pl,sec.vp,sec.vl);
}
};
class frac_base
{
protected:
frac_base ()
: frac_id(-1),
plane_id(-1),
cohesion(0),
f_angle(0),
aperture(0){}
public:
int plane_id; //裂隙所在平面的ID
int frac_id; //裂隙的ID,正数
FT cohesion;
FT f_angle;
FT aperture;
};
class poly_frac: public frac_base
{
public:
enum Type {Pos_side, Neg_side, Both_side};
typedef std::vector <point_3> f_loop;
std::vector <f_loop> vl; //表示多边形裂隙的边界loop,vl[0]是外表面边界,其余是内表面边界,从plane_id这个平面看下去,外表面是逆时针,其余表面边界是顺时针
Type type; //记录这个裂隙的哪一侧参与切割,默认是Both_side
void proj_plane (const plane_3& pl) //将这个裂隙上的点都投影到pl上
{
for (int i(0);i!=(int)vl.size ();++i)
for (int j(0);j!=(int)vl[i].size ();++j)
vl[i][j] = pl.projection (vl[i][j]);
}
int to_2d (const plane_3&pl, std::vector<std::vector<point_2>> &vvp) const;
int to_2d (const plane_3&pl, polygon_with_holes_2 &pwh) const;
void revise_loops ()
{
for (int i(0);i!=(int)vl.size ();++i)
std::reverse (vl[i].begin (),vl[i].end ());
}
bbox_3 init_bbox (double tol = 0.0000001) const
{
if (vl.empty ())
throw std::logic_error ("init_bbox, poly is empty");
using CGAL::to_double;
FT minx (vl[0][0].x()), maxx (vl[0][0].x());
FT miny (vl[0][0].y()), maxy (vl[0][0].y());
FT minz (vl[0][0].z()), maxz (vl[0][0].z());
for (int i(0);i!=vl.size ();++i)
for (int j(0);j!=vl[i].size ();++j)
{
if (vl[i][j].x() > maxx) maxx = vl[i][j].x();
if (vl[i][j].x() < minx) minx = vl[i][j].x();
if (vl[i][j].y() > maxy) maxy = vl[i][j].y();
if (vl[i][j].y() < miny) miny = vl[i][j].y();
if (vl[i][j].z() > maxz) maxz = vl[i][j].z();
if (vl[i][j].z() < minz) minz = vl[i][j].z();
}
return bbox_3 (to_double(minx)-tol, to_double(miny) - tol, to_double(minz) -tol,
to_double (maxx)+tol, to_double (maxy) + tol, to_double (maxz) + tol);
}
void clear ()
{ vl.clear ();}
};
class disc_frac: public frac_base
{
public:
point_3 center;
FT r;
vector_3 normal;
};
template <typename K>
inline int add_set (std::vector<K> &p, const K &po)
{
int i(0);
for (i;i!=p.size ();++i)
if (p[i] == po)
break;
if (i==p.size ())
p.push_back (po);
return i;
}
inline int add_set_pl (std::vector<plane_3> &vp, const plane_3 &p)
{
int i(0);
for (i;i!=vp.size ();++i)
if (CGAL::parallel(vp[i],p) && vp[i].has_on(p.point()))
break;
if (i==vp.size ())
vp.push_back (p);
return i;
}
//在ve中添加新的线段,要求是如果e与ve中的其他线段相交, 则将这些相交的线段拆开。
int add_set_seg_3 (std::vector<segment_3> &ve, const segment_3 &e,std::vector <bbox_3> &vebox);
template <typename K>
inline void remove_set (std::vector<K> &vi, const std::vector <K> &tar)
{
for (int i(0);i!=tar.size ();++i)
vi.resize (std::remove (vi.begin (),vi.end (),tar[i]) - vi.begin ());
}
template <typename K>
inline void remove_set (std::vector<K> &vi, const K &tar)
{
vi.resize (std::remove (vi.begin (),vi.end (),tar) - vi.begin ());
}
//将一个倾向倾角表示的方向计算出来,当然这种计算不是严格的,因为中间用到了sin和cos函数
inline vector_3 dip2normal (const FT& dip_dir_, const FT& dip_,const FT& dx_)
{
double dip_dir = CGAL::to_double(dip_dir_*M_PI/180.0);
double dip = CGAL::to_double(dip_*M_PI/180.0);
double dx = CGAL::to_double(dx_*M_PI/180.0);
return vector_3 (std::sin(dip)*std::cos(dip_dir-dx),
-std::sin(dip)*std::sin(dip_dir-dx),
std::cos(dip));
}
class right_most_compare_2
{
const std::vector<point_2> &vp;
const edge &e;
public:
right_most_compare_2 (const std::vector<point_2> & vp_, const edge&e_): vp(vp_), e(e_) {}
bool operator() (const edge&e1, const edge&e2) const //e1在e2右侧时返回true,即e1比e2对应的右角小
{
vector_2 v (vp[e.n[1]],vp[e.n[0]]);
vector_2 v1 (vp[e1.n[0]],vp[e1.n[1]]);
vector_2 v2 (vp[e2.n[0]],vp[e2.n[1]]);
FT cs_prod1 (v.x()*v1.y()-v1.x()*v.y());
FT cs_prod2 (v.x()*v2.y()-v2.x()*v.y());
FT dot_prod1(v*v1);
FT dot_prod2(v*v2);
// 3 | 2
// |
//--------------------
// 4 | 1
// |
// v
int quad1, quad2; //象限分布按照上面的顺序来,如果将v的方向视为y轴逆向
if (cs_prod1>=0 && dot_prod1>0)
quad1 = 1;
else if (cs_prod1 >0 && dot_prod1<=0)
quad1 = 2;
else if (cs_prod1<=0 && dot_prod1<0)
quad1 = 3;
else
quad1 = 4;
if (cs_prod2>=0 && dot_prod2>0)
quad2 = 1;
else if (cs_prod2 >0 && dot_prod2<=0)
quad2 = 2;
else if (cs_prod2<=0 && dot_prod2<0)
quad2 = 3;
else
quad2 = 4;
if (quad2 > quad1)
return true; //e1在e2右侧
if (quad1 > quad2)
return false; //e1在e2左侧
FT scs_prod1 (CGAL::square(dot_prod1)*v2.squared_length ());
FT scs_prod2 (CGAL::square(dot_prod2)*v1.squared_length ());
if (quad1 == 1 || quad1 == 3)
return (scs_prod1 > scs_prod2); //返回true表明e1在e2右侧
else
return (scs_prod1 < scs_prod2); //返回true表明e1在e2右侧
}
};
class right_most_compare_3
{
const std::vector<point_3> &vp;
const plane_3 &pl;
const edge &e;
public:
right_most_compare_3 (const plane_3 &pl_, const std::vector<point_3> &vp_, const edge&e_)
: pl(pl_), vp(vp_), e(e_) {}
bool operator () (const edge &e1, const edge &e2) const //从pl的正向往下看,e1在e2右侧时返回true,即e1比e2对应的右角小
{
vector_3 v (vp[e.n[1]], vp[e.n[0]]);
vector_3 v1 (vp[e1.n[0]],vp[e1.n[1]]);
vector_3 v2 (vp[e2.n[0]],vp[e2.n[1]]);
FT cs_prod1 (CGAL::cross_product(v,v1) * pl.orthogonal_vector());
FT cs_prod2 (CGAL::cross_product(v,v2) * pl.orthogonal_vector());
FT dot_prod1 (v*v1);
FT dot_prod2 (v*v2);
int quad1,quad2;
if (cs_prod1>=0 && dot_prod1>0)
quad1 = 1;
else if (cs_prod1 > 0 && dot_prod1<=0)
quad1 = 2;
else if (cs_prod1 <=0 && dot_prod1<0)
quad1 = 3;
else
quad1 = 4;
if (cs_prod2>=0 && dot_prod2>0)
quad2 = 1;
else if (cs_prod2 >0 && dot_prod2<=0)
quad2 = 2;
else if (cs_prod2<=0 && dot_prod2<0)
quad2 = 3;
else
quad2 = 4;
if (quad2 > quad1)
return true; //e1在e2右侧
if (quad1 > quad2)
return false; //e1在e2左侧
FT scs_prod1 (CGAL::square(dot_prod1)*v2.squared_length ());
FT scs_prod2 (CGAL::square(dot_prod2)*v1.squared_length ());
if (quad1 == 1 || quad1 == 3)
return (scs_prod1 > scs_prod2); //返回true表明e1在e2右侧
else
return (scs_prod1 < scs_prod2); //返回true表明e1在e2右侧
}
};
class right_most_compare_3_vector
{
const vector_3 &n;
const vector_3 &org;
public:
right_most_compare_3_vector (const vector_3 &n_, const vector_3 &org_) : n(n_) , org(org_){}
bool operator () (const vector_3 &v1, const vector_3 &v2) const //逆着n看下去,v1在v2右侧时返回true,即v1比v2对应的右角小
{
vector_3 v (-org);
FT cs_prod1 (CGAL::cross_product(v,v1) * n);
FT cs_prod2 (CGAL::cross_product(v,v2) * n);
FT dot_prod1 (v*v1);
FT dot_prod2 (v*v2);
int quad1,quad2;
if (cs_prod1>=0 && dot_prod1>0)
quad1 = 1;
else if (cs_prod1 > 0 && dot_prod1<=0)
quad1 = 2;
else if (cs_prod1 <=0 && dot_prod1<0)
quad1 = 3;
else
quad1 = 4;
if (cs_prod2>=0 && dot_prod2>0)
quad2 = 1;
else if (cs_prod2 >0 && dot_prod2<=0)
quad2 = 2;
else if (cs_prod2<=0 && dot_prod2<0)
quad2 = 3;
else
quad2 = 4;
if (quad2 > quad1)
return true; //e1在e2右侧
if (quad1 > quad2)
return false; //e1在e2左侧
FT scs_prod1 (CGAL::square(dot_prod1)*v2.squared_length ());
FT scs_prod2 (CGAL::square(dot_prod2)*v1.squared_length ());
if (quad1 == 1 || quad1 == 3)
return (scs_prod1 > scs_prod2); //返回true表明e1在e2右侧
else
return (scs_prod1 < scs_prod2); //返回true表明e1在e2右侧
}
};
class edge_compare
{
public:
bool operator () (const edge&e1, const edge&e2)
{
if (e1.n[0] < e2.n[0])
return true;
if (e1.n[0] == e2.n[0])
if (e1.n[1] < e2.n[1])
return true;
return false;
}
};
class point_compare_3
{
public:
bool operator () (const point_3&p1, const point_3&p2)
{
if (CGAL::compare_xyz(p1,p2) == CGAL::Comparison_result::SMALLER)
return true;
else
return false;
}
};
//计算np中索引所指向的点组成的法线方向。假设pn中所有点都在pl上(exactly)
vector_3 oriented_normal (const std::vector<point_3> &vp, const std::vector<int> &np, const plane_3 &pl);
//同上,计算np中索引所指向的点组成的法线方向。假设pn中所有点都(exactly)在同一个平面上
vector_3 oriented_normal (const std::vector<point_3> &vp, const std::vector<int> &np);
//同上,计算vp中所有点的组成边的法线方向。假设vp中所有点都(exactly)在同一个平面上
vector_3 oriented_normal (const std::vector<point_3> &vp);
//检查tar是否在向量beg,end的左侧,返回1表示在左侧,返回0表示在向量上,返回2表示在右侧
inline int is_left_2(const point_2 &beg, const point_2 &end, const point_2 &tar)
{
FT temp = (end.x()-beg.x()) * (tar.y() - beg.y()) - (tar.x()-beg.x())*(end.y()-beg.y());
if (temp>0)
return 1;
if (temp<0)
return 2;
else
return 0;
}
//同上,假设beg和end都在pl上,结果是viewed against pl的正向
inline int is_left_3(const plane_3 &pl, const point_3 &beg, const point_3 &end, const point_3 &tar)
{
FT temp = CGAL::cross_product (vector_3(tar,beg),vector_3(tar,end)) * pl.orthogonal_vector();
if (temp > 0)
return 1;
if (temp < 0)
return 2;
else
return 0;
}
//返回0表示在多边形上,返回1表示在多边形内,返回2表示在多边形外
int point_in_polygon_2 (const std::vector<point_2> &vp, const std::vector<index_l> & vl, const point_2& tar);
////前提是ob和tar不在边界处相交,只在顶点处相交(不检查)。
////1表示tar的顶点完全包含在ob内,返回2表示tar有一个顶点包含在ob外
//int polygon_in_polygon_2 (const std::vector <point_2> &vp, const index_l &ob, const index_l &tar);
//同上,假设vl中的点都在pl上,并且从pl正向往下看逆时针的loop是内部,顺时针的loop是外部
//要求有且仅有一个外表面loop
//返回0表示在多边形上,返回1表示在多边形内,返回2表示在多边形外
int point_in_polygon_3 (const std::vector<point_3> &vp, const std::vector<index_l> & vl,const plane_3 &pl, const point_3 &tar);
int point_in_polygon_3 (const std::vector<point_3> &vp, const std::vector<loop> & vl,const plane_3 &pl, const point_3 &tar);
int point_in_polygon_3 (const std::vector<std::vector<point_3>> &vl, const plane_3&pl, const point_3 &tar);
int point_in_polygon_3 (const std::vector<point_3> &vp, const index_l & l,const plane_3 &pl, const point_3 &tar);
//判断一个点和一个多面体的关系,假设b中的各个面围成一个封闭空间(体积大于0),并且忽略各个面的方向性
//0:这个点在多面体上
//1:这个点在多面性内
//2:这个点在多边形外
int point_in_polyhedron_3 (const std::vector <point_3> &vp, const std::vector <face> &vfa, const std::vector<plane_3> &vpl, const block &b, const std::vector<bbox_3> &vbbox, const point_3 &tar);
//判断一个线段和一个多边形的位置关系
//-1:线段和多边形不相交
//1:线段和多边形共面(不管相交不相交)
//2:线段的某个端点在多边形的边界上
//3:线段的某个端点在多边形内
//4:线段和多边形的边界相交
//5:线段和多边形内相交
int seg_intersect_polygon_3 (const std::vector<point_3> &vp, const std::vector<loop> &vl, const plane_3 &pl, const point_3 &beg, const point_3 &end);
//-1:不相交
//1:可能相交
inline int seg_intersect_bbox_3 (const bbox_3 &bbox, const point_3 &beg, const point_3 &end)
{
for (int i(0);i!=3;++i)
{
if (beg[i]<bbox.min(i) && end[i]<bbox.min(i))
return -1;
if (beg[i]>bbox.max(i) && end[i]>bbox.max(i))
return -1;
}
return 1;
}
//前提是ob和tar不在边界处相交,只在顶点处相交(不检查)。
//要求ob是逆时针旋转
//1表示tar的顶点完全包含在ob内,返回2表示tar有一个顶点包含在ob外
int polygon_in_polygon_3 (const std::vector <point_3> &vp, const index_l & ob, const index_l &tar, const plane_3 &pl);
//前提是ob和tar不在边界处相交,只在顶点处相交,并且ob和tar除了边界处没有重合的地方
//要求ob和tar都围成一个封闭的空间。体积不为0,判断的时候忽略其方向性。并且需要给出已经计算出的体积
//返回1表示tar的顶点完全包含在ob内,返回2表示tar至少有一个顶点包含在ob外
int polyhedron_in_polyhedron_3 (const std::vector<point_3> &vp,
const std::vector<face> &vfa,
const std::vector<plane_3> &vpl,
const block&ob, const block& tar,
const FT &v_ob, const FT &v_tar,
const std::vector<bbox_3>& vbox_ob, const std::vector<bbox_3>& vbox_tar);
//假设vl上的点都在同一个平面pl内
point_3 get_point_in_face_3 (const std::vector<point_3> &vp, const plane_3 &pl, const face &fa);
//用户需要保证blk的体积不为零,并且blk围成一个封闭的空间,如果blk的体积小于零,则调用时需将reverse设置为true
point_3 get_point_in_polyhedron_3 (const std::vector<point_3> &vp,
const std::vector <face> &vfa,
const std::vector <plane_3> &vpl,
const block&blk, const std::vector<bbox_3> &vbbox,const bool& reverse=false);
//分裂一个loop,同时分裂这个loop中所包含的边界信息
void split_loop (const loop& l, std::vector<loop> &vl);
//用po分裂vseg中的线段,并且更新vbox_seg
int split_seg (std::vector<segment_3> &vseg, std::vector<bbox_3> &vbox_seg, const point_3 & po);
//为blk的每一个边界初始化一个边界盒
void get_vbox_of_blk (const std::vector<point_3> &vp, const std::vector<face> &vfa, const block &blk, std::vector<bbox_3> &vbox);
//inline void out_line_3_rhino (std::ostream &os, const plane_3& pl, const std::vector<point_2> &vp, const std::vector<loop> &vl)
//{
// for (int i(0);i!=vl.size ();++i)
// {
// os<<"polyline ";
// for (int j(0);j!=vl[i].vpi.size ();++j)
// {
// point_3 temp (pl.to_3d(vp[vl[i].vpi[j]]));
// os<<temp.x()<<','<<temp.y()<<','<<temp.z()<<std::endl;
// }
// os<<"c"<<std::endl;
// }
//}
inline void out_line_3_rhino (std::ostream &os, const std::vector<point_3> &vpo, const index_l&l)
{
os<<"polyline ";
for (int j(0);j!=l.size ();++j)
{
const point_3 &temp (vpo[l[j]]);
os<<temp.x()<<','<<temp.y()<<','<<temp.z()<<std::endl;
}
os<<"c"<<std::endl;
}
inline void out_line_3_rhino (std::ostream &os, const segment_3 &s)
{
os<<"line "
<<s.source ().x()<<","<<s.source ().y()<<","<<s.source ().z()<<" "
<<s.target ().x()<<","<<s.target ().y()<<","<<s.target ().z()<<" "<<std::endl ;
}
//输出一个平面的stl,flag=true,将该平面输出成一个单独的stl文件
void out_face_STL (std::ostream &outfile, const std::vector <point_3> &vp, const face &fa, const plane_3 &pl, bool flag ,const std::string &s = "");
//计算两个pf的交点,rese记录所有的线段,resp记录所有的点,返回值是(rese增加的值,resp增加的值)
//计算出来的交点不会是rese中线段的端点或在这些线段上
//添加rese时用的是add_set_seg_3,添加resp时是直接添加
std::pair<int,int> intersection (const poly_frac &pf1, const plane_3 &pl1,
const poly_frac &pf2, const plane_3 &pl2,
std::vector<segment_3> & rese, std::vector<point_3> &resp,
std::vector <bbox_3> &vebox);
//计算loop和直线(p, v)的交点,返回值保存在res中,表示计算出来的交点,即p+res[i]*v
//precondition: loop和给定直线共面
//如果loop的某个边界线段和直线相交,则返回两个边界线段的顶点
void intersection_points (const std::vector<point_3> & loop, const point_3&p, const vector_3& v, std::vector<FT> &res);
void intersection_points (const std::vector<std::vector<point_3>> &vl, const point_3&p, const vector_3& v, std::vector<FT> &res);
inline void intersection_points (const poly_frac &pf, const point_3&p, const vector_3&v, std::vector <FT>&res)
{ intersection_points(pf.vl,p,v,res);}
//判断segs给定的线段是否包含在pf中或在其边界上,res[i]中值表示线段segs[i],segs[i+1]中的线段是否在pf上.
//pf中各个loop的旋转方向是从pl的正向看下去的方向
//要求segs中的元素不重复
void mark_segments (const poly_frac &pf, const plane_3 &pl, const point_3&p, const vector_3&v, const std::vector <FT> &segs, std::vector <bool> &res);
//将返回值记为x,则有tar = p+x*v
inline FT get_para (const point_3&p, const vector_3&v, const point_3& tar)
{
using CGAL::abs;
if (abs(v.x()) >= abs(v.y()) && abs(v.x()) >= abs (v.z()))
return (tar.x()-p.x())/v.x();
else if (abs(v.y()) >= abs(v.x()) && abs(v.y()) >= abs(v.z()))
return (tar.y()-p.y())/v.y();
else
return (tar.z()-p.z())/v.z();
}
inline bbox_3 seg2bbox (const segment_3&seg, const double &tol = 0.00000001)
{
return bbox_3 (CGAL::to_double (CGAL::min(seg.source ().x(), seg.target ().x())) - tol,
CGAL::to_double (CGAL::min(seg.source ().y(), seg.target ().y())) - tol,
CGAL::to_double (CGAL::min(seg.source ().z(), seg.target ().z())) - tol,
CGAL::to_double (CGAL::max(seg.source ().x(), seg.target ().x())) + tol,
CGAL::to_double (CGAL::max(seg.source ().y(), seg.target ().y())) + tol,
CGAL::to_double (CGAL::max(seg.source ().z(), seg.target ().z())) + tol);
}
inline bbox_3 point2bbox (const point_3&p, const double &tol=0.00000001)
{
using CGAL::to_double;
return bbox_3 (to_double (p.x()) - tol, to_double(p.y())-tol, to_double (p.z()) - tol,
to_double (p.x()) + tol, to_double (p.y()) +tol, to_double (p.z()) + tol);
}
//将一个圆盘转换成一个n边形,当然,转换不可能是exact的
void disc2pf (const point_3& center, const FT &r, const plane_3 &pl, poly_frac & res, const int& n = 10);
//用来标记三角形面,在输出outer_boundary和inner_boundary的STL时有用到。只能用来标记嵌套过一次的面
template <typename CDT>
inline void mark_domains (CDT &cdt, typename CDT::Face_handle start, int index, std::list<typename CDT::Edge>& border)
{
if (start->info().nesting_level !=-1)
return ;
std::list<CDT::Face_handle> queue;
queue.push_back (start);
while (!queue.empty())
{
CDT::Face_handle fh = queue.front();
queue.pop_front();
if (fh->info().nesting_level == -1)
{
fh->info().nesting_level = index;
for (int i(0);i<3;++i)
{
CDT::Edge e(fh,i);
CDT::Face_handle n = fh->neighbor(i);
if (n->info().nesting_level == -1)
if (cdt.is_constrained(e)) border.push_back (e);
else queue.push_back(n);
}
}
}
}
//和上面那个函数结合使用,(其实是上面那个函数和这个函数结合使用)
template <typename CDT>
inline void mark_domains (CDT &cdt)
{
for (CDT::All_faces_iterator it = cdt.all_faces_begin(); it!=cdt.all_faces_end();++it)
it->info().nesting_level = -1;
std::list<CDT::Edge> border;
mark_domains(cdt,cdt.infinite_face(),0,border);
while (!border.empty())
{
CDT::Edge e = border.front();
border.pop_front();
CDT::Face_handle n = e.first->neighbor(e.second);
if (n->info().nesting_level == -1)
mark_domains(cdt,n,e.first->info().nesting_level+1,border);
}
}
//这个函数用来给一个Constrained Delaunay Triangulation (CDT)中添加多边形限制的
template <typename CDT>
inline void insert_polygon(CDT& cdt, const std::vector<point_3> &vp, const plane_3& pl, const loop& l)
{
if (l.vpi.empty())
return;
CDT::Vertex_handle v_prev = cdt.insert (pl.to_2d (vp[l.vpi.back()]));
for (int i(0);i!=l.vpi.size ();++i)
{
CDT::Vertex_handle vh = cdt.insert (pl.to_2d (vp[l.vpi[i]]));
cdt.insert_constraint (vh,v_prev);
v_prev = vh;
}
}
}
|
a14e0cc44a2616a1b743f813864bfe47b3931df0
|
ce9046039502146ffc454248be1d47d5b01d3894
|
/2011/2011.cpp
|
961a33a9f2e339a6a486596abfaab534cbe766eb
|
[] |
no_license
|
yjm6560/BOJ
|
476ac9fcdb14e320547d570fe9589542fd13314e
|
5532d1e31bc0384148eab09b726dcfcb1c0a96d0
|
refs/heads/master
| 2021-07-19T08:39:33.144380
| 2021-01-01T12:52:33
| 2021-01-01T12:52:33
| 230,388,040
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 693
|
cpp
|
2011.cpp
|
/*
암호코드
DP
*/
#include <iostream>
#include <string>
using namespace std;
#define MOD 1000000
int e[5001], dp[5001], N;
string input;
int decode(int idx){
if(dp[idx] != -1)
return dp[idx];
if(e[idx] == 0){
if(e[idx-1] != 1 && e[idx-1] != 2)
dp[idx] = 0;
else
dp[idx] = decode(idx-2);
} else if((e[idx-1] == 2 && e[idx] <= 6) || e[idx-1] == 1){
dp[idx] = decode(idx-1) + decode(idx-2);
} else {
dp[idx] = decode(idx-1);
}
return dp[idx]%MOD;
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cin >> input;
N = input.length();
for(int i=0;i<N;i++){
e[i+1] = input[i] - '0';
dp[i+1] = -1;
}
e[0] = 0;
dp[0] = 1;
cout << decode(N) << endl;
}
|
6245f3a160aefdc7387b968e185d37b545ac1419
|
2c5f05bad4097cf15170bf11f75535256b4ed790
|
/a4.cpp
|
bbf78b524c5c5d7a1d76ebbea129b541ac22bb7e
|
[] |
no_license
|
MooKnee/CIS-265
|
9e5b22ff76f2fbb07ecc8cfa2c311b2ac235a67e
|
f1fd31413021efa58e50f735bfaca78b1459b59e
|
refs/heads/master
| 2020-08-01T12:00:56.003649
| 2019-09-26T03:22:43
| 2019-09-26T03:22:43
| 210,990,001
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,983
|
cpp
|
a4.cpp
|
///
//2. Rainfall Statistics
//Write a program that lets the user enter the total rainfall for
//each of 12 months into an array of doubles. The program should
//calculate and display the total rainfall for the year, the
//average monthly rainfall, and the months with the highest and lowest
//amounts. Input Validation: Do not accept negative numbers for monthly
//rainfall figures.
#include <iostream>
#include <string>
using namespace std;
int main()
{
const int NUM_MONTHS=12;
double rainfall[NUM_MONTHS];
string months[NUM_MONTHS]={"January","February","March","April",
"May","June","July","August",
"September","October","November",
"December"};
double total=0,
average=0,
highest=0,
lowest=0;
//input amount of rainfall for each month
for (int i=0; i<NUM_MONTHS; i++)
{
cout<<"Enter the amount of rainfall in inches for the \n";
cout<<months[i]<<" months.\n";
cin>>rainfall[i];
while (rainfall[i]< 0)
{
cout<<"This is an error.";
cout<<"Enter the amount of rainfall in inches for the \n";
cout<<months[i]<<" months.\n";
cin>>rainfall[i];
}
}
for (int f=0; f<NUM_MONTHS; f++)
{
total+=rainfall[f];
}
average=total/(NUM_MONTHS);
cout<<"The average amount of rainfall per month is "<<average<<".\n";
highest=rainfall[0];
for (int ree=1; ree<NUM_MONTHS; ree++)
{
if (rainfall[ree]>highest)
{
highest=rainfall[ree];
}
}
cout<<highest<<endl;
//cout<<"The month with the highest amount of rainfall is the month of "<<months[ree]<<" with "<<highest<<" amount of rain.\n";
lowest=rainfall[0];
for (int yeet=1;yeet<NUM_MONTHS; yeet++)
{
if (rainfall[yeet]<lowest)
{
lowest=rainfall[yeet];
}
}
cout<<lowest<<endl;
//cout<<"The month with the lowest amount of rainfall is the month of "<<months[yeet]<<" with "<<lowest<<" amount of rain.\n";
system ("PAUSE");
return 0;
}
|
0cc4247c74624730b0255a16c65811d548d53da9
|
88ae8695987ada722184307301e221e1ba3cc2fa
|
/third_party/angle/src/compiler/translator/TextureFunctionHLSL.cpp
|
2c81a3945326d763f3e53751578db404c3758adf
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] |
permissive
|
iridium-browser/iridium-browser
|
71d9c5ff76e014e6900b825f67389ab0ccd01329
|
5ee297f53dc7f8e70183031cff62f37b0f19d25f
|
refs/heads/master
| 2023-08-03T16:44:16.844552
| 2023-07-20T15:17:00
| 2023-07-23T16:09:30
| 220,016,632
| 341
| 40
|
BSD-3-Clause
| 2021-08-13T13:54:45
| 2019-11-06T14:32:31
| null |
UTF-8
|
C++
| false
| false
| 61,653
|
cpp
|
TextureFunctionHLSL.cpp
|
//
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// TextureFunctionHLSL: Class for writing implementations of ESSL texture functions into HLSL
// output. Some of the implementations are straightforward and just call the HLSL equivalent of the
// ESSL texture function, others do more work to emulate ESSL texture sampling or size query
// behavior.
//
#include "compiler/translator/TextureFunctionHLSL.h"
#include "compiler/translator/ImmutableStringBuilder.h"
#include "compiler/translator/UtilsHLSL.h"
namespace sh
{
namespace
{
void OutputIntTexCoordWrap(TInfoSinkBase &out,
const char *wrapMode,
const char *size,
const ImmutableString &texCoord,
const char *texCoordOffset,
const char *texCoordOutName)
{
// GLES 3.0.4 table 3.22 specifies how the wrap modes work. We don't use the formulas verbatim
// but rather use equivalent formulas that map better to HLSL.
out << "int " << texCoordOutName << ";\n";
out << "float " << texCoordOutName << "Offset = " << texCoord << " + float(" << texCoordOffset
<< ") / " << size << ";\n";
out << "bool " << texCoordOutName << "UseBorderColor = false;\n";
// CLAMP_TO_EDGE / D3D11_TEXTURE_ADDRESS_CLAMP == 3
out << "if (" << wrapMode << " == 3)\n";
out << "{\n";
out << " " << texCoordOutName << " = clamp(int(floor(" << size << " * " << texCoordOutName
<< "Offset)), 0, int(" << size << ") - 1);\n";
out << "}\n";
// CLAMP_TO_BORDER / D3D11_TEXTURE_ADDRESS_BORDER == 4
out << "else if (" << wrapMode << " == 4)\n";
out << "{\n";
out << " int texCoordInt = int(floor(" << size << " * " << texCoordOutName << "Offset));\n";
out << " " << texCoordOutName << " = clamp(texCoordInt, 0, int(" << size << ") - 1);\n";
out << " " << texCoordOutName << "UseBorderColor = (texCoordInt != " << texCoordOutName
<< ");\n";
out << "}\n";
// MIRRORED_REPEAT / D3D11_TEXTURE_ADDRESS_MIRROR == 2
out << "else if (" << wrapMode << " == 2)\n";
out << "{\n";
out << " float coordWrapped = 1.0 - abs(frac(abs(" << texCoordOutName
<< "Offset) * 0.5) * 2.0 - 1.0);\n";
out << " " << texCoordOutName << " = min(int(floor(" << size << " * coordWrapped)), int("
<< size << ") - 1);\n";
out << "}\n";
// MIRROR_CLAMP_TO_EDGE_EXT / D3D11_TEXTURE_ADDRESS_MIRROR_ONCE == 5
out << "else if (" << wrapMode << " == 5)\n";
out << "{\n";
out << " " << texCoordOutName << " = min(int(floor(" << size << " * abs(" << texCoordOutName
<< "Offset))), int(" << size << ") - 1);\n";
out << "}\n";
// REPEAT / D3D11_TEXTURE_ADDRESS_WRAP == 1
out << "else\n";
out << "{\n";
out << " " << texCoordOutName << " = int(floor(" << size << " * frac(" << texCoordOutName
<< "Offset)));\n";
out << "}\n";
}
void OutputIntTexCoordWraps(TInfoSinkBase &out,
const TextureFunctionHLSL::TextureFunction &textureFunction,
ImmutableString *texCoordX,
ImmutableString *texCoordY,
ImmutableString *texCoordZ)
{
// Convert from normalized floating-point to integer
out << "int wrapS = samplerMetadata[samplerIndex].wrapModes & 0x7;\n";
if (textureFunction.offset)
{
OutputIntTexCoordWrap(out, "wrapS", "width", *texCoordX, "offset.x", "tix");
}
else
{
OutputIntTexCoordWrap(out, "wrapS", "width", *texCoordX, "0", "tix");
}
*texCoordX = ImmutableString("tix");
out << "int wrapT = (samplerMetadata[samplerIndex].wrapModes >> 3) & 0x7;\n";
if (textureFunction.offset)
{
OutputIntTexCoordWrap(out, "wrapT", "height", *texCoordY, "offset.y", "tiy");
}
else
{
OutputIntTexCoordWrap(out, "wrapT", "height", *texCoordY, "0", "tiy");
}
*texCoordY = ImmutableString("tiy");
bool tizAvailable = false;
if (IsSamplerArray(textureFunction.sampler))
{
*texCoordZ = ImmutableString("int(max(0, min(layers - 1, floor(0.5 + t.z))))");
}
else if (!IsSamplerCube(textureFunction.sampler) && !IsSampler2D(textureFunction.sampler))
{
out << "int wrapR = (samplerMetadata[samplerIndex].wrapModes >> 6) & 0x7;\n";
if (textureFunction.offset)
{
OutputIntTexCoordWrap(out, "wrapR", "depth", *texCoordZ, "offset.z", "tiz");
}
else
{
OutputIntTexCoordWrap(out, "wrapR", "depth", *texCoordZ, "0", "tiz");
}
*texCoordZ = ImmutableString("tiz");
tizAvailable = true;
}
out << "bool useBorderColor = tixUseBorderColor || tiyUseBorderColor"
<< (tizAvailable ? " || tizUseBorderColor" : "") << ";\n";
}
void OutputHLSL4SampleFunctionPrefix(TInfoSinkBase &out,
const TextureFunctionHLSL::TextureFunction &textureFunction,
const ImmutableString &textureReference,
const ImmutableString &samplerReference)
{
out << textureReference;
if (IsIntegerSampler(textureFunction.sampler) ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::FETCH)
{
out << ".Load(";
return;
}
if (IsShadowSampler(textureFunction.sampler))
{
switch (textureFunction.method)
{
case TextureFunctionHLSL::TextureFunction::IMPLICIT:
case TextureFunctionHLSL::TextureFunction::BIAS:
case TextureFunctionHLSL::TextureFunction::LOD:
out << ".SampleCmp(";
break;
case TextureFunctionHLSL::TextureFunction::LOD0:
case TextureFunctionHLSL::TextureFunction::LOD0BIAS:
case TextureFunctionHLSL::TextureFunction::GRAD:
out << ".SampleCmpLevelZero(";
break;
default:
UNREACHABLE();
}
}
else
{
switch (textureFunction.method)
{
case TextureFunctionHLSL::TextureFunction::IMPLICIT:
out << ".Sample(";
break;
case TextureFunctionHLSL::TextureFunction::BIAS:
out << ".SampleBias(";
break;
case TextureFunctionHLSL::TextureFunction::LOD:
case TextureFunctionHLSL::TextureFunction::LOD0:
case TextureFunctionHLSL::TextureFunction::LOD0BIAS:
out << ".SampleLevel(";
break;
case TextureFunctionHLSL::TextureFunction::GRAD:
out << ".SampleGrad(";
break;
default:
UNREACHABLE();
}
}
out << samplerReference << ", ";
}
const char *GetSamplerCoordinateTypeString(
const TextureFunctionHLSL::TextureFunction &textureFunction,
int hlslCoords)
{
// Gather[Red|Green|Blue|Alpha] accepts float texture coordinates on textures in integer or
// unsigned integer formats.
// https://docs.microsoft.com/en-us/windows/desktop/direct3dhlsl/dx-graphics-hlsl-to-gather
if ((IsIntegerSampler(textureFunction.sampler) &&
textureFunction.method != TextureFunctionHLSL::TextureFunction::GATHER) ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::FETCH)
{
switch (hlslCoords)
{
case 1:
return "int";
case 2:
if (IsSampler2DMS(textureFunction.sampler))
{
return "int2";
}
else
{
return "int3";
}
case 3:
if (IsSampler2DMSArray(textureFunction.sampler))
{
return "int3";
}
else
{
return "int4";
}
default:
UNREACHABLE();
}
}
else
{
switch (hlslCoords)
{
case 1:
return "float";
case 2:
return "float2";
case 3:
return "float3";
case 4:
return "float4";
default:
UNREACHABLE();
}
}
return "";
}
int GetHLSLCoordCount(const TextureFunctionHLSL::TextureFunction &textureFunction,
ShShaderOutput outputType)
{
if (outputType == SH_HLSL_3_0_OUTPUT)
{
int hlslCoords = 2;
switch (textureFunction.sampler)
{
case EbtSamplerBuffer:
hlslCoords = 1;
break;
case EbtSampler2D:
case EbtSamplerExternalOES:
case EbtSampler2DMS:
case EbtSamplerVideoWEBGL:
hlslCoords = 2;
break;
case EbtSamplerCube:
hlslCoords = 3;
break;
default:
UNREACHABLE();
}
switch (textureFunction.method)
{
case TextureFunctionHLSL::TextureFunction::IMPLICIT:
case TextureFunctionHLSL::TextureFunction::GRAD:
return hlslCoords;
case TextureFunctionHLSL::TextureFunction::BIAS:
case TextureFunctionHLSL::TextureFunction::LOD:
case TextureFunctionHLSL::TextureFunction::LOD0:
case TextureFunctionHLSL::TextureFunction::LOD0BIAS:
return 4;
default:
UNREACHABLE();
}
}
else
{
if (IsSamplerBuffer(textureFunction.sampler))
{
return 1;
}
else if (IsSampler3D(textureFunction.sampler) || IsSamplerArray(textureFunction.sampler) ||
IsSamplerCube(textureFunction.sampler))
{
return 3;
}
ASSERT(IsSampler2D(textureFunction.sampler));
return 2;
}
return 0;
}
void OutputTextureFunctionArgumentList(TInfoSinkBase &out,
const TextureFunctionHLSL::TextureFunction &textureFunction,
const ShShaderOutput outputType)
{
if (outputType == SH_HLSL_3_0_OUTPUT)
{
switch (textureFunction.sampler)
{
case EbtSampler2D:
case EbtSamplerVideoWEBGL:
case EbtSamplerExternalOES:
out << "sampler2D s";
break;
case EbtSamplerCube:
out << "samplerCUBE s";
break;
default:
UNREACHABLE();
}
}
else
{
if (outputType == SH_HLSL_4_0_FL9_3_OUTPUT)
{
out << TextureString(textureFunction.sampler) << " x, "
<< SamplerString(textureFunction.sampler) << " s";
}
else
{
ASSERT(outputType == SH_HLSL_4_1_OUTPUT);
// A bug in the D3D compiler causes some nested sampling operations to fail.
// See http://anglebug.com/1923
// TODO(jmadill): Reinstate the const keyword when possible.
out << /*"const"*/ "uint samplerIndex";
}
}
if (textureFunction.method ==
TextureFunctionHLSL::TextureFunction::FETCH) // Integer coordinates
{
switch (textureFunction.coords)
{
case 1:
out << ", int t";
break;
case 2:
out << ", int2 t";
break;
case 3:
out << ", int3 t";
break;
default:
UNREACHABLE();
}
}
else // Floating-point coordinates (except textureSize)
{
switch (textureFunction.coords)
{
case 0:
break; // textureSize(gSampler2DMS sampler)
case 1:
out << ", int lod";
break; // textureSize()
case 2:
out << ", float2 t";
break;
case 3:
out << ", float3 t";
break;
case 4:
out << ", float4 t";
break;
default:
UNREACHABLE();
}
}
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::GRAD)
{
switch (textureFunction.sampler)
{
case EbtSampler2D:
case EbtISampler2D:
case EbtUSampler2D:
case EbtSampler2DArray:
case EbtISampler2DArray:
case EbtUSampler2DArray:
case EbtSampler2DShadow:
case EbtSampler2DArrayShadow:
case EbtSamplerExternalOES:
case EbtSamplerVideoWEBGL:
out << ", float2 ddx, float2 ddy";
break;
case EbtSampler3D:
case EbtISampler3D:
case EbtUSampler3D:
case EbtSamplerCube:
case EbtISamplerCube:
case EbtUSamplerCube:
case EbtSamplerCubeShadow:
out << ", float3 ddx, float3 ddy";
break;
default:
UNREACHABLE();
}
}
switch (textureFunction.method)
{
case TextureFunctionHLSL::TextureFunction::IMPLICIT:
break;
case TextureFunctionHLSL::TextureFunction::BIAS:
break; // Comes after the offset parameter
case TextureFunctionHLSL::TextureFunction::LOD:
out << ", float lod";
break;
case TextureFunctionHLSL::TextureFunction::LOD0:
break;
case TextureFunctionHLSL::TextureFunction::LOD0BIAS:
break; // Comes after the offset parameter
case TextureFunctionHLSL::TextureFunction::SIZE:
break;
case TextureFunctionHLSL::TextureFunction::FETCH:
if (IsSampler2DMS(textureFunction.sampler) ||
IsSampler2DMSArray(textureFunction.sampler))
out << ", int index";
else if (!IsSamplerBuffer(textureFunction.sampler))
out << ", int mip";
break;
case TextureFunctionHLSL::TextureFunction::GRAD:
break;
case TextureFunctionHLSL::TextureFunction::GATHER:
break;
default:
UNREACHABLE();
}
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::GATHER &&
IsShadowSampler(textureFunction.sampler))
{
out << ", float refZ";
}
if (textureFunction.offset)
{
switch (textureFunction.sampler)
{
case EbtSampler3D:
case EbtISampler3D:
case EbtUSampler3D:
out << ", int3 offset";
break;
case EbtSampler2D:
case EbtSampler2DArray:
case EbtISampler2D:
case EbtISampler2DArray:
case EbtUSampler2D:
case EbtUSampler2DArray:
case EbtSampler2DShadow:
case EbtSampler2DArrayShadow:
case EbtSamplerExternalOES:
case EbtSamplerVideoWEBGL:
out << ", int2 offset";
break;
default:
// Offset is not supported for multisampled textures.
UNREACHABLE();
}
}
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::BIAS ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::LOD0BIAS)
{
out << ", float bias";
}
else if (textureFunction.method == TextureFunctionHLSL::TextureFunction::GATHER &&
!IsShadowSampler(textureFunction.sampler))
{
out << ", int comp = 0";
}
}
void GetTextureReference(TInfoSinkBase &out,
const TextureFunctionHLSL::TextureFunction &textureFunction,
const ShShaderOutput outputType,
ImmutableString *textureReference,
ImmutableString *samplerReference)
{
if (outputType == SH_HLSL_4_1_OUTPUT)
{
static const ImmutableString kTexturesStr("textures");
static const ImmutableString kSamplersStr("samplers");
static const ImmutableString kSamplerIndexStr("[samplerIndex]");
static const ImmutableString kTextureIndexStr("[textureIndex]");
static const ImmutableString kSamplerArrayIndexStr("[samplerArrayIndex]");
ImmutableString suffix(TextureGroupSuffix(textureFunction.sampler));
if (TextureGroup(textureFunction.sampler) == HLSL_TEXTURE_2D)
{
ImmutableStringBuilder textureRefBuilder(kTexturesStr.length() + suffix.length() +
kSamplerIndexStr.length());
textureRefBuilder << kTexturesStr << suffix << kSamplerIndexStr;
*textureReference = textureRefBuilder;
ImmutableStringBuilder samplerRefBuilder(kSamplersStr.length() + suffix.length() +
kSamplerIndexStr.length());
samplerRefBuilder << kSamplersStr << suffix << kSamplerIndexStr;
*samplerReference = samplerRefBuilder;
}
else
{
out << " const uint textureIndex = samplerIndex - textureIndexOffset"
<< suffix.data() << ";\n";
ImmutableStringBuilder textureRefBuilder(kTexturesStr.length() + suffix.length() +
kTextureIndexStr.length());
textureRefBuilder << kTexturesStr << suffix << kTextureIndexStr;
*textureReference = textureRefBuilder;
out << " const uint samplerArrayIndex = samplerIndex - samplerIndexOffset"
<< suffix.data() << ";\n";
ImmutableStringBuilder samplerRefBuilder(kSamplersStr.length() + suffix.length() +
kSamplerArrayIndexStr.length());
samplerRefBuilder << kSamplersStr << suffix << kSamplerArrayIndexStr;
*samplerReference = samplerRefBuilder;
}
}
else
{
*textureReference = ImmutableString("x");
*samplerReference = ImmutableString("s");
}
}
void OutputTextureSizeFunctionBody(TInfoSinkBase &out,
const TextureFunctionHLSL::TextureFunction &textureFunction,
const ImmutableString &textureReference,
bool getDimensionsIgnoresBaseLevel)
{
if (IsSampler2DMS(textureFunction.sampler))
{
out << " uint width; uint height; uint samples;\n"
<< " " << textureReference << ".GetDimensions(width, height, samples);\n";
}
else if (IsSampler2DMSArray(textureFunction.sampler))
{
out << " uint width; uint height; uint depth; uint samples;\n"
<< " " << textureReference << ".GetDimensions(width, height, depth, samples);\n";
}
else if (IsSamplerBuffer(textureFunction.sampler))
{
out << " uint width;\n"
<< " " << textureReference << ".GetDimensions(width);\n";
}
else
{
if (getDimensionsIgnoresBaseLevel)
{
out << " int baseLevel = samplerMetadata[samplerIndex].baseLevel;\n";
}
else
{
out << " int baseLevel = 0;\n";
}
if (IsSampler3D(textureFunction.sampler) || IsSamplerArray(textureFunction.sampler) ||
(IsIntegerSampler(textureFunction.sampler) && IsSamplerCube(textureFunction.sampler)))
{
// "depth" stores either the number of layers in an array texture or 3D depth
out << " uint width; uint height; uint depth; uint numberOfLevels;\n"
<< " " << textureReference
<< ".GetDimensions(baseLevel, width, height, depth, numberOfLevels);\n"
<< " width = max(width >> lod, 1);\n"
<< " height = max(height >> lod, 1);\n";
if (!IsSamplerArray(textureFunction.sampler))
{
out << " depth = max(depth >> lod, 1);\n";
}
}
else if (IsSampler2D(textureFunction.sampler) || IsSamplerCube(textureFunction.sampler))
{
out << " uint width; uint height; uint numberOfLevels;\n"
<< " " << textureReference
<< ".GetDimensions(baseLevel, width, height, numberOfLevels);\n"
<< " width = max(width >> lod, 1);\n"
<< " height = max(height >> lod, 1);\n";
}
else
UNREACHABLE();
}
const char *returnType = textureFunction.getReturnType();
if (strcmp(returnType, "int3") == 0)
{
out << " return int3(width, height, depth);\n";
}
else if (strcmp(returnType, "int2") == 0)
{
out << " return int2(width, height);\n";
}
else
{
out << " return int(width);\n";
}
}
void ProjectTextureCoordinates(const TextureFunctionHLSL::TextureFunction &textureFunction,
ImmutableString *texCoordX,
ImmutableString *texCoordY,
ImmutableString *texCoordZ)
{
if (textureFunction.proj)
{
ImmutableString proj("");
switch (textureFunction.coords)
{
case 3:
proj = ImmutableString(" / t.z");
break;
case 4:
proj = ImmutableString(" / t.w");
break;
default:
UNREACHABLE();
}
ImmutableStringBuilder texCoordXBuilder(texCoordX->length() + proj.length() + 2u);
texCoordXBuilder << '(' << *texCoordX << proj << ')';
*texCoordX = texCoordXBuilder;
ImmutableStringBuilder texCoordYBuilder(texCoordY->length() + proj.length() + 2u);
texCoordYBuilder << '(' << *texCoordY << proj << ')';
*texCoordY = texCoordYBuilder;
ImmutableStringBuilder texCoordZBuilder(texCoordZ->length() + proj.length() + 2u);
texCoordZBuilder << '(' << *texCoordZ << proj << ')';
*texCoordZ = texCoordZBuilder;
}
}
void OutputIntegerTextureSampleFunctionComputations(
TInfoSinkBase &out,
const TextureFunctionHLSL::TextureFunction &textureFunction,
const ShShaderOutput outputType,
const ImmutableString &textureReference,
ImmutableString *texCoordX,
ImmutableString *texCoordY,
ImmutableString *texCoordZ,
bool getDimensionsIgnoresBaseLevel)
{
if (!IsIntegerSampler(textureFunction.sampler))
{
return;
}
if (getDimensionsIgnoresBaseLevel)
{
out << " int baseLevel = samplerMetadata[samplerIndex].baseLevel;\n";
}
else
{
out << " int baseLevel = 0;\n";
}
if (IsSamplerCube(textureFunction.sampler))
{
out << " float width; float height; float layers; float levels;\n";
out << " uint mip = 0;\n";
out << " " << textureReference
<< ".GetDimensions(baseLevel + mip, width, height, layers, levels);\n";
out << " bool xMajor = abs(t.x) >= abs(t.y) && abs(t.x) >= abs(t.z);\n";
out << " bool yMajor = abs(t.y) >= abs(t.z) && abs(t.y) > abs(t.x);\n";
out << " bool zMajor = abs(t.z) > abs(t.x) && abs(t.z) > abs(t.y);\n";
out << " bool negative = (xMajor && t.x < 0.0f) || (yMajor && t.y < 0.0f) || "
"(zMajor && t.z < 0.0f);\n";
// FACE_POSITIVE_X = 000b
// FACE_NEGATIVE_X = 001b
// FACE_POSITIVE_Y = 010b
// FACE_NEGATIVE_Y = 011b
// FACE_POSITIVE_Z = 100b
// FACE_NEGATIVE_Z = 101b
out << " int face = (int)negative + (int)yMajor * 2 + (int)zMajor * 4;\n";
out << " float u = xMajor ? -t.z : (yMajor && t.y < 0.0f ? -t.x : t.x);\n";
out << " float v = yMajor ? t.z : (negative ? t.y : -t.y);\n";
out << " float m = xMajor ? t.x : (yMajor ? t.y : t.z);\n";
out << " float3 r = any(t) ? t : float3(1, 0, 0);\n";
out << " t.x = (u * 0.5f / m) + 0.5f;\n";
out << " t.y = (v * 0.5f / m) + 0.5f;\n";
// Mip level computation.
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::IMPLICIT ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::LOD ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::GRAD)
{
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::IMPLICIT)
{
// We would like to calculate tha maximum of how many texels we move in the major
// face's texture as we move across the screen in any direction. Namely, we want the
// length of the directional derivative of the function p (defined below), maximized
// over screen space directions. (For short: we want the norm of Dp.) For
// simplicity, assume that z-axis is the major axis. By symmetry, we can assume that
// the positive z direction is major. (The calculated value will be the same even if
// this is false.) Let r denote the function from screen position to cube texture
// coordinates. Then p can be written as p = s . P . r, where P(r) = (r.x, r.y)/r.z
// is the projection onto the major cube face, and s = diag(width, height)/2. (s
// linearly maps from the cube face into texture space, so that p(r) is in units of
// texels.) The derivative is
// Dp(r) = s |1 0 -r.x/r.z|
// |0 1 -r.y/r.z| |ddx(r) ddy(r)| / r.z
// = |dot(a, ddx(r)) dot(a, ddy(r))|
// |dot(b, ddx(r)) dot(b, ddy(r))| / (2 r.z)
// where a = w * vec3(1, 0, -r.x/r.z)
// b = h * vec3(0, 1, -r.y/r.z)
// We would like to know max(L(x)) over unit vectors x, where L(x) = |Dp(r) x|^2.
// Since ddx(r) and ddy(r) are unknown, the best we can do is to sample L in some
// directions and take the maximum across the samples.
//
// Some implementations use max(L(n1), L(n2)) where n1 = vec2(1,0) and n2 =
// vec2(0,1).
//
// Some implementations use max(L(n1), L(n2), L(n3), L(n4)),
// where n3 = (n1 + n2) / |n1 + n2| = (n1 + n2)/sqrt(2)
// n4 = (n1 - n2) / |n1 - n2| = (n1 - n2)/sqrt(2).
// In other words, two samples along the diagonal screen space directions have been
// added, giving a strictly better estimate of the true maximum.
//
// It turns out we can get twice the sample count very cheaply.
// We can use the linearity of Dp(r) to get these extra samples of L cheaply in
// terms of the already taken samples, L(n1) and L(n2):
// Denoting
// dpx = Dp(r)n1
// dpy = Dp(r)n2
// dpxx = dot(dpx, dpx)
// dpyy = dot(dpy, dpy)
// dpxy = dot(dpx, dpy)
// we obtain
// L(n3) = |Dp(r)n1 + Dp(r)n2|^2/2 = (dpxx + dpyy)/2 + dpxy
// L(n4) = |Dp(r)n1 - Dp(r)n2|^2/2 = (dpxx + dpyy)/2 - dpxy
// max(L(n1), L(n2), L(n3), L(n4))
// = max(max(L(n1), L(n2)), max(L(n3), L(n4)))
// = max(max(dpxx, dpyy), (dpxx + dpyy)/2 + abs(dpxy))
// So the extra cost is: one dot, one abs, one add, one multiply-add and one max.
// (All scalar.)
//
// In section 3.8.10.1, the OpenGL ES 3 specification defines the "scale factor",
// rho. In our terminology, this definition works out to taking sqrt(max(L(n1),
// L(n2))). Some implementations will use this estimate, here we use the strictly
// better sqrt(max(L(n1), L(n2), L(n3), L(n4))), since it's not much more expensive
// to calculate.
// Swap coordinates such that we can assume that the positive z-axis is major, in
// what follows.
out << " float3 ddxr = xMajor ? ddx(r).yzx : yMajor ? ddx(r).zxy : ddx(r).xyz;\n"
" float3 ddyr = xMajor ? ddy(r).yzx : yMajor ? ddy(r).zxy : ddy(r).xyz;\n"
" r = xMajor ? r.yzx : yMajor ? r.zxy : r.xyz;\n";
out << " float2 s = 0.5*float2(width, height);\n"
" float2 dpx = s * (ddxr.xy - ddxr.z*r.xy/r.z)/r.z;\n"
" float2 dpy = s * (ddyr.xy - ddyr.z*r.xy/r.z)/r.z;\n"
" float dpxx = dot(dpx, dpx);\n;"
" float dpyy = dot(dpy, dpy);\n;"
" float dpxy = dot(dpx, dpy);\n"
" float ma = max(dpxx, dpyy);\n"
" float mb = 0.5 * (dpxx + dpyy) + abs(dpxy);\n"
" float mab = max(ma, mb);\n"
" float lod = 0.5f * log2(mab);\n";
}
else if (textureFunction.method == TextureFunctionHLSL::TextureFunction::GRAD)
{
// ESSL 3.00.6 spec section 8.8: "For the cube version, the partial
// derivatives of P are assumed to be in the coordinate system used before
// texture coordinates are projected onto the appropriate cube face."
// ddx[0] and ddy[0] are the derivatives of t.x passed into the function
// ddx[1] and ddy[1] are the derivatives of t.y passed into the function
// ddx[2] and ddy[2] are the derivatives of t.z passed into the function
// Determine the derivatives of u, v and m
out << " float dudx = xMajor ? ddx[2] : (yMajor && t.y < 0.0f ? -ddx[0] "
": ddx[0]);\n"
" float dudy = xMajor ? ddy[2] : (yMajor && t.y < 0.0f ? -ddy[0] "
": ddy[0]);\n"
" float dvdx = yMajor ? ddx[2] : (negative ? ddx[1] : -ddx[1]);\n"
" float dvdy = yMajor ? ddy[2] : (negative ? ddy[1] : -ddy[1]);\n"
" float dmdx = xMajor ? ddx[0] : (yMajor ? ddx[1] : ddx[2]);\n"
" float dmdy = xMajor ? ddy[0] : (yMajor ? ddy[1] : ddy[2]);\n";
// Now determine the derivatives of the face coordinates, using the
// derivatives calculated above.
// d / dx (u(x) * 0.5 / m(x) + 0.5)
// = 0.5 * (m(x) * u'(x) - u(x) * m'(x)) / m(x)^2
out << " float dfacexdx = 0.5f * (m * dudx - u * dmdx) / (m * m);\n"
" float dfaceydx = 0.5f * (m * dvdx - v * dmdx) / (m * m);\n"
" float dfacexdy = 0.5f * (m * dudy - u * dmdy) / (m * m);\n"
" float dfaceydy = 0.5f * (m * dvdy - v * dmdy) / (m * m);\n"
" float2 sizeVec = float2(width, height);\n"
" float2 faceddx = float2(dfacexdx, dfaceydx) * sizeVec;\n"
" float2 faceddy = float2(dfacexdy, dfaceydy) * sizeVec;\n";
// Optimization: instead of: log2(max(length(faceddx), length(faceddy)))
// we compute: log2(max(length(faceddx)^2, length(faceddy)^2)) / 2
out << " float lengthfaceddx2 = dot(faceddx, faceddx);\n"
" float lengthfaceddy2 = dot(faceddy, faceddy);\n"
" float lod = log2(max(lengthfaceddx2, lengthfaceddy2)) * 0.5f;\n";
}
out << " mip = uint(min(max(round(lod), 0), levels - 1));\n"
<< " " << textureReference
<< ".GetDimensions(baseLevel + mip, width, height, layers, levels);\n";
}
// Convert from normalized floating-point to integer
static const ImmutableString kXPrefix("int(floor(width * frac(");
static const ImmutableString kYPrefix("int(floor(height * frac(");
static const ImmutableString kSuffix(")))");
ImmutableStringBuilder texCoordXBuilder(kXPrefix.length() + texCoordX->length() +
kSuffix.length());
texCoordXBuilder << kXPrefix << *texCoordX << kSuffix;
*texCoordX = texCoordXBuilder;
ImmutableStringBuilder texCoordYBuilder(kYPrefix.length() + texCoordX->length() +
kSuffix.length());
texCoordYBuilder << kYPrefix << *texCoordY << kSuffix;
*texCoordY = texCoordYBuilder;
*texCoordZ = ImmutableString("face");
}
else if (textureFunction.method != TextureFunctionHLSL::TextureFunction::FETCH)
{
if (IsSamplerArray(textureFunction.sampler))
{
out << " float width; float height; float layers; float levels;\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::LOD0)
{
out << " uint mip = 0;\n";
}
else if (textureFunction.method == TextureFunctionHLSL::TextureFunction::LOD0BIAS)
{
out << " uint mip = bias;\n";
}
else
{
out << " " << textureReference
<< ".GetDimensions(baseLevel, width, height, layers, levels);\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::IMPLICIT ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::BIAS)
{
out << " float2 tSized = float2(t.x * width, t.y * height);\n"
" float dx = length(ddx(tSized));\n"
" float dy = length(ddy(tSized));\n"
" float lod = log2(max(dx, dy));\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::BIAS)
{
out << " lod += bias;\n";
}
}
else if (textureFunction.method == TextureFunctionHLSL::TextureFunction::GRAD)
{
out << " float2 sizeVec = float2(width, height);\n"
" float2 sizeDdx = ddx * sizeVec;\n"
" float2 sizeDdy = ddy * sizeVec;\n"
" float lod = log2(max(dot(sizeDdx, sizeDdx), "
"dot(sizeDdy, sizeDdy))) * 0.5f;\n";
}
out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
}
out << " " << textureReference
<< ".GetDimensions(baseLevel + mip, width, height, layers, levels);\n";
}
else if (IsSampler2D(textureFunction.sampler))
{
out << " float width; float height; float levels;\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::LOD0)
{
out << " uint mip = 0;\n";
}
else if (textureFunction.method == TextureFunctionHLSL::TextureFunction::LOD0BIAS)
{
out << " uint mip = bias;\n";
}
else
{
out << " " << textureReference
<< ".GetDimensions(baseLevel, width, height, levels);\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::IMPLICIT ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::BIAS)
{
out << " float2 tSized = float2(t.x * width, t.y * height);\n"
" float dx = length(ddx(tSized));\n"
" float dy = length(ddy(tSized));\n"
" float lod = log2(max(dx, dy));\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::BIAS)
{
out << " lod += bias;\n";
}
}
else if (textureFunction.method == TextureFunctionHLSL::TextureFunction::GRAD)
{
out << " float2 sizeVec = float2(width, height);\n"
" float2 sizeDdx = ddx * sizeVec;\n"
" float2 sizeDdy = ddy * sizeVec;\n"
" float lod = log2(max(dot(sizeDdx, sizeDdx), "
"dot(sizeDdy, sizeDdy))) * 0.5f;\n";
}
out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
}
out << " " << textureReference
<< ".GetDimensions(baseLevel + mip, width, height, levels);\n";
}
else if (IsSampler3D(textureFunction.sampler))
{
out << " float width; float height; float depth; float levels;\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::LOD0)
{
out << " uint mip = 0;\n";
}
else if (textureFunction.method == TextureFunctionHLSL::TextureFunction::LOD0BIAS)
{
out << " uint mip = bias;\n";
}
else
{
out << " " << textureReference
<< ".GetDimensions(baseLevel, width, height, depth, levels);\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::IMPLICIT ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::BIAS)
{
out << " float3 tSized = float3(t.x * width, t.y * height, t.z * depth);\n"
" float dx = length(ddx(tSized));\n"
" float dy = length(ddy(tSized));\n"
" float lod = log2(max(dx, dy));\n";
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::BIAS)
{
out << " lod += bias;\n";
}
}
else if (textureFunction.method == TextureFunctionHLSL::TextureFunction::GRAD)
{
out << " float3 sizeVec = float3(width, height, depth);\n"
" float3 sizeDdx = ddx * sizeVec;\n"
" float3 sizeDdy = ddy * sizeVec;\n"
" float lod = log2(max(dot(sizeDdx, sizeDdx), dot(sizeDdy, "
"sizeDdy))) * 0.5f;\n";
}
out << " uint mip = uint(min(max(round(lod), 0), levels - 1));\n";
}
out << " " << textureReference
<< ".GetDimensions(baseLevel + mip, width, height, depth, levels);\n";
}
else
UNREACHABLE();
OutputIntTexCoordWraps(out, textureFunction, texCoordX, texCoordY, texCoordZ);
}
}
void OutputTextureGatherFunctionBody(TInfoSinkBase &out,
const TextureFunctionHLSL::TextureFunction &textureFunction,
ShShaderOutput outputType,
const ImmutableString &textureReference,
const ImmutableString &samplerReference,
const ImmutableString &texCoordX,
const ImmutableString &texCoordY,
const ImmutableString &texCoordZ)
{
const int hlslCoords = GetHLSLCoordCount(textureFunction, outputType);
ImmutableString samplerCoordTypeString(
GetSamplerCoordinateTypeString(textureFunction, hlslCoords));
ImmutableStringBuilder samplerCoordBuilder(
samplerCoordTypeString.length() + strlen("(") + texCoordX.length() + strlen(", ") +
texCoordY.length() + strlen(", ") + texCoordZ.length() + strlen(")"));
samplerCoordBuilder << samplerCoordTypeString << "(" << texCoordX << ", " << texCoordY;
if (hlslCoords >= 3)
{
if (textureFunction.coords < 3)
{
samplerCoordBuilder << ", 0";
}
else
{
samplerCoordBuilder << ", " << texCoordZ;
}
}
samplerCoordBuilder << ")";
ImmutableString samplerCoordString(samplerCoordBuilder);
if (IsShadowSampler(textureFunction.sampler))
{
out << "return " << textureReference << ".GatherCmp(" << samplerReference << ", "
<< samplerCoordString << ", refZ";
if (textureFunction.offset)
{
out << ", offset";
}
out << ");\n";
return;
}
constexpr std::array<const char *, 4> kHLSLGatherFunctions = {
{"GatherRed", "GatherGreen", "GatherBlue", "GatherAlpha"}};
out << " switch(comp)\n"
" {\n";
for (size_t component = 0; component < kHLSLGatherFunctions.size(); ++component)
{
out << " case " << component << ":\n"
<< " return " << textureReference << "." << kHLSLGatherFunctions[component]
<< "(" << samplerReference << ", " << samplerCoordString;
if (textureFunction.offset)
{
out << ", offset";
}
out << ");\n";
}
out << " default:\n"
" return float4(0.0, 0.0, 0.0, 1.0);\n"
" }\n";
}
void OutputTextureSampleFunctionReturnStatement(
TInfoSinkBase &out,
const TextureFunctionHLSL::TextureFunction &textureFunction,
const ShShaderOutput outputType,
const ImmutableString &textureReference,
const ImmutableString &samplerReference,
const ImmutableString &texCoordX,
const ImmutableString &texCoordY,
const ImmutableString &texCoordZ)
{
out << " return ";
if (IsIntegerSampler(textureFunction.sampler) && !IsSamplerCube(textureFunction.sampler) &&
textureFunction.method != TextureFunctionHLSL::TextureFunction::FETCH)
{
out << " useBorderColor ? ";
if (IsIntegerSamplerUnsigned(textureFunction.sampler))
{
out << "asuint";
}
out << "(samplerMetadata[samplerIndex].intBorderColor) : ";
}
// HLSL intrinsic
if (outputType == SH_HLSL_3_0_OUTPUT)
{
switch (textureFunction.sampler)
{
case EbtSampler2D:
case EbtSamplerVideoWEBGL:
case EbtSamplerExternalOES:
out << "tex2D";
break;
case EbtSamplerCube:
out << "texCUBE";
break;
default:
UNREACHABLE();
}
switch (textureFunction.method)
{
case TextureFunctionHLSL::TextureFunction::IMPLICIT:
out << "(" << samplerReference << ", ";
break;
case TextureFunctionHLSL::TextureFunction::BIAS:
out << "bias(" << samplerReference << ", ";
break;
case TextureFunctionHLSL::TextureFunction::LOD:
out << "lod(" << samplerReference << ", ";
break;
case TextureFunctionHLSL::TextureFunction::LOD0:
out << "lod(" << samplerReference << ", ";
break;
case TextureFunctionHLSL::TextureFunction::LOD0BIAS:
out << "lod(" << samplerReference << ", ";
break;
case TextureFunctionHLSL::TextureFunction::GRAD:
out << "grad(" << samplerReference << ", ";
break;
default:
UNREACHABLE();
}
}
else if (outputType == SH_HLSL_4_1_OUTPUT || outputType == SH_HLSL_4_0_FL9_3_OUTPUT)
{
OutputHLSL4SampleFunctionPrefix(out, textureFunction, textureReference, samplerReference);
}
else
UNREACHABLE();
const int hlslCoords = GetHLSLCoordCount(textureFunction, outputType);
out << GetSamplerCoordinateTypeString(textureFunction, hlslCoords);
if (hlslCoords >= 2)
{
out << "(" << texCoordX << ", " << texCoordY;
}
else if (hlslCoords == 1)
{
std::string varName(texCoordX.data());
if (size_t pos = varName.find_last_of('.') != std::string::npos)
{
varName = varName.substr(0, pos);
}
out << "(" << varName;
}
else
{
out << "(";
}
if (outputType == SH_HLSL_3_0_OUTPUT)
{
if (hlslCoords >= 3)
{
if (textureFunction.coords < 3)
{
out << ", 0";
}
else
{
out << ", " << texCoordZ;
}
}
if (hlslCoords == 4)
{
switch (textureFunction.method)
{
case TextureFunctionHLSL::TextureFunction::BIAS:
out << ", bias";
break;
case TextureFunctionHLSL::TextureFunction::LOD:
out << ", lod";
break;
case TextureFunctionHLSL::TextureFunction::LOD0:
out << ", 0";
break;
case TextureFunctionHLSL::TextureFunction::LOD0BIAS:
out << ", bias";
break;
default:
UNREACHABLE();
}
}
out << ")";
}
else if (outputType == SH_HLSL_4_1_OUTPUT || outputType == SH_HLSL_4_0_FL9_3_OUTPUT)
{
if (hlslCoords >= 3)
{
ASSERT(!IsIntegerSampler(textureFunction.sampler) ||
!IsSamplerCube(textureFunction.sampler) || texCoordZ == "face");
out << ", " << texCoordZ;
}
if (textureFunction.method == TextureFunctionHLSL::TextureFunction::GRAD)
{
if (IsIntegerSampler(textureFunction.sampler))
{
out << ", mip)";
}
else if (IsShadowSampler(textureFunction.sampler))
{
// Compare value
if (textureFunction.proj)
{
// According to ESSL 3.00.4 sec 8.8 p95 on textureProj:
// The resulting third component of P' in the shadow forms is used as
// Dref
out << "), " << texCoordZ;
}
else
{
switch (textureFunction.coords)
{
case 3:
out << "), t.z";
break;
case 4:
out << "), t.w";
break;
default:
UNREACHABLE();
}
}
}
else
{
out << "), ddx, ddy";
}
}
else if (IsIntegerSampler(textureFunction.sampler) ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::FETCH)
{
if (IsSampler2DMS(textureFunction.sampler) ||
IsSampler2DMSArray(textureFunction.sampler))
out << "), index";
else if (IsSamplerBuffer(textureFunction.sampler))
out << ")";
else
out << ", mip)";
}
else if (IsShadowSampler(textureFunction.sampler))
{
// Compare value
if (textureFunction.proj)
{
// According to ESSL 3.00.4 sec 8.8 p95 on textureProj:
// The resulting third component of P' in the shadow forms is used as Dref
out << "), " << texCoordZ;
}
else
{
switch (textureFunction.coords)
{
case 3:
out << "), t.z";
break;
case 4:
out << "), t.w";
break;
default:
UNREACHABLE();
}
}
}
else
{
switch (textureFunction.method)
{
case TextureFunctionHLSL::TextureFunction::IMPLICIT:
out << ")";
break;
case TextureFunctionHLSL::TextureFunction::BIAS:
out << "), bias";
break;
case TextureFunctionHLSL::TextureFunction::LOD:
out << "), lod";
break;
case TextureFunctionHLSL::TextureFunction::LOD0:
out << "), 0";
break;
case TextureFunctionHLSL::TextureFunction::LOD0BIAS:
out << "), bias";
break;
default:
UNREACHABLE();
}
}
if (textureFunction.offset &&
(!IsIntegerSampler(textureFunction.sampler) ||
textureFunction.method == TextureFunctionHLSL::TextureFunction::FETCH))
{
out << ", offset";
}
}
else
UNREACHABLE();
out << ");\n"; // Close the sample function call and return statement
}
} // Anonymous namespace
ImmutableString TextureFunctionHLSL::TextureFunction::name() const
{
static const ImmutableString kGlTextureName("gl_texture");
ImmutableString suffix(TextureTypeSuffix(this->sampler));
ImmutableStringBuilder name(kGlTextureName.length() + suffix.length() + 4u + 6u + 5u);
name << kGlTextureName;
// We need to include full the sampler type in the function name to make the signature unique
// on D3D11, where samplers are passed to texture functions as indices.
name << suffix;
if (proj)
{
name << "Proj";
}
if (offset)
{
name << "Offset";
}
switch (method)
{
case IMPLICIT:
break;
case BIAS:
break; // Extra parameter makes the signature unique
case LOD:
name << "Lod";
break;
case LOD0:
name << "Lod0";
break;
case LOD0BIAS:
name << "Lod0";
break; // Extra parameter makes the signature unique
case SIZE:
name << "Size";
break;
case FETCH:
name << "Fetch";
break;
case GRAD:
name << "Grad";
break;
case GATHER:
name << "Gather";
break;
default:
UNREACHABLE();
}
return name;
}
const char *TextureFunctionHLSL::TextureFunction::getReturnType() const
{
if (method == TextureFunction::SIZE)
{
switch (sampler)
{
case EbtSampler2D:
case EbtISampler2D:
case EbtUSampler2D:
case EbtSampler2DShadow:
case EbtSamplerCube:
case EbtISamplerCube:
case EbtUSamplerCube:
case EbtSamplerCubeShadow:
case EbtSamplerExternalOES:
case EbtSampler2DMS:
case EbtISampler2DMS:
case EbtUSampler2DMS:
case EbtSamplerVideoWEBGL:
return "int2";
case EbtSampler3D:
case EbtISampler3D:
case EbtUSampler3D:
case EbtSampler2DArray:
case EbtISampler2DArray:
case EbtUSampler2DArray:
case EbtSampler2DMSArray:
case EbtISampler2DMSArray:
case EbtUSampler2DMSArray:
case EbtSampler2DArrayShadow:
return "int3";
case EbtISamplerBuffer:
case EbtUSamplerBuffer:
case EbtSamplerBuffer:
return "int";
default:
UNREACHABLE();
}
}
else // Sampling function
{
switch (sampler)
{
case EbtSampler2D:
case EbtSampler2DMS:
case EbtSampler2DMSArray:
case EbtSampler3D:
case EbtSamplerCube:
case EbtSampler2DArray:
case EbtSamplerExternalOES:
case EbtSamplerVideoWEBGL:
case EbtSamplerBuffer:
return "float4";
case EbtISampler2D:
case EbtISampler2DMS:
case EbtISampler2DMSArray:
case EbtISampler3D:
case EbtISamplerCube:
case EbtISampler2DArray:
case EbtISamplerBuffer:
return "int4";
case EbtUSampler2D:
case EbtUSampler2DMS:
case EbtUSampler2DMSArray:
case EbtUSampler3D:
case EbtUSamplerCube:
case EbtUSampler2DArray:
case EbtUSamplerBuffer:
return "uint4";
case EbtSampler2DShadow:
case EbtSamplerCubeShadow:
case EbtSampler2DArrayShadow:
if (method == TextureFunctionHLSL::TextureFunction::GATHER)
{
return "float4";
}
else
{
return "float";
}
default:
UNREACHABLE();
}
}
return "";
}
bool TextureFunctionHLSL::TextureFunction::operator<(const TextureFunction &rhs) const
{
return std::tie(sampler, coords, proj, offset, method) <
std::tie(rhs.sampler, rhs.coords, rhs.proj, rhs.offset, rhs.method);
}
ImmutableString TextureFunctionHLSL::useTextureFunction(const ImmutableString &name,
TBasicType samplerType,
int coords,
size_t argumentCount,
bool lod0,
sh::GLenum shaderType)
{
TextureFunction textureFunction;
textureFunction.sampler = samplerType;
textureFunction.coords = coords;
textureFunction.method = TextureFunction::IMPLICIT;
textureFunction.proj = false;
textureFunction.offset = false;
if (name == "texture2D" || name == "textureCube" || name == "texture")
{
textureFunction.method = TextureFunction::IMPLICIT;
}
else if (name == "texture2DProj" || name == "textureProj")
{
textureFunction.method = TextureFunction::IMPLICIT;
textureFunction.proj = true;
}
else if (name == "texture2DLod" || name == "textureCubeLod" || name == "textureLod" ||
name == "texture2DLodEXT" || name == "textureCubeLodEXT")
{
textureFunction.method = TextureFunction::LOD;
}
else if (name == "texture2DProjLod" || name == "textureProjLod" ||
name == "texture2DProjLodEXT")
{
textureFunction.method = TextureFunction::LOD;
textureFunction.proj = true;
}
else if (name == "textureSize")
{
textureFunction.method = TextureFunction::SIZE;
}
else if (name == "textureOffset")
{
textureFunction.method = TextureFunction::IMPLICIT;
textureFunction.offset = true;
}
else if (name == "textureProjOffset")
{
textureFunction.method = TextureFunction::IMPLICIT;
textureFunction.offset = true;
textureFunction.proj = true;
}
else if (name == "textureLodOffset")
{
textureFunction.method = TextureFunction::LOD;
textureFunction.offset = true;
}
else if (name == "textureProjLodOffset")
{
textureFunction.method = TextureFunction::LOD;
textureFunction.proj = true;
textureFunction.offset = true;
}
else if (name == "texelFetch")
{
textureFunction.method = TextureFunction::FETCH;
}
else if (name == "texelFetchOffset")
{
textureFunction.method = TextureFunction::FETCH;
textureFunction.offset = true;
}
else if (name == "textureGrad" || name == "texture2DGradEXT")
{
textureFunction.method = TextureFunction::GRAD;
}
else if (name == "textureGradOffset")
{
textureFunction.method = TextureFunction::GRAD;
textureFunction.offset = true;
}
else if (name == "textureProjGrad" || name == "texture2DProjGradEXT" ||
name == "textureCubeGradEXT")
{
textureFunction.method = TextureFunction::GRAD;
textureFunction.proj = true;
}
else if (name == "textureProjGradOffset")
{
textureFunction.method = TextureFunction::GRAD;
textureFunction.proj = true;
textureFunction.offset = true;
}
else if (name == "textureGather")
{
textureFunction.method = TextureFunction::GATHER;
}
else if (name == "textureGatherOffset")
{
textureFunction.method = TextureFunction::GATHER;
textureFunction.offset = true;
}
else if (name == "textureVideoWEBGL")
{
textureFunction.method = TextureFunction::IMPLICIT;
}
else
UNREACHABLE();
if (textureFunction.method ==
TextureFunction::IMPLICIT) // Could require lod 0 or have a bias argument
{
size_t mandatoryArgumentCount = 2; // All functions have sampler and coordinate arguments
if (textureFunction.offset)
{
mandatoryArgumentCount++;
}
bool bias = (argumentCount > mandatoryArgumentCount); // Bias argument is optional
if (lod0 || shaderType == GL_VERTEX_SHADER || shaderType == GL_COMPUTE_SHADER)
{
if (bias)
{
textureFunction.method = TextureFunction::LOD0BIAS;
}
else
{
textureFunction.method = TextureFunction::LOD0;
}
}
else if (bias)
{
textureFunction.method = TextureFunction::BIAS;
}
}
mUsesTexture.insert(textureFunction);
return textureFunction.name();
}
void TextureFunctionHLSL::textureFunctionHeader(TInfoSinkBase &out,
const ShShaderOutput outputType,
bool getDimensionsIgnoresBaseLevel)
{
for (const TextureFunction &textureFunction : mUsesTexture)
{
// Function header
out << textureFunction.getReturnType() << " " << textureFunction.name() << "(";
OutputTextureFunctionArgumentList(out, textureFunction, outputType);
out << ")\n"
"{\n";
// In some cases we use a variable to store the texture/sampler objects, but to work around
// a D3D11 compiler bug related to discard inside a loop that is conditional on texture
// sampling we need to call the function directly on references to the texture and sampler
// arrays. The bug was found using dEQP-GLES3.functional.shaders.discard*loop_texture*
// tests.
ImmutableString textureReference("");
ImmutableString samplerReference("");
GetTextureReference(out, textureFunction, outputType, &textureReference, &samplerReference);
if (textureFunction.method == TextureFunction::SIZE)
{
OutputTextureSizeFunctionBody(out, textureFunction, textureReference,
getDimensionsIgnoresBaseLevel);
}
else
{
ImmutableString texCoordX("t.x");
ImmutableString texCoordY("t.y");
ImmutableString texCoordZ("t.z");
if (textureFunction.method == TextureFunction::GATHER)
{
OutputTextureGatherFunctionBody(out, textureFunction, outputType, textureReference,
samplerReference, texCoordX, texCoordY, texCoordZ);
}
else
{
ProjectTextureCoordinates(textureFunction, &texCoordX, &texCoordY, &texCoordZ);
OutputIntegerTextureSampleFunctionComputations(
out, textureFunction, outputType, textureReference, &texCoordX, &texCoordY,
&texCoordZ, getDimensionsIgnoresBaseLevel);
OutputTextureSampleFunctionReturnStatement(out, textureFunction, outputType,
textureReference, samplerReference,
texCoordX, texCoordY, texCoordZ);
}
}
out << "}\n"
"\n";
}
}
} // namespace sh
|
1bbb4459acfde7c53ed987ce910414d4a621d40f
|
74437d065ca1be70812a3d5209f80fd97305740b
|
/AtomSubMoveState.h
|
8e4c7cf1350b84627a3cd45b9854a9e680223e8a
|
[] |
no_license
|
aabramovsky/DeepImpactPublic
|
8fb8c9adebbf1be0fda44f4f53a58ef4a4302db6
|
90e556bcaf23feb89bce575a17d7156883c768c2
|
refs/heads/master
| 2020-04-01T01:45:59.099834
| 2018-10-12T13:07:19
| 2018-10-12T13:07:19
| 152,751,451
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 392
|
h
|
AtomSubMoveState.h
|
#pragma once
#include "ObjectState2.h"
#include "LuaScript.h"
#include "Controller.h"
namespace Game
{
class AtomSubMoveState : public ObjectState
{
public:
AtomSubMoveState();
virtual ~AtomSubMoveState();
virtual bool Init();
virtual void Loop(float dt);
virtual void Event_DamagedBy( Game::IObject* pDamagingObject, float fDamage );
};
}//namespace Game
|
ec49ac55131bb270e27b1e20b0951b03d407a7a9
|
96e8048d809d1459f019e6a5aa2829d0c55c957c
|
/project/src/StdLib/Macro.cpp
|
a4873af70dc08384b26c56f825f5ed0e8fbcdba1
|
[] |
no_license
|
Hnatekmar/TPJ
|
caec78d5ff92c9f46a54f6897b7c90fa6e1060ac
|
ef322615d5c07e3dda97ecd8b335fd22992e8a26
|
refs/heads/master
| 2021-06-06T09:36:31.422467
| 2021-04-05T05:41:19
| 2021-04-05T05:41:19
| 72,508,926
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,603
|
cpp
|
Macro.cpp
|
#include "../../include/StdLib/Macro.h"
#include "../../include/CompilerException.h"
#include <list>
Macro::Macro(std::vector<std::shared_ptr<AST> > &code)
{
if(code.size() < 3)
{
throw InterpreterException("Makro potřebuje minimálně neprázdný seznam argumentů a tělo, které obsahuje minimálně jeden výraz!", code.at(0)->value);
}
for(auto it = code.at(1)->children.begin(); it != code.at(1)->children.end(); it++)
{
std::shared_ptr<AST>& arg = (*it);
if(arg->value.type != TokenType::IDENTIFIER)
{
throw InterpreterException("Argument musí být validní identifikátor", arg->value);
}
std::string argName = boost::get<std::string>(arg->value.value);
if(argName == "..." && std::next(it) != code.at(1)->children.end())
{
throw InterpreterException("Variadická funkce musí mít označení pro variabilní počet argumentů na konci listu argumentů.", arg->value);
}
m_args.push_back(argName);
}
m_body.insert(m_body.begin(), code.begin() + 2, code.end());
}
Context IMacro::argsToContext(std::vector<std::shared_ptr<AST>>& args, Context context)
{
auto it = args.begin() + 1;
for(std::string& argName : m_args)
{
if(argName == "...")
{
List<Token> variadic;
while(it != args.end())
{
variadic = variadic.addBack(quote(*it));
it++;
}
context[argName] = Token{
TokenType::LIST,
variadic,
args.front()->value.filePos
};
break;
}
if(it == args.end())
{
throw InterpreterException("Neplatné množství argumentů", args.back()->value);
}
context[argName] = quote(*it);
it++;
}
if(it != args.end())
{
throw InterpreterException("Neplatné množství argumentů", args.front()->value);
}
return context;
}
Token quote(std::shared_ptr<AST> &ast)
{
if(ast->call)
{
return Token{
TokenType::LIST,
astToList(ast),
ast->value.filePos
};
}
Token copy = ast->value;
copy.quote = true;
return copy;
}
std::shared_ptr<AST> unquote(Token &value)
{
if(value.type == TokenType::LIST)
{
return listToAst(boost::get<List<Token>>(value.value));
}
std::shared_ptr<AST> top(nullptr);
Token copy = value;
copy.quote = false;
return std::make_shared<AST>(
copy,
top,
false);
}
std::shared_ptr<AST> listToAst(const List<Token>& list)
{
std::shared_ptr<AST> top(nullptr);
std::shared_ptr<AST> node = std::make_shared<AST>(Token{}, top, true);
if(list.size() == 0)
{
return node;
}
node->value = list.first();
List<Token> it = list;
while(!it.empty())
{
if(it.first().type == TokenType::LIST)
{
auto subNode = listToAst(boost::get<List<Token>>(it.first().value));
subNode->call = true;
node->children.push_back(subNode);
}
else
{
Token copy = it.first();
copy.quote = false;
node->children.push_back(std::make_shared<AST>(copy, node, false));
}
it = it.rest();
}
return node;
}
List<Token> astToList(std::shared_ptr<AST> &ast)
{
List<Token> list;
for(std::shared_ptr<AST>& elem : ast->children)
{
list = list.addBack(quote(elem));
}
return list;
}
std::shared_ptr<AST> IMacro::expand(std::vector<std::shared_ptr<AST> > &args, Context &context)
{
Context copy = argsToContext(args, context);
// Samotná evaluace funkce probíhá zde. Vrací se vždy hodnota posledního výrazu v těle funkce.
for(auto it = m_body.begin(); it != m_body.end(); it++)
{
if(std::next(it) == m_body.end())
{
Token token = (*it)->evaluate(copy);
if(token.type != TokenType::LIST)
{
throw InterpreterException("Makro musí vracet list", token);
}
return listToAst(boost::get<List<Token>>(token.value));
}
else
{
(*it)->evaluate(copy);
}
}
assert(false);
return nullptr;
}
Token CreateMacro::execute(std::vector<std::shared_ptr<AST> > &args, Context &)
{
Token returnVal{
TokenType::MACRO_FN,
std::make_shared<Macro>(args),
{}
};
return returnVal;
}
|
66593beb5ed5c50d7f6a090033097573eff5cfce
|
b08b5a534f96ce065de97de0debbc4bcf71b8698
|
/border.h
|
bda5ec2ced0fdf65350d1c859476fc58700fd1ce
|
[] |
no_license
|
paolini/surf
|
3e095d3e8eb54b1416f5eabe0b5bd05d8dfe16e2
|
90d136cb72536b04470e9e56dabf4b27b70944d6
|
refs/heads/master
| 2021-05-16T03:14:01.649749
| 2017-07-30T15:33:54
| 2017-07-30T15:33:54
| 42,228,410
| 4
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 444
|
h
|
border.h
|
#include <map>
#include <string>
#include "surf.h"
class Border: public surf {
public:
typedef Border *(*factory_function_ptr)();
typedef std::map<std::string, factory_function_ptr> Registry;
static Registry factory;
};
template<class T> Border *factory_function() {
return new T();
};
template<class T> bool registry_function(const char *border_name) {
Border::factory[border_name] = factory_function<T>;
return true;
}
|
b76cce6fcc9f7fc68f45d30f52c73b0fd9f3a851
|
afb7006e47e70c1deb2ddb205f06eaf67de3df72
|
/third_party/rust/glslopt/glsl-optimizer/src/compiler/glsl/ir_rvalue_visitor.h
|
be19fc7d14cbad4257ed7b8cf657f88b49773199
|
[
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] |
permissive
|
marco-c/gecko-dev-wordified
|
a66383f85db33911b6312dd094c36f88c55d2e2c
|
3509ec45ecc9e536d04a3f6a43a82ec09c08dff6
|
refs/heads/master
| 2023-08-10T16:37:56.660204
| 2023-08-01T00:39:54
| 2023-08-01T00:39:54
| 211,297,590
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,864
|
h
|
ir_rvalue_visitor.h
|
/
*
*
Copyright
2010
Intel
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
(
including
the
next
*
paragraph
)
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
.
*
/
/
*
*
*
\
file
ir_rvalue_visitor
.
h
*
*
Generic
class
to
implement
the
common
pattern
we
have
of
wanting
to
*
visit
each
ir_rvalue
*
and
possibly
change
that
node
to
a
different
*
class
.
Just
implement
handle_rvalue
(
)
and
you
will
be
called
with
*
a
pointer
to
each
rvalue
in
the
tree
.
*
/
#
ifndef
GLSL_IR_RVALUE_VISITOR_H
#
define
GLSL_IR_RVALUE_VISITOR_H
class
ir_rvalue_base_visitor
:
public
ir_hierarchical_visitor
{
public
:
ir_visitor_status
rvalue_visit
(
ir_assignment
*
)
;
ir_visitor_status
rvalue_visit
(
ir_call
*
)
;
ir_visitor_status
rvalue_visit
(
ir_dereference_array
*
)
;
ir_visitor_status
rvalue_visit
(
ir_dereference_record
*
)
;
ir_visitor_status
rvalue_visit
(
ir_discard
*
)
;
ir_visitor_status
rvalue_visit
(
ir_expression
*
)
;
ir_visitor_status
rvalue_visit
(
ir_if
*
)
;
ir_visitor_status
rvalue_visit
(
ir_return
*
)
;
ir_visitor_status
rvalue_visit
(
ir_swizzle
*
)
;
ir_visitor_status
rvalue_visit
(
ir_texture
*
)
;
ir_visitor_status
rvalue_visit
(
ir_emit_vertex
*
)
;
ir_visitor_status
rvalue_visit
(
ir_end_primitive
*
)
;
virtual
void
handle_rvalue
(
ir_rvalue
*
*
rvalue
)
=
0
;
}
;
class
ir_rvalue_visitor
:
public
ir_rvalue_base_visitor
{
public
:
virtual
ir_visitor_status
visit_leave
(
ir_assignment
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_call
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_dereference_array
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_dereference_record
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_discard
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_expression
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_if
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_return
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_swizzle
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_texture
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_emit_vertex
*
)
;
virtual
ir_visitor_status
visit_leave
(
ir_end_primitive
*
)
;
}
;
class
ir_rvalue_enter_visitor
:
public
ir_rvalue_base_visitor
{
public
:
virtual
ir_visitor_status
visit_enter
(
ir_assignment
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_call
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_dereference_array
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_dereference_record
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_discard
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_expression
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_if
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_return
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_swizzle
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_texture
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_emit_vertex
*
)
;
virtual
ir_visitor_status
visit_enter
(
ir_end_primitive
*
)
;
}
;
#
endif
/
*
GLSL_IR_RVALUE_VISITOR_H
*
/
|
7b4e1d7178a36459269cfe8cb2cfcff92e351229
|
8bc40f27ed58d161dc79c90d4a3c860101ef1753
|
/libraries/basics/code/base/adapters/android/Android_Application.hpp
|
744b702d4e09bc8ce4e80b76e4290f25db0e65ec
|
[
"BSL-1.0"
] |
permissive
|
LoronsoDev/basics-hexagon
|
905d11ed931293908c307c89ab1899100abf9145
|
8db5958d4ef59a34551c4cb8f4eddc9a462b08a0
|
refs/heads/main
| 2023-06-30T20:14:30.240521
| 2021-07-10T22:00:23
| 2021-07-10T22:00:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,592
|
hpp
|
Android_Application.hpp
|
/*
* ANDROID APPLICATION
* Copyright © 2017+ Ángel Rodríguez Ballesteros
*
* Distributed under the Boost Software License, version 1.0
* See documents/LICENSE.TXT or www.boost.org/LICENSE_1_0.txt
*
* angel.rodriguez@esne.edu
*
* C1712291010
*/
#ifndef BASICS_ANDROID_APPLICATION_HEADER
#define BASICS_ANDROID_APPLICATION_HEADER
#include <atomic>
#include <basics/Application>
namespace basics { namespace internal
{
class Android_Application : public Application
{
std::atomic< Application::State > state;
const char * internal_data_path = "";
const char * external_data_path = "";
public:
State get_state () const override
{
return state;
}
void set_state (State new_state)
{
state = new_state;
}
void clear_events ()
{
event_queue.clear ();
}
void set_internal_data_path (const char * value)
{
internal_data_path = value;
}
void set_external_data_path (const char * value)
{
external_data_path = value;
}
const char * get_internal_data_path ()
{
return internal_data_path;
}
const char * get_external_data_path ()
{
return external_data_path;
}
};
extern Android_Application application;
}}
#endif
|
ec5f4c799c409ae3fd79d5988d203d62e45a34d7
|
c646dda13bbb0f250106c551c856e84ed1cf3312
|
/TFN118A_APP/configpage.cpp
|
c494d89adbf283101022915f719b51c140b52ab5
|
[] |
no_license
|
icprog/TFN118A_APP
|
208f06da8a63f3bef5e1d4b87c1a364a7d5af36d
|
95bf6a3d93b61f377ab4987de4c5cacfc915b996
|
refs/heads/master
| 2020-04-07T01:26:36.656703
| 2017-09-11T02:53:48
| 2017-09-11T02:53:48
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 34,541
|
cpp
|
configpage.cpp
|
#include "configpage.h"
#include "packet.h"
ConfigPage::ConfigPage(QWidget *parent) : QWidget(parent)
{
//时间
QGroupBox *timeGroup = new QGroupBox("时间");
timeGroup->setMaximumHeight(100);
timeGroup->setMaximumWidth(180);
getTimeBtn = new QPushButton("获取时间");
setTimeBtn = new QPushButton("时间设置");
QDialogButtonBox *dlgBtnBox = new QDialogButtonBox(Qt::Horizontal);
dlgBtnBox->addButton(getTimeBtn, QDialogButtonBox::ActionRole);
dlgBtnBox->addButton(setTimeBtn, QDialogButtonBox::ActionRole);
// QLabel *timeLabel = new QLabel("时间:");
dateEdit = new QDateTimeEdit(QDateTime::currentDateTime());
dateEdit->setDisplayFormat("yyyy/MM/dd HH:mm:ss");
QGridLayout *timeLayout = new QGridLayout;
timeLayout->addWidget(dlgBtnBox, 0, 0,1,1);
timeLayout->addWidget(setTimeBtn, 0, 1,1,1);
timeLayout->addWidget(dateEdit, 1, 0,1,2);
timeGroup->setLayout(timeLayout);
//参数
QGroupBox *paraGroup = new QGroupBox("腕带参数");
paraGroup->setMaximumHeight(240);
paraGroup->setMaximumWidth(180);
QLabel *TargetIDLabel = new QLabel("目标ID:");
TargetIDLineEdt = new QLineEdit;
TargetIDLineEdt->setMaxLength(8);
//发射功率
QLabel *pwrLabel = new QLabel("发射功率:");
pwrCombo = new QComboBox;
pwrCombo->addItem(tr("-30dBm"));
pwrCombo->addItem(tr("-20dBm"));
pwrCombo->addItem(tr("-16dBm"));
pwrCombo->addItem(tr("-12dBm"));
pwrCombo->addItem(tr("-8dBm"));
pwrCombo->addItem(tr("-4dBm"));
pwrCombo->addItem(tr("0dBm"));
pwrCombo->addItem(tr("4dBm"));
pwrCombo->setCurrentIndex(6);
// QLabel *pwrUnitLabel = new QLabel("dBm");
//工作模式
QLabel *wModeLabel = new QLabel("工作模式:");
wModeCombo = new QComboBox;
wModeCombo->addItem("活动模式");
wModeCombo->addItem("保存模式");
// QLabel *spaceLabel = new QLabel;
//报警时间
QLabel *alarmLabel = new QLabel("报警时间:");
alarmCombo = new QComboBox;
alarmCombo->addItem(tr("1s"));
alarmCombo->addItem(tr("2s"));
alarmCombo->addItem(tr("3s"));
alarmCombo->addItem(tr("4s"));
alarmCombo->addItem(tr("5s"));
alarmCombo->addItem(tr("6s"));
alarmCombo->setCurrentIndex(3);
// QLabel *alarmUnitLabel = new QLabel("s");
//设置按钮
setParaBtn = new QPushButton("参数设置");
//layout
QGridLayout *paraLayout = new QGridLayout;
paraLayout->addWidget(TargetIDLabel, 0,0);
paraLayout->addWidget(TargetIDLineEdt, 0,1);
paraLayout->addWidget(pwrLabel, 1,0);
paraLayout->addWidget(pwrCombo, 1,1);
// paraLayout->addWidget(pwrUnitLabel,0,3);
paraLayout->addWidget(wModeLabel, 2, 0);
paraLayout->addWidget(wModeCombo, 2,1);
// paraLayout->addWidget(spaceLabel,1,3);
paraLayout->addWidget(alarmLabel, 3, 0);
paraLayout->addWidget(alarmCombo, 3, 1);
// paraLayout->addWidget(alarmUnitLabel, 2, 3);
paraLayout->addWidget(setParaBtn,4,0,1,2);
paraGroup->setLayout(paraLayout);
//消息
QGroupBox *messageGroup = new QGroupBox("消息");
messageGroup->setMaximumHeight(150);
messageGroup->setMaximumWidth(180);
messageTedt = new QTextEdit;
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB18030"));
messageTedt->setText("小朋友,你们好!");
messageTedt->setMaximumHeight(50);
messageTedt->setMaximumWidth(160);
messageBtn = new QPushButton("发送消息");
QGridLayout *messageLayout = new QGridLayout;
messageLayout->addWidget(messageTedt,0,0,1,2);
messageLayout->addWidget(messageBtn,1,0,1,2);
messageGroup->setLayout(messageLayout);
//文件操作
QGroupBox *fileGroup = new QGroupBox("文件操作");
fileGroup->setMaximumHeight(280);
fileGroup->setMaximumWidth(180);
//QButtonGroup无布局管理,需要layout布局管理
QButtonGroup *WRBtnGroup = new QButtonGroup;
readRadioBtn = new QRadioButton("读操作");
writeRadioBtn = new QRadioButton("写操作");
WRBtnGroup->addButton(readRadioBtn,0);
WRBtnGroup->addButton(writeRadioBtn,1);
WRBtnGroup->setExclusive(true);//按钮互斥
QLabel* TargetIDLabel1 = new QLabel("目标ID:");
TargetIDLineEdt1 = new QLineEdit;
TargetIDLineEdt1->setMaxLength(8);
QLabel *modeLabel = new QLabel("模式:");
QLabel *OTLabel = new QLabel("命令超时:");//超时时间
OverTime = new QComboBox();
OverTime->addItem("无超时");
QStringList OTList;
for(uint8_t i = 1; i< 10 ;i++)
{
QString OTStr = QString::number(i);
OTStr += "s";
OTList << OTStr;
}
OverTime->addItems(OTList);
OverTime->setCurrentIndex(9);
modeCombo = new QComboBox;
modeCombo->addItem("参数区");
modeCombo->addItem("保留区");
modeCombo->addItem("用户区1");
modeCombo->addItem("用户区2");
QLabel *offsetLabel = new QLabel("偏移:");
offsetCombo = new QComboBox;
offsetCombo->addItem("最新记录");
QStringList offsetList;
for(int i=0;i<32;i++)
{
QString offsetstr = QString::number(i);
offsetList << offsetstr;
}
offsetCombo->addItems(offsetList);
offsetCombo->setCurrentIndex(0);
QLabel *lenthLabel = new QLabel("长度:");
lenthCombo = new QComboBox;
QStringList lenthList;
for(int i=0;i<17;i++)
{
QString LengthStr = QString::number(i);
lenthList+=LengthStr;
}
lenthCombo->addItems(lenthList);
lenthCombo->setCurrentIndex(16);
QLabel *dataLabel = new QLabel("数据:");
dataTedt = new QTextEdit;
dataTedt->setText("01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16");
dataTedt->setMaximumHeight(40);
dataTedt->setMaximumWidth(160);
WRFileBtn = new QPushButton("文件操作");
QGridLayout *fileLayout = new QGridLayout;
fileLayout->addWidget(readRadioBtn,0,0);
fileLayout->addWidget(writeRadioBtn,0,1);
fileLayout->addWidget(TargetIDLabel1, 1,0);
fileLayout->addWidget(TargetIDLineEdt1, 1,1);
fileLayout->addWidget(OTLabel,2,0);
fileLayout->addWidget(OverTime,2,1);
fileLayout->addWidget(modeLabel,3,0);
fileLayout->addWidget(modeCombo,3,1);
fileLayout->addWidget(offsetLabel,4,0);
fileLayout->addWidget(offsetCombo,4,1);
fileLayout->addWidget(lenthLabel,5,0);
fileLayout->addWidget(lenthCombo,5,1);
fileLayout->addWidget(dataLabel,6,0);
fileLayout->addWidget(dataTedt,7,0,1,2);
fileLayout->addWidget(WRFileBtn,8,0,1,2);
fileGroup->setLayout(fileLayout);
//射频测试
QGroupBox *radioGroup = new QGroupBox("射频性能");
radioGroup->setMaximumHeight(70);
radioGroup->setMaximumWidth(180);
radioBtn = new QPushButton("射频性能测试");
QGridLayout *radioLayout = new QGridLayout;
radioLayout->addWidget(radioBtn,0,0,1,2);
radioGroup->setLayout(radioLayout);
radioBtn->setCheckable(true);
//! [0]
radioBtn->setAutoDefault(false);
//扩展窗口放在主界面
// createExtension();
//! [1]
//整机测试
testBtn = new QPushButton("整机测试");
// QLabel *stateLable = new QLabel("执行成功");
// stateLable->setAlignment(Qt::AlignBottom | Qt::AlignLeft);
// stateLable->setFrameStyle(QFrame::Panel | QFrame::Sunken);
// QHBoxLayout *bottomLayout = new QHBoxLayout;
// bottomLayout->addWidget(testBtn);
// bottomLayout->addWidget(stateLable);
QVBoxLayout *leftLayout = new QVBoxLayout;
leftLayout->addWidget(timeGroup);
leftLayout->addWidget(paraGroup);
leftLayout->addWidget(messageGroup);
leftLayout->addSpacing(12);
leftLayout->addWidget(testBtn);
leftLayout->addStretch(1);
QVBoxLayout *rightLayout = new QVBoxLayout;
rightLayout->addWidget(fileGroup);
rightLayout->addWidget(radioGroup);
rightLayout->addStretch(12);
QGridLayout *mainLayout = new QGridLayout;
mainLayout->addLayout(leftLayout,0,0,1,1);
mainLayout->addLayout(rightLayout,0,1,1,1);
// mainLayout->addWidget(extension,0,2,1,1);
setLayout(mainLayout);
}
void ConfigPage::createExtension()
{
extension = new QWidget;
//列出标签
QGroupBox *searchDeviceGroup = new QGroupBox("查询设备");
QLabel *searchDevicelabel = new QLabel("查询时间");
searchTimeCombox = new QComboBox;
QStringList searchTimeList;
for(uint8_t i = 1; i< 8 ;i++)
{
QString searchTimeStr = QString::number(i);
searchTimeStr += "s";
searchTimeList << searchTimeStr;
}
searchTimeCombox->addItems(searchTimeList);
searchTimeCombox->setCurrentIndex(2);
lpfilterCheckBox = new QCheckBox("低电过滤");
rssiCheckBox = new QCheckBox("RSSI过滤");
rssiCombox = new QComboBox;
QStringList rssiList;
for(uint8_t i = 0; i< 128 ;i++)
{
QString rssistr = QString::number(i);
rssistr += "dBm";
rssiList << rssistr;
}
rssiCombox->addItems(rssiList);
rssiCombox->setCurrentIndex(64);
rssiCombox->setDisabled(true);
searchTagBtn = new QPushButton("查询标签");
searchReaderBtn = new QPushButton("查询读写器");
QGridLayout *searchDeviceLayout = new QGridLayout;
searchDeviceLayout->addWidget(searchDevicelabel,0,0);
searchDeviceLayout->addWidget(searchTimeCombox,0,1);
searchDeviceLayout->addWidget(lpfilterCheckBox,1,0,1,2);
searchDeviceLayout->addWidget(rssiCheckBox,2,0);
searchDeviceLayout->addWidget(rssiCombox,2,1);
searchDeviceLayout->addWidget(searchTagBtn,3,0);
searchDeviceLayout->addWidget(searchReaderBtn,3,1);
searchDeviceGroup->setLayout(searchDeviceLayout);
//自动上报
QGroupBox *autoreportGroup = new QGroupBox("自动上报");
QLabel *leaveTimeLabel = new QLabel("离开时间:");
leaveTimeCombox = new QComboBox;
QStringList leaveTimeList;
for(uint8_t i = 1; i< 11 ;i++)
{
QString leaveTimeStr = QString::number(i);
leaveTimeStr += "s";
leaveTimeList << leaveTimeStr;
}
leaveTimeCombox->addItems(leaveTimeList);
leaveTimeCombox->setCurrentIndex(2);
QLabel *reportTimeLabel = new QLabel("上报间隔:");
reportTimeCombox = new QComboBox;
QStringList reportTimeList;
for(uint8_t i = 1; i< 8 ;i++)
{
QString reportTimeStr = QString::number(i);
reportTimeStr += "s";
reportTimeList << reportTimeStr;
}
reportTimeCombox->addItems(reportTimeList);
reportTimeCombox->setCurrentIndex(2);
lpfilterAutoCheckBox = new QCheckBox("低电过滤");
rssiAutoCheckBox = new QCheckBox("RSSI过滤");
rssiAutoCombox = new QComboBox;
QStringList rssiAutoList;
for(uint8_t i = 0; i< 128 ;i++)
{
QString rssiAutostr = QString::number(i);
rssiAutostr += "dBm";
rssiAutoList << rssiAutostr;
}
rssiAutoCombox->addItems(rssiAutoList);
rssiAutoCombox->setCurrentIndex(64);
rssiAutoCombox->setDisabled(true);
AutoReportOpenBtn = new QPushButton("打开自动上报");
AutoReportCloseBtn = new QPushButton("关闭自动上报");
QGridLayout *autoreportLayout = new QGridLayout;
autoreportLayout->addWidget(leaveTimeLabel,0,0);
autoreportLayout->addWidget(leaveTimeCombox,0,1);
autoreportLayout->addWidget(reportTimeLabel,2,0);
autoreportLayout->addWidget(reportTimeCombox,2,1);
autoreportLayout->addWidget(lpfilterAutoCheckBox,3,0);
autoreportLayout->addWidget(rssiAutoCheckBox,4,0);
autoreportLayout->addWidget(rssiAutoCombox,4,1);
autoreportLayout->addWidget(AutoReportOpenBtn,5,0);
autoreportLayout->addWidget(AutoReportCloseBtn,5,1);
autoreportGroup->setLayout(autoreportLayout);
//设备信息
infoDevice = new QTableView;
device_model = new QStandardItemModel();
device_model->setHorizontalHeaderItem(0,new QStandardItem(QObject::tr("TYPE")));//传感类型
device_model->setHorizontalHeaderItem(1,new QStandardItem(QObject::tr("ID")));
device_model->setHorizontalHeaderItem(2,new QStandardItem(QObject::tr("State")));
device_model->setHorizontalHeaderItem(3,new QStandardItem(QObject::tr("RSSI")));
device_model->setHorizontalHeaderItem(4,new QStandardItem(QObject::tr("DATA")));
device_model->setHorizontalHeaderItem(5,new QStandardItem(QObject::tr("BASEID")));//边界管理器ID
device_model->setHorizontalHeaderItem(6,new QStandardItem(QObject::tr("VER")));
//利用setModel()方法将数据模型与QTableView绑定
infoDevice->setModel(device_model);
// infoDevice->setEditTriggers(QAbstractItemView::NoEditTriggers);//只读
//如果你用在QTableView中使用右键菜单,需启用该属性
infoDevice->setContextMenuPolicy(Qt::CustomContextMenu);
// device_model->setItem(0,1,new QStandardItem("张三"));
// device_model->setItem(1,1,new QStandardItem("张三"));
QGridLayout *extensionLayout = new QGridLayout;
extensionLayout->addWidget(searchDeviceGroup,0,0,1,1);
extensionLayout->addWidget(autoreportGroup,0,1,1,1);
extensionLayout->addWidget(infoDevice,1,0,1,3);
//扩展窗口
connect(radioBtn, &QAbstractButton::toggled, extension, &QWidget::setVisible);
QVBoxLayout *extensionMainLayout = new QVBoxLayout;
extensionMainLayout->setMargin(0);
extensionMainLayout->addLayout(extensionLayout);
extension->setLayout(extensionMainLayout);
extension->setMinimumHeight(400);
extension->setMinimumWidth(600);
extension->setMaximumHeight(400);
extension->setMaximumWidth(800);
extension->hide();
event_init();
//
}
void ConfigPage::event_init()
{
connect(getTimeBtn,&QPushButton::clicked,this,&ConfigPage::updateTime);//获取时间
connect(setTimeBtn,&QPushButton::clicked,this,&ConfigPage::setTimebuf);//设置时间
connect(setParaBtn,&QPushButton::clicked,this,&ConfigPage::setParaBuf);//设置参数
connect(WRFileBtn,&QPushButton::clicked,this,&ConfigPage::WriteReadFile);//文件操作
connect(rssiCheckBox,&QCheckBox::clicked,rssiCombox,&QComboBox::setEnabled);//选择
connect(rssiAutoCheckBox,&QCheckBox::clicked,rssiAutoCombox,&QComboBox::setEnabled);
connect(messageTedt,&QTextEdit::textChanged,this,&ConfigPage::msgMaxLength);//消息最大长度
connect(messageBtn,&QPushButton::clicked,this,&ConfigPage::msgSend);//消息下发
connect(searchTagBtn,&QPushButton::clicked,this,&ConfigPage::SearchTag);//查询标签
connect(searchReaderBtn,&QPushButton::clicked,this,&ConfigPage::SearchReader);//查询读写器
connect(AutoReportOpenBtn,&QPushButton::clicked,this,&ConfigPage::AutoReportOpen);//打开自动上报
connect(AutoReportCloseBtn,&QPushButton::clicked,this,&ConfigPage::AutoReportClose);//关闭自动上报
connect(testBtn,&QPushButton::clicked,this,&ConfigPage::DeviceTest);//整机测试
}
//清空数据
void ConfigPage::ClearReadFileData()
{
dataTedt->clear();
}
//显示读取内容数据
void ConfigPage::ShowReadFileData(QByteArray Data_Src)
{
QString StrDataDes = QString::fromLatin1(Data_Src.toHex(' '));
// QString StrDes;
// for(int i=0;i<StrDataDes.length();)
// {
// StrDes+=StrDataDes[i];
// StrDes+=StrDataDes[i+1];
// StrDes+=" ";
// i=i+2;
// }
qDebug() <<"数据内容"<< StrDataDes;
dataTedt->setPlainText(StrDataDes);
}
//时间更新
void ConfigPage::updateTime()
{
dateEdit->setDateTime(QDateTime::currentDateTime());
}
//更新时间数据
/****************************************************
串口通信 上位机->接收器 命令字90
时间设置信息内容
年月日时分秒:6字节 2017-08-01 14:40:30-> 17 08 01 14 40 30
******************************************************/
void ConfigPage::setTimebuf()
{
QByteArray timebuff;
QString datasrc= dateEdit->text();
timebuff = QByteArray::fromHex(datasrc.toLatin1());
timebuff.remove(0,1);
// qDebug() << timebuff;
config_Btn = settimeBtnPD;//按键按下
emit sendsignal(timebuff);
}
//更新参数buff
#define TAGP_PWR_IDX 1
#define TAGP_PWR_Pos 4
#define TAGP_WORKMODE_IDX 2
#define TAGP_WORKMODE_Pos 0
#define TAGP_WORKMODE_Msk 0x0f
#define TAGP_WORKMODE_MAX_VALUE 0x01
#define TAGP_KEYALARM_IDX 4
#define OVER_TIME 9//9S
/****************************************************
串口通信 上位机->接收器 命令F0
参数设置信息内容
目标ID:XXXXXXXX 4字节
超时时间:0~9 0:无超时时间 单位s
保留:0000
写参数区:01
写最新参数:FFFF
写长度:10
数据内容:16字节
******************************************************/
void ConfigPage::setParaBuf()
{
//参数buff
QByteArray parabuff;
QString DestIDSrc = TargetIDLineEdt->text();
config_Btn = setparaBtnPD;//按键按下
if(DestIDSrc.length()<8)
{
QByteArray error;
emit sendsignal(error);
}
else
{
char txpower = 0x00;
char workmode = 0x00;
for(int i=0;i< 16;i++)
parabuff[i] = 0;
QString tag_txpower = pwrCombo->currentText();
if(tag_txpower == "-30dBm")
txpower |= (0<<TAGP_PWR_Pos);
else if(tag_txpower == "-20dBm")
txpower |= (1<<TAGP_PWR_Pos);
else if(tag_txpower == "-16dBm")
txpower |= (2<<TAGP_PWR_Pos);
else if(tag_txpower == "-12dBm")
txpower |= (3<<TAGP_PWR_Pos);
else if(tag_txpower == "-8dBm")
txpower |= (4<<TAGP_PWR_Pos);
else if(tag_txpower == "-4dBm")
txpower |= (5<<TAGP_PWR_Pos);
else if(tag_txpower == "0dBm")
txpower |= (6<<TAGP_PWR_Pos);
else if(tag_txpower == "4dBm")
txpower |= (7<<TAGP_PWR_Pos);
else
txpower|=(6<<TAGP_PWR_Pos);
QString tag_workmode = wModeCombo->currentText();
if("保存模式" == tag_workmode)
workmode|=0x00;
else
workmode|=0x01;
QString tag_alarmtime = alarmCombo->currentText();
tag_alarmtime.chop(1);//移除最后一位s
char alarmtimeSrc = tag_alarmtime.toInt();
parabuff[TAGP_PWR_IDX] = txpower;//发射功率
parabuff[TAGP_WORKMODE_IDX] =workmode;//工作模式
parabuff[TAGP_KEYALARM_IDX] = alarmtimeSrc;//报警时间
QByteArray sendparabuff;
// QString DestIDSrc = TargetIDLineEdt->text();
QByteArray DestIDDec = QByteArray::fromHex(DestIDSrc.toLatin1());//目标ID
sendparabuff+=DestIDDec;//目标ID
sendparabuff+=OVER_TIME;//超时时间
sendparabuff+=(char)(U_FILE_RESERVER>>8);//保留
sendparabuff+=(char)U_FILE_RESERVER;//保留
sendparabuff+=U_FILE_MODE_PARA;//内部参数区
sendparabuff+=(char)(U_FILE_OFFSET_RNEW>>8);
sendparabuff+=(char)U_FILE_OFFSET_RNEW;//写最新参数
sendparabuff+=(char)0x10;//长度
sendparabuff+=parabuff;
qDebug() << "获取参数值:" << sendparabuff.toHex();
config_Btn = setparaBtnPD;//按键按下
emit sendsignal(sendparabuff);
}
}
/****************************************************
串口通信 上位机->接收器
写命令F0
参数设置信息内容
目标ID:XXXXXXXX 4字节
超时时间:0~9 0:无超时时间 单位s
保留:0000
区选择:01~04
写最新参数:FFFF
写长度:01~10
数据内容:字节数,最大16字节
-----------------------------------------------------
读命令F1
目标ID:XXXXXXXX 4字节
超时时间:0~9 0:无超时时间 单位s
保留:0000
区选择:01~04
读最新参数:FFFF 参数区 保留区 0~15 用户区1、2 0~31
长度 01~10
******************************************************/
void ConfigPage::WriteReadFile()
{
QString DestIDSrc1 = TargetIDLineEdt1->text();
if(DestIDSrc1.length()<8)
{
QByteArray error;
config_Btn = WriteFileBtnPD;//按键按下
emit sendsignal(error);
}
else
{
//超时时间
char OverTimeDest;
QString OverTimeSrc = OverTime->currentText();
if("无超时" == OverTimeSrc)
{
OverTimeDest = 0x00;
}
else
{
OverTimeSrc.chop(1);//去掉单位s
OverTimeDest = OverTimeSrc.toInt();
}
//参数区
char AreaDest=0;
QString AreaSrc = modeCombo->currentText();
if("参数区" == AreaSrc)
{
AreaDest = U_FILE_MODE_PARA;
}
else if("保留区" == AreaSrc)
{
AreaDest = U_FILE_MODE_RESERVER;
}
else if("用户区1" == AreaSrc)
{
AreaDest = U_FILE_MODE_USER1;
}
else if("用户区2" == AreaSrc)
{
AreaDest = U_FILE_MODE_USER2;
}
//长度
char LenthDest;
QString LenthSrc = lenthCombo->currentText();
LenthDest = LenthSrc.toInt();
//写命令
if(writeRadioBtn->isChecked())//写操作
{
QByteArray WriteBuff;
// QString DestIDSrc1 = TargetIDLineEdt1->text();
QByteArray DestIDDec1 = QByteArray::fromHex(DestIDSrc1.toLatin1());//目标ID
WriteBuff+=U_CMD_FILE_WRITE;//命令
WriteBuff+=DestIDDec1;//目标ID
WriteBuff+=OverTimeDest;//超时时间
WriteBuff+=(char)(U_FILE_RESERVER>>8);//保留
WriteBuff+=(char)U_FILE_RESERVER;//保留
WriteBuff+=AreaDest;//操作区
WriteBuff+=(char)(U_FILE_OFFSET_RNEW>>8);
WriteBuff+=(char)U_FILE_OFFSET_RNEW;//写最新参数
WriteBuff+=LenthDest;//长度
QString DataSrc = dataTedt->toPlainText();
QByteArray DataDes = QByteArray::fromHex(DataSrc.toLatin1());
WriteBuff.append(DataDes,(int)LenthDest);
qDebug() << WriteBuff.toHex();
config_Btn = WriteFileBtnPD;//按键按下
emit sendsignal(WriteBuff);
}
else if(readRadioBtn->isChecked())//读操作
{
QByteArray ReadBuff;
QString DestIDSrc1 = TargetIDLineEdt1->text();
QByteArray DestIDDec1 = QByteArray::fromHex(DestIDSrc1.toLatin1());//目标ID
ReadBuff+=U_CMD_FILE_READ;//命令
ReadBuff+=DestIDDec1;//目标ID
ReadBuff+=OverTimeDest;//超时时间
ReadBuff+=(char)(U_FILE_RESERVER>>8);//保留
ReadBuff+=(char)U_FILE_RESERVER;//保留
ReadBuff+=AreaDest;//操作区
//偏移
QString OffsetSrc =offsetCombo->currentText();
if("最新记录" == OffsetSrc)
{
ReadBuff+=(char)(U_FILE_OFFSET_RNEW>>8);
ReadBuff+=(char)U_FILE_OFFSET_RNEW;//写最新参数
}
else
{
char OffsetDest = OffsetSrc.toInt();
ReadBuff+=(char)0x00;
ReadBuff+=OffsetDest;
}
ReadBuff+=LenthDest;//长度
qDebug() << ReadBuff.toHex();
config_Btn = ReadFileBtnPD;//按键按下
emit sendsignal(ReadBuff);
}
}
}
//qstring(unicode)->gbk
QByteArray ConfigPage::U2GBK(QString unic)
{
QTextCodec* pCodec = QTextCodec::codecForName("GB18030");
QByteArray gbk = pCodec->fromUnicode(unic);
return gbk;
}
//qstring(unicode)->unicode
QByteArray ConfigPage::QString2Unicode(QString src)
{
QByteArray unic;
for(int i=0;i<src.length();i++)
{
const QChar a = src.at(i);
ushort s = a.unicode();
char data_h = (char)(s>>8);
char data_l = (char)(s);
unic+=data_h;
unic+=data_l;
}
return unic;
}
/****************************************************
串口通信 上位机->接收器
消息命令89
信息内容构成:消息长度+消息内容
消息长度1字节
消息内容
******************************************************/
#define GBK 1
void ConfigPage::msgSend()
{
QByteArray MsgBuff;//消息缓存
QString MsgSrc = messageTedt->toPlainText();
#if GBK
QByteArray MsgDest = this->U2GBK(MsgSrc);
#else
QByteArray MsgDest = this->QString2Unicode(MsgSrc);
#endif
char MsgLen = MsgDest.length();
MsgBuff+=U_CMD_MSG_PUSH;//消息命令
MsgBuff+=MsgLen;//消息长度
MsgBuff+=MsgDest;//消息内容
config_Btn = MsgBtnPD;//按键按下
qDebug() <<"消息命令内容"<< MsgBuff.toHex();
emit sendsignal(MsgBuff);
}
/****************************************************
串口通信 上位机->接收器
整机测试命令F3
信息内容
0:0x01
消息长度1字节
消息内容
******************************************************/
void ConfigPage::DeviceTest()
{
QString DestIDSrc = TargetIDLineEdt->text();
config_Btn = DeviceTestPD;//按键按下
if(DestIDSrc.length()<8)
{
QByteArray error;
emit sendsignal(error);
}
else
{
QByteArray DeviceTestBuf;
DeviceTestBuf[0] = (char)U_CMD_DEVICE_TEST;
QByteArray DestIDDec = QByteArray::fromHex(DestIDSrc.toLatin1());//目标ID
DeviceTestBuf+=DestIDDec;
DeviceTestBuf+= (char)0x01;
qDebug() <<"整机测试"<< DeviceTestBuf.toHex();
emit sendsignal(DeviceTestBuf);
}
}
/****************************************************
串口通信 上位机->接收器
列出标签命令F4 列出读写器命令F5
信息内容
0:bit3~1 查询时间
bit0:1使能低电过滤;0不使能低电过滤
1: bit7:1:使能RSSI过滤;0:不使能RSSI过滤
bit6~0 0~127 RSSI过滤值
消息长度1字节
消息内容
******************************************************/
#define LP_FILTEREN_Pos 0
#define LP_FILTEREN_Msk 0x01 //使能低电过滤
#define RSSI_FILTEREN_Pos 7
#define RSSI_FILTEREN_Msk 0x80 //使能RSSI过滤
#define RSSI_FILTERVALUE_Pos 0
#define RSSI_FILTERVALUE_Msk 0x7F //RSSI过滤值
#define SEARCH_TIME_Pos 1
#define SEARCH_TIME_Msk 0x0E //
void ConfigPage::SearchTag()
{
QByteArray SearchTagBuf;
char temp[2]={0,0};
QString SearchTimeSrc = searchTimeCombox->currentText();
SearchTimeSrc.chop(1);//移除最后一位s
char SearchTime = SearchTimeSrc.toInt();
temp[0] = (SearchTime<<SEARCH_TIME_Pos)&SEARCH_TIME_Msk;
if(lpfilterCheckBox->isChecked())
{
temp[0]|=LP_FILTEREN_Msk;
}
if(rssiCheckBox->isChecked())
{
temp[1] = RSSI_FILTEREN_Msk;
QString SearchRSSISrc = rssiCombox->currentText();
SearchRSSISrc.chop(3);//移除dbm
char SearchRSSI = SearchRSSISrc.toInt();
temp[1] |= (SearchRSSI&RSSI_FILTERVALUE_Msk)<<RSSI_FILTERVALUE_Pos;
}
else
{
temp[1] = 0x00;
}
SearchTagBuf[0] = (char)U_CMD_LIST_TAG;
SearchTagBuf[1] = temp[0];
SearchTagBuf[2] = temp[1];
config_Btn = SesrchTagPD;//按键按下
device_model->clear();
device_model->setHorizontalHeaderItem(0,new QStandardItem(QObject::tr("TYPE")));//传感类型
device_model->setHorizontalHeaderItem(1,new QStandardItem(QObject::tr("ID")));
device_model->setHorizontalHeaderItem(2,new QStandardItem(QObject::tr("State")));
device_model->setHorizontalHeaderItem(3,new QStandardItem(QObject::tr("RSSI")));
device_model->setHorizontalHeaderItem(4,new QStandardItem(QObject::tr("DATA")));
device_model->setHorizontalHeaderItem(5,new QStandardItem(QObject::tr("BASEID")));//边界管理器ID
device_model->setHorizontalHeaderItem(6,new QStandardItem(QObject::tr("VER")));
qDebug() <<"查询标签"<< SearchTagBuf.toHex();
emit sendsignal(SearchTagBuf);
}
//查询读写器
void ConfigPage::SearchReader()
{
QByteArray SearchReaderBuf;
char temp[2]={0,0};
QString SearchTimeSrc = searchTimeCombox->currentText();
SearchTimeSrc.chop(1);//移除最后一位s
char SearchTime = SearchTimeSrc.toInt();
temp[0] = (SearchTime<<SEARCH_TIME_Pos)&SEARCH_TIME_Msk;
if(lpfilterCheckBox->isChecked())
{
temp[0]|=LP_FILTEREN_Msk;
}
if(rssiCheckBox->isChecked())
{
temp[1] = RSSI_FILTEREN_Msk;
QString SearchRSSISrc = rssiCombox->currentText();
SearchRSSISrc.chop(3);//移除dbm
char SearchRSSI = SearchRSSISrc.toInt();
temp[1] |= (SearchRSSI&RSSI_FILTERVALUE_Msk)<<RSSI_FILTERVALUE_Pos;
}
else
{
temp[1] = 0x00;
}
SearchReaderBuf[0] = (char)U_CMD_LIST_READER;
SearchReaderBuf[1] = temp[0];
SearchReaderBuf[2] = temp[1];
config_Btn = SesrchTagPD;//按键按下
device_model->clear();
device_model->setHorizontalHeaderItem(0,new QStandardItem(QObject::tr("TYPE")));//传感类型
device_model->setHorizontalHeaderItem(1,new QStandardItem(QObject::tr("ID")));
device_model->setHorizontalHeaderItem(2,new QStandardItem(QObject::tr("RSSI")));
device_model->setHorizontalHeaderItem(3,new QStandardItem(QObject::tr("DATA")));
device_model->setHorizontalHeaderItem(4,new QStandardItem(QObject::tr("VER")));
qDebug() <<"查询读写器"<< SearchReaderBuf.toHex();
emit sendsignal(SearchReaderBuf);
}
/****************************************************
串口通信 上位机->接收器
自动上报命令F6
信息内容
0:bit3~1 自动上报时间
bit0:1使能低电过滤;0不使能低电过滤
1: bit7:1:使能RSSI过滤;0:不使能RSSI过滤
bit6~0 0~127 RSSI过滤值
2:bit0: 1:打开自动上报命令,0:关闭自动上报
消息长度1字节
消息内容
******************************************************/
#define LEAVE_TIME_Msk 0xf0
#define LEAVE_TIME_Pos 4
void ConfigPage::AutoReportOpen()
{
QByteArray AutoReportBuf;
char temp[2]={0,0};
//上报时间
QString ReportTimeSrc = reportTimeCombox->currentText();
ReportTimeSrc.chop(1);//移除最后一位s
char ReportTime = ReportTimeSrc.toInt();
//离开时间
QString LeaveTimeSrc = leaveTimeCombox->currentText();
LeaveTimeSrc.chop(1);//移除最后一位s
char LeaveTime = LeaveTimeSrc.toInt();
LeaveTime = (LeaveTime<<LEAVE_TIME_Pos)&LEAVE_TIME_Msk;//离开时间
temp[0] = (ReportTime<<SEARCH_TIME_Pos)&SEARCH_TIME_Msk;//上报时间
temp[0]|=LeaveTime;
if(lpfilterAutoCheckBox->isChecked())
{
temp[0]|=LP_FILTEREN_Msk;
}
if(rssiAutoCheckBox->isChecked())
{
temp[1] = RSSI_FILTEREN_Msk;
QString rssiAutoSrc = rssiAutoCombox->currentText();
rssiAutoSrc.chop(3);//移除dbm
char rssiAuto = rssiAutoSrc.toInt();
temp[1] |= (rssiAuto&RSSI_FILTERVALUE_Msk)<<RSSI_FILTERVALUE_Pos;
}
else
{
temp[1] = 0x00;
}
AutoReportBuf[0] = (char)U_CMD_AUTO_REPORT;
AutoReportBuf[1] = temp[0];
AutoReportBuf[2] = temp[1];
AutoReportBuf[3] = char(0x01);
config_Btn = AutoReportPD;//按键按下
device_model->clear();
device_model->setHorizontalHeaderItem(0,new QStandardItem(QObject::tr("TYPE")));//传感类型
device_model->setHorizontalHeaderItem(1,new QStandardItem(QObject::tr("ID")));
device_model->setHorizontalHeaderItem(2,new QStandardItem(QObject::tr("State")));
device_model->setHorizontalHeaderItem(3,new QStandardItem(QObject::tr("RSSI")));
device_model->setHorizontalHeaderItem(4,new QStandardItem(QObject::tr("DATA")));
device_model->setHorizontalHeaderItem(5,new QStandardItem(QObject::tr("BASEID")));//边界管理器ID
device_model->setHorizontalHeaderItem(6,new QStandardItem(QObject::tr("VER")));
qDebug() <<"打开自动上报"<< AutoReportBuf.toHex();
emit sendsignal(AutoReportBuf);
}
void ConfigPage::AutoReportClose()
{
QByteArray AutoReportBuf;
char temp[2]={0,0};
//上报时间
QString ReportTimeSrc = reportTimeCombox->currentText();
ReportTimeSrc.chop(1);//移除最后一位s
char ReportTime = ReportTimeSrc.toInt();
//离开时间
QString LeaveTimeSrc = leaveTimeCombox->currentText();
LeaveTimeSrc.chop(1);//移除最后一位s
char LeaveTime = LeaveTimeSrc.toInt();
LeaveTime = (LeaveTime<<LEAVE_TIME_Pos)&LEAVE_TIME_Msk;//离开时间
temp[0] = (ReportTime<<SEARCH_TIME_Pos)&SEARCH_TIME_Msk;//上报时间
temp[0]|=LeaveTime;
if(lpfilterAutoCheckBox->isChecked())
{
temp[0]|=LP_FILTEREN_Msk;
}
if(rssiAutoCheckBox->isChecked())
{
temp[1] = RSSI_FILTEREN_Msk;
QString rssiAutoSrc = rssiAutoCombox->currentText();
rssiAutoSrc.chop(3);//移除dbm
char rssiAuto = rssiAutoSrc.toInt();
temp[1] |= (rssiAuto&RSSI_FILTERVALUE_Msk)<<RSSI_FILTERVALUE_Pos;
}
else
{
temp[1] = 0x00;
}
AutoReportBuf[0] = (char)U_CMD_AUTO_REPORT;
AutoReportBuf[1] = temp[0];
AutoReportBuf[2] = temp[1];
AutoReportBuf[3] = char(0x00);
config_Btn = AutoReportPD;//按键按下
device_model->clear();
device_model->setHorizontalHeaderItem(0,new QStandardItem(QObject::tr("TYPE")));//传感类型
device_model->setHorizontalHeaderItem(1,new QStandardItem(QObject::tr("ID")));
device_model->setHorizontalHeaderItem(2,new QStandardItem(QObject::tr("State")));
device_model->setHorizontalHeaderItem(3,new QStandardItem(QObject::tr("RSSI")));
device_model->setHorizontalHeaderItem(4,new QStandardItem(QObject::tr("DATA")));
device_model->setHorizontalHeaderItem(5,new QStandardItem(QObject::tr("BASEID")));//边界管理器ID
device_model->setHorizontalHeaderItem(6,new QStandardItem(QObject::tr("VER")));
qDebug() <<"关闭自动上报"<< AutoReportBuf.toHex();
emit sendsignal(AutoReportBuf);
}
//消息最大长度
void ConfigPage::msgMaxLength()
{
QString textContent = messageTedt->toPlainText();
int length = textContent.count();
int maxLength = 64; // 最大字符数
if(length > maxLength)
{
int position = messageTedt->textCursor().position();
QTextCursor textCursor = messageTedt->textCursor();
textContent.remove(position - (length - maxLength), length - maxLength);
messageTedt->setText(textContent);
textCursor.setPosition(position - (length - maxLength));
messageTedt->setTextCursor(textCursor);
}
}
|
f3c4062b590679d39e0068255a02fd42a910ea78
|
bd7d2ab3fbfb4817cf28c19739dae8d3fa3b500d
|
/src/include/espbot_sntp.hpp
|
524bab1ce4db4a15752a33dac79d7506762040d4
|
[
"Beerware"
] |
permissive
|
quackmore/hamsters
|
50c6d01167e710ea43065d7baf2b037ecd03b66e
|
ebaf52227ddbadcdb607fa6a2f19bff35027cc5e
|
refs/heads/master
| 2020-10-01T02:52:36.197200
| 2019-12-11T19:05:28
| 2019-12-11T19:05:28
| 227,437,866
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 686
|
hpp
|
espbot_sntp.hpp
|
/*
* ----------------------------------------------------------------------------
* "THE BEER-WARE LICENSE" (Revision 42):
* <quackmore-ff@yahoo.com> wrote this file. As long as you retain this notice
* you can do whatever you want with this stuff. If we meet some day, and you
* think this stuff is worth it, you can buy me a beer in return. Quackmore
* ----------------------------------------------------------------------------
*/
#ifndef __SNTP_HPP__
#define __SNTP_HPP__
extern "C"
{
#include "c_types.h"
}
class Sntp
{
private:
public:
Sntp(){};
~Sntp(){};
void start(void);
void stop(void);
uint32 get_timestamp();
char *get_timestr(uint32);
};
#endif
|
5892d87f255f85a623c0b4b191b20bef3cbc1ce2
|
80f7d15cda1f70bcf38ba32ffa2c1742c9d34b6f
|
/ctpgateway/servicemgr.cpp
|
b05e7aa7d10f9e7278504c6555a9b26f23b147c4
|
[] |
no_license
|
rafaelchan/lianghuabao
|
7d69a0f53e58297f2343446bf395c5ea336b652e
|
668253a8529f9d9b16a15b26fa89020643eccd00
|
refs/heads/master
| 2020-06-28T10:19:19.051902
| 2017-11-25T14:13:54
| 2017-11-25T14:13:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,231
|
cpp
|
servicemgr.cpp
|
#include "servicemgr.h"
#include "ctamgr.h"
#include "dbservice.h"
#include "gatewaymgr.h"
#include "logger.h"
#include "profile.h"
#include "pushservice.h"
#include "rpcservice.h"
#include <QThread>
ServiceMgr* g_sm = nullptr;
ServiceMgr::ServiceMgr(QObject* parent)
: QObject(parent)
{
g_sm = this;
}
void ServiceMgr::init()
{
if (init_ == true) {
qFatal("init_ == true");
return;
}
init_ = true;
main_thread_ = QThread::currentThread();
db_thread_ = new QThread;
push_thread_ = new QThread;
rpc_thread_ = new QThread;
blogic_thread_ = new QThread;
flogic_thread_ = new QThread;
logger_ = new Logger;
profile_ = new Profile;
dbService_ = new DbService;
dbService_->moveToThread(db_thread_);
pushService_ = new PushService;
pushService_->moveToThread(push_thread_);
rpcService_ = new RpcService;
rpcService_->moveToThread(rpc_thread_);
gatewayMgr_ = new GatewayMgr;
gatewayMgr_->moveToThread(blogic_thread_);
ctaMgr_ = new CtaMgr;
ctaMgr_->moveToThread(flogic_thread_);
// ui objects
logger_->init();
profile_->init();
QObject::connect(db_thread_, &QThread::started, this, &ServiceMgr::dbThreadStarted, Qt::DirectConnection);
QObject::connect(push_thread_, &QThread::started, this, &ServiceMgr::pushThreadStarted, Qt::DirectConnection);
QObject::connect(rpc_thread_, &QThread::started, this, &ServiceMgr::rpcThreadStarted, Qt::DirectConnection);
QObject::connect(blogic_thread_, &QThread::started, this, &ServiceMgr::blogicThreadStarted, Qt::DirectConnection);
QObject::connect(flogic_thread_, &QThread::started, this, &ServiceMgr::flogicThreadStarted, Qt::DirectConnection);
QObject::connect(db_thread_, &QThread::finished, this, &ServiceMgr::dbThreadFinished, Qt::DirectConnection);
QObject::connect(push_thread_, &QThread::finished, this, &ServiceMgr::pushThreadFinished, Qt::DirectConnection);
QObject::connect(rpc_thread_, &QThread::finished, this, &ServiceMgr::rpcThreadFinished, Qt::DirectConnection);
QObject::connect(blogic_thread_, &QThread::finished, this, &ServiceMgr::blogicThreadFinished, Qt::DirectConnection);
QObject::connect(flogic_thread_, &QThread::finished, this, &ServiceMgr::flogicThreadFinished, Qt::DirectConnection);
db_thread_->start();
push_thread_->start();
rpc_thread_->start();
blogic_thread_->start();
flogic_thread_->start();
}
void ServiceMgr::dbThreadStarted()
{
checkCurrentOn(DB);
dbService_->init();
}
void ServiceMgr::dbThreadFinished()
{
checkCurrentOn(DB);
dbService_->shutdown();
dbService_->moveToThread(main_thread_);
}
void ServiceMgr::pushThreadStarted()
{
checkCurrentOn(PUSH);
pushService_->init();
}
void ServiceMgr::pushThreadFinished()
{
checkCurrentOn(PUSH);
pushService_->shutdown();
pushService_->moveToThread(main_thread_);
}
void ServiceMgr::rpcThreadStarted()
{
checkCurrentOn(RPC);
rpcService_->init();
}
void ServiceMgr::rpcThreadFinished()
{
checkCurrentOn(RPC);
rpcService_->shutdown();
rpcService_->moveToThread(main_thread_);
}
void ServiceMgr::blogicThreadStarted()
{
checkCurrentOn(BLOGIC);
gatewayMgr_->init();
}
void ServiceMgr::blogicThreadFinished()
{
checkCurrentOn(BLOGIC);
gatewayMgr_->shutdown();
gatewayMgr_->moveToThread(main_thread_);
}
void ServiceMgr::flogicThreadStarted()
{
checkCurrentOn(FLOGIC);
ctaMgr_->init();
}
void ServiceMgr::flogicThreadFinished()
{
checkCurrentOn(FLOGIC);
ctaMgr_->shutdown();
ctaMgr_->moveToThread(main_thread_);
}
DbService* ServiceMgr::dbService()
{
check();
return this->dbService_;
}
PushService* ServiceMgr::pushService()
{
check();
return this->pushService_;
}
RpcService* ServiceMgr::rpcService()
{
check();
return this->rpcService_;
}
GatewayMgr* ServiceMgr::gatewayMgr()
{
check();
return this->gatewayMgr_;
}
CtaMgr* ServiceMgr::ctaMgr()
{
check();
return this->ctaMgr_;
}
void ServiceMgr::shutdown()
{
if (shutdown_ == true) {
qFatal("shutdown_ == true");
return;
}
flogic_thread_->quit();
flogic_thread_->wait();
delete flogic_thread_;
flogic_thread_ = nullptr;
blogic_thread_->quit();
blogic_thread_->wait();
delete blogic_thread_;
blogic_thread_ = nullptr;
rpc_thread_->quit();
rpc_thread_->wait();
delete rpc_thread_;
rpc_thread_ = nullptr;
push_thread_->quit();
push_thread_->wait();
delete push_thread_;
push_thread_ = nullptr;
db_thread_->quit();
db_thread_->wait();
delete db_thread_;
db_thread_ = nullptr;
profile_->shutdown();
logger_->shutdown();
delete ctaMgr_;
ctaMgr_ = nullptr;
delete gatewayMgr_;
gatewayMgr_ = nullptr;
delete rpcService_;
rpcService_ = nullptr;
delete pushService_;
pushService_ = nullptr;
delete dbService_;
dbService_ = nullptr;
delete profile_;
profile_ = nullptr;
delete logger_;
logger_ = nullptr;
main_thread_ = nullptr;
shutdown_ = true;
}
void ServiceMgr::check()
{
if (shutdown_ || !init_) {
qFatal("shutdown_ || !init_");
}
}
Profile* ServiceMgr::profile()
{
check();
return this->profile_;
}
Logger* ServiceMgr::logger()
{
check();
return this->logger_;
}
QThread* ServiceMgr::getThread(ThreadType p)
{
check();
if (p == ServiceMgr::MAIN) {
return this->main_thread_;
}
if (p == ServiceMgr::DB) {
return this->db_thread_;
}
if (p == ServiceMgr::PUSH) {
return this->push_thread_;
}
if (p == ServiceMgr::RPC) {
return this->rpc_thread_;
}
if (p == ServiceMgr::BLOGIC) {
return this->blogic_thread_;
}
if (p == ServiceMgr::FLOGIC) {
return this->flogic_thread_;
}
qFatal("getThread");
return nullptr;
}
bool ServiceMgr::isCurrentOn(ServiceMgr::ThreadType p)
{
check();
QThread* cur = QThread::currentThread();
if (p == ServiceMgr::MAIN && cur == main_thread_) {
return true;
}
if (p == ServiceMgr::DB && cur == db_thread_) {
return true;
}
if (p == ServiceMgr::PUSH && cur == push_thread_) {
return true;
}
if (p == ServiceMgr::RPC && cur == rpc_thread_) {
return true;
}
if (p == ServiceMgr::BLOGIC && cur == blogic_thread_) {
return true;
}
if (p == ServiceMgr::FLOGIC && cur == flogic_thread_) {
return true;
}
if (p == ServiceMgr::EXTERNAL) {
if (cur != main_thread_ && cur != db_thread_
&& cur != push_thread_ && cur != rpc_thread_
&& cur != blogic_thread_ && cur != flogic_thread_) {
return true;
}
}
return false;
}
void ServiceMgr::checkCurrentOn(ThreadType p)
{
if (!isCurrentOn(p)) {
qFatal("checkCurrentOn");
}
}
//////////////////////
void BfLog(const char* msg, ...)
{
va_list ap;
va_start(ap, msg);
QString buf = QString::vasprintf(msg, ap);
va_end(ap);
g_sm->logger()->log(buf);
}
void BfLog(QString msg)
{
g_sm->logger()->log(msg);
}
|
330df9fbb0e50bb74c9a9c4410d7dc2fb7bb1a5a
|
6d58cb903b7b5128a0fbbd41325204500b8076b6
|
/Engine/script/ex_label.cpp
|
fcec30ab2cb84ce1bcb5b32514e91e415b69324e
|
[
"Artistic-2.0"
] |
permissive
|
CliffsDover/ags
|
a13d968bcd15bd1df9b163055b1489d1045e219c
|
d79afca04d2a81b7146e638ecdd218b465aa539e
|
refs/heads/main
| 2021-01-17T12:03:06.997569
| 2013-08-16T20:36:42
| 2013-08-16T20:36:42
| 84,053,912
| 0
| 0
| null | 2017-03-06T09:22:20
| 2017-03-06T09:22:20
| null |
UTF-8
|
C++
| false
| false
| 1,582
|
cpp
|
ex_label.cpp
|
//=============================================================================
//
// Adventure Game Studio (AGS)
//
// Copyright (C) 1999-2011 Chris Jones and 2011-20xx others
// The full list of copyright holders can be found in the Copyright.txt
// file, which is part of this source code distribution.
//
// The AGS source code is provided under the Artistic License 2.0.
// A copy of this license can be found in the file License.txt and at
// http://www.opensource.org/licenses/artistic-license-2.0.php
//
//=============================================================================
//
// Exporting Label script functions
//
//=============================================================================
// the ^n after the function name is the number of params
// this is to allow an extra parameter to be added in a later
// version without screwing up the stack in previous versions
// (just export both the ^n and the ^m as seperate funcs)
#include "script/symbol_registry.h"
void register_label_script_functions()
{
scAdd_External_Symbol("Label::GetText^1", (void *)Label_GetText);
scAdd_External_Symbol("Label::SetText^1", (void *)Label_SetText);
scAdd_External_Symbol("Label::get_Font", (void *)Label_GetFont);
scAdd_External_Symbol("Label::set_Font", (void *)Label_SetFont);
scAdd_External_Symbol("Label::get_Text", (void *)Label_GetText_New);
scAdd_External_Symbol("Label::set_Text", (void *)Label_SetText);
scAdd_External_Symbol("Label::get_TextColor", (void *)Label_GetColor);
scAdd_External_Symbol("Label::set_TextColor", (void *)Label_SetColor);
}
|
41aa9ac1a22b22e9ffb61fce010a2a3814ec2e7a
|
1a51c7612e1a89305358acb580cc4e5dbf843bb5
|
/Problemset/A - AquaMoon and Two Arrays.cpp
|
7ae49ab459f0a76f1a098e856d6c18d2c3812bfa
|
[] |
no_license
|
ankitsharma1530/Codechef-Codeforces
|
47de72f71586bb4d6a05290ece63e49be2876865
|
5ad38963732c88ed70e570aa1f7411db1bbba3a0
|
refs/heads/main
| 2023-07-15T00:26:55.760726
| 2021-08-17T07:07:43
| 2021-08-17T07:07:43
| 344,685,363
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,753
|
cpp
|
A - AquaMoon and Two Arrays.cpp
|
#include<bits/stdc++.h>
#define mod 1000000007
#define lli long long int
#define ll long long
#define pll pair<long long,long long>
const int INF = 1000000000;
#define el '\n'
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
// for loops shortcut
#define garr(i, n) for(ll i = 0; i < (n); i++)
#define parr(i, n, arr) for(ll i = 0; i < (n); i++) cout<<arr[i]<<" ";
/*
vector<ll>arr;
for(int i=0;i<n;i++)
{
ll it;
cin>>it;
arr.push_back(it);
}
*/
/*
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++){
cin>>arr[i];
}
*/
using namespace std;
void solve()
{
int n;
cin>>n;
int a[n],b[n];
int s1= 0;
int s2=0;
for(int i=0;i<n;i++){
cin>>a[i];
s1+=a[i];
}
for(int i=0;i<n;i++){
cin>>b[i];
s2+=b[i];
}
vector<pair<int,int>>pq;
int c = 0;
for(int i=0;i<n;i++){
if(abs(a[i]-b[i])>0){
pq.push_back({(b[i]-a[i]),i});
c+=abs(b[i]-a[i]);
}
}
sort(pq.begin(),pq.end());
int i=0;
int j = pq.size()-1;
vector<pair<int,int>>v;
while(i<j){
v.push_back({pq[i].second,pq[j].second});
if(pq[i].first+1<0){
pq[i].first+=1;
}
else if(pq[i].first-1>0){
pq[i].first-=1;
}
else{
i++;
}
if(pq[j].first+1<0){
pq[j].first+=1;
}
else if(pq[j].first-1>0){
pq[j].first-=1;
}
else{
j--;
}
}
// cout<<v.size()<<endl;
if(s1!=s2){
cout<<-1<<endl;
return;
}
cout<<v.size()<<endl;
for(auto x:v){
cout<<x.first+1<<" "<<x.second+1<<endl;
}
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
#ifndef ONLINE_JUDGE
freopen("input.txt","r",stdin);
freopen("output.txt","w",stdout);
#endif
int t;
cin>>t;
// t = 1;
while(t--)
{
// memset(vis,0,sizeof(vis));
// memset(dp,-1,sizeof(dp));
solve();
// cout<<el;
}
}
|
18d86ff65c4bf7e0050a35d17a18d62f496602a5
|
f4aced01d7e577c2f4ddc9e63c409665af22d512
|
/c/c3.cpp
|
b55d9cdba899ca9c05e5e1c71250c7dfd474b438
|
[] |
no_license
|
xuanyuweihe/Learn
|
38dd90d9471c23fcb8d927e682aafe5be61d1b80
|
bfb046fac24536666243d591ca81f22f7f02bb4b
|
refs/heads/master
| 2022-04-19T12:27:47.996803
| 2020-04-15T09:18:50
| 2020-04-15T09:18:50
| 255,335,117
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,481
|
cpp
|
c3.cpp
|
//走迷宫
//采用四叉树递归遍历
#include <iostream>
#include <fstream>
using namespace std;
#define NOARRIVE 1000
#define ZHANGAI 1001
#define ROW 10
#define COL 10
int map[ROW][COL][3]={};//x[][]0|1表示前一个点的rc坐标,[][]2表示类型或者记录当前步数
int col=0;
int row=0;
int slw[2]={0,0};//起点坐标
int elw[2]={0,0};//终点坐标
void show(int x,int y){
int row=0,col=0;
system("clear");//ubtunu下清屏 windows下为 “clr”
cout<<" 0123456789"<<endl;
while (row!=ROW)
{
cout<<row;
while(col!=COL)
{
if(row==x&&col==y)cout<<'n';//当前所在位置
else if(map[row][col][2]==NOARRIVE)cout<<' ';//从未到达
else if(map[row][col][2]==ZHANGAI)cout<<'#';//路障
else cout<<'0';
col++;
}
col=0;
cout<<endl;
row++;
}
cout<<endl;
}
void floodfill(int x,int y,int last_x,int last_y,int step_num)
{
if(map[x][y][2]==ZHANGAI)return;//已经找到了当前位置最小路径,或者终点的最小路径
if(map[x][y][2]>step_num){//有更短的路径
cout<<x<<','<<y<<'#'<<last_x<<','<<last_y<<'#'<<step_num<<endl;
map[x][y][0]=last_x;
map[x][y][1]=last_y;
map[x][y][2]=step_num;
// //判断是否为最短路径,周围都是最短,后来发现无法判断
// flag[x][y]=1;//假定现在是最短了
// if(flag[max(x-1,0)][y]==1\
// &&flag[min(x+1,ROW)][y]==1\
// &&flag[x][max(y-1,0)]==1\
// &&flag[x][min(y+1,9)]==1)
// { }//说名确实是最短
// else{
// flag[x][y]=0;//不是最短
// }
show(x,y);
floodfill(min(x+1,ROW),y,x,y,step_num+1);//下走
show(x,y);
floodfill(x,min(y+1,COL),x,y,step_num+1);
show(x,y);
floodfill(max(x-1,0),y,x,y,step_num+1);//
show(x,y);
floodfill(x,max(y-1,0),x,y,step_num+1);
show(x,y);
}
else{
return;
}
}
void get_map()
{
int temp;
ifstream f("c3.txt");
if(!f.is_open()){
cout<<"error";
}
row=0;col=0;
while (!f.eof())
{
temp=f.get();
while (temp=='\n')
{
temp=f.get();
}
if(temp=='5')//起点
{
slw[0]=row;
slw[1]=col;
map[row][col][0]=slw[0];
map[row][col][1]=slw[1];
map[row][col][2]=NOARRIVE;//起点只要第一步
}else if(temp=='8')//终点
{
elw[0]=row;
elw[1]=col;
map[row][col][2]=NOARRIVE;
}else if(temp=='1')//障碍
{
map[row][col][2]=ZHANGAI;
map[row][col][0]=ZHANGAI;
map[row][col][1]=ZHANGAI;
}else if(temp=='0')//路径
{
map[row][col][2]=NOARRIVE;
}
col++;
if(col==COL){
col=0;
row++;
}
}
f.close();
}
void show_way()
{
int temp=0;
row=elw[0];col=elw[1];
cout<<row<<','<<col<<endl;
do{
temp=row;
row=map[temp][col][0];
col=map[temp][col][1];
cout<<row<<','<<col<<endl;
}while(map[row][col][0]!=slw[0]||map[row][col][1]!=slw[1]);
cout<<slw[0]<<','<<slw[1]<<endl;
}
int main()
{
row=0;col=0;
get_map();
floodfill(slw[0],slw[1],slw[0],slw[1],0);
show_way();
return 0;
}
|
a64550b54d1fccd49760cd07e9cf6f65ba2fc4e2
|
a9922d559d43880009effef26ec3b6263e93f88e
|
/solutions/kattis/naipc18/doubleclique_hcz.cpp
|
5840f68414f7b1198f22a9d771b7e8494376e4a3
|
[] |
no_license
|
buckeye-cn/ACM_ICPC_Materials
|
e7cc8e476de42f8b8a3559a9721b421a85a95a48
|
6d32af96030397926c8d5e354c239802d5d171db
|
refs/heads/master
| 2023-04-26T03:02:51.341470
| 2023-04-16T10:46:17
| 2023-04-16T10:46:17
| 102,976,270
| 23
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,532
|
cpp
|
doubleclique_hcz.cpp
|
// https://open.kattis.com/problems/doubleclique
#include <cstdlib>
#include <cstdint>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <iostream>
using namespace std;
int n, m;
int deg[200000];
int from[200000];
int to[200000];
int limit;
int v_deg[200000];
int e_deg[200000];
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
a -= 1;
b -= 1;
deg[a] += 1;
deg[b] += 1;
from[i] = min(a, b);
to[i] = max(a, b);
}
for (int i = 0; i < n; ++i) {
v_deg[deg[i]] += 1;
}
limit = n - 1;
for (int i = 0; i < m; ++i) {
e_deg[min(deg[from[i]], deg[to[i]])] += 1;
limit = min(limit, max(deg[from[i]], deg[to[i]]));
}
for (int i = n - 2; i >= 0; --i) {
v_deg[i] += v_deg[i + 1];
e_deg[i] += e_deg[i + 1];
}
for (int i = 1; i <= limit; ++i) {
if (2 * e_deg[i] != v_deg[i] * (v_deg[i] - 1)) continue;
int result = 1;
for (int j = 0; j < n; ++j) {
if (deg[j] < i) {
if (deg[j] == v_deg[i]) {
result += 1;
}
} else {
if (deg[j] == v_deg[i] - 1) {
result += 1;
}
}
}
cout << result << endl;
return 0;
}
cout << 0 << endl;
return 0;
}
|
7fa4bda5e480c51cc780705803a205b52ddc5f22
|
85c7a681d926c4b8682b61f8f53b2368788306c4
|
/arduino101_code/game_fire.ino
|
31334955285a2a21114bf1ba273d5e09e07ad122
|
[] |
no_license
|
gliber/arduino-magic-ball
|
d741878fae6277b2425f7f43d076da23678b5561
|
b0001b93220024d502ebbecd1c49d6f96d2e48c1
|
refs/heads/master
| 2020-03-13T03:51:31.716079
| 2018-04-25T04:58:22
| 2018-04-25T04:58:22
| 130,951,915
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,428
|
ino
|
game_fire.ino
|
#include "ICBall.h"
#define FIRE_EVENTS_DELAY 1000
#define FIRE_MAX_VALUE 300
#define FIRE_STEP_DOWN 5
#define FIRE_DETECTION_NORMAL 2
void gameFirePlay()
{
unsigned long lastFireEvent = 0;
int lastTone = 0;
int fireStatus = 0;
while (!gameChanged())
{
unsigned long current = millis();
float accelNormal = getAccelerometerNormal();
if (millis()-lastTone>3000-map(fireStatus,0,FIRE_MAX_VALUE,0,3000))
{
tone(ICBALL_BUZZER, NOTE_C3,100);
lastTone=millis();
}
if (accelNormal > FIRE_DETECTION_NORMAL)
{
fireStatus += accelNormal/2;
lastFireEvent = current;
ICBprint(F("FIRE UP "));
ICBprint(accelNormal);
ICBprint(" stat=");
ICBprintln(fireStatus);
}
else
{
//if ((lastFireEvent > 0) && (current - lastFireEvent > FIRE_EVENTS_DELAY))
{
if (fireStatus > 0)
{
ICBprint(F("FIRE DOWN "));
ICBprintln(fireStatus);
}
fireStatus -= FIRE_STEP_DOWN;
}
}
if (fireStatus < 0)
{
fireStatus=0;
}
if (fireStatus > FIRE_MAX_VALUE)
{
fireStatus = FIRE_MAX_VALUE;
}
delay(50);
int redValue = fireStatus;
if (redValue > 255)
{
redValue = 255;
}
solidColorQuick(colorRGB((redValue/LED_POWER_SAVE_FACTOR), 0, (255-redValue)/LED_POWER_SAVE_FACTOR));
setGameValue(fireStatus);
}
}
|
20c6f4f947cfc02a6473a4ee55c72545f9eb54fe
|
08b8cf38e1936e8cec27f84af0d3727321cec9c4
|
/data/crawl/git/hunk_7223.cpp
|
575c9f5acfbf3619e309ca09c6b8b73fad30ac4a
|
[] |
no_license
|
ccdxc/logSurvey
|
eaf28e9c2d6307140b17986d5c05106d1fd8e943
|
6b80226e1667c1e0760ab39160893ee19b0e9fb1
|
refs/heads/master
| 2022-01-07T21:31:55.446839
| 2018-04-21T14:12:43
| 2018-04-21T14:12:43
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 281
|
cpp
|
hunk_7223.cpp
|
opts.rename_limit = merge_rename_limit >= 0 ? merge_rename_limit :
diff_rename_limit >= 0 ? diff_rename_limit :
500;
+ opts.warn_on_too_large_rename = 1;
opts.output_format = DIFF_FORMAT_NO_OUTPUT;
if (diff_setup_done(&opts) < 0)
die("diff setup failed");
|
f02d1291593fb2b62656aab17f85a89d061c4b74
|
707e7b234487c48077fe0eeabfbd5309b19d4742
|
/Lesson1/Task 5/main.cpp
|
08b96f8df26c960b15d6cd8b4ddb933ba0c76cf1
|
[] |
no_license
|
GlebGritsay/NG_2021_Gritsay_Gleb
|
2d72cad0c886839048b4d1f97ef31b0dcf767692
|
e76b1c69eb23ff447926d69b88bda05c41e411f7
|
refs/heads/main
| 2023-08-21T08:30:37.751546
| 2021-10-26T17:52:39
| 2021-10-26T17:52:39
| null | 0
| 0
| null | null | null | null |
WINDOWS-1251
|
C++
| false
| false
| 411
|
cpp
|
main.cpp
|
#include <iostream>
#include <cmath>
#include <math.h>
using namespace std;
int main()
{
int mess ;
cout << "Enter the mess of the spaceship:";
cin >> mess;
int Fuel;
Fuel=mess/3-2;
Fuel=Fuel*300;
cout << "Fuel=";
cout << Fuel;
// Есть проблема в коде,если масса корабля менше 8, то топлево не нужно .
return 0;
}
|
1f839b4a04137a36b2b52b70f67e0a3084570f09
|
d92304badb95993099633c5989f6cd8af57f9b1f
|
/LightOJ old/1155.cpp
|
7f16ec9b4196d52702d83200347fd35bccf23948
|
[] |
no_license
|
tajirhas9/Problem-Solving-and-Programming-Practice
|
c5e2b77c7ac69982a53d5320cebe874a7adec750
|
00c298233a9cde21a1cdca1f4a2b6146d0107e73
|
refs/heads/master
| 2020-09-25T22:52:00.716014
| 2019-12-05T13:04:40
| 2019-12-05T13:04:40
| 226,103,342
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,275
|
cpp
|
1155.cpp
|
#include <bits/stdc++.h>
using namespace std;
const int inf = INT_MAX;
class Dinic {
int n,source,sink;
vector < vector < int > > graph,f,c;
vector < int > level;
bool bfs() {
level.assign(n+1,-1);
queue < int > q;
q.push(source);
level[source] = 0;
while(!q.empty()) {
int top = q.front();
q.pop();
for(int i = 0; i < graph[top].size(); ++i) {
int v = graph[top][i];
if(level[v] == -1 && f[top][v] < c[top][v]) {
level[v] = level[top] + 1;
q.push(v);
}
}
}
return level[sink] != -1;
}
int dfs(int u , int flow) {
if(flow == 0) return flow;
if(u == sink) return flow;
for(int i = 0; i < graph[u].size(); ++i) {
int v = graph[u][i];
if(level[v] != level[u] + 1) continue;
int pushed = dfs(v , min( flow , c[u][v] - f[u][v] ) );
if( pushed ) {
f[u][v] += pushed;
f[v][u] -= pushed;
return pushed;
}
}
return 0;
}
public:
Dinic(int nodes, vector < vector < int > > g, vector < vector < int > > cost) {
n = nodes;
graph = g , c = cost;
level.assign(n+1,-1);
f.assign(n+1,vector<int>(n+1,0));
}
int MaxFlow(int sc, int sk) {
source = sc , sink = sk;
int flow = 0;
while(bfs()) {
while(int pushed = dfs(source,inf)) {
flow += pushed;
}
}
return flow;
}
};
int main() {
#ifdef tajir
freopen("input.txt","r",stdin);
#else
//online submission
#endif
int T;
cin >> T;
for(int kase = 1; kase <= T; ++kase) {
int n,m;
cin >> n;
vector < vector < int > > g(n+n+2),c(n+n+2,vector<int>(n+n+2,0));
for(int i = 1; i <= n; ++i) {
int w;
cin >> w;
g[i].push_back(i+n);
c[i][i+n] = w;
}
cin >> m;
for(int i = 1; i <= m; ++i) {
int u,v,w;
cin >> u >> v >> w;
g[u+n].push_back(v);
c[u+n][v] = w;
}
int b,d;
cin >> b >> d;
for(int i = 1; i <= b; ++i) {
int u = 0 , v = 1;
cin >> v;
g[u].push_back(v);
c[u][v] = inf;
}
for(int i = 1; i <= d; ++i) {
int v = n+n+1 , u;
cin >> u;
g[u].push_back(v);
c[u][v] = inf;
}
Dinic dinic(n+n+2,g,c);
cout << "Case " << kase << ": " << dinic.MaxFlow(0,n+n+1) << endl;
}
return 0;
}
|
958a5849390ab1ca3e81b4dd21213228ca1098d2
|
b6490ead30210ebb35d4c527c8a9ac7ebb70473a
|
/Algorithmic Tools/Week 5/Money Change Again.cpp
|
e72ea0f80845472771c09f28a1584159aeb8cf59
|
[] |
no_license
|
Muskan-1527/Data-structure-And-Algorithm
|
a2bf3a59f02ccae76ba28a576e8025cda7c4e52f
|
86078bff82507e35f700b848d5c40a8394a92eae
|
refs/heads/master
| 2023-08-24T20:02:00.852922
| 2020-10-20T04:38:32
| 2020-10-20T04:38:32
| 274,994,417
| 1
| 3
| null | 2021-10-05T11:47:51
| 2020-06-25T19:05:05
|
C++
|
UTF-8
|
C++
| false
| false
| 415
|
cpp
|
Money Change Again.cpp
|
#include<bits/stdc++.h>
using namespace std;
int money_change(int n)
{
int a[n+5];
a[0] = 0;
a[1] = 1;
a[2] = 2;
a[3] = 1;
a[4] = 1;
for(int i = 5 ; i <= n ; i++)
{
int x = a[i-1];
int y = a[i-3];
int z = a[i-4];
a[i] = 1 + min(x , min(y , z));
}
return a[n];
}
int main()
{
int n;
cin>>n;
cout<<money_change(n);
return 0;
}
|
14419aa3d9a3a4ba306a245e2275a3e4122c3b6a
|
59418b5794f251391650d8593704190606fa2b41
|
/sample_plugins/original_snippets/em5/logic/local/gangsters/eventspecific/GangsterBlackoutFP.cpp
|
b865c60cc8e1bb1f5edc46ee447d790768e1f58a
|
[] |
no_license
|
JeveruBerry/emergency5_sdk
|
8e5726f28123962541f7e9e4d70b2d8d5cc76cff
|
e5b23d905c356aab6f8b26432c72d18e5838ccf6
|
refs/heads/master
| 2023-08-25T12:25:19.117165
| 2018-12-18T16:55:16
| 2018-12-18T17:09:54
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,722
|
cpp
|
GangsterBlackoutFP.cpp
|
// Copyright (C) 2012-2018 Promotion Software GmbH
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "em5/PrecompiledHeader.h"
#include "em5/logic/local/gangsters/eventspecific/GangsterBlackoutFP.h"
#include "em5/action/base/PlayAnimationAction.h"
#include "em5/action/move/MoveAction.h"
#include "em5/action/move/TurnToAction.h"
#include "em5/action/ActionPriority.h"
#include "em5/action/SignalAction.h"
#include "em5/ai/MovementModes.h"
#include "em5/component/objects/UsableByEngineerComponent.h"
#include "em5/game/animation/AnimationHelper.h"
#include "em5/game/targetpoint/GotoObjectFrontsideTargetPointProvider.h"
#include "em5/map/EntityHelper.h"
#include <qsf_game/base/DistanceHelper.h>
#include <qsf_ai/navigation/goal/ReachObjectGoal.h>
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace em5
{
//[-------------------------------------------------------]
//[ Public definitions ]
//[-------------------------------------------------------]
const uint32 GangsterBlackoutFP::GAMELOGIC_TYPE_ID = qsf::StringHash("em5::GangsterBlackoutFP");
const qsf::NamedIdentifier GangsterBlackoutFP::MESSAGE_ON_EBOX_DAMAGE = "GangsterBlackoutFP_onEboxDamage";
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
GangsterBlackoutFP::GangsterBlackoutFP() :
GangsterBaseLogic(GAMELOGIC_TYPE_ID)
{
// We want to receive "onUnitsSpotted" and "onNoUnitsSpotted" callbacks
mUseOldSpottedUnitsLogic = true;
}
void GangsterBlackoutFP::setTargetEboxes(const std::vector<qsf::Entity*>& eboxes)
{
mTargetEboxes.clear();
for (qsf::Entity* ebox : eboxes)
{
mTargetEboxes.push_back(ebox);
}
}
void GangsterBlackoutFP::setTimeToDamageEbox(qsf::Time time)
{
mTimeToDamageEbox = time;
}
//[-------------------------------------------------------]
//[ Protected virtual em5::GangsterBaseLogic methods ]
//[-------------------------------------------------------]
void GangsterBlackoutFP::onSimulationUpdate(const qsf::JobArguments& jobArguments)
{
// Nothing special to do in here, all gangster behavior is handled in "onIdle"
}
void GangsterBlackoutFP::onIdle()
{
// Go to next ebox
if (mTargetEboxes.empty())
{
// His work is done, now away from here!
escape(EscapeType::ESCAPE_FOOT_LONG);
}
else
{
qsf::Entity& nextTarget = mTargetEboxes.front().getSafe();
qsf::ActionComponent& actionComponent = mActionComponent.getSafe();
// Check if he is already there
if (qsf::game::DistanceHelper::get2dDistance(*getEntity(), nextTarget) > 2.0f)
{
actionComponent.pushAction<MoveAction>().init(new qsf::ai::ReachObjectGoal(*getEntity(), nextTarget, GotoObjectFrontsideTargetPointProvider::TARGET_POINT_ID), MovementModes::MOVEMENT_MODE_RUN);
}
else if (nullptr == nextTarget.getComponent<UsableByEngineerComponent>())
{
// Turn to box and do some animation
actionComponent.pushAction<TurnToAction>().init(nextTarget.getId());
actionComponent.pushAction<PlayAnimationAction>().init(AnimationHelper(*getEntity()).getAnimationEngineerRepairStandingLoop(), true, true, false, qsf::Time::ZERO, mTimeToDamageEbox);
// Signal the event what's going on
// -> It will do the actual damaging
actionComponent.pushAction<SignalAction>().init(qsf::MessageConfiguration(MESSAGE_ON_EBOX_DAMAGE, nextTarget.getId()), qsf::MessageConfiguration(""));
}
else
{
// Box was just damaged, go on to the next one
mTargetEboxes.pop_front();
}
}
}
void GangsterBlackoutFP::onUnitsSpotted(std::vector<SpottedUnit>& sightedPoliceUnits)
{
QSF_CHECK(!sightedPoliceUnits.empty(), "sightedPoliceUnits is empty", return);
// Attacking uses priority "action::COMMAND_HIGH"
if (mActionComponent->getCurrentPriority() < action::COMMAND_HIGH)
{
// Prefer attacking persons, not vehicles
for (const SpottedUnit& spottedUnit : sightedPoliceUnits)
{
if (nullptr != spottedUnit.mEntity->getComponentById("em5::PersonComponent"))
{
attack(*spottedUnit.mEntity);
break;
}
}
}
}
void GangsterBlackoutFP::onNoUnitsSpotted()
{
// Nothing here yet
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // em5
|
0b667a6b62c5c0f8ca5f9b167a5b666b4e2959fc
|
d4a7a5a7e2868f5b3563b69d6e457e53d9f1c18e
|
/1071.cpp
|
21d8cde6e732bbdabb323337b4f013175b744bd0
|
[] |
no_license
|
cli851/noi
|
630328d2e08785caf2bc559618fa1c415a39f647
|
3245e8ea84486553ef24d05ab50aa81837d36657
|
refs/heads/master
| 2023-04-19T16:04:52.275245
| 2021-05-08T14:38:50
| 2021-05-08T14:38:50
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 324
|
cpp
|
1071.cpp
|
#include <iostream>
#include <cstdio>
#include <math.h>
using namespace std;
int main()
{
int k,a=1,b=1,c;
//k=5;
cin>>k;
for(int i=3;i<=k;i++){
c=a+b;
a=b;
b=c;
}
// int i;
// i=3;
// c=a+b;
// a=b;
// b=c;
//
// i=4;
// c=a+b;
// a=b;
// b=c;
//
// i=5;
// c=a+b;
// a=b;
// b=c;
//
cout<<c;
return 0;
}
|
1a23ab8778f5d7bae0eb75d38ef65d932dfe5f89
|
aed4c1086ac3e5803912a68d63b8ca3388cc94af
|
/VotingSimulator/VotingSimulator/MMPVotingSystem.h
|
94cbac052a73db891a63906ef83f39c03e3c975d
|
[] |
no_license
|
mfow/uoa-political-science
|
e78c957019f9260aeb207351d4deaff0e49981c2
|
77decef08a7ba9a04c1262ad33a803ad90de51b1
|
refs/heads/master
| 2023-04-25T11:17:59.577779
| 2021-05-06T08:36:10
| 2021-05-06T08:36:10
| 139,300,729
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,342
|
h
|
MMPVotingSystem.h
|
#pragma once
#include <String>
#include "votingsystem.h"
// Although this class is called MMPVotingSystem, it includes a special case for Supplementary Member.
enum MMPOptions
{
AllowOverhang,
NoOverhang,
NonAward,
SupplementaryMember,
Proportional,
};
struct MMPVote
{
int localVote;
int partyVote;
};
struct MMPCandidate
{
int partyIndex;
int votes;
bool isExcluded;
map<String, String>* properties;
};
struct MMPElectorate
{
int candidateCount;
int winnerIndex;
MMPCandidate* candidates;
map<String, String>* properties;
vector<MMPVote>* votes;
};
struct MMPParty
{
bool isElected;
String partyName;
int listSeats;
int partyVotes;
vector<int>* electorateSeatWinners;
};
class MMPVotingSystem :
public VotingSystem
{
public:
MMPVotingSystem(MMPOptions overhang);
~MMPVotingSystem(void);
int MMPVotingSystem::Load(wifstream &in, int partyCount, map<String, String>* customMetaData);
int MMPVotingSystem::PrintResults();
vector<int>* MMPVotingSystem::WithPreferenceOrders(WithPreferenceOrdersInfo info);
vector<int>* MMPVotingSystem::CalculateAdditional(vector<int>* currentSeatCount, vector<double>* nationalSupport);
private:
int electorateCount;
MMPElectorate* electorates;
MMPOptions overhang;
double threshold;
int seatCount;
int finalSeatCount;
double smAmount;
vector<MMPParty>* parties;
};
|
43d3e1583db1cd3504259feccabba71f89aee2ae
|
27bff64421b33ff20f12d290318f8a4c9b65c4da
|
/libaad/include/aad/EllipticCurves.h
|
20fe84b8de4c4b16c6b2229a8fcae704ceb44d9e
|
[] |
no_license
|
huyuncong/libaad-ccs2019
|
68418f6b3cda9409f15906b41a3755fb45132c29
|
2f31566bbdac4891df45eee2e9268bc4681533dd
|
refs/heads/master
| 2023-01-14T11:58:57.982435
| 2020-11-22T22:30:08
| 2020-11-22T22:30:08
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,320
|
h
|
EllipticCurves.h
|
#pragma once
#include <utility>
#include <libff/algebra/curves/public_params.hpp>
#include <libff/common/default_types/ec_pp.hpp>
namespace libaad {
// Type of group G1
using G1 = typename libff::default_ec_pp::G1_type;
// Type of group G2
using G2 = typename libff::default_ec_pp::G2_type;
// Type of group GT (recall pairing e : G1 x G2 -> GT)
using GT = typename libff::default_ec_pp::GT_type;
// Type of the finite field "in the exponent" of the EC group elements
using Fr = typename libff::default_ec_pp::Fp_type;
// Pairing function, takes an element in G1, another in G2 and returns the one in GT
//using libff::default_ec_pp::reduced_pairing;
//using ECPP::reduced_pairing;
// Found this solution on SO: https://stackoverflow.com/questions/9864125/c11-how-to-alias-a-function
// ('using ECPP::reduced_pairing;' doesn't work, even if you expand ECPP)
template <typename... Args>
auto ReducedPairing(Args&&... args) -> decltype(libff::default_ec_pp::reduced_pairing(std::forward<Args>(args)...)) {
return libff::default_ec_pp::reduced_pairing(std::forward<Args>(args)...);
}
constexpr static int G1ElementSize = 32; // WARNING: Assuming BN128 curve
constexpr static int G2ElementSize = 64; // WARNING: Assuming BN128 curve
}
|
05885a8df8b48e16a4ca1aff4ea785f468d643a0
|
38a164760fcf3d1321cf05ce5b3e181dabaf7575
|
/src/linux_parser.cpp
|
1537223e5f7ad859c593db1dc0bf14eaaa335d2d
|
[
"MIT"
] |
permissive
|
edfex/LinuxSystemMonitor
|
2a66ae23cedd9f9086ced0bec72b6b86cca3f18a
|
efe060bd250cb6e449bba875ceb5c0a17789f078
|
refs/heads/master
| 2023-03-09T08:41:48.519955
| 2021-02-10T22:46:54
| 2021-02-10T22:46:54
| 337,873,585
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,210
|
cpp
|
linux_parser.cpp
|
#include "linux_parser.h"
#include <dirent.h>
#include <unistd.h>
#include <string>
#include <vector>
using std::stof;
using std::string;
using std::to_string;
using std::vector;
// Read and return OS information
string LinuxParser::OperatingSystem() {
string line;
string key;
string value;
std::ifstream filestream(kOSPath);
if (filestream.is_open()) {
// Clean up each line
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ' ', '_');
std::replace(line.begin(), line.end(), '=', ' ');
std::replace(line.begin(), line.end(), '"', ' ');
std::istringstream linestream(line);
// Parse each line, looking for specific key/value
while (linestream >> key >> value) {
if (key == "PRETTY_NAME") {
std::replace(value.begin(), value.end(), '_', ' ');
return value;
}
}
}
}
return value;
}
// Read and return Kernel information
string LinuxParser::Kernel() {
string os, kernel;
string line;
std::ifstream stream(kProcDirectory + kVersionFilename);
if (stream.is_open()) {
// Necessary data is on first line, no need for parsing
std::getline(stream, line);
std::istringstream linestream(line);
linestream >> os >> os >> kernel;
}
return kernel;
}
// Read and return list of PIDs
vector<int> LinuxParser::Pids() {
vector<int> pids;
// Create pointer to a directory in filesystem
DIR* directory = opendir(kProcDirectory.c_str());
// Create pointer to file
struct dirent* file;
// Read each of the files in a directory
while ((file = readdir(directory)) != nullptr) {
// Checks to see that a file is a directory or not
if (file->d_type == DT_DIR) {
// PID files consist of all numbers, check to see if this is a PID file
string filename(file->d_name);
if (std::all_of(filename.begin(), filename.end(), isdigit)) {
// Get PID from filename and add to vector
int pid = stoi(filename);
pids.push_back(pid);
}
}
}
// Close directory
closedir(directory);
return pids;
}
// Read and return Memory Utilization
float LinuxParser::MemoryUtilization() {
string line;
string key;
float value;
float memUtil = 0;
float memTotal, memFree;
float buffers;
float cache, sreclaim, shmem;
std::ifstream stream(kProcDirectory + kMeminfoFilename);
if (stream.is_open()) {
// Parse each line, looking for specific keys/values
while (std::getline(stream, line)) {
std::replace(line.begin(), line.end(), ':', ' ');
std::istringstream linestream(line);
value = 0;
linestream >> key >> value;
if (key == "MemTotal") memTotal = value;
if (key == "MemFree") memFree = value;
if (key == "Buffers") buffers = value;
if (key == "Cached") cache = value;
if (key == "Shmem") shmem = value;
if (key == "SReclaimable") sreclaim = value;
}
// Total available memory = memTotal - memFree
memTotal = memTotal - memFree;
// Total used memory = totalAvail - (Buffers + (Cached + Sreclaimable -
// Shmem)))
memUtil = memTotal - (buffers + (cache + sreclaim - shmem));
// Turn into percentage
memUtil = memUtil / memTotal;
return memUtil;
}
return memUtil;
}
// Read and return CPU UpTime
long LinuxParser::UpTime() {
string line;
double uptime;
double idletime;
long upTimeValue = 0;
std::ifstream filestream(kProcDirectory + kUptimeFilename);
if (filestream.is_open()) {
// Data is on first line, no need to parse
std::getline(filestream, line);
std::istringstream linestream(line);
linestream >> uptime >> idletime;
upTimeValue = (long)uptime;
}
return upTimeValue;
}
// Read and return the process cpu utilization for a PID
float LinuxParser::CpuUtilization(int pid) {
string line, txt;
long utime, stime;
float cpuutil{0};
string pidS = to_string(pid);
std::ifstream filestream(kProcDirectory + pidS + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
// Get 14th and 15th values
std::istringstream linestream(line);
int i = 1;
while (i != 14) {
linestream >> txt;
i++;
}
linestream >> utime >> stime;
cpuutil = utime + stime;
// Convert into seconds
cpuutil = cpuutil / sysconf(_SC_CLK_TCK);
return cpuutil;
}
}
return cpuutil;
}
// Returns current CPU utilization
vector<string> LinuxParser::CpuUtilization() {
string line;
string cpu;
vector<string> value(8, "");
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
std::istringstream linestream(line);
linestream >> cpu >> value[kUser_] >> value[kNice_] >> value[kSystem_] >>
value[kIdle_] >> value[kIOwait_] >> value[kIRQ_] >> value[kSoftIRQ_] >>
value[kSteal_];
}
return value;
}
// Read and return the total number of processes
int LinuxParser::TotalProcesses() {
string line, key;
int value{0};
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "processes") {
return value;
}
}
}
}
return value;
}
// Read and return the number of running processes
int LinuxParser::RunningProcesses() {
string line, key;
int value{0};
std::ifstream filestream(kProcDirectory + kStatFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key >> value) {
if (key == "procs_running") {
return value;
}
}
}
}
return value;
}
// Read and return the command associated with a process
string LinuxParser::Command(int pid) {
string line{}, command{};
std::ifstream filestream(kProcDirectory + to_string(pid) + kCmdlineFilename);
if (filestream.is_open()) {
std::getline(filestream, line);
std::istringstream linestream(line);
linestream >> command;
return command;
}
return command;
}
// Read and return the memory used by a process
string LinuxParser::Ram(int pid) {
string line, key, value;
float mem{0};
string pidS = to_string(pid);
std::ifstream filestream(kProcDirectory + pidS + kStatusFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key) {
if (key == "VmSize:") {
linestream >> mem;
// Convert from kB to mB
mem /= 1000;
value = to_string(mem);
// Truncate extra decimal points
value.erase(value.find('.') + 3);
return value;
}
}
}
}
return value;
}
// Read and return the user ID associated with a process
string LinuxParser::Uid(int pid) {
string uid, key, line;
std::ifstream filestream(kProcDirectory + to_string(pid) + kStatusFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key) {
if (key == "Uid:") {
linestream >> uid;
return uid;
}
}
}
}
return uid;
}
// Read and return the user associated with a process
string LinuxParser::User(int pid) {
string uid, user, txt, key, line;
string pidS = to_string(pid);
bool flag{false};
// Open file, get uid
std::ifstream filestream(kProcDirectory + pidS + kStatusFilename);
if (filestream.is_open()) {
while (std::getline(filestream, line)) {
std::istringstream linestream(line);
while (linestream >> key) {
if (key == "Uid:") {
linestream >> uid;
flag = true;
break;
}
break;
}
if (flag) break;
}
}
// Open new file, use uid to get user string
filestream.close();
filestream.open(kPasswordPath);
if (filestream.is_open()) {
// Parse file
while (std::getline(filestream, line)) {
std::replace(line.begin(), line.end(), ':', ' ');
std::istringstream linestream(line);
// Find the UID / user pair
while (linestream >> user >> txt >> key) {
if (key == uid) {
return user;
}
}
}
}
return user;
}
// Read and return the uptime of a process
long LinuxParser::UpTime(int pid) {
string line, key, value;
string pidS = to_string(pid);
long uptime{0};
std::ifstream filestream(kProcDirectory + pidS + kStatFilename);
if (filestream.is_open()) {
// Parse file for uptime, value 22 in line
std::getline(filestream, line);
std::istringstream linestream(line);
int i = 1;
while (i != 22) {
linestream >> key;
i++;
}
linestream >> value;
uptime = stol(value);
// Convert from clock ticks to seconds
uptime = uptime / sysconf(_SC_CLK_TCK);
// Subtract from system runtime to get process runtime
long systime = UpTime();
uptime = systime - uptime;
return uptime;
}
return uptime;
}
|
0282ad3b72e56e70c2fbbc3361b8b9a0771eea16
|
0236cd084f91e8f545a972948c40cae7ea832819
|
/src/platform/tls_pointer_win.cpp
|
3c4c3410da9ac1be4c6c2134508220aa4354ef13
|
[
"MIT"
] |
permissive
|
alan0526/cpp-ipc
|
ce4c8e79a3da1cb89e3241a5301a72679236d40c
|
82e0809f9991e39c291b7bee0bf5311ddc35d100
|
refs/heads/master
| 2020-06-13T20:13:34.187609
| 2020-04-02T09:37:49
| 2020-04-02T09:37:49
| 194,775,767
| 0
| 0
|
MIT
| 2020-04-02T09:37:50
| 2019-07-02T02:43:46
|
C++
|
UTF-8
|
C++
| false
| false
| 7,762
|
cpp
|
tls_pointer_win.cpp
|
#include "tls_pointer.h"
#include "log.h"
#include <Windows.h> // ::Tls...
#include <atomic>
namespace ipc {
/*
* <Remarks>
*
* Windows doesn't support a per-thread destructor with its TLS primitives.
* So, here will build it manually by inserting a function to be called on each thread's exit.
*
* <Reference>
* - https://www.codeproject.com/Articles/8113/Thread-Local-Storage-The-C-Way
* - https://src.chromium.org/viewvc/chrome/trunk/src/base/threading/thread_local_storage_win.cc
* - https://github.com/mirror/mingw-org-wsl/blob/master/src/libcrt/crt/tlssup.c
* - https://github.com/Alexpux/mingw-w64/blob/master/mingw-w64-crt/crt/tlssup.c
* - http://svn.boost.org/svn/boost/trunk/libs/thread/src/win32/tss_pe.cpp
*/
namespace {
struct tls_data {
using destructor_t = void(*)(void*);
unsigned index_;
DWORD win_key_;
destructor_t destructor_;
bool valid() const noexcept {
return win_key_ != TLS_OUT_OF_INDEXES;
}
void* get() const {
return ::TlsGetValue(win_key_);
}
bool set(void* p) {
return TRUE == ::TlsSetValue(win_key_, static_cast<LPVOID>(p));
}
void destruct() {
void* data = valid() ? get() : nullptr;
if (data != nullptr) {
if (destructor_ != nullptr) destructor_(data);
set(nullptr);
}
}
void clear_self() {
if (valid()) {
destruct();
::TlsFree(win_key_);
}
delete this;
}
};
struct tls_recs {
tls_data* recs_[TLS_MINIMUM_AVAILABLE] {};
unsigned index_ = 0;
bool insert(tls_data* data) noexcept {
if (index_ >= TLS_MINIMUM_AVAILABLE) {
ipc::error("[tls_recs] insert tls_data failed[index_ >= TLS_MINIMUM_AVAILABLE].\n");
return false;
}
recs_[(data->index_ = index_++)] = data;
return true;
}
bool erase(tls_data* data) noexcept {
if (data->index_ >= TLS_MINIMUM_AVAILABLE) return false;
recs_[data->index_] = nullptr;
return true;
}
tls_data* * begin() noexcept { return &recs_[0]; }
tls_data* const * begin() const noexcept { return &recs_[0]; }
tls_data* * end () noexcept { return &recs_[index_]; }
tls_data* const * end () const noexcept { return &recs_[index_]; }
};
struct key_gen {
DWORD rec_key_;
key_gen() : rec_key_(::TlsAlloc()) {
if (rec_key_ == TLS_OUT_OF_INDEXES) {
ipc::error("[record_key] TlsAlloc failed[%lu].\n", ::GetLastError());
}
}
~key_gen() {
::TlsFree(rec_key_);
rec_key_ = TLS_OUT_OF_INDEXES;
}
} gen__;
DWORD& record_key() noexcept {
return gen__.rec_key_;
}
bool record(tls_data* tls_dat) {
if (record_key() == TLS_OUT_OF_INDEXES) return false;
auto rec = static_cast<tls_recs*>(::TlsGetValue(record_key()));
if (rec == nullptr) {
if (FALSE == ::TlsSetValue(record_key(), static_cast<LPVOID>(rec = new tls_recs))) {
ipc::error("[record] TlsSetValue failed[%lu].\n", ::GetLastError());
return false;
}
}
return rec->insert(tls_dat);
}
void erase_record(tls_data* tls_dat) {
if (tls_dat == nullptr) return;
if (record_key() == TLS_OUT_OF_INDEXES) return;
auto rec = static_cast<tls_recs*>(::TlsGetValue(record_key()));
if (rec == nullptr) return;
rec->erase(tls_dat);
tls_dat->clear_self();
}
void clear_all_records() {
if (record_key() == TLS_OUT_OF_INDEXES) return;
auto rec = static_cast<tls_recs*>(::TlsGetValue(record_key()));
if (rec == nullptr) return;
for (auto tls_dat : *rec) {
if (tls_dat != nullptr) tls_dat->destruct();
}
delete rec;
::TlsSetValue(record_key(), static_cast<LPVOID>(nullptr));
}
} // internal-linkage
namespace tls {
key_t create(destructor_t destructor) {
record_key(); // gen record-key
auto tls_dat = new tls_data { unsigned(-1), ::TlsAlloc(), destructor };
std::atomic_thread_fence(std::memory_order_seq_cst);
if (!tls_dat->valid()) {
ipc::error("[tls::create] TlsAlloc failed[%lu].\n", ::GetLastError());
tls_dat->clear_self();
return invalid_value;
}
return reinterpret_cast<key_t>(tls_dat);
}
void release(key_t tls_key) {
if (tls_key == invalid_value) {
ipc::error("[tls::release] tls_key is invalid_value.\n");
return;
}
auto tls_dat = reinterpret_cast<tls_data*>(tls_key);
if (tls_dat == nullptr) {
ipc::error("[tls::release] tls_dat is nullptr.\n");
return;
}
erase_record(tls_dat);
}
bool set(key_t tls_key, void* ptr) {
if (tls_key == invalid_value) {
ipc::error("[tls::set] tls_key is invalid_value.\n");
return false;
}
auto tls_dat = reinterpret_cast<tls_data*>(tls_key);
if (tls_dat == nullptr) {
ipc::error("[tls::set] tls_dat is nullptr.\n");
return false;
}
if (!tls_dat->set(ptr)) {
ipc::error("[tls::set] TlsSetValue failed[%lu].\n", ::GetLastError());
return false;
}
record(tls_dat);
return true;
}
void* get(key_t tls_key) {
if (tls_key == invalid_value) {
ipc::error("[tls::get] tls_key is invalid_value.\n");
return nullptr;
}
auto tls_dat = reinterpret_cast<tls_data*>(tls_key);
if (tls_dat == nullptr) {
ipc::error("[tls::get] tls_dat is nullptr.\n");
return nullptr;
}
return tls_dat->get();
}
} // namespace tls
namespace {
void NTAPI OnTlsCallback(PVOID, DWORD dwReason, PVOID) {
if (dwReason == DLL_THREAD_DETACH) clear_all_records();
}
} // internal-linkage
////////////////////////////////////////////////////////////////
/// Call destructors on thread exit
////////////////////////////////////////////////////////////////
#if defined(_MSC_VER)
#if defined(WIN64) || defined(_WIN64) || defined(__WIN64__)
#pragma comment(linker, "/INCLUDE:_tls_used")
#pragma comment(linker, "/INCLUDE:_tls_xl_b__")
extern "C" {
# pragma const_seg(".CRT$XLB")
extern const PIMAGE_TLS_CALLBACK _tls_xl_b__;
const PIMAGE_TLS_CALLBACK _tls_xl_b__ = OnTlsCallback;
# pragma const_seg()
}
#else /*!WIN64*/
#pragma comment(linker, "/INCLUDE:__tls_used")
#pragma comment(linker, "/INCLUDE:__tls_xl_b__")
extern "C" {
# pragma data_seg(".CRT$XLB")
PIMAGE_TLS_CALLBACK _tls_xl_b__ = OnTlsCallback;
# pragma data_seg()
}
#endif/*!WIN64*/
#elif defined(__GNUC__)
#define IPC_CRTALLOC__(x) __attribute__ ((section (x) ))
#if defined(__MINGW64__) || (__MINGW64_VERSION_MAJOR) || \
(__MINGW32_MAJOR_VERSION > 3) || ((__MINGW32_MAJOR_VERSION == 3) && (__MINGW32_MINOR_VERSION >= 18))
extern "C" {
IPC_CRTALLOC__(".CRT$XLB") PIMAGE_TLS_CALLBACK _tls_xl_b__ = OnTlsCallback;
}
#else /*!MINGW*/
extern "C" {
ULONG _tls_index__ = 0;
IPC_CRTALLOC__(".tls$AAA") char _tls_start__ = 0;
IPC_CRTALLOC__(".tls$ZZZ") char _tls_end__ = 0;
IPC_CRTALLOC__(".CRT$XLA") PIMAGE_TLS_CALLBACK _tls_xl_a__ = 0;
IPC_CRTALLOC__(".CRT$XLB") PIMAGE_TLS_CALLBACK _tls_xl_b__ = OnTlsCallback;
IPC_CRTALLOC__(".CRT$XLZ") PIMAGE_TLS_CALLBACK _tls_xl_z__ = 0;
}
extern "C" NX_CRTALLOC_(".tls") const IMAGE_TLS_DIRECTORY _tls_used = {
(ULONG_PTR)(&_tls_start__ + 1),
(ULONG_PTR) &_tls_end__,
(ULONG_PTR) &_tls_index__,
(ULONG_PTR) &_tls_xl_b__,
(ULONG)0, (ULONG)0
}
#endif/*!MINGW*/
#endif/*_MSC_VER, __GNUC__*/
} // namespace ipc
|
921dc4c908a0d5eeb581a21ba43f8a32aded2285
|
24973c04627980df24b453a51663db953cb69d81
|
/CoherentTest/Plugins/Runtime/Coherent/CohtmlPlugin/Source/CohtmlEditorPlugin/Private/CohtmlEditorPlugin.cpp
|
9f2027dcc6a38c49c6b6ec9e0a363ca91f4ac4a5
|
[] |
no_license
|
akrzon/Coherent
|
5aa0dabc0cda6b27a32d24d5b572aebf322a5d78
|
719f10c388250168986c2488ee40dba0216d2608
|
refs/heads/master
| 2022-11-23T10:27:57.029408
| 2020-07-26T20:33:24
| 2020-07-26T20:33:24
| 282,515,484
| 2
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 9,959
|
cpp
|
CohtmlEditorPlugin.cpp
|
/*
This file is part of Cohtml, modern user interface library for
games. Release $RELEASE$. Build $VERSION$ for $LICENSEE$.
Copyright (c) 2012-2018 Coherent Labs AD and/or its licensors. All
rights reserved in all media.
The coded instructions, statements, computer programs, and/or related
material (collectively the "Data") in these files contain confidential
and unpublished information proprietary Coherent Labs and/or its
licensors, which is protected by United States of America federal
copyright law and by international treaties.
This software or source code is supplied under the terms of a license
agreement and nondisclosure agreement with Coherent Labs Limited and may
not be copied, disclosed, or exploited except in accordance with the
terms of that agreement. The Data may not be disclosed or distributed to
third parties, in whole or in part, without the prior written consent of
Coherent Labs Limited.
COHERENT LABS MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS
SOURCE CODE FOR ANY PURPOSE. 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, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER, ITS AFFILIATES,
PARENT COMPANIES, LICENSORS, SUPPLIERS, 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 OR PERFORMANCE OF THIS SOFTWARE OR SOURCE CODE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "CohtmlEditorPluginPrivatePCH.h"
#include "CohtmlEditorCommands.h"
#include "Editor/MainFrame/Public/Interfaces/IMainFrameModule.h"
#include "ISettingsModule.h"
#include "AssetRegistryModule.h"
#include "AssetToolsModule.h"
#include "PropertyEditorModule.h"
#include "Framework/Commands/GenericCommands.h"
#include "CohtmlSettings.h"
#include "CohtmlTriggerEventDetails.h"
#include "CohtmlEditorDirectoryWatcher.h"
#include "CohtmlAtlasDirectoryWatcher.h"
#include "CohtmlAtlasAssetTypeActions.h"
#include "CohtmlAtlasManager.h"
#include "ICoherentRenderingPlugin.h"
#include "Framework/MultiBox/MultiBoxBuilder.h"
#include "GameFramework/GameModeBase.h"
#if COHTML_IS_GAMEFACE
DEFINE_LOG_CATEGORY(LogPrysmEditor);
#else
DEFINE_LOG_CATEGORY(LogPrysmEditor);
#endif
class FCohtmlEditorPlugin : public ICohtmlEditorPlugin
{
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
private:
void AddMenuBarExtension(FMenuBarBuilder&);
FDelegateHandle ContentBrowserCommandExtenderDelegateHandle;
TSharedPtr<FUICommandList> PluginCommands;
TSharedPtr<FExtensibilityManager> ExtensibilityManager;
TSharedPtr<FExtender> Extender;
TSharedPtr<const FExtensionBase> Extension;
};
IMPLEMENT_MODULE(FCohtmlEditorPlugin, CohtmlEditorPlugin)
namespace
{
#define LOCTEXT_NAMESPACE "MainCohtmlMenu"
static void FillCohtmlMenu(FMenuBuilder& MenuBuilder, const TSharedRef< FExtender > Extender)
{
MenuBuilder.BeginSection("Cohtml_CreateEdit", LOCTEXT("Cohtml_CreateEditHeading", "Create + Edit"));
{
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().AddHUD);
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().AddPlane);
}
MenuBuilder.EndSection();
MenuBuilder.BeginSection("Cohtml_Documentation", LOCTEXT("Cohtml_Documentation", "Documentation"));
{
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().LaunchDocs);
}
MenuBuilder.EndSection();
MenuBuilder.BeginSection("Cohtml_Debug", LOCTEXT("Cohtml_Debug", "Debug"));
{
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().LaunchDevTools);
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().ShowProfilingInfo);
}
MenuBuilder.EndSection();
MenuBuilder.BeginSection("Cohtml_Miscellaneous", LOCTEXT("Cohtml_MiscellaneousHeading", "Miscellaneous"));
{
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().ShowOptions);
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().LaunchAtlasViewer);
}
MenuBuilder.EndSection();
MenuBuilder.BeginSection("Cohtml_NewVersionInfo", LOCTEXT("Cohtml_NewVersionInfo", "New versions and information"));
{
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().LaunchDevPortal);
MenuBuilder.AddMenuEntry(FCohtmlEditorCommands::Get().LaunchChangelog);
}
MenuBuilder.EndSection();
}
#undef LOCTEXT_NAMESPACE
void MapCohtmlActions(TSharedPtr<FUICommandList> PluginCommands)
{
PluginCommands->MapAction(FCohtmlEditorCommands::Get().AddHUD,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::AddHUD),
FCanExecuteAction::CreateStatic(&FCohtmlEditorCommands::CanExecute::AddHUD));
PluginCommands->MapAction(FCohtmlEditorCommands::Get().AddPlane,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::AddPlane),
FCanExecuteAction::CreateStatic(&FCohtmlEditorCommands::CanExecute::AddPlane));
PluginCommands->MapAction(FCohtmlEditorCommands::Get().LaunchDevTools,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::LaunchDevTools),
FCanExecuteAction::CreateStatic(&FCohtmlEditorCommands::CanExecute::LaunchDevTools));
PluginCommands->MapAction(FCohtmlEditorCommands::Get().ShowProfilingInfo,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::ShowProfilingInfo));
PluginCommands->MapAction(FCohtmlEditorCommands::Get().LaunchDocs,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::LaunchDocs));
PluginCommands->MapAction(FCohtmlEditorCommands::Get().LaunchDevPortal,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::LaunchDevPortal));
PluginCommands->MapAction(FCohtmlEditorCommands::Get().LaunchChangelog,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::LaunchChangelog));
PluginCommands->MapAction(FCohtmlEditorCommands::Get().ShowOptions,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::ShowOptions));
PluginCommands->MapAction(FCohtmlEditorCommands::Get().LaunchAtlasViewer,
FExecuteAction::CreateStatic(&FCohtmlEditorCommands::Execute::LaunchAtlasViewer));
}
void RegisterSettings()
{
#define LOCTEXT_NAMESPACE "CohtmlEditorSettings"
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
auto DefaultValues = GetMutableDefault<UCohtmlSettings>();
SettingsModule->RegisterSettings("Project", "Plugins", COHTML_PRODUCT,
LOCTEXT("RuntimeSettingsName", COHTML_PRODUCT),
LOCTEXT("RuntimeSettingsDescription", "Configure the " COHTML_PRODUCT " plugin"),
DefaultValues
);
}
#undef LOCTEXT_NAMESPACE
}
void UnregisterSettings()
{
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
SettingsModule->UnregisterSettings("Project", "Plugins", COHTML_PRODUCT);
}
}
}
void FCohtmlEditorPlugin::StartupModule()
{
FCohtmlEditorCommands::Register();
PluginCommands = MakeShareable(new FUICommandList);
MapCohtmlActions(PluginCommands);
FCohtmlEditorDirectoryWatcher::Initialize();
FCohtmlAtlasDirectoryWatcher::Initialize();
Extender = MakeShareable(new FExtender);
Extension = Extender->AddMenuBarExtension("Window",
EExtensionHook::After, PluginCommands, FMenuBarExtensionDelegate::CreateRaw(this, &FCohtmlEditorPlugin::AddMenuBarExtension));
RegisterSettings();
ICoherentRenderingPlugin::Load().RegisterSettings();
FGenericCommands::Register(); // Required for the successful load of FLevelEditorModule
FLevelEditorModule& LevelEditorModule = FModuleManager::LoadModuleChecked<FLevelEditorModule>("LevelEditor");
ExtensibilityManager = LevelEditorModule.GetMenuExtensibilityManager();
ExtensibilityManager->AddExtender(Extender);
// Register the details customizations
{
FPropertyEditorModule& PropertyModule = FModuleManager::LoadModuleChecked<FPropertyEditorModule>("PropertyEditor");
PropertyModule.RegisterCustomClassLayout("K2Node_CohtmlTriggerEventOneOff",
FOnGetDetailCustomizationInstance::CreateStatic(&FCohtmlTriggerEventDetails::MakeInstance));
PropertyModule.NotifyCustomizationModuleChanged();
}
FCohtmlAtlasManagerCallbacks::RegisterCallbacks();
TSharedRef<FCohtmlAtlasAssetTypeActions> AtlasAssetTypeActions(new FCohtmlAtlasAssetTypeActions());
IAssetTools& AssetTools = FModuleManager::LoadModuleChecked<FAssetToolsModule>("AssetTools").Get();
AssetTools.RegisterAssetTypeActions(AtlasAssetTypeActions);
COHTML_EDITOR_UE_LOG(Log, TEXT("Editor plugin initialized!"));
}
void FCohtmlEditorPlugin::ShutdownModule()
{
// This function may be called during shutdown to clean up your module. For modules that support dynamic reloading,
// we call this function before unloading the module.
FCohtmlEditorCommands::Unregister();
FCohtmlEditorDirectoryWatcher::Uninitialize();
FCohtmlAtlasDirectoryWatcher::Uninitialize();
Extender->RemoveExtension(Extension.ToSharedRef());
if (ExtensibilityManager.IsValid())
{
ExtensibilityManager->RemoveExtender(Extender);
}
else
{
ExtensibilityManager.Reset();
}
UnregisterSettings();
FCohtmlAtlasManagerCallbacks::UnregisterCallbacks();
COHTML_EDITOR_UE_LOG(Log, TEXT("Editor plugin shut-down!"));
}
void FCohtmlEditorPlugin::AddMenuBarExtension(FMenuBarBuilder& MenuBuilder)
{
#define LOCTEXT_NAMESPACE "MainMenu"
COHTML_EDITOR_UE_LOG(Log, TEXT("Starting Extension logic"));
MenuBuilder.AddPullDownMenu(
LOCTEXT("CohtmlMenu", COHTML_PRODUCT),
LOCTEXT("CohtmlMenu_Tooltip", "Open the " COHTML_PRODUCT " menu."),
FNewMenuDelegate::CreateStatic(&FillCohtmlMenu, Extender.ToSharedRef()),
"CohtmlMenu"
);
#undef LOCTEXT_NAMESPACE
}
|
aea6e0d2cece5099c03bffe723109f317529bef6
|
a7c14f2f0fd386f6f4eb8d610bb40b45168724f9
|
/Plat4m_Core/STM32F4xx/GpioPinSTM32F4xx.h
|
67c6d9af6445ca2d6a581dd4b906005376483dcd
|
[] |
no_license
|
bminerd/Plat4m_Core
|
ecd6939dba658130d4aad5bd9f3d70b35884773c
|
809c49fcd739f449f3ea36aad2b2273c57c9ba8e
|
refs/heads/develop
| 2022-02-13T15:04:39.663751
| 2021-06-23T04:47:46
| 2021-06-23T04:47:46
| 5,208,847
| 1
| 0
| null | 2021-06-23T04:47:47
| 2012-07-27T19:59:29
|
C
|
UTF-8
|
C++
| false
| false
| 9,757
|
h
|
GpioPinSTM32F4xx.h
|
//------------------------------------------------------------------------------
// _______ __ ___
// || ___ \ || | __ // |
// || | || | || | _______ || |__ // | _____ ___
// || |__|| | || | // ___ | || __| // _ | || _ \/ _ \
// || ____/ || | || | || | || | // /|| | || |\\ /\\ \
// || | || | || |__|| | || | // /_|| |_ || | || | || |
// || | || | \\____ | || |__ //_____ _| || | || | || |
// ||_| ||_| ||_| \\___| ||_| ||_| ||_| ||_|
//
//
// The MIT License (MIT)
//
// Copyright (c) 2017 Benjamin Minerd
//
// 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.
//------------------------------------------------------------------------------
///
/// @file GpioPinSTM32F4xx.h
/// @author Ben Minerd
/// @date 3/22/2013
/// @brief GpioPinSTM32F4xx class header file.
///
#ifndef PLAT4M_GPIO_PIN_STM32F4XX_H
#define PLAT4M_GPIO_PIN_STM32F4XX_H
//------------------------------------------------------------------------------
// Include files
//------------------------------------------------------------------------------
#include <stm32f4xx.h>
#include <stm32f4xx_gpio.h>
#include <Plat4m_Core/Plat4m.h>
#include <Plat4m_Core/GpioPin.h>
#include <Plat4m_Core/STM32F4xx/GpioPortSTM32F4xx.h>
//------------------------------------------------------------------------------
// Namespaces
//------------------------------------------------------------------------------
namespace Plat4m
{
//------------------------------------------------------------------------------
// Classes
//------------------------------------------------------------------------------
class GpioPinSTM32F4xx : public GpioPin
{
public:
//--------------------------------------------------------------------------
// Public types
//--------------------------------------------------------------------------
enum Id
{
ID_0 = 0,
ID_1,
ID_2,
ID_3,
ID_4,
ID_5,
ID_6,
ID_7,
ID_8,
ID_9,
ID_10,
ID_11,
ID_12,
ID_13,
ID_14,
ID_15
};
enum AlternateFunction
{
ALTERNATE_FUNCTION_0 = 0,
ALTERNATE_FUNCTION_RTC_50Hz = ALTERNATE_FUNCTION_0,
ALTERNATE_FUNCTION_MCO = ALTERNATE_FUNCTION_0,
ALTERNATE_FUNCTION_TAMPER = ALTERNATE_FUNCTION_0,
ALTERNATE_FUNCTION_SWJ = ALTERNATE_FUNCTION_0,
ALTERNATE_FUNCTION_TRACE = ALTERNATE_FUNCTION_0,
ALTERNATE_FUNCTION_1 = 1,
ALTERNATE_FUNCTION_TIM1 = ALTERNATE_FUNCTION_1,
ALTERNATE_FUNCTION_TIM2 = ALTERNATE_FUNCTION_1,
ALTERNATE_FUNCTION_2 = 2,
ALTERNATE_FUNCTION_TIM3 = ALTERNATE_FUNCTION_2,
ALTERNATE_FUNCTION_TIM4 = ALTERNATE_FUNCTION_2,
ALTERNATE_FUNCTION_TIM5 = ALTERNATE_FUNCTION_2,
ALTERNATE_FUNCTION_3 = 3,
ALTERNATE_FUNCTION_TIM8 = ALTERNATE_FUNCTION_3,
ALTERNATE_FUNCTION_TIM9 = ALTERNATE_FUNCTION_3,
ALTERNATE_FUNCTION_TIM10 = ALTERNATE_FUNCTION_3,
ALTERNATE_FUNCTION_TIM11 = ALTERNATE_FUNCTION_3,
ALTERNATE_FUNCTION_4 = 4,
ALTERNATE_FUNCTION_I2C1 = ALTERNATE_FUNCTION_4,
ALTERNATE_FUNCTION_I2C2 = ALTERNATE_FUNCTION_4,
ALTERNATE_FUNCTION_I2C3 = ALTERNATE_FUNCTION_4,
ALTERNATE_FUNCTION_5 = 5,
ALTERNATE_FUNCTION_SPI1 = ALTERNATE_FUNCTION_5,
ALTERNATE_FUNCTION_SPI2 = ALTERNATE_FUNCTION_5,
ALTERNATE_FUNCTION_6 = 6,
ALTERNATE_FUNCTION_SPI3 = ALTERNATE_FUNCTION_6,
ALTERNATE_FUNCTION_7 = 7,
ALTERNATE_FUNCTION_USART1 = ALTERNATE_FUNCTION_7,
ALTERNATE_FUNCTION_USART2 = ALTERNATE_FUNCTION_7,
ALTERNATE_FUNCTION_USART3 = ALTERNATE_FUNCTION_7,
ALTERNATE_FUNCTION_8 = 8,
ALTERNATE_FUNCTION_UART4 = ALTERNATE_FUNCTION_8,
ALTERNATE_FUNCTION_UART5 = ALTERNATE_FUNCTION_8,
ALTERNATE_FUNCTION_USART6 = ALTERNATE_FUNCTION_8,
ALTERNATE_FUNCTION_9 = 9,
ALTERNATE_FUNCTION_CAN1 = ALTERNATE_FUNCTION_9,
ALTERNATE_FUNCTION_CAN2 = ALTERNATE_FUNCTION_9,
ALTERNATE_FUNCTION_TIM12 = ALTERNATE_FUNCTION_9,
ALTERNATE_FUNCTION_TIM13 = ALTERNATE_FUNCTION_9,
ALTERNATE_FUNCTION_TIM14 = ALTERNATE_FUNCTION_9,
ALTERNATE_FUNCTION_10 = 10,
ALTERNATE_FUNCTION_OTG_FS = ALTERNATE_FUNCTION_10,
ALTERNATE_FUNCTION_OTG_HS = ALTERNATE_FUNCTION_10,
ALTERNATE_FUNCTION_11 = 11,
ALTERNATE_FUNCTION_ETH = ALTERNATE_FUNCTION_11,
ALTERNATE_FUNCTION_12 = 12,
ALTERNATE_FUNCTION_FSMC = ALTERNATE_FUNCTION_12,
ALTERNATE_FUNCTION_OTG_HS_FS = ALTERNATE_FUNCTION_12,
ALTERNATE_FUNCTION_SDIO = ALTERNATE_FUNCTION_12,
ALTERNATE_FUNCTION_13 = 13,
ALTERNATE_FUNCTION_DCMI = ALTERNATE_FUNCTION_13,
ALTERNATE_FUNCTION_15 = 15,
ALTERNATE_FUNCTION_EVENTOUT = ALTERNATE_FUNCTION_15
};
enum OutputType
{
OUTPUT_TYPE_PUSH_PULL = GPIO_OType_PP,
OUTPUT_TYPE_OPEN_DRAIN = GPIO_OType_OD
};
enum OutputSpeed
{
OUTPUT_SPEED_2MHZ = GPIO_Speed_2MHz,
OUTPUT_SPEED_25MHZ = GPIO_Speed_25MHz,
OUTPUT_SPEED_50MHZ = GPIO_Speed_50MHz,
OUTPUT_SPEED_100MHZ = GPIO_Speed_100MHz
};
struct STM32F4xxConfig
{
AlternateFunction alternateFunction;
OutputType outputType;
OutputSpeed outputSpeed;
};
//--------------------------------------------------------------------------
// Public constructors
//--------------------------------------------------------------------------
GpioPinSTM32F4xx(GpioPortSTM32F4xx& gpioPort, const Id id);
//--------------------------------------------------------------------------
// Public virtual methods implemented from GpioPin
//--------------------------------------------------------------------------
void setLevelFast(const Level level);
Level getLevelFast();
Level readLevelFast();
void toggleLevelFast();
//--------------------------------------------------------------------------
// Public methods
//--------------------------------------------------------------------------
GpioPortSTM32F4xx& getGpioPort();
Id getId() const;
void setSTM32F4xxConfig(STM32F4xxConfig& config);
private:
//--------------------------------------------------------------------------
// Private static data members
//--------------------------------------------------------------------------
static const GPIOMode_TypeDef myModeMap[];
static const GPIOPuPd_TypeDef myResistorMap[];
static const OutputSpeed myDefaultOutputSpeed;
//--------------------------------------------------------------------------
// Private data members
//--------------------------------------------------------------------------
GpioPortSTM32F4xx& myGpioPort;
const Id myId;
const uint16_t myPinBitMask;
STM32F4xxConfig mySTM32F4xxConfig;
//--------------------------------------------------------------------------
// Private methods implemented from Module
//--------------------------------------------------------------------------
Module::Error driverSetEnabled(const bool enabled);
//--------------------------------------------------------------------------
// Private methods implemented from GpioPin
//--------------------------------------------------------------------------
GpioPin::Error driverConfigure(const Config& config);
GpioPin::Error driverSetLevel(const Level level);
GpioPin::Error driverGetLevel(Level& level);
GpioPin::Error driverReadLevel(Level& level);
GpioPin::Error driverToggleLevel();
//--------------------------------------------------------------------------
// Private methods
//--------------------------------------------------------------------------
void setOutputType(const OutputType outputType);
void setOutputSpeed(const OutputSpeed outputSpeed);
};
}; // namespace Plat4m
#endif // PLAT4M_GPIO_PIN_STM32F4XX_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.