hexsha
stringlengths 40
40
| size
int64 7
1.05M
| ext
stringclasses 13
values | lang
stringclasses 1
value | max_stars_repo_path
stringlengths 4
269
| max_stars_repo_name
stringlengths 5
109
| max_stars_repo_head_hexsha
stringlengths 40
40
| max_stars_repo_licenses
listlengths 1
9
| max_stars_count
int64 1
191k
⌀ | max_stars_repo_stars_event_min_datetime
stringlengths 24
24
⌀ | max_stars_repo_stars_event_max_datetime
stringlengths 24
24
⌀ | max_issues_repo_path
stringlengths 4
269
| max_issues_repo_name
stringlengths 5
116
| max_issues_repo_head_hexsha
stringlengths 40
40
| max_issues_repo_licenses
listlengths 1
9
| max_issues_count
int64 1
48.5k
⌀ | max_issues_repo_issues_event_min_datetime
stringlengths 24
24
⌀ | max_issues_repo_issues_event_max_datetime
stringlengths 24
24
⌀ | max_forks_repo_path
stringlengths 4
269
| max_forks_repo_name
stringlengths 5
116
| max_forks_repo_head_hexsha
stringlengths 40
40
| max_forks_repo_licenses
listlengths 1
9
| max_forks_count
int64 1
105k
⌀ | max_forks_repo_forks_event_min_datetime
stringlengths 24
24
⌀ | max_forks_repo_forks_event_max_datetime
stringlengths 24
24
⌀ | content
stringlengths 7
1.05M
| avg_line_length
float64 1.21
330k
| max_line_length
int64 6
990k
| alphanum_fraction
float64 0.01
0.99
| author_id
stringlengths 2
40
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21b7b165f624e89398583caebcbdf007153ffcea
| 6,181
|
cpp
|
C++
|
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
|
igagis/best84kb
|
e4f58e0138b0835b39e636d69658183a8e74594e
|
[
"MIT"
] | 2
|
2019-05-13T05:19:02.000Z
|
2021-11-29T09:07:43.000Z
|
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
|
igagis/best84kb
|
e4f58e0138b0835b39e636d69658183a8e74594e
|
[
"MIT"
] | null | null | null |
qmk_firmware/quantum/serial_link/tests/transport_tests.cpp
|
igagis/best84kb
|
e4f58e0138b0835b39e636d69658183a8e74594e
|
[
"MIT"
] | 1
|
2020-11-05T02:23:49.000Z
|
2020-11-05T02:23:49.000Z
|
/*
The MIT License (MIT)
Copyright (c) 2016 Fred Sundvik
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include "gtest/gtest.h"
#include "gmock/gmock.h"
using testing::_;
using testing::ElementsAreArray;
using testing::Args;
extern "C" {
#include "serial_link/protocol/transport.h"
}
struct test_object1 {
uint32_t test;
};
struct test_object2 {
uint32_t test1;
uint32_t test2;
};
MASTER_TO_ALL_SLAVES_OBJECT(master_to_slave, test_object1);
MASTER_TO_SINGLE_SLAVE_OBJECT(master_to_single_slave, test_object1);
SLAVE_TO_MASTER_OBJECT(slave_to_master, test_object1);
static remote_object_t* test_remote_objects[] = {
REMOTE_OBJECT(master_to_slave),
REMOTE_OBJECT(master_to_single_slave),
REMOTE_OBJECT(slave_to_master),
};
class Transport : public testing::Test {
public:
Transport() {
Instance = this;
add_remote_objects(test_remote_objects, sizeof(test_remote_objects) / sizeof(remote_object_t*));
}
~Transport() {
Instance = nullptr;
reinitialize_serial_link_transport();
}
MOCK_METHOD0(signal_data_written, void ());
MOCK_METHOD1(router_send_frame, void (uint8_t destination));
void router_send_frame(uint8_t destination, uint8_t* data, uint16_t size) {
router_send_frame(destination);
std::copy(data, data + size, std::back_inserter(sent_data));
}
static Transport* Instance;
std::vector<uint8_t> sent_data;
};
Transport* Transport::Instance = nullptr;
extern "C" {
void signal_data_written(void) {
Transport::Instance->signal_data_written();
}
void router_send_frame(uint8_t destination, uint8_t* data, uint16_t size) {
Transport::Instance->router_send_frame(destination, data, size);
}
}
TEST_F(Transport, write_to_local_signals_an_event) {
begin_write_master_to_slave();
EXPECT_CALL(*this, signal_data_written());
end_write_master_to_slave();
begin_write_slave_to_master();
EXPECT_CALL(*this, signal_data_written());
end_write_slave_to_master();
begin_write_master_to_single_slave(1);
EXPECT_CALL(*this, signal_data_written());
end_write_master_to_single_slave(1);
}
TEST_F(Transport, writes_from_master_to_all_slaves) {
update_transport();
test_object1* obj = begin_write_master_to_slave();
obj->test = 5;
EXPECT_CALL(*this, signal_data_written());
end_write_master_to_slave();
EXPECT_CALL(*this, router_send_frame(0xFF));
update_transport();
transport_recv_frame(0, sent_data.data(), sent_data.size());
test_object1* obj2 = read_master_to_slave();
EXPECT_NE(obj2, nullptr);
EXPECT_EQ(obj2->test, 5);
}
TEST_F(Transport, writes_from_slave_to_master) {
update_transport();
test_object1* obj = begin_write_slave_to_master();
obj->test = 7;
EXPECT_CALL(*this, signal_data_written());
end_write_slave_to_master();
EXPECT_CALL(*this, router_send_frame(0));
update_transport();
transport_recv_frame(3, sent_data.data(), sent_data.size());
test_object1* obj2 = read_slave_to_master(2);
EXPECT_EQ(read_slave_to_master(0), nullptr);
EXPECT_NE(obj2, nullptr);
EXPECT_EQ(obj2->test, 7);
}
TEST_F(Transport, writes_from_master_to_single_slave) {
update_transport();
test_object1* obj = begin_write_master_to_single_slave(3);
obj->test = 7;
EXPECT_CALL(*this, signal_data_written());
end_write_master_to_single_slave(3);
EXPECT_CALL(*this, router_send_frame(4));
update_transport();
transport_recv_frame(0, sent_data.data(), sent_data.size());
test_object1* obj2 = read_master_to_single_slave();
EXPECT_NE(obj2, nullptr);
EXPECT_EQ(obj2->test, 7);
}
TEST_F(Transport, ignores_object_with_invalid_id) {
update_transport();
test_object1* obj = begin_write_master_to_single_slave(3);
obj->test = 7;
EXPECT_CALL(*this, signal_data_written());
end_write_master_to_single_slave(3);
EXPECT_CALL(*this, router_send_frame(4));
update_transport();
sent_data[sent_data.size() - 1] = 44;
transport_recv_frame(0, sent_data.data(), sent_data.size());
test_object1* obj2 = read_master_to_single_slave();
EXPECT_EQ(obj2, nullptr);
}
TEST_F(Transport, ignores_object_with_size_too_small) {
update_transport();
test_object1* obj = begin_write_master_to_slave();
obj->test = 7;
EXPECT_CALL(*this, signal_data_written());
end_write_master_to_slave();
EXPECT_CALL(*this, router_send_frame(_));
update_transport();
sent_data[sent_data.size() - 2] = 0;
transport_recv_frame(0, sent_data.data(), sent_data.size() - 1);
test_object1* obj2 = read_master_to_slave();
EXPECT_EQ(obj2, nullptr);
}
TEST_F(Transport, ignores_object_with_size_too_big) {
update_transport();
test_object1* obj = begin_write_master_to_slave();
obj->test = 7;
EXPECT_CALL(*this, signal_data_written());
end_write_master_to_slave();
EXPECT_CALL(*this, router_send_frame(_));
update_transport();
sent_data.resize(sent_data.size() + 22);
sent_data[sent_data.size() - 1] = 0;
transport_recv_frame(0, sent_data.data(), sent_data.size());
test_object1* obj2 = read_master_to_slave();
EXPECT_EQ(obj2, nullptr);
}
| 32.703704
| 104
| 0.738554
|
igagis
|
21c04010e161eed4e3d4bc7c6c16d1be21dec5af
| 2,977
|
hpp
|
C++
|
src/number_theory/modulo.hpp
|
RamchandraApte/OmniTemplate
|
f150f451871b0ab43ac39a798186278106da1527
|
[
"MIT"
] | 14
|
2019-04-23T21:44:12.000Z
|
2022-03-04T22:48:59.000Z
|
src/number_theory/modulo.hpp
|
RamchandraApte/OmniTemplate
|
f150f451871b0ab43ac39a798186278106da1527
|
[
"MIT"
] | 3
|
2019-04-25T10:45:32.000Z
|
2020-08-05T22:40:39.000Z
|
src/number_theory/modulo.hpp
|
RamchandraApte/OmniTemplate
|
f150f451871b0ab43ac39a798186278106da1527
|
[
"MIT"
] | 1
|
2020-07-16T22:16:33.000Z
|
2020-07-16T22:16:33.000Z
|
#pragma once
#include "core/all.hpp"
namespace modulo_namespace {
template <typename... Args> using invert_t = decltype(invert(std::declval<Args>()...));
/*! @brief Returns \f$a^b\f$
* @param a the base
* @param b the exponent
*
* Time complexity: \f$O(\log_2 |b|)\f$ multiplications
*/
template <typename T> T power(T a, ll b) {
if (b < 0) {
if constexpr (experimental::is_detected_v<invert_t, multiplies<>, decltype(a)>) {
a = invert(multiplies{}, a);
b = -b;
} else {
assert(("b < 0 but unable to inverse a", false));
}
}
T ret = identity(multiplies<>{}, a);
for (; b; b >>= 1, a *= a) {
if (b & 1) {
ret *= a;
}
}
return ret;
}
/*! @brief Returns the remainder of a divided by b as a nonnegative integer in [0, b).*/
ll mod(ll a, const ll b) {
a %= b;
if (a < 0) {
a += b;
}
return a;
}
/*! Set a to the remainder when divided by b. */
ll mod_eq(ll &a, const ll b) { return a = mod(a, b); }
/*! no_mod tag class allows a modulo object to be quickly constructed from an integer in the range
* [0, b) without performing a modulo operation.*/
struct no_mod {};
struct modulo {
inline static ll modulus =
1e9 + 7; //!< Modulus used for operations like modular multiplication
/*! Modular arithmetic class */
ll x; //!< The representative element, which is in [0, M)
modulo() : x{0LL} {}
template <typename T, typename = enable_if_t<is_integral<T>::value, void>>
modulo(T x_) : x(mod(x_, modulo::modulus)) {}
modulo(ll x_, no_mod) : x(x_) {}
explicit operator auto() const { return x; }
};
modulo operator"" _M(const unsigned long long x) { return modulo{x}; }
modulo identity(plus<>, modulo) { return 0; }
modulo identity(multiplies<>, modulo) { return 1; }
modulo operator+(modulo const &a, modulo const &b) {
ll const sum = a.x + b.x;
return {sum >= modulo::modulus ? sum - modulo::modulus : sum, no_mod{}};
}
modulo operator++(modulo &a) { return a += 1; }
modulo operator-(modulo const &a) { return {modulo::modulus - a.x, no_mod{}}; }
// To avoid ADL issues
using ::operator-;
bin(==, modulo);
modulo operator*(modulo const &a, modulo const &b) {
/*! Computes a times b modulo modulo::modulus using long double */
const ull quot = ld(a.x) * ld(b.x) / ld(modulo::modulus);
// Computes the approximate remainder
const ll rem = ull(a.x) * ull(b.x) - ull(modulo::modulus) * quot;
if (rem < 0) {
return {rem + modulo::modulus, no_mod{}};
}
if (rem >= modulo::modulus) {
return {rem - modulo::modulus, no_mod{}};
}
return {rem, no_mod{}};
}
modulo invert(multiplies<>, modulo const &b) {
/*! Computes the modular inverse \f$b^{-1} \pmod{M}\f$ */
assert(b != 0);
return power(b, modulo::modulus - 2);
}
using ::operator/;
template <typename Stream> auto &operator<<(Stream &os, modulo const &m) { return os << m.x; }
} // namespace modulo_namespace
using namespace modulo_namespace;
namespace std {
template <> struct hash<modulo> {
ll operator()(modulo const &x) const { return x.x; }
};
} // namespace std
| 32.714286
| 98
| 0.642257
|
RamchandraApte
|
21cb346ca25d20a839156d4a39c533e1731addd1
| 737
|
cpp
|
C++
|
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
|
PrakharPipersania/LeetCode-Solutions
|
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
|
[
"MIT"
] | 2
|
2021-03-05T22:32:23.000Z
|
2021-03-05T22:32:29.000Z
|
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
|
PrakharPipersania/LeetCode-Solutions
|
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
|
[
"MIT"
] | null | null | null |
Questions Level-Wise/Hard/find-minimum-in-rotated-sorted-array-ii.cpp
|
PrakharPipersania/LeetCode-Solutions
|
ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7
|
[
"MIT"
] | null | null | null |
class Solution {
public:
int binarysearch(vector<int> nums,int l,int h)
{
while(l<h)
{
int mid=(h-l)/2+l;
if(nums[l]<nums[h])
return nums[l];
else if(l+1==h)
return nums[h];
else if(nums[l]>=nums[mid]&&nums[mid]<=nums[h])
{
int temp1=binarysearch(nums,l,mid);
int temp2=binarysearch(nums,mid,h);
if(temp1<temp2)
return temp1;
return temp2;
}
else
l=mid;
}
return nums[0];
}
int findMin(vector<int>& nums)
{
return binarysearch(nums,0,nums.size()-1);
}
};
| 24.566667
| 59
| 0.419267
|
PrakharPipersania
|
21d3802f04245351d855c9ca5900a75a6cde87b5
| 2,522
|
cpp
|
C++
|
src/EZOI/1018/kaleidoscope.cpp
|
krishukr/cpp-code
|
1c94401682227bd86c0d9295134d43582247794e
|
[
"MIT"
] | 1
|
2021-08-13T14:27:39.000Z
|
2021-08-13T14:27:39.000Z
|
src/EZOI/1018/kaleidoscope.cpp
|
krishukr/cpp-code
|
1c94401682227bd86c0d9295134d43582247794e
|
[
"MIT"
] | null | null | null |
src/EZOI/1018/kaleidoscope.cpp
|
krishukr/cpp-code
|
1c94401682227bd86c0d9295134d43582247794e
|
[
"MIT"
] | null | null | null |
#include <algorithm>
#include <cstdio>
#include <iostream>
typedef long long ll;
int n, m;
template <typename T>
T read();
class Star {
private:
const static int MAX_N = 200050;
public:
struct Node {
int v;
int nxt;
ll w;
} node[MAX_N << 1];
int head[MAX_N];
int cnt;
void create(int u, int v, ll w) {
node[++cnt].v = v;
node[cnt].nxt = head[u];
node[cnt].w = w;
head[u] = cnt;
}
};
class MST {
private:
Star* star;
const static int MAX_N = 200050;
protected:
ll dis[MAX_N];
bool vis[MAX_N];
int tot, crt = 1;
public:
MST(Star* star) { this->star = star; }
ll prim() {
std::fill(dis, dis + n + 10, 0x3f3f3f3f3f3f3f3f);
for (int i = star->head[1]; i; i = star->node[i].nxt) {
int v = star->node[i].v;
dis[v] = std::min(dis[v], star->node[i].w);
}
ll ans = 0;
while (++tot < n) {
ll min = 0x3f3f3f3f3f3f3f3f;
vis[crt] = true;
for (int i = 1; i <= n; i++) {
if (!vis[i] and min > dis[i]) {
min = dis[i];
crt = i;
}
}
ans += min;
for (int i = star->head[crt]; i; i = star->node[i].nxt) {
int v = star->node[i].v;
ll w = star->node[i].w;
if (dis[v] > w and !vis[v]) {
dis[v] = w;
}
}
}
return ans;
}
};
signed main() {
freopen("kaleidoscope.in", "r", stdin);
freopen("kaleidoscope.out", "w", stdout);
int t = read<int>();
while (t--) {
n = read<int>(), m = read<int>();
Star* star = new Star();
for (int i = 1; i <= m; i++) {
int x = read<int>(), y = read<int>();
ll z = read<ll>();
for (int i = 0; i < n; i++) {
star->create((x + i) % n + 1, (y + i) % n + 1, z);
star->create((y + i) % n + 1, (x + i) % n + 1, z);
}
}
MST* mst = new MST(star);
std::cout << mst->prim() << '\n';
}
fclose(stdin);
fclose(stdout);
return 0;
}
template <typename T>
T read() {
T x = 0, f = 1;
char ch = getchar();
while (!isdigit(ch)) {
if (ch == '-') f = -1;
ch = getchar();
}
while (isdigit(ch)) {
x = x * 10 + ch - 48;
ch = getchar();
}
return x * f;
}
| 21.016667
| 69
| 0.406027
|
krishukr
|
21dcf21fc5692fa094e45e1ac901bd23ca517dbe
| 146
|
cpp
|
C++
|
MemLeak/src/Shape/Line/Line.cpp
|
pk8868/MemLeak
|
72f937110c2b67547f67bdea60d2e80b0f5581a1
|
[
"MIT"
] | null | null | null |
MemLeak/src/Shape/Line/Line.cpp
|
pk8868/MemLeak
|
72f937110c2b67547f67bdea60d2e80b0f5581a1
|
[
"MIT"
] | null | null | null |
MemLeak/src/Shape/Line/Line.cpp
|
pk8868/MemLeak
|
72f937110c2b67547f67bdea60d2e80b0f5581a1
|
[
"MIT"
] | null | null | null |
#include "mpch.h"
#include "Line.hpp"
namespace ml {
Line::Line(Vec2f a, Vec2f b) {
transform.setPoint(a, 0);
transform.setPoint(b, 1);
}
}
| 16.222222
| 31
| 0.650685
|
pk8868
|
21e7e4c022bf5ddcc7dc9dfefcdc89b2686c2df5
| 332
|
cpp
|
C++
|
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 965
|
2017-06-25T23:57:11.000Z
|
2022-03-31T14:17:32.000Z
|
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 3,272
|
2017-06-24T00:26:34.000Z
|
2022-03-31T22:14:07.000Z
|
docs/mfc/codesnippet/CPP/clistbox-class_29.cpp
|
bobbrow/cpp-docs
|
769b186399141c4ea93400863a7d8463987bf667
|
[
"CC-BY-4.0",
"MIT"
] | 951
|
2017-06-25T12:36:14.000Z
|
2022-03-26T22:49:06.000Z
|
void CMyODListBox::OnLButtonDown(UINT nFlags, CPoint point)
{
BOOL bOutside = TRUE;
UINT uItem = ItemFromPoint(point, bOutside);
if (!bOutside)
{
// Set the anchor to be the middle item.
SetAnchorIndex(uItem);
ASSERT((UINT)GetAnchorIndex() == uItem);
}
CListBox::OnLButtonDown(nFlags, point);
}
| 23.714286
| 59
| 0.662651
|
bobbrow
|
21e9d91ffbb9f9ccc18cf739ab91c534075e5f63
| 422
|
cpp
|
C++
|
CodeForces/SystemofEquations.cpp
|
mysterio0801/CP
|
68983c423a42f98d6e9bf5375bc3f936e980d631
|
[
"MIT"
] | null | null | null |
CodeForces/SystemofEquations.cpp
|
mysterio0801/CP
|
68983c423a42f98d6e9bf5375bc3f936e980d631
|
[
"MIT"
] | null | null | null |
CodeForces/SystemofEquations.cpp
|
mysterio0801/CP
|
68983c423a42f98d6e9bf5375bc3f936e980d631
|
[
"MIT"
] | null | null | null |
#include<bits/stdc++.h>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int temp = n;
int count = 0;
map<int, int> mp;
while (n != 0) {
int a = sqrt(n);
int b = temp - pow(a, 2);
mp[a] = b;
n--;
}
for (auto &pr : mp) {
if (pr.first + pow(pr.second, 2) == m) {
count++;
}
if (pr.second + pow(pr.first, 2) == m && (pr.second == 0 || pr.first == 0)) {
count++;
}
}
cout << count;
}
| 16.88
| 79
| 0.481043
|
mysterio0801
|
21e9ecdbe50ce01fc0c3a82d9ea330a09897dad5
| 14,755
|
cpp
|
C++
|
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
|
John3/t3d_benchmarking
|
27a5780ad704aa91b45ff1bb0d69ed07668d03be
|
[
"MIT"
] | 10
|
2015-03-12T20:20:34.000Z
|
2021-02-03T08:07:31.000Z
|
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
|
John3/t3d_benchmarking
|
27a5780ad704aa91b45ff1bb0d69ed07668d03be
|
[
"MIT"
] | 3
|
2015-07-04T23:50:43.000Z
|
2016-08-01T09:19:52.000Z
|
Engine/source/T3D/components/physics/rigidBodyComponent.cpp
|
John3/t3d_benchmarking
|
27a5780ad704aa91b45ff1bb0d69ed07668d03be
|
[
"MIT"
] | 6
|
2015-11-28T16:18:26.000Z
|
2020-03-29T17:14:56.000Z
|
//-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------
#include "T3D/components/physics/rigidBodyComponent.h"
#include "core/util/safeDelete.h"
#include "console/consoleTypes.h"
#include "console/consoleObject.h"
#include "core/stream/bitStream.h"
#include "console/engineAPI.h"
#include "sim/netConnection.h"
#include "T3D/physics/physicsBody.h"
#include "T3D/physics/physicsPlugin.h"
#include "T3D/physics/physicsWorld.h"
#include "T3D/physics/physicsCollision.h"
#include "T3D/components/collision/collisionComponent.h"
bool RigidBodyComponent::smNoCorrections = false;
bool RigidBodyComponent::smNoSmoothing = false;
//////////////////////////////////////////////////////////////////////////
// Constructor/Destructor
//////////////////////////////////////////////////////////////////////////
RigidBodyComponent::RigidBodyComponent() : Component()
{
mMass = 20;
mDynamicFriction = 1;
mStaticFriction = 0.1f;
mRestitution = 10;
mLinearDamping = 0;
mAngularDamping = 0;
mLinearSleepThreshold = 1;
mAngularSleepThreshold = 1;
mWaterDampingScale = 0.1f;
mBuoyancyDensity = 1;
mSimType = SimType_ServerOnly;
mPhysicsRep = NULL;
mResetPos = MatrixF::Identity;
mOwnerColComponent = NULL;
mFriendlyName = "RigidBody(Component)";
}
RigidBodyComponent::~RigidBodyComponent()
{
}
IMPLEMENT_CO_NETOBJECT_V1(RigidBodyComponent);
bool RigidBodyComponent::onAdd()
{
if(! Parent::onAdd())
return false;
return true;
}
void RigidBodyComponent::onRemove()
{
Parent::onRemove();
}
void RigidBodyComponent::initPersistFields()
{
Parent::initPersistFields();
}
//This is mostly a catch for situations where the behavior is re-added to the object and the like and we may need to force an update to the behavior
void RigidBodyComponent::onComponentAdd()
{
Parent::onComponentAdd();
if (isServerObject())
{
storeRestorePos();
PhysicsPlugin::getPhysicsResetSignal().notify(this, &RigidBodyComponent::_onPhysicsReset);
}
CollisionComponent *colComp = mOwner->getComponent<CollisionComponent>();
if (colComp)
{
colComp->onCollisionChanged.notify(this, &RigidBodyComponent::updatePhysics);
updatePhysics(colComp->getCollisionData());
}
else
updatePhysics();
}
void RigidBodyComponent::onComponentRemove()
{
Parent::onComponentRemove();
if (isServerObject())
{
PhysicsPlugin::getPhysicsResetSignal().remove(this, &RigidBodyComponent::_onPhysicsReset);
}
CollisionComponent *colComp = mOwner->getComponent<CollisionComponent>();
if (colComp)
{
colComp->onCollisionChanged.remove(this, &RigidBodyComponent::updatePhysics);
}
SAFE_DELETE(mPhysicsRep);
}
void RigidBodyComponent::componentAddedToOwner(Component *comp)
{
CollisionComponent *colComp = dynamic_cast<CollisionComponent*>(comp);
if (colComp)
{
colComp->onCollisionChanged.notify(this, &RigidBodyComponent::updatePhysics);
updatePhysics(colComp->getCollisionData());
}
}
void RigidBodyComponent::componentRemovedFromOwner(Component *comp)
{
//test if this is a shape component!
CollisionComponent *colComp = dynamic_cast<CollisionComponent*>(comp);
if (colComp)
{
colComp->onCollisionChanged.remove(this, &RigidBodyComponent::updatePhysics);
updatePhysics();
}
}
void RigidBodyComponent::ownerTransformSet(MatrixF *mat)
{
if (mPhysicsRep)
mPhysicsRep->setTransform(mOwner->getTransform());
}
void RigidBodyComponent::updatePhysics(PhysicsCollision* collision)
{
SAFE_DELETE(mPhysicsRep);
if (!PHYSICSMGR)
return;
mWorld = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client");
if (!collision)
return;
mPhysicsRep = PHYSICSMGR->createBody();
mPhysicsRep->init(collision, mMass, 0, mOwner, mWorld);
mPhysicsRep->setMaterial(mRestitution, mDynamicFriction, mStaticFriction);
mPhysicsRep->setDamping(mLinearDamping, mAngularDamping);
mPhysicsRep->setSleepThreshold(mLinearSleepThreshold, mAngularSleepThreshold);
mPhysicsRep->setTransform(mOwner->getTransform());
// The reset position is the transform on the server
// at creation time... its not used on the client.
if (isServerObject())
{
storeRestorePos();
PhysicsPlugin::getPhysicsResetSignal().notify(this, &RigidBodyComponent::_onPhysicsReset);
}
}
U32 RigidBodyComponent::packUpdate(NetConnection *con, U32 mask, BitStream *stream)
{
U32 retMask = Parent::packUpdate(con, mask, stream);
if (stream->writeFlag(mask & StateMask))
{
// This will encode the position relative to the control
// object position.
//
// This will compress the position to as little as 6.25
// bytes if the position is within about 30 meters of the
// control object.
//
// Worst case its a full 12 bytes + 2 bits if the position
// is more than 500 meters from the control object.
//
stream->writeCompressedPoint(mState.position);
// Use only 3.5 bytes to send the orientation.
stream->writeQuat(mState.orientation, 9);
// If the server object has been set to sleep then
// we don't need to send any velocity.
if (!stream->writeFlag(mState.sleeping))
{
// This gives me ~0.015f resolution in velocity magnitude
// while only costing me 1 bit of the velocity is zero length,
// <5 bytes in normal cases, and <8 bytes if the velocity is
// greater than 1000.
AssertWarn(mState.linVelocity.len() < 1000.0f,
"PhysicsShape::packUpdate - The linVelocity is out of range!");
stream->writeVector(mState.linVelocity, 1000.0f, 16, 9);
// For angular velocity we get < 0.01f resolution in magnitude
// with the most common case being under 4 bytes.
AssertWarn(mState.angVelocity.len() < 10.0f,
"PhysicsShape::packUpdate - The angVelocity is out of range!");
stream->writeVector(mState.angVelocity, 10.0f, 10, 9);
}
}
return retMask;
}
void RigidBodyComponent::unpackUpdate(NetConnection *con, BitStream *stream)
{
Parent::unpackUpdate(con, stream);
if (stream->readFlag()) // StateMask
{
PhysicsState state;
// Read the encoded and compressed position... commonly only 6.25 bytes.
stream->readCompressedPoint(&state.position);
// Read the compressed quaternion... 3.5 bytes.
stream->readQuat(&state.orientation, 9);
state.sleeping = stream->readFlag();
if (!state.sleeping)
{
stream->readVector(&state.linVelocity, 1000.0f, 16, 9);
stream->readVector(&state.angVelocity, 10.0f, 10, 9);
}
if (!smNoCorrections && mPhysicsRep && mPhysicsRep->isDynamic())
{
// Set the new state on the physics object immediately.
mPhysicsRep->applyCorrection(state.getTransform());
mPhysicsRep->setSleeping(state.sleeping);
if (!state.sleeping)
{
mPhysicsRep->setLinVelocity(state.linVelocity);
mPhysicsRep->setAngVelocity(state.angVelocity);
}
mPhysicsRep->getState(&mState);
}
// If there is no physics object then just set the
// new state... the tick will take care of the
// interpolation and extrapolation.
if (!mPhysicsRep || !mPhysicsRep->isDynamic())
mState = state;
}
}
void RigidBodyComponent::processTick()
{
Parent::processTick();
if (!mPhysicsRep || !PHYSICSMGR)
return;
// Note that unlike TSStatic, the serverside PhysicsShape does not
// need to play the ambient animation because even if the animation were
// to move collision shapes it would not affect the physx representation.
PROFILE_START(RigidBodyComponent_ProcessTick);
if (!mPhysicsRep->isDynamic())
return;
// SINGLE PLAYER HACK!!!!
if (PHYSICSMGR->isSinglePlayer() && isClientObject() && getServerObject())
{
RigidBodyComponent *servObj = (RigidBodyComponent*)getServerObject();
mOwner->setTransform(servObj->mState.getTransform());
mRenderState[0] = servObj->mRenderState[0];
mRenderState[1] = servObj->mRenderState[1];
return;
}
// Store the last render state.
mRenderState[0] = mRenderState[1];
// If the last render state doesn't match the last simulation
// state then we got a correction and need to
Point3F errorDelta = mRenderState[1].position - mState.position;
const bool doSmoothing = !errorDelta.isZero() && !smNoSmoothing;
const bool wasSleeping = mState.sleeping;
// Get the new physics state.
mPhysicsRep->getState(&mState);
updateContainerForces();
// Smooth the correction back into the render state.
mRenderState[1] = mState;
if (doSmoothing)
{
F32 correction = mClampF(errorDelta.len() / 20.0f, 0.1f, 0.9f);
mRenderState[1].position.interpolate(mState.position, mRenderState[0].position, correction);
mRenderState[1].orientation.interpolate(mState.orientation, mRenderState[0].orientation, correction);
}
//Check if any collisions occured
findContact();
// If we haven't been sleeping then update our transform
// and set ourselves as dirty for the next client update.
if (!wasSleeping || !mState.sleeping)
{
// Set the transform on the parent so that
// the physics object isn't moved.
mOwner->setTransform(mState.getTransform());
// If we're doing server simulation then we need
// to send the client a state update.
if (isServerObject() && mPhysicsRep && !smNoCorrections &&
!PHYSICSMGR->isSinglePlayer() // SINGLE PLAYER HACK!!!!
)
setMaskBits(StateMask);
}
PROFILE_END();
}
void RigidBodyComponent::findContact()
{
SceneObject *contactObject = NULL;
VectorF *contactNormal = new VectorF(0, 0, 0);
Vector<SceneObject*> overlapObjects;
mPhysicsRep->findContact(&contactObject, contactNormal, &overlapObjects);
if (!overlapObjects.empty())
{
//fire our signal that the physics sim said collisions happened
onPhysicsCollision.trigger(*contactNormal, overlapObjects);
}
}
void RigidBodyComponent::_onPhysicsReset(PhysicsResetEvent reset)
{
if (reset == PhysicsResetEvent_Store)
mResetPos = mOwner->getTransform();
else if (reset == PhysicsResetEvent_Restore)
{
mOwner->setTransform(mResetPos);
}
}
void RigidBodyComponent::storeRestorePos()
{
mResetPos = mOwner->getTransform();
}
void RigidBodyComponent::applyImpulse(const Point3F &pos, const VectorF &vec)
{
if (mPhysicsRep && mPhysicsRep->isDynamic())
mPhysicsRep->applyImpulse(pos, vec);
}
void RigidBodyComponent::applyRadialImpulse(const Point3F &origin, F32 radius, F32 magnitude)
{
if (!mPhysicsRep || !mPhysicsRep->isDynamic())
return;
// TODO: Find a better approximation of the
// force vector using the object box.
VectorF force = mOwner->getWorldBox().getCenter() - origin;
F32 dist = force.magnitudeSafe();
force.normalize();
if (dist == 0.0f)
force *= magnitude;
else
force *= mClampF(radius / dist, 0.0f, 1.0f) * magnitude;
mPhysicsRep->applyImpulse(origin, force);
// TODO: There is no simple way to really sync this sort of an
// event with the client.
//
// The best is to send the current physics snapshot, calculate the
// time difference from when this event occured and the time when the
// client recieves it, and then extrapolate where it should be.
//
// Even then its impossible to be absolutely sure its synced.
//
// Bottom line... you shouldn't use physics over the network like this.
//
}
void RigidBodyComponent::updateContainerForces()
{
PROFILE_SCOPE(RigidBodyComponent_updateContainerForces);
// If we're not simulating don't update forces.
PhysicsWorld *world = PHYSICSMGR->getWorld(isServerObject() ? "server" : "client");
if (!world || !world->isEnabled())
return;
ContainerQueryInfo info;
info.box = mOwner->getWorldBox();
info.mass = mMass;
// Find and retreive physics info from intersecting WaterObject(s)
mOwner->getContainer()->findObjects(mOwner->getWorldBox(), WaterObjectType | PhysicalZoneObjectType, findRouter, &info);
// Calculate buoyancy and drag
F32 angDrag = mAngularDamping;
F32 linDrag = mLinearDamping;
F32 buoyancy = 0.0f;
Point3F cmass = mPhysicsRep->getCMassPosition();
F32 density = mBuoyancyDensity;
if (density > 0.0f)
{
if (info.waterCoverage > 0.0f)
{
F32 waterDragScale = info.waterViscosity * mWaterDampingScale;
F32 powCoverage = mPow(info.waterCoverage, 0.25f);
angDrag = mLerp(angDrag, angDrag * waterDragScale, powCoverage);
linDrag = mLerp(linDrag, linDrag * waterDragScale, powCoverage);
}
buoyancy = (info.waterDensity / density) * mPow(info.waterCoverage, 2.0f);
// A little hackery to prevent oscillation
// Based on this blog post:
// (http://reinot.blogspot.com/2005/11/oh-yes-they-float-georgie-they-all.html)
// JCF: disabled!
Point3F buoyancyForce = buoyancy * -world->getGravity() * TickSec * mMass;
mPhysicsRep->applyImpulse(cmass, buoyancyForce);
}
// Update the dampening as the container might have changed.
mPhysicsRep->setDamping(linDrag, angDrag);
// Apply physical zone forces.
if (!info.appliedForce.isZero())
mPhysicsRep->applyImpulse(cmass, info.appliedForce);
}
| 31.595289
| 148
| 0.681261
|
John3
|
21ed3f17619794aef95953a386f528f7ea2f97a7
| 1,335
|
cpp
|
C++
|
Sort/heap_sort_src/heap_sort.cpp
|
yichenluan/Algorithm101
|
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
|
[
"MIT"
] | 1
|
2018-10-30T10:02:11.000Z
|
2018-10-30T10:02:11.000Z
|
Sort/heap_sort_src/heap_sort.cpp
|
yichenluan/Algorithm101
|
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
|
[
"MIT"
] | null | null | null |
Sort/heap_sort_src/heap_sort.cpp
|
yichenluan/Algorithm101
|
a516fa5dad34ed431fa6fb2efab7bce4a90213bc
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <iostream>
using namespace std;
template<class It>
void printByIt(It begin, It end);
template<class It>
void printByIt(It begin, It end) {
for (It curr = begin; curr != end; ++curr) {
cout << *curr << " ";
}
cout << endl;
}
void sink(vector<int>& a, int k, int N) {
int child = 2 * (k+1) - 1;
while (child <= N) {
if (child < N && a[child] < a[child+1]) {
child++;
}
if (a[k] >= a[child]) {
break;
}
swap(a[k], a[child]);
k = child;
child = 2 *(k+1) - 1;
}
}
void heap_sort(vector<int>& a) {
int N = a.size() - 1;
for (int k = N/2; k >= 0; --k) {
sink(a, k, N);
}
while (N > 0) {
swap(a[0], a[N--]);
sink(a, 0, N);
}
}
int main() {
//vector<int> unorder = {5, 4, 3, 4, 1, 4, 2};
//vector<int> unorder = { 2, 4, 3, 1};
//vector<int> unorder = {5, 4, 9, 4, 7, 4, 2};
//vector<int> unorder = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
//vector<int> unorder = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
//vector<int> unorder = { 3, 2, 1};
vector<int> unorder;
cout << "before order: ";
printByIt(unorder.begin(), unorder.end());
heap_sort(unorder);
cout << "after order: ";
printByIt(unorder.begin(), unorder.end());
}
| 22.25
| 60
| 0.468914
|
yichenluan
|
21ee74d06c68e18c398f9bb4c9583345361f9456
| 60
|
hpp
|
C++
|
src/boost_spirit_home_support_nonterminal_locals.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_spirit_home_support_nonterminal_locals.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_spirit_home_support_nonterminal_locals.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/spirit/home/support/nonterminal/locals.hpp>
| 30
| 59
| 0.816667
|
miathedev
|
21fb53a330953c1ce3974576a63b90ad5df83880
| 4,214
|
hpp
|
C++
|
include/ndtree/algorithm/node_neighbors.hpp
|
gnzlbg/htree
|
30e29145b6b0b0f4d1106f05376df94bd58cadc9
|
[
"BSL-1.0"
] | 15
|
2015-09-02T13:25:55.000Z
|
2021-04-23T04:02:19.000Z
|
include/ndtree/algorithm/node_neighbors.hpp
|
gnzlbg/htree
|
30e29145b6b0b0f4d1106f05376df94bd58cadc9
|
[
"BSL-1.0"
] | 1
|
2015-11-18T03:50:18.000Z
|
2016-06-16T08:34:01.000Z
|
include/ndtree/algorithm/node_neighbors.hpp
|
gnzlbg/htree
|
30e29145b6b0b0f4d1106f05376df94bd58cadc9
|
[
"BSL-1.0"
] | 4
|
2016-05-20T18:57:27.000Z
|
2019-03-17T09:18:13.000Z
|
#pragma once
/// \file node_neighbors.hpp
#include <ndtree/algorithm/node_location.hpp>
#include <ndtree/algorithm/node_or_parent_at.hpp>
#include <ndtree/algorithm/shift_location.hpp>
#include <ndtree/concepts.hpp>
#include <ndtree/location/default.hpp>
#include <ndtree/relations/neighbor.hpp>
#include <ndtree/types.hpp>
#include <ndtree/utility/static_const.hpp>
#include <ndtree/utility/stack_vector.hpp>
namespace ndtree {
inline namespace v1 {
//
struct node_neighbors_fn {
/// Finds neighbors of node at location \p loc across the Manifold
/// (appends them to a push_back-able container)
template <typename Manifold, typename Tree, typename Loc,
typename PushBackableContainer, CONCEPT_REQUIRES_(Location<Loc>{})>
auto operator()(Manifold positions, Tree const& t, Loc&& loc,
PushBackableContainer& s) const noexcept -> void {
static_assert(Tree::dimension() == ranges::uncvref_t<Loc>::dimension(), "");
// For all same level neighbor positions
for (auto&& sl_pos : positions()) {
auto neighbor
= node_or_parent_at(t, shift_location(loc, positions[sl_pos]));
if (!neighbor.idx) { continue; }
NDTREE_ASSERT((neighbor.level == loc.level())
|| (neighbor.level == (loc.level() - 1)),
"found neighbor must either be at the same level or at the "
"parent level");
// if the neighbor found is a leaf node we are done
// note: it is either at the same or parent level of the node
// (doesn't matter which case it is, it is the correct neighbor)
if (t.is_leaf(neighbor.idx)) {
s.push_back(neighbor.idx);
} else {
// if it has children we add the children sharing a face with the node
for (auto&& cp : Manifold{}.children_sharing_face(sl_pos)) {
s.push_back(t.child(neighbor.idx, cp));
}
}
}
}
/// Finds neighbors of node at location \p loc across the Manifold
///
/// \returns stack allocated vector containing the neighbors
template <typename Manifold, typename Tree, typename Loc,
int max_no_neighbors = Manifold::no_child_level_neighbors(),
CONCEPT_REQUIRES_(Location<Loc>{})>
auto operator()(Manifold, Tree const& t, Loc&& loc) const noexcept
-> stack_vector<node_idx, max_no_neighbors> {
static_assert(Tree::dimension() == ranges::uncvref_t<Loc>::dimension(), "");
stack_vector<node_idx, max_no_neighbors> neighbors;
(*this)(Manifold{}, t, loc, neighbors);
return neighbors;
}
/// Finds set of unique neighbors of node at location \p loc across all
/// manifolds
///
/// \param t [in] tree.
/// \param loc [in] location (location of the node).
/// \returns stack allocated vector containing the unique set of neighbors
///
template <typename Tree, typename Loc, int nd = Tree::dimension(),
CONCEPT_REQUIRES_(Location<Loc>{})>
auto operator()(Tree const& t, Loc&& loc) const noexcept
-> stack_vector<node_idx, max_no_neighbors(nd)> {
stack_vector<node_idx, max_no_neighbors(nd)> neighbors;
// For each surface manifold append the neighbors
using manifold_rng = meta::as_list<meta::integer_range<int, 1, nd + 1>>;
meta::for_each(manifold_rng{}, [&](auto m_) {
using manifold = manifold_neighbors<nd, decltype(m_){}>;
(*this)(manifold{}, t, loc, neighbors);
});
// sort them and remove dupplicates
ranges::sort(neighbors);
neighbors.erase(ranges::unique(neighbors), end(neighbors));
return neighbors;
}
/// Finds set of unique neighbors of node \p n across all manifolds
///
/// \param t [in] tree.
/// \param n [in] node index.
/// \returns stack allocated vector containing the unique set of neighbors
///
template <typename Tree,
typename Loc = location::default_location<Tree::dimension()>,
CONCEPT_REQUIRES_(Location<Loc>{})>
auto operator()(Tree const& t, node_idx n, Loc l = Loc{}) const noexcept {
return (*this)(t, node_location(t, n, l));
}
};
namespace {
constexpr auto&& node_neighbors = static_const<node_neighbors_fn>::value;
} // namespace
} // namespace v1
} // namespace ndtree
| 38.66055
| 80
| 0.665638
|
gnzlbg
|
21fd4bc267f14b60f09e459e847e00fd01369c86
| 995
|
cpp
|
C++
|
Arrays/moveposneg.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | 4
|
2020-12-29T09:27:10.000Z
|
2022-02-12T14:20:23.000Z
|
Arrays/moveposneg.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | 1
|
2021-11-27T06:15:28.000Z
|
2021-11-27T06:15:28.000Z
|
Arrays/moveposneg.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | 1
|
2021-11-17T21:42:57.000Z
|
2021-11-17T21:42:57.000Z
|
/*
Move all negative numbers to beginning and positive to end with constant extra space
Input: -12, 11, -13, -5, 6, -7, 5, -3, -6
Output: -12 -13 -5 -7 -3 -6 11 6 5
https://www.geeksforgeeks.org/move-negative-numbers-beginning-positive-end-constant-extra-space/
*/
#include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0; i<n; i++){
cin>>arr[i];
}
//two pointer approach
int left = 0, right = n-1;
while(left <= right){
if(arr[left] < 0 && arr[right] < 0)
left++;
else if(arr[left] > 0 && arr[right] < 0){
swap(arr[left], arr[right]);
left++; right--;
}
else if(arr[left] > 0 && arr[right] > 0){
right--;
}
else if(arr[left] < 0 && arr[right] > 0){
left++;
right--;
}
}
//display the array
for(int i=0; i<n; i++)
cout<<arr[i]<<" ";
cout<<endl;
return 0;
}
| 21.170213
| 96
| 0.491457
|
thisisnitish
|
1d019fde0e400dd85407182f3575e568a42677b0
| 1,127
|
cpp
|
C++
|
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
|
HeadClot/ue4-rts
|
53499c49942aada835b121c89419aaa0be624cbd
|
[
"MIT"
] | 617
|
2017-04-16T13:34:20.000Z
|
2022-03-31T23:43:47.000Z
|
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
|
freezernick/ue4-rts
|
14ac47ce07d920c01c999f78996791c75de8ff8a
|
[
"MIT"
] | 178
|
2017-04-05T19:30:21.000Z
|
2022-03-11T05:44:03.000Z
|
Source/RTSProject/Plugins/RealTimeStrategy/Source/RealTimeStrategy/Private/Libraries/RTSConstructionLibrary.cpp
|
freezernick/ue4-rts
|
14ac47ce07d920c01c999f78996791c75de8ff8a
|
[
"MIT"
] | 147
|
2017-06-27T08:35:09.000Z
|
2022-03-28T03:06:17.000Z
|
#include "Libraries/RTSConstructionLibrary.h"
#include "Construction/RTSBuilderComponent.h"
int32 URTSConstructionLibrary::GetConstructableBuildingIndex(AActor* Builder, TSubclassOf<AActor> BuildingClass)
{
if (!IsValid(Builder))
{
return INDEX_NONE;
}
URTSBuilderComponent* BuilderComponent = Builder->FindComponentByClass<URTSBuilderComponent>();
if (!IsValid(BuilderComponent))
{
return INDEX_NONE;
}
return BuilderComponent->GetConstructibleBuildingClasses().IndexOfByKey(BuildingClass);
}
TSubclassOf<AActor> URTSConstructionLibrary::GetConstructableBuildingClass(AActor* Builder, int32 BuildingIndex)
{
if (!IsValid(Builder))
{
return nullptr;
}
URTSBuilderComponent* BuilderComponent = Builder->FindComponentByClass<URTSBuilderComponent>();
if (!IsValid(BuilderComponent))
{
return nullptr;
}
TArray<TSubclassOf<AActor>> ConstructableBuildings = BuilderComponent->GetConstructibleBuildingClasses();
return ConstructableBuildings.IsValidIndex(BuildingIndex) ? ConstructableBuildings[BuildingIndex] : nullptr;
}
| 28.175
| 112
| 0.753327
|
HeadClot
|
1d01d78a62b4b0e4ac4e5254e1866e2051263ade
| 710
|
hpp
|
C++
|
source/query_processor.hpp
|
simonenkos/dnsperf
|
85f8ba97b9a85cf84b2d87610f829d526af459f8
|
[
"MIT"
] | null | null | null |
source/query_processor.hpp
|
simonenkos/dnsperf
|
85f8ba97b9a85cf84b2d87610f829d526af459f8
|
[
"MIT"
] | null | null | null |
source/query_processor.hpp
|
simonenkos/dnsperf
|
85f8ba97b9a85cf84b2d87610f829d526af459f8
|
[
"MIT"
] | null | null | null |
#ifndef DNSPERF_QUERY_PROCESSOR_HPP
#define DNSPERF_QUERY_PROCESSOR_HPP
#include <string>
#include <cstdint>
#include "query_result.hpp"
/**
* Interface of processor which is responsible for making a query.
*/
struct query_processor
{
query_processor() = default;
query_processor(const query_processor & other) = default;
query_processor( query_processor && other) = default;
query_processor & operator=(const query_processor & other) = default;
query_processor & operator=( query_processor && other) = default;
virtual ~query_processor() = default;
virtual query_result process(const std::string & url) const = 0;
};
#endif //DNSPERF_QUERY_PROCESSOR_HPP
| 25.357143
| 73
| 0.725352
|
simonenkos
|
1d0af241a2faaa6acd1f66644a479013f931bef4
| 868
|
cpp
|
C++
|
src/lib/MutexBase.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/MutexBase.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
src/lib/MutexBase.cpp
|
romoadri21/boi
|
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
|
[
"BSD-3-Clause"
] | null | null | null |
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved.
* This code is licensed under a BSD-style license that can be
* found in the LICENSE file. The license can also be found at:
* http://www.boi-project.org/license
*/
#include "ThreadLockData.h"
#include "Mutex.h"
#include "MutexBase.h"
namespace BOI {
MutexBase::MutexBase()
: m_mutexId(0),
m_lockData()
{
}
void MutexBase::Attach(Mutex* pMutex)
{
pMutex->m_pBase = this;
pMutex->m_pMutex = &m_mutexes[m_mutexId];
m_mutexId = (m_mutexId + 1) % BOI_MUTEXBASE_MAX_QMUTEXES;
}
ThreadLockData* MutexBase::GetData()
{
ThreadLockData* pThreadLockData = m_lockData.localData();
if (pThreadLockData == NULL)
{
pThreadLockData = new ThreadLockData;
m_lockData.setLocalData(pThreadLockData);
}
return pThreadLockData;
}
} // namespace BOI
| 18.869565
| 63
| 0.686636
|
romoadri21
|
1d0bd93afc7c766106a533846cefcae4e2fd40c8
| 3,426
|
cc
|
C++
|
src/server_main.cc
|
magazino/tf_service
|
da63e90b062a57eb1280b589ef8f249be5d422c4
|
[
"Apache-2.0"
] | 17
|
2019-12-11T14:26:21.000Z
|
2022-01-30T03:41:40.000Z
|
src/server_main.cc
|
magazino/tf_service
|
da63e90b062a57eb1280b589ef8f249be5d422c4
|
[
"Apache-2.0"
] | 8
|
2019-12-13T14:45:32.000Z
|
2022-02-14T16:22:30.000Z
|
src/server_main.cc
|
magazino/tf_service
|
da63e90b062a57eb1280b589ef8f249be5d422c4
|
[
"Apache-2.0"
] | 2
|
2020-07-29T08:47:50.000Z
|
2021-12-13T10:38:39.000Z
|
// Copyright 2019 Magazino GmbH
//
// 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
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <memory>
#include <thread>
#include "ros/ros.h"
#include "tf_service/buffer_server.h"
#include "boost/program_options.hpp"
namespace po = boost::program_options;
int main(int argc, char** argv) {
int num_threads = 0;
po::options_description desc("Options");
// clang-format off
desc.add_options()
("help", "show usage")
("num_threads", po::value<int>(&num_threads)->default_value(0),
"Number of handler threads. 0 means number of CPU cores.")
("cache_time", po::value<double>(),
"Buffer cache time of the underlying TF buffer in seconds.")
("max_timeout", po::value<double>(),
"Requests with lookup timeouts (seconds) above this will be blocked.")
("frames_service", "Advertise the tf2_frames service.")
("debug", "Advertise the tf2_frames service (same as --frames_service).")
("add_legacy_server", "If set, also run a tf2_ros::BufferServer.")
("legacy_server_namespace", po::value<std::string>(),
"Use a separate namespace for the legacy action server.")
;
// clang-format on
po::variables_map vm;
try {
po::store(po::parse_command_line(argc, argv, desc), vm);
} catch (const po::error& exception) {
std::cerr << exception.what() << std::endl;
return EXIT_FAILURE;
}
po::notify(vm);
if (vm.count("help")) {
std::cout << desc << std::endl;
return EXIT_FAILURE;
}
ros::init(argc, argv, "tf_service");
// boost::po overflows unsigned int for negative values passed to argv,
// so we use a signed one and check manually.
if (num_threads < 0) {
ROS_ERROR("The number of threads can't be negative.");
return EXIT_FAILURE;
} else if (num_threads == 0) {
ROS_INFO_STREAM("--num_threads unspecified / zero, using available cores.");
num_threads = std::thread::hardware_concurrency();
}
tf_service::ServerOptions options;
if (vm.count("cache_time"))
options.cache_time = ros::Duration(vm["cache_time"].as<double>());
if (vm.count("max_timeout"))
options.max_timeout = ros::Duration(vm["max_timeout"].as<double>());
options.debug = vm.count("frames_service") || vm.count("debug");
options.add_legacy_server = vm.count("add_legacy_server");
options.legacy_server_namespace =
vm.count("legacy_server_namespace")
? vm["legacy_server_namespace"].as<std::string>()
: ros::this_node::getName();
ROS_INFO_STREAM("Starting server with " << num_threads << " handler threads");
ROS_INFO_STREAM_COND(options.add_legacy_server,
"Also starting a legacy tf2::BufferServer in namespace "
<< options.legacy_server_namespace);
tf_service::Server server(options);
ros::AsyncSpinner spinner(num_threads);
spinner.start();
ros::waitForShutdown();
spinner.stop();
return EXIT_SUCCESS;
}
| 36.063158
| 80
| 0.686223
|
magazino
|
1d0ebd650e004eb8f4e81f6a905b6b1723f5f9f7
| 63,741
|
cpp
|
C++
|
src/plugin/kernel/src/AFCKernelModule.cpp
|
ArkGame/ArkGameFrame
|
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
|
[
"Apache-2.0"
] | 168
|
2016-08-18T07:24:48.000Z
|
2018-02-06T06:40:45.000Z
|
src/plugin/kernel/src/AFCKernelModule.cpp
|
Mu-L/ARK
|
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
|
[
"Apache-2.0"
] | 11
|
2019-05-27T12:26:02.000Z
|
2021-05-12T02:45:16.000Z
|
src/plugin/kernel/src/AFCKernelModule.cpp
|
ArkGame/ArkGameFrame
|
a7f8413dd416cd1ac5b12adbdd84f010f59f11e2
|
[
"Apache-2.0"
] | 51
|
2016-09-01T10:17:38.000Z
|
2018-02-06T10:45:25.000Z
|
/*
* This source file is part of ARK
* For the latest info, see https://github.com/ArkNX
*
* Copyright (c) 2013-2020 ArkNX authors.
*
* Licensed under the Apache License, Version 2.0 (the "License"),
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "base/AFDefine.hpp"
#include "kernel/include/AFCKernelModule.hpp"
#include "kernel/include/AFCEntity.hpp"
#include "kernel/include/AFCTable.hpp"
#include "kernel/include/AFCDataList.hpp"
#include "kernel/include/AFCContainer.hpp"
namespace ark {
AFCKernelModule::AFCKernelModule()
{
inner_nodes_.AddElement(AFEntityMetaBaseEntity::config_id(), ARK_NEW int32_t(0));
inner_nodes_.AddElement(AFEntityMetaBaseEntity::class_name(), ARK_NEW int32_t(0));
inner_nodes_.AddElement(AFEntityMetaBaseEntity::map_id(), ARK_NEW int32_t(0));
inner_nodes_.AddElement(AFEntityMetaBaseEntity::map_inst_id(), ARK_NEW int32_t(0));
}
AFCKernelModule::~AFCKernelModule()
{
objects_.clear();
}
bool AFCKernelModule::Init()
{
delete_list_.clear();
m_pMapModule = FindModule<AFIMapModule>();
m_pClassModule = FindModule<AFIClassMetaModule>();
m_pConfigModule = FindModule<AFIConfigModule>();
m_pGUIDModule = FindModule<AFIGUIDModule>();
auto container_func = std::bind(&AFCKernelModule::OnContainerCallBack, this, std::placeholders::_1,
std::placeholders::_2, std::placeholders::_3, std::placeholders::_4, std::placeholders::_5);
AddCommonContainerCallBack(std::move(container_func), 999999); // after other callbacks being done
AddSyncCallBack();
return true;
}
bool AFCKernelModule::Update()
{
cur_exec_object_ = NULL_GUID;
if (!delete_list_.empty())
{
for (auto it : delete_list_)
{
DestroyEntity(it);
}
delete_list_.clear();
}
for (auto& iter : objects_)
{
auto pEntity = iter.second;
if (pEntity == nullptr)
{
continue;
}
pEntity->Update();
}
AFClassCallBackManager::OnDelaySync();
return true;
}
bool AFCKernelModule::PreShut()
{
return DestroyAll();
}
bool AFCKernelModule::CopyData(std::shared_ptr<AFIEntity> pEntity, std::shared_ptr<AFIStaticEntity> pStaticEntity)
{
if (pEntity == nullptr || nullptr == pStaticEntity)
{
return false;
}
// static node manager must be not empty
auto pStaticNodeManager = GetNodeManager(pStaticEntity);
if (pStaticNodeManager == nullptr || pStaticNodeManager->IsEmpty())
{
return false;
}
// node manager must be empty
auto pNodeManager = GetNodeManager(pEntity);
if (pNodeManager == nullptr || !pNodeManager->IsEmpty())
{
return false;
}
// copy data
auto& data_list = pStaticNodeManager->GetDataList();
for (auto& iter : data_list)
{
auto pData = iter.second;
pNodeManager->CreateData(pData);
}
return true;
}
std::shared_ptr<AFIEntity> AFCKernelModule::CreateEntity(const guid_t& self, const int map_id,
const int map_instance_id, const std::string& class_name, const ID_TYPE config_id, const AFIDataList& args)
{
guid_t object_id = self;
auto pMapInfo = m_pMapModule->GetMapInfo(map_id);
if (pMapInfo == nullptr)
{
ARK_LOG_ERROR("There is no scene, scene = {}", map_id);
return nullptr;
}
if (!pMapInfo->ExistInstance(map_instance_id))
{
ARK_LOG_ERROR("There is no group, scene = {} group = {}", map_id, map_instance_id);
return nullptr;
}
auto pClassMeta = m_pClassModule->FindMeta(class_name);
if (nullptr == pClassMeta)
{
ARK_LOG_ERROR("There is no class meta, name = {}", class_name);
return nullptr;
}
std::shared_ptr<AFIStaticEntity> pStaticEntity = nullptr;
if (config_id > 0)
{
auto pStaticEntity = GetStaticEntity(config_id);
if (nullptr == pStaticEntity)
{
ARK_LOG_ERROR("There is no config, config_id = {}", config_id);
return nullptr;
}
if (pStaticEntity->GetClassName() != class_name)
{
ARK_LOG_ERROR("Config class does not match entity class, config_id = {}", config_id);
return nullptr;
}
}
// check args num
size_t arg_count = args.GetCount();
if (arg_count % 2 != 0)
{
ARK_LOG_ERROR("Args count is wrong, count = {}", arg_count);
return nullptr;
}
if (object_id == NULL_GUID)
{
object_id = m_pGUIDModule->CreateGUID();
}
// Check if the entity exists
if (GetEntity(object_id) != nullptr)
{
ARK_LOG_ERROR("The entity has existed, id = {}", object_id);
return nullptr;
}
std::shared_ptr<AFIEntity> pEntity =
std::make_shared<AFCEntity>(pClassMeta, object_id, config_id, map_id, map_instance_id, args);
objects_.insert(object_id, pEntity);
if (class_name == AFEntityMetaPlayer::self_name())
{
pMapInfo->AddEntityToInstance(map_instance_id, object_id, true);
}
//else if (class_name == AFEntityMetaPlayer::self_name()) // to do : npc type for now we do not have
//{
//}
CopyData(pEntity, pStaticEntity);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args);
// original args here
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args);
return pEntity;
}
std::shared_ptr<AFIEntity> AFCKernelModule::CreateContainerEntity(
const guid_t& self, const uint32_t container_index, const std::string& class_name, const ID_TYPE config_id)
{
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("There is no object, object = {}", self);
return nullptr;
}
auto pContainer = pEntity->FindContainer(container_index);
if (pContainer == nullptr)
{
ARK_LOG_ERROR("There is no container, container = {}", container_index);
return nullptr;
}
auto pClassMeta = m_pClassModule->FindMeta(class_name);
if (nullptr == pClassMeta)
{
ARK_LOG_ERROR("There is no class meta, name = {}", class_name);
return nullptr;
}
std::shared_ptr<AFIStaticEntity> pStaticEntity = nullptr;
if (config_id > 0)
{
auto pStaticEntity = GetStaticEntity(config_id);
if (nullptr == pStaticEntity)
{
ARK_LOG_ERROR("There is no config, config_id = {}", config_id);
return nullptr;
}
if (pStaticEntity->GetClassName() != class_name)
{
ARK_LOG_ERROR("Config class does not match entity class, config_id = {}", config_id);
return nullptr;
}
}
auto map_id = pEntity->GetMapID();
auto pMapInfo = m_pMapModule->GetMapInfo(map_id);
if (pMapInfo == nullptr)
{
ARK_LOG_ERROR("There is no scene, scene = {}", map_id);
return nullptr;
}
auto map_instance_id = pEntity->GetMapEntityID();
if (!pMapInfo->ExistInstance(map_instance_id))
{
ARK_LOG_ERROR("There is no group, scene = {} group = {}", map_id, map_instance_id);
return nullptr;
}
guid_t object_id = m_pGUIDModule->CreateGUID();
// Check if the entity exists
if (GetEntity(object_id) != nullptr)
{
ARK_LOG_ERROR("The entity has existed, id = {}", object_id);
return nullptr;
}
std::shared_ptr<AFIEntity> pContainerEntity =
std::make_shared<AFCEntity>(pClassMeta, object_id, config_id, map_id, map_instance_id, AFCDataList());
objects_.insert(object_id, pContainerEntity);
CopyData(pContainerEntity, pStaticEntity);
pContainer->Place(pContainerEntity);
AFCDataList args;
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args);
DoEvent(object_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args);
return pContainerEntity;
}
std::shared_ptr<AFIStaticEntity> AFCKernelModule::GetStaticEntity(const ID_TYPE config_id)
{
return m_pConfigModule->FindStaticEntity(config_id);
}
std::shared_ptr<AFIEntity> AFCKernelModule::GetEntity(const guid_t& self)
{
return objects_.find_value(self);
}
bool AFCKernelModule::DestroyAll()
{
for (auto& iter : objects_)
{
auto& pEntity = iter.second;
if (pEntity->GetParentContainer() != nullptr)
{
continue;
}
delete_list_.push_back(iter.second->GetID());
}
// run another frame
Update();
return true;
}
bool AFCKernelModule::DestroyEntity(const guid_t& self)
{
if (self == cur_exec_object_ && self != NULL_GUID)
{
return DestroySelf(self);
}
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("Cannot find this object, self={}", NULL_GUID);
return false;
}
auto pParentContainer = pEntity->GetParentContainer();
if (pParentContainer)
{
// use container to destroy its entity
return pParentContainer->Destroy(self);
}
else
{
return InnerDestroyEntity(pEntity);
}
}
bool AFCKernelModule::DestroySelf(const guid_t& self)
{
delete_list_.push_back(self);
return true;
}
bool AFCKernelModule::InnerDestroyEntity(std::shared_ptr<AFIEntity> pEntity)
{
if (pEntity == nullptr)
{
ARK_LOG_ERROR("Cannot find this object, self={}", NULL_GUID);
return false;
}
auto& self = pEntity->GetID();
int32_t map_id = pEntity->GetMapID();
int32_t inst_id = pEntity->GetMapEntityID();
std::shared_ptr<AFMapInfo> pMapInfo = m_pMapModule->GetMapInfo(map_id);
if (pMapInfo != nullptr)
{
const std::string& class_name = pEntity->GetClassName();
pMapInfo->RemoveEntityFromInstance(
inst_id, self, ((class_name == AFEntityMetaPlayer::self_name()) ? true : false));
DoEvent(self, class_name, ArkEntityEvent::ENTITY_EVT_PRE_DESTROY, AFCDataList());
DoEvent(self, class_name, ArkEntityEvent::ENTITY_EVT_DESTROY, AFCDataList());
return objects_.erase(self);
}
else
{
ARK_LOG_ERROR("Cannot find this map, object_id={} map={} inst={}", self, map_id, inst_id);
return false;
}
}
bool AFCKernelModule::AddEventCallBack(const guid_t& self, const int nEventID, EVENT_PROCESS_FUNCTOR&& cb)
{
std::shared_ptr<AFIEntity> pEntity = GetEntity(self);
ARK_ASSERT_RET_VAL(pEntity != nullptr, false);
auto pEventManager = GetEventManager(pEntity);
ARK_ASSERT_RET_VAL(pEventManager != nullptr, false);
return pEventManager->AddEventCallBack(nEventID, std::move(cb));
}
bool AFCKernelModule::AddClassCallBack(const std::string& class_name, CLASS_EVENT_FUNCTOR&& cb, const int32_t prio)
{
return m_pClassModule->AddClassCallBack(class_name, std::move(cb), prio);
}
bool AFCKernelModule::AddNodeCallBack(
const std::string& class_name, const std::string& name, DATA_NODE_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(class_name);
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto index = pClassMeta->GetIndex(name);
if (index == 0)
{
return false;
}
AddNodeCallBack(class_name, index, std::move(cb), prio);
return true;
}
bool AFCKernelModule::AddTableCallBack(
const std::string& class_name, const std::string& name, DATA_TABLE_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(class_name);
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto index = pClassMeta->GetIndex(name);
if (index == 0)
{
return false;
}
AddTableCallBack(class_name, index, std::move(cb), prio);
return true;
}
bool AFCKernelModule::AddNodeCallBack(
const std::string& class_name, const uint32_t index, DATA_NODE_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(class_name);
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto pDataMeta = pClassMeta->FindDataMeta(index);
ARK_ASSERT_RET_VAL(pDataMeta != nullptr, false);
auto pCallBack = pClassMeta->GetClassCallBackManager();
ARK_ASSERT_RET_VAL(pCallBack != nullptr, false);
pCallBack->AddDataCallBack(index, std::move(cb), prio);
return true;
}
bool AFCKernelModule::AddTableCallBack(
const std::string& class_name, const uint32_t index, DATA_TABLE_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(class_name);
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto pTableMeta = pClassMeta->FindTableMeta(index);
ARK_ASSERT_RET_VAL(pTableMeta != nullptr, false);
auto pCallBack = pClassMeta->GetClassCallBackManager();
ARK_ASSERT_RET_VAL(pCallBack != nullptr, false);
pCallBack->AddTableCallBack(index, std::move(cb), prio);
return true;
}
bool AFCKernelModule::AddContainerCallBack(
const std::string& class_name, const uint32_t index, CONTAINER_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(class_name);
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto pContainerMeta = pClassMeta->FindContainerMeta(index);
ARK_ASSERT_RET_VAL(pContainerMeta != nullptr, false);
auto pCallBack = pClassMeta->GetClassCallBackManager();
ARK_ASSERT_RET_VAL(pCallBack != nullptr, false);
pCallBack->AddContainerCallBack(index, std::move(cb), prio);
return true;
}
bool AFCKernelModule::AddCommonContainerCallBack(CONTAINER_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(AFEntityMetaPlayer::self_name());
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto& meta_list = pClassMeta->GetContainerMetaList();
for (auto& iter : meta_list)
{
auto pMeta = iter.second;
if (!pMeta)
{
continue;
}
AddContainerCallBack(AFEntityMetaPlayer::self_name(), pMeta->GetIndex(), std::move(cb), prio);
}
return true;
}
bool AFCKernelModule::AddCommonClassEvent(CLASS_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto& class_meta_list = m_pClassModule->GetMetaList();
for (auto& iter : class_meta_list)
{
auto pClassMeta = iter.second;
if (nullptr == pClassMeta)
{
continue;
}
AddClassCallBack(iter.first, std::move(cb), prio);
}
return true;
}
bool AFCKernelModule::AddLeaveSceneEvent(const std::string& class_name, SCENE_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(class_name);
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto pCallBack = pClassMeta->GetClassCallBackManager();
ARK_ASSERT_RET_VAL(pCallBack != nullptr, false);
return pCallBack->AddLeaveSceneEvent(std::move(cb), prio);
}
bool AFCKernelModule::AddEnterSceneEvent(const std::string& class_name, SCENE_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(class_name);
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto pCallBack = pClassMeta->GetClassCallBackManager();
ARK_ASSERT_RET_VAL(pCallBack != nullptr, false);
return pCallBack->AddEnterSceneEvent(std::move(cb), prio);
}
bool AFCKernelModule::AddMoveEvent(const std::string& class_name, MOVE_EVENT_FUNCTOR&& cb, const int32_t prio)
{
auto pClassMeta = m_pClassModule->FindMeta(class_name);
ARK_ASSERT_RET_VAL(pClassMeta != nullptr, false);
auto pCallBack = pClassMeta->GetClassCallBackManager();
ARK_ASSERT_RET_VAL(pCallBack != nullptr, false);
return pCallBack->AddMoveEvent(std::move(cb), prio);
}
void AFCKernelModule::AddSyncCallBack()
{
// node sync call back
auto node_func = std::bind(&AFCKernelModule::OnSyncNode, this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4);
AFClassCallBackManager::AddNodeSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(node_func));
AFClassCallBackManager::AddNodeSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(node_func));
// table sync call back
auto table_func = std::bind(&AFCKernelModule::OnSyncTable, this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4);
AFClassCallBackManager::AddTableSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(table_func));
AFClassCallBackManager::AddTableSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(table_func));
// container sync call back
auto container_func =
std::bind(&AFCKernelModule::OnSyncContainer, this, std::placeholders::_1, std::placeholders::_2,
std::placeholders::_3, std::placeholders::_4, std::placeholders::_5, std::placeholders::_6);
AFClassCallBackManager::AddContainerSyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(container_func));
AFClassCallBackManager::AddContainerSyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(container_func));
// data delay call back
auto delay_func = std::bind(
&AFCKernelModule::OnDelaySyncData, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
AFClassCallBackManager::AddDelaySyncCallBack(ArkDataMask::PF_SYNC_VIEW, std::move(delay_func));
AFClassCallBackManager::AddDelaySyncCallBack(ArkDataMask::PF_SYNC_SELF, std::move(delay_func));
// send msg functor
auto view_func = std::bind(&AFCKernelModule::SendToView, this, std::placeholders::_1, std::placeholders::_2);
sync_functors.insert(std::make_pair(ArkDataMask::PF_SYNC_VIEW, std::forward<SYNC_FUNCTOR>(view_func)));
auto self_func = std::bind(&AFCKernelModule::SendToSelf, this, std::placeholders::_1, std::placeholders::_2);
sync_functors.insert(std::make_pair(ArkDataMask::PF_SYNC_SELF, std::forward<SYNC_FUNCTOR>(self_func)));
}
int AFCKernelModule::OnSyncNode(
const guid_t& self, const uint32_t index, const ArkDataMask mask_value, const AFIData& data)
{
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync node failed entity do no exist, self={}", self);
return -1;
}
AFMsg::pb_entity pb_data;
auto entity_id = self;
auto pb_entity = pb_data.mutable_data();
auto pParentContainer = pEntity->GetParentContainer();
if (pParentContainer != nullptr)
{
if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity))
{
ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self);
return -1;
}
}
if (!NodeToPBData(index, data, pb_entity))
{
ARK_LOG_ERROR("node to pb failed, self={}, index={}", self, index);
return -1;
}
pb_data.set_id(entity_id);
if (SendSyncMsg(entity_id, mask_value, pb_data) < 0)
{
ARK_LOG_ERROR("send sync msg failed, self={}, index={}", entity_id, index);
return -1;
}
return 0;
}
int AFCKernelModule::OnSyncTable(
const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value, const AFIData& data)
{
ArkTableOpType op_type = static_cast<ArkTableOpType>(event.op_type_);
switch (op_type)
{
case ArkTableOpType::TABLE_ADD:
{
OnSyncTableAdd(self, event, mask_value);
}
break;
case ArkTableOpType::TABLE_DELETE:
{
OnSyncTableDelete(self, event, mask_value);
}
break;
case ArkTableOpType::TABLE_SWAP:
// do not have yet
break;
case ArkTableOpType::TABLE_UPDATE:
{
OnSyncTableUpdate(self, event, mask_value, data);
}
break;
case ArkTableOpType::TABLE_COVERAGE:
// will do something
break;
default:
break;
}
return 0;
}
int AFCKernelModule::OnSyncContainer(const guid_t& self, const uint32_t index, const ArkDataMask mask,
const ArkContainerOpType op_type, uint32_t src_index, uint32_t dest_index)
{
switch (op_type)
{
case ArkContainerOpType::OP_PLACE:
{
OnSyncContainerPlace(self, index, mask, src_index);
}
break;
case ArkContainerOpType::OP_REMOVE:
{
OnSyncContainerRemove(self, index, mask, src_index);
}
break;
case ArkContainerOpType::OP_DESTROY:
{
OnSyncContainerDestroy(self, index, mask, src_index);
}
break;
case ArkContainerOpType::OP_SWAP:
{
OnSyncContainerSwap(self, index, mask, src_index, dest_index);
}
break;
default:
break;
}
return 0;
}
int AFCKernelModule::OnDelaySyncData(const guid_t& self, const ArkDataMask mask_value, const AFDelaySyncData& data)
{
if (data.node_list_.size() == 0 && data.table_list_.size() == 0)
{
return 0;
}
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync delay data failed entity do no exist, self={}", self);
return -1;
}
AFMsg::pb_delay_entity pb_data;
auto entity_id = self;
auto pb_entity = pb_data.mutable_data();
auto pParentContainer = pEntity->GetParentContainer();
if (pParentContainer != nullptr)
{
if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity))
{
ARK_LOG_ERROR("sync delay data failed container entity do no exist, self={}", self);
return -1;
}
}
// node to pb
for (auto& iter : data.node_list_)
{
auto pNode = iter;
if (!NodeToPBData(pNode, pb_entity))
{
continue;
}
}
// table to pb
for (auto& iter : data.table_list_)
{
auto table_index = iter.first;
auto& table = iter.second;
DelayTableToPB(table, table_index, pb_data, *pb_entity);
}
// container to pb
for (auto& iter : data.container_list_)
{
auto container_index = iter.first;
auto& container = iter.second;
DelayContainerToPB(pEntity, container, container_index, pb_data);
}
pb_data.set_id(entity_id);
if (SendSyncMsg(entity_id, mask_value, pb_data) < 0)
{
ARK_LOG_ERROR("send sync msg failed, self={}", self);
return -1;
}
return 0;
}
int AFCKernelModule::OnSyncTableAdd(const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value)
{
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self);
return -1;
}
auto pTable = pEntity->FindTable(event.table_index_);
if (nullptr == pTable)
{
ARK_LOG_ERROR("sync table failed table do no exist, self={}, table={}", self, event.table_name_);
return -1;
}
auto pRow = pTable->FindRow(event.row_);
if (nullptr == pRow)
{
ARK_LOG_ERROR(
"sync table failed table row do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_);
return -1;
}
AFMsg::pb_entity_table_add pb_data;
auto entity_id = self;
auto pb_entity = pb_data.mutable_data();
auto pParentContainer = pEntity->GetParentContainer();
if (pParentContainer != nullptr)
{
if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity))
{
ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self);
return -1;
}
}
AFMsg::pb_entity_data pb_row;
if (!RowToPBData(pRow, event.row_, &pb_row))
{
ARK_LOG_ERROR(
"sync table failed table row do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_);
return -1;
}
AFMsg::pb_table pb_table;
pb_table.mutable_datas_value()->insert({event.row_, pb_row});
pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table});
pb_data.set_id(entity_id);
SendSyncMsg(entity_id, mask_value, pb_data);
return 0;
}
int AFCKernelModule::OnSyncTableDelete(const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value)
{
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self);
return -1;
}
AFMsg::pb_entity_table_delete pb_data;
auto entity_id = self;
auto pb_entity = pb_data.mutable_data();
auto pParentContainer = pEntity->GetParentContainer();
if (pParentContainer != nullptr)
{
if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity))
{
ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self);
return -1;
}
}
AFMsg::pb_entity_data pb_row;
AFMsg::pb_table pb_table;
pb_table.mutable_datas_value()->insert({event.row_, pb_row});
pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table});
SendSyncMsg(entity_id, mask_value, pb_data);
return 0;
}
int AFCKernelModule::OnSyncTableUpdate(
const guid_t& self, const TABLE_EVENT_DATA& event, const ArkDataMask mask_value, const AFIData& data)
{
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync table failed entity do no exist, self={}", self);
return -1;
}
AFMsg::pb_entity_table_update pb_data;
auto entity_id = self;
auto pb_entity = pb_data.mutable_data();
auto pParentContainer = pEntity->GetParentContainer();
if (pParentContainer != nullptr)
{
if (!TryAddContainerPBEntity(pParentContainer, self, *pb_data.mutable_data(), entity_id, pb_entity))
{
ARK_LOG_ERROR("sync node failed container entity do no exist, self={}", self);
return -1;
}
}
AFMsg::pb_entity_data pb_row;
if (!NodeToPBData(event.data_index_, data, &pb_row))
{
ARK_LOG_ERROR(
"sync table failed table node do no exist, self={}, table={}, row={}", self, event.table_name_, event.row_);
return -1;
}
AFMsg::pb_table pb_table;
pb_table.mutable_datas_value()->insert({event.row_, pb_row});
pb_entity->mutable_datas_table()->insert({event.table_index_, pb_table});
pb_data.set_id(entity_id);
SendSyncMsg(entity_id, mask_value, pb_data);
return 0;
}
int AFCKernelModule::OnSyncContainerPlace(
const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index)
{
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self);
return -1;
}
auto pContainer = pEntity->FindContainer(index);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync container failed container do no exist, self={}, container={}", self, index);
return -1;
}
auto pContainerEntity = pContainer->Find(src_index);
if (pContainerEntity == nullptr)
{
ARK_LOG_ERROR("sync container failed container entity do no exist, self={}, container={}, entity={}", self,
index, src_index);
return -1;
}
if (pContainerEntity->IsSent())
{
AFMsg::pb_container_place pb_data;
pb_data.set_id(self);
pb_data.set_index(index);
pb_data.set_entity_index(src_index);
pb_data.set_entity_id(pContainerEntity->GetID());
SendSyncMsg(self, mask, pb_data);
}
else
{
AFMsg::pb_container_create pb_data;
if (!EntityToPBData(pContainerEntity, pb_data.mutable_data()))
{
ARK_LOG_ERROR("sync container failed container entity to pb failed, self={}, container={}, entity={}", self,
index, src_index);
return -1;
}
pb_data.set_id(self);
pb_data.set_index(index);
pb_data.set_entity_index(src_index);
SendSyncMsg(self, mask, pb_data);
}
return 0;
}
int AFCKernelModule::OnSyncContainerRemove(
const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index)
{
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self);
return -1;
}
AFMsg::pb_container_remove pb_data;
pb_data.set_id(self);
pb_data.set_index(index);
pb_data.set_entity_index(src_index);
SendSyncMsg(self, mask, pb_data);
return 0;
}
int AFCKernelModule::OnSyncContainerDestroy(
const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index)
{
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self);
return -1;
}
AFMsg::pb_container_destroy pb_data;
pb_data.set_id(self);
pb_data.set_index(index);
pb_data.set_entity_index(src_index);
SendSyncMsg(self, mask, pb_data);
return 0;
}
int AFCKernelModule::OnSyncContainerSwap(
const guid_t& self, const uint32_t index, const ArkDataMask mask, uint32_t src_index, uint32_t dest_index)
{
// find parent entity
auto pEntity = GetEntity(self);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("sync container failed entity do no exist, self={}", self);
return -1;
}
AFMsg::pb_container_swap pb_data;
pb_data.set_id(self);
pb_data.set_index(index);
pb_data.set_src_index(src_index);
pb_data.set_dest_index(dest_index);
SendSyncMsg(self, mask, pb_data);
return 0;
}
bool AFCKernelModule::DelayTableToPB(
const AFDelaySyncTable& table, const uint32_t index, AFMsg::pb_delay_entity& data, AFMsg::pb_entity_data& pb_entity)
{
AFMsg::pb_table pb_table;
AFMsg::delay_clear_row clear_row_list;
for (auto& iter : table.row_list_)
{
AFMsg::pb_entity_data pb_row;
auto row_index = iter.first;
auto& row_data = iter.second;
for (auto& iter_row : row_data.node_list_)
{
auto pNode = iter_row;
if (NodeToPBData(pNode, &pb_row))
{
pb_table.mutable_datas_value()->insert({row_index, pb_row});
}
}
if (row_data.need_clear_)
{
clear_row_list.add_row_list(row_index);
}
}
if (table.need_clear_)
{
data.add_clear_tables(index);
}
if (clear_row_list.row_list_size() > 0)
{
data.mutable_clear_rows()->insert({index, clear_row_list});
}
pb_entity.mutable_datas_table()->insert({index, pb_table});
return true;
}
bool AFCKernelModule::DelayContainerToPB(std::shared_ptr<AFIEntity> pEntity, const AFDelaySyncContainer& container,
const uint32_t index, AFMsg::pb_delay_entity& data)
{
AFMsg::delay_container pb_delay_container;
AFMsg::pb_container pb_conatiner;
for (auto& iter : container.index_list_)
{
auto entity_index = iter;
auto pContaier = pEntity->FindContainer(index);
if (pContaier == nullptr)
{
continue;
}
auto pContainerEntity = pContaier->Find(entity_index);
if (pContainerEntity == nullptr)
{
pb_delay_container.mutable_entity_list()->insert({entity_index, NULL_GUID});
}
else if (pEntity->IsSent())
{
pb_delay_container.mutable_entity_list()->insert({entity_index, pContainerEntity->GetID()});
}
else
{
AFMsg::pb_entity pb_container_entity;
if (!EntityToPBData(pContainerEntity, &pb_container_entity))
{
continue;
}
pb_conatiner.mutable_datas_value()->insert({entity_index, pb_container_entity});
}
}
if (pb_conatiner.datas_value_size() > 0)
{
data.mutable_data()->mutable_datas_container()->insert({index, pb_conatiner});
}
data.mutable_container_entity()->insert({index, pb_delay_container});
AFMsg::delay_container pb_destroy_entity;
for (auto& iter : container.destroy_list_)
{
auto entity_index = iter;
pb_destroy_entity.mutable_entity_list()->insert({entity_index, NULL_GUID});
}
data.mutable_destroy_entity()->insert({index, pb_destroy_entity});
return true;
}
bool AFCKernelModule::TryAddContainerPBEntity(std::shared_ptr<AFIContainer> pContainer, const guid_t& self,
AFMsg::pb_entity_data& pb_entity_data, guid_t& parent_id, AFMsg::pb_entity_data*& pb_container_entity)
{
parent_id = pContainer->GetParentID();
auto pParentEntity = GetEntity(parent_id);
if (pParentEntity == nullptr)
{
ARK_LOG_ERROR("parent entity do no exist, parent={}", parent_id);
return false;
}
auto self_index = pContainer->Find(self);
if (self_index == 0)
{
ARK_LOG_ERROR("entity is not in container, self={}", self);
return false;
}
AFMsg::pb_container pb_container;
auto result_container = pb_entity_data.mutable_datas_container()->insert({pContainer->GetIndex(), pb_container});
if (!result_container.second)
{
ARK_LOG_ERROR("entity insert container failed, self={} container index = {}", self, pContainer->GetIndex());
return false;
}
auto& container = result_container.first->second;
AFMsg::pb_entity pb_entity;
auto result_entity = container.mutable_datas_value()->insert({self_index, pb_entity});
if (!result_entity.second)
{
ARK_LOG_ERROR("container insert entity failed, self={} container index = {}", self, pContainer->GetIndex());
return false;
}
auto& entity = result_entity.first->second;
pb_container_entity = entity.mutable_data();
return true;
}
int AFCKernelModule::SendSyncMsg(const guid_t& self, const ArkDataMask mask_value, const google::protobuf::Message& msg)
{
auto iter = sync_functors.find(mask_value);
if (iter == sync_functors.end())
{
return -1;
}
iter->second(self, msg);
return 0;
}
int AFCKernelModule::SendToView(const guid_t& self, const google::protobuf::Message& msg)
{
auto pEntity = GetEntity(self);
if (nullptr == pEntity)
{
return -1;
}
auto map_id = pEntity->GetMapID();
auto inst_id = pEntity->GetMapEntityID();
AFCDataList map_inst_entity_list;
m_pMapModule->GetInstEntityList(map_id, inst_id, map_inst_entity_list);
for (size_t i = 0; i < map_inst_entity_list.GetCount(); i++)
{
auto pViewEntity = GetEntity(map_inst_entity_list.Int64(i));
if (pViewEntity == nullptr)
{
continue;
}
const std::string& strObjClassName = pViewEntity->GetClassName();
if (AFEntityMetaPlayer::self_name() == strObjClassName)
{
SendToSelf(pViewEntity->GetID(), msg);
}
}
return 0;
}
int AFCKernelModule::SendToSelf(const guid_t& self, const google::protobuf::Message& msg)
{
//SendMsgPBToGate(AFMsg::EGMI_ACK_NODE_DATA, entity, ident);
return 0;
}
bool AFCKernelModule::DoEvent(
const guid_t& self, const std::string& class_name, ArkEntityEvent class_event, const AFIDataList& args)
{
return m_pClassModule->DoClassEvent(self, class_name, class_event, args);
}
bool AFCKernelModule::DoEvent(const guid_t& self, const int event_id, const AFIDataList& args)
{
std::shared_ptr<AFIEntity> pEntity = GetEntity(self);
ARK_ASSERT_RET_VAL(pEntity != nullptr, false);
auto pEventManager = GetEventManager(pEntity);
ARK_ASSERT_RET_VAL(pEventManager != nullptr, false);
return pEventManager->DoEvent(event_id, args);
}
bool AFCKernelModule::Exist(const guid_t& self)
{
return (objects_.find_value(self) != nullptr);
}
bool AFCKernelModule::LogSelfInfo(const guid_t& id)
{
return false;
}
int AFCKernelModule::LogObjectData(const guid_t& guid)
{
auto entity = GetEntity(guid);
if (entity == nullptr)
{
return -1;
}
auto pNodeManager = GetNodeManager(entity);
ARK_ASSERT_RET_VAL(pNodeManager != nullptr, -1);
auto pTableManager = GetTableManager(entity);
ARK_ASSERT_RET_VAL(pTableManager != nullptr, -1);
auto& node_list = pNodeManager->GetDataList();
for (auto& iter : node_list)
{
auto pData = iter.second;
if (!pData)
{
continue;
}
ARK_LOG_TRACE("Player[{}] Node[{}] Value[{}]", guid, pData->GetName(), pData->ToString());
}
auto& table_list = pTableManager->GetTableList();
for (auto& iter : table_list)
{
auto pTable = iter.second;
if (!pTable)
{
continue;
}
for (auto pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next())
{
auto pRowNodeManager = GetNodeManager(pRow);
if (!pRowNodeManager)
{
continue;
}
auto& row_data_list = pRowNodeManager->GetDataList();
for (auto& iter_row : row_data_list)
{
auto pNode = iter_row.second;
if (!pNode)
{
continue;
}
ARK_LOG_TRACE("Player[{}] Table[{}] Row[{}] Col[{}] Value[{}]", guid, pTable->GetName(), pRow->GetRow(),
pNode->GetName(), pNode->ToString());
}
}
}
return 0;
}
bool AFCKernelModule::LogInfo(const guid_t& id)
{
std::shared_ptr<AFIEntity> pEntity = GetEntity(id);
if (pEntity == nullptr)
{
ARK_LOG_ERROR("Cannot find entity, id = {}", id);
return false;
}
if (m_pMapModule->IsInMapInstance(id))
{
int map_id = pEntity->GetMapID();
ARK_LOG_INFO("----------child object list-------- , id = {} mapid = {}", id, map_id);
AFCDataList entity_list;
int online_count = m_pMapModule->GetMapOnlineList(map_id, entity_list);
for (int i = 0; i < online_count; ++i)
{
guid_t target_entity_id = entity_list.Int64(i);
ARK_LOG_INFO("id = {} mapid = {}", target_entity_id, map_id);
}
}
else
{
ARK_LOG_INFO("---------print object start--------, id = {}", id);
ARK_LOG_INFO("---------print object end--------, id = {}", id);
}
return true;
}
//--------------entity to pb db data------------------
bool AFCKernelModule::EntityToDBData(const guid_t& self, AFMsg::pb_db_entity& pb_data)
{
std::shared_ptr<AFIEntity> pEntity = GetEntity(self);
return EntityToDBData(pEntity, pb_data);
}
bool AFCKernelModule::EntityToDBData(std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_db_entity& pb_data)
{
ARK_ASSERT_RET_VAL(pEntity != nullptr, false);
auto pNodeManager = GetNodeManager(pEntity);
ARK_ASSERT_RET_VAL(pNodeManager != nullptr, false);
auto pTableManager = GetTableManager(pEntity);
ARK_ASSERT_RET_VAL(pTableManager != nullptr, false);
auto pContainerManager = GetContainerManager(pEntity);
ARK_ASSERT_RET_VAL(pContainerManager != nullptr, false);
pb_data.set_id(pEntity->GetID());
pb_data.set_config_id(pEntity->GetConfigID());
pb_data.set_map_id(pEntity->GetMapID());
pb_data.set_map_inst_id(pEntity->GetMapEntityID());
pb_data.set_class_name(pEntity->GetClassName());
// node to db
auto& node_list = pNodeManager->GetDataList();
for (auto& iter : node_list)
{
auto pNode = iter.second;
if (!pNode)
{
continue;
}
if (!pNode->HaveMask(ArkDataMask::PF_SAVE))
{
continue;
}
NodeToDBData(pNode, *pb_data.mutable_data());
}
// table to db
auto& table_list = pTableManager->GetTableList();
for (auto& iter : table_list)
{
auto pTable = iter.second;
if (!pTable)
{
continue;
}
if (!pTable->HaveMask(ArkDataMask::PF_SAVE))
{
continue;
}
AFMsg::pb_db_table pb_table;
if (!TableToDBData(pTable, pb_table))
{
continue;
}
pb_data.mutable_data()->mutable_datas_table()->insert({pTable->GetName(), pb_table});
}
// container to db
auto& container_list = pContainerManager->GetContainerList();
for (auto& iter : container_list)
{
auto pContainer = iter.second;
if (!pContainer)
{
continue;
}
AFMsg::pb_db_container pb_container;
for (auto index = pContainer->First(); index > 0; index = pContainer->Next())
{
auto pSubEntity = pContainer->Find(index);
if (!pSubEntity)
{
continue;
}
AFMsg::pb_db_entity pb_container_entity;
if (!EntityToDBData(pSubEntity, pb_container_entity))
{
continue;
}
pb_container.mutable_datas_value()->insert({index, pb_container_entity});
}
if (pb_container.datas_value_size() > 0)
{
pb_data.mutable_data()->mutable_datas_entity()->insert({pContainer->GetName(), pb_container});
}
}
return true;
}
std::shared_ptr<AFIEntity> AFCKernelModule::CreateEntity(const AFMsg::pb_db_entity& pb_data)
{
auto entity_id = pb_data.id();
auto pEntity = GetEntity(entity_id);
if (pEntity != nullptr)
{
ARK_LOG_ERROR("entity already exists, object = {}", entity_id);
return nullptr;
}
const std::string& class_name = pb_data.class_name();
auto pClassMeta = m_pClassModule->FindMeta(class_name);
if (nullptr == pClassMeta)
{
ARK_LOG_ERROR("There is no class meta, name = {}", class_name);
return nullptr;
}
auto map_id = pb_data.map_id();
auto map_inst_id = pb_data.map_inst_id();
auto pMapInfo = m_pMapModule->GetMapInfo(map_id);
if (pMapInfo == nullptr)
{
ARK_LOG_ERROR("There is no scene, scene = {}", map_id);
return nullptr;
}
auto pCEntity = std::make_shared<AFCEntity>(pClassMeta, entity_id, NULL_INT, map_id, map_inst_id, AFCDataList());
pEntity = std::static_pointer_cast<AFIEntity>(pCEntity);
objects_.insert(entity_id, pEntity);
if (class_name == AFEntityMetaPlayer::self_name())
{
pMapInfo->AddEntityToInstance(map_inst_id, entity_id, true);
}
//else if (class_name == AFEntityMetaPlayer::self_name()) // to do : npc type for now we do not have
//{
//}
// init data
auto& pb_db_entity_data = pb_data.data();
// node data
auto pNodeManager = pCEntity->GetNodeManager();
if (nullptr != pNodeManager)
{
DBDataToNode(pNodeManager, pb_db_entity_data);
}
// table data
auto pTableManager = pCEntity->GetTableManager();
if (nullptr != pTableManager)
{
for (auto& iter : pb_db_entity_data.datas_table())
{
DBDataToTable(pEntity, iter.first, iter.second);
}
}
// container data
for (auto& iter : pb_db_entity_data.datas_entity())
{
DBDataToContainer(pEntity, iter.first, iter.second);
}
// todo : add new event?
AFCDataList args;
DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_LOAD_DATA, args);
DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_LOAD_DATA, args);
DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_PRE_EFFECT_DATA, args);
DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_EFFECT_DATA, args);
DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_POST_EFFECT_DATA, args);
DoEvent(entity_id, class_name, ArkEntityEvent::ENTITY_EVT_DATA_FINISHED, args);
return pEntity;
}
bool AFCKernelModule::SendCustomMessage(const guid_t& target, const uint32_t msg_id, const AFIDataList& args)
{
ARK_ASSERT_RET_VAL(Exist(target) && msg_id > 0, false);
AFMsg::pb_custom_message custom_message;
custom_message.set_message_id(msg_id);
size_t count = args.GetCount();
for (size_t i = 0; i < count; i++)
{
auto data_type = args.GetType(i);
switch (data_type)
{
case ark::ArkDataType::DT_BOOLEAN:
custom_message.add_data_list()->set_bool_value(args.Bool(i));
break;
case ark::ArkDataType::DT_INT32:
custom_message.add_data_list()->set_int_value(args.Int(i));
break;
case ark::ArkDataType::DT_UINT32:
custom_message.add_data_list()->set_uint_value(args.UInt(i));
break;
case ark::ArkDataType::DT_INT64:
custom_message.add_data_list()->set_int64_value(args.Int64(i));
break;
case ark::ArkDataType::DT_UINT64:
custom_message.add_data_list()->set_uint64_value(args.UInt64(i));
break;
case ark::ArkDataType::DT_FLOAT:
custom_message.add_data_list()->set_float_value(args.Float(i));
break;
case ark::ArkDataType::DT_DOUBLE:
custom_message.add_data_list()->set_double_value(args.Double(i));
break;
case ark::ArkDataType::DT_STRING:
custom_message.add_data_list()->set_str_value(args.String(i));
break;
default:
break;
}
}
// send message
return true;
}
// pb table to entity table
bool AFCKernelModule::DBDataToTable(
std::shared_ptr<AFIEntity> pEntity, const std::string& name, const AFMsg::pb_db_table& pb_table)
{
auto pTable = pEntity->FindTable(name);
ARK_ASSERT_RET_VAL(pTable != nullptr, false);
auto pCTable = dynamic_cast<AFCTable*>(pTable);
ARK_ASSERT_RET_VAL(pCTable != nullptr, false);
for (auto& iter : pb_table.datas_value())
{
auto row_index = iter.first;
if (row_index == NULL_INT)
{
continue;
}
auto& pb_db_entity_data = iter.second;
auto pRow = pCTable->CreateRow(row_index, AFCDataList());
if (pRow == nullptr)
{
continue;
}
auto pNodeManager = GetNodeManager(pRow);
if (pNodeManager == nullptr)
{
continue;
}
DBDataToNode(pNodeManager, pb_db_entity_data);
}
return true;
}
bool AFCKernelModule::DBDataToContainer(
std::shared_ptr<AFIEntity> pEntity, const std::string& name, const AFMsg::pb_db_container& pb_data)
{
auto pContainer = pEntity->FindContainer(name);
if (nullptr == pContainer)
{
return false;
}
auto pCContainer = std::dynamic_pointer_cast<AFCContainer>(pContainer);
if (nullptr == pCContainer)
{
return false;
}
for (auto& iter : pb_data.datas_value())
{
auto pContainerEntity = CreateEntity(iter.second);
if (nullptr == pContainerEntity)
{
continue;
}
pCContainer->InitEntityList(iter.first, pContainerEntity);
}
return true;
}
int AFCKernelModule::OnContainerCallBack(const guid_t& self, const uint32_t index, const ArkContainerOpType op_type,
const uint32_t src_index, const uint32_t dest_index)
{
if (op_type == ArkContainerOpType::OP_DESTROY)
{
// destroy entity
auto pEntity = GetEntity(self);
ARK_ASSERT_RET_VAL(pEntity != nullptr, 0);
auto pContainer = pEntity->FindContainer(index);
ARK_ASSERT_RET_VAL(pContainer != nullptr, 0);
auto pContainerEntity = pContainer->Find(src_index);
ARK_ASSERT_RET_VAL(pContainerEntity != nullptr, 0);
InnerDestroyEntity(pContainerEntity);
}
return 0;
}
bool AFCKernelModule::DBDataToNode(
std::shared_ptr<AFNodeManager> pNodeManager, const AFMsg::pb_db_entity_data& pb_db_entity_data)
{
//bool data
for (auto& iter : pb_db_entity_data.datas_bool())
{
auto pNode = pNodeManager->CreateData(iter.first);
if (pNode == nullptr)
{
continue;
}
pNode->SetBool(iter.second);
}
//int32 data
for (auto& iter : pb_db_entity_data.datas_int32())
{
auto pNode = pNodeManager->CreateData(iter.first);
if (pNode == nullptr)
{
continue;
}
pNode->SetInt32(iter.second);
}
//uint32 data
for (auto& iter : pb_db_entity_data.datas_uint32())
{
auto pNode = pNodeManager->CreateData(iter.first);
if (pNode == nullptr)
{
continue;
}
pNode->SetUInt32(iter.second);
}
//int64 data
for (auto& iter : pb_db_entity_data.datas_int64())
{
auto pNode = pNodeManager->CreateData(iter.first);
if (pNode == nullptr)
{
continue;
}
pNode->SetInt64(iter.second);
}
//uint64 data
for (auto& iter : pb_db_entity_data.datas_uint64())
{
auto pNode = pNodeManager->CreateData(iter.first);
if (pNode == nullptr)
{
continue;
}
pNode->SetUInt64(iter.second);
}
//float data
for (auto& iter : pb_db_entity_data.datas_float())
{
auto pNode = pNodeManager->CreateData(iter.first);
if (pNode == nullptr)
{
continue;
}
pNode->SetFloat(iter.second);
}
//double data
for (auto& iter : pb_db_entity_data.datas_double())
{
auto pNode = pNodeManager->CreateData(iter.first);
if (pNode == nullptr)
{
continue;
}
pNode->SetDouble(iter.second);
}
//string data
for (auto& iter : pb_db_entity_data.datas_string())
{
auto pNode = pNodeManager->CreateData(iter.first);
if (pNode == nullptr)
{
continue;
}
pNode->SetString(iter.second);
}
return true;
}
//-----------------------------
bool AFCKernelModule::NodeToDBData(AFINode* pNode, AFMsg::pb_db_entity_data& pb_data)
{
ARK_ASSERT_RET_VAL(pNode != nullptr, false);
auto& name = pNode->GetName();
switch (pNode->GetType())
{
case ArkDataType::DT_BOOLEAN:
pb_data.mutable_datas_bool()->insert({name, pNode->GetBool()});
break;
case ArkDataType::DT_INT32:
pb_data.mutable_datas_int32()->insert({name, pNode->GetInt32()});
break;
case ArkDataType::DT_UINT32:
pb_data.mutable_datas_uint32()->insert({name, pNode->GetUInt32()});
break;
case ArkDataType::DT_INT64:
pb_data.mutable_datas_int64()->insert({name, pNode->GetInt64()});
break;
case ArkDataType::DT_UINT64:
pb_data.mutable_datas_uint64()->insert({name, pNode->GetUInt64()});
break;
case ArkDataType::DT_FLOAT:
pb_data.mutable_datas_float()->insert({name, pNode->GetFloat()});
break;
case ArkDataType::DT_DOUBLE:
pb_data.mutable_datas_double()->insert({name, pNode->GetDouble()});
break;
case ArkDataType::DT_STRING:
pb_data.mutable_datas_string()->insert({name, pNode->GetString()});
break;
default:
ARK_ASSERT_RET_VAL(0, false);
break;
}
return true;
}
bool AFCKernelModule::TableToDBData(AFITable* pTable, AFMsg::pb_db_table& pb_data)
{
ARK_ASSERT_RET_VAL(pTable != nullptr, false);
for (auto pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next())
{
auto pNodeManager = GetNodeManager(pRow);
if (!pNodeManager)
{
continue;
}
AFMsg::pb_db_entity_data row_data;
auto& data_list = pNodeManager->GetDataList();
for (auto& iter : data_list)
{
NodeToDBData(iter.second, row_data);
}
pb_data.mutable_datas_value()->insert({pRow->GetRow(), row_data});
}
return true;
}
//----------entity to pb client data---------------
bool AFCKernelModule::NodeToPBData(AFINode* pNode, AFMsg::pb_entity_data* pb_data)
{
ARK_ASSERT_RET_VAL(pNode != nullptr && pb_data != nullptr, false);
auto index = pNode->GetIndex();
switch (pNode->GetType())
{
case ArkDataType::DT_BOOLEAN:
pb_data->mutable_datas_bool()->insert({index, pNode->GetBool()});
break;
case ArkDataType::DT_INT32:
pb_data->mutable_datas_int32()->insert({index, pNode->GetInt32()});
break;
case ArkDataType::DT_UINT32:
pb_data->mutable_datas_uint32()->insert({index, pNode->GetUInt32()});
break;
case ArkDataType::DT_INT64:
pb_data->mutable_datas_int64()->insert({index, pNode->GetInt64()});
break;
case ArkDataType::DT_UINT64:
pb_data->mutable_datas_uint64()->insert({index, pNode->GetUInt64()});
break;
case ArkDataType::DT_FLOAT:
pb_data->mutable_datas_float()->insert({index, pNode->GetFloat()});
break;
case ArkDataType::DT_DOUBLE:
pb_data->mutable_datas_double()->insert({index, pNode->GetDouble()});
break;
case ArkDataType::DT_STRING:
pb_data->mutable_datas_string()->insert({index, pNode->GetString()});
break;
default:
ARK_ASSERT_RET_VAL(0, false);
break;
}
return true;
}
bool AFCKernelModule::NodeToPBData(const uint32_t index, const AFIData& data, AFMsg::pb_entity_data* pb_data)
{
ARK_ASSERT_RET_VAL(index > 0 && pb_data != nullptr, false);
switch (data.GetType())
{
case ArkDataType::DT_BOOLEAN:
pb_data->mutable_datas_bool()->insert({index, data.GetBool()});
break;
case ArkDataType::DT_INT32:
pb_data->mutable_datas_int32()->insert({index, data.GetInt()});
break;
case ArkDataType::DT_UINT32:
pb_data->mutable_datas_uint32()->insert({index, data.GetUInt()});
break;
case ArkDataType::DT_INT64:
pb_data->mutable_datas_int64()->insert({index, data.GetInt64()});
break;
case ArkDataType::DT_UINT64:
pb_data->mutable_datas_uint64()->insert({index, data.GetUInt64()});
break;
case ArkDataType::DT_FLOAT:
pb_data->mutable_datas_float()->insert({index, data.GetFloat()});
break;
case ArkDataType::DT_DOUBLE:
pb_data->mutable_datas_double()->insert({index, data.GetDouble()});
break;
case ArkDataType::DT_STRING:
pb_data->mutable_datas_string()->insert({index, data.GetString()});
break;
default:
ARK_ASSERT_RET_VAL(0, false);
break;
}
return true;
}
bool AFCKernelModule::TableToPBData(AFITable* pTable, const uint32_t index, AFMsg::pb_table* pb_data)
{
ARK_ASSERT_RET_VAL(pTable != nullptr && index > 0 && pb_data != nullptr, false);
for (AFIRow* pRow = pTable->First(); pRow != nullptr; pRow = pTable->Next())
{
AFMsg::pb_entity_data row_data;
if (!RowToPBData(pRow, pRow->GetRow(), &row_data))
{
continue;
}
pb_data->mutable_datas_value()->insert({index, row_data});
}
return true;
}
bool AFCKernelModule::ContainerToPBData(std::shared_ptr<AFIContainer> pContainer, AFMsg::pb_container* pb_data)
{
ARK_ASSERT_RET_VAL(pContainer != nullptr && pb_data != nullptr, false);
for (auto index = pContainer->First(); index > 0; index = pContainer->Next())
{
auto pEntity = pContainer->Find(index);
if (nullptr == pEntity)
{
continue;
}
AFMsg::pb_entity pb_entity;
if (!EntityToPBData(pEntity, &pb_entity))
{
continue;
}
pb_data->mutable_datas_value()->insert({index, pb_entity});
}
return true;
}
bool AFCKernelModule::RowToPBData(AFIRow* pRow, const uint32_t index, AFMsg::pb_entity_data* pb_data)
{
ARK_ASSERT_RET_VAL(pRow != nullptr && index > 0 && pb_data != nullptr, false);
auto pNodeManager = GetNodeManager(pRow);
if (!pNodeManager)
{
return false;
}
auto& data_list = pNodeManager->GetDataList();
for (auto& iter : data_list)
{
NodeToPBData(iter.second, pb_data);
}
return true;
}
bool AFCKernelModule::TableRowDataToPBData(
const uint32_t index, uint32_t row, const uint32_t col, const AFIData& data, AFMsg::pb_entity_data* pb_data)
{
ARK_ASSERT_RET_VAL(index > 0 && row > 0 && col > 0 && pb_data != nullptr, false);
AFMsg::pb_entity_data row_data;
if (!NodeToPBData(col, data, &row_data))
{
return false;
}
AFMsg::pb_table table_data;
table_data.mutable_datas_value()->insert({row, row_data});
pb_data->mutable_datas_table()->insert({index, table_data});
return true;
}
bool AFCKernelModule::EntityToPBData(std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity* pb_data)
{
ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false);
pb_data->set_id(pEntity->GetID());
EntityNodeToPBData(pEntity, pb_data->mutable_data());
EntityTableToPBData(pEntity, pb_data->mutable_data());
EntityContainerToPBData(pEntity, pb_data->mutable_data());
return true;
}
bool AFCKernelModule::EntityToPBDataByMask(
std::shared_ptr<AFIEntity> pEntity, ArkMaskType mask, AFMsg::pb_entity* pb_data)
{
ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false);
pb_data->set_id(pEntity->GetID());
EntityNodeToPBData(pEntity, pb_data->mutable_data(), mask);
EntityTableToPBData(pEntity, pb_data->mutable_data(), mask);
EntityContainerToPBData(pEntity, pb_data->mutable_data(), mask);
return true;
}
bool AFCKernelModule::EntityContainerToPBData(
std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask)
{
ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false);
auto pContainerManager = GetContainerManager(pEntity);
ARK_ASSERT_RET_VAL(pContainerManager != nullptr, false);
auto& container_list = pContainerManager->GetContainerList();
for (auto& iter : container_list)
{
auto pContainer = iter.second;
if (!pContainer)
{
continue;
}
if (!mask.none())
{
auto result = (pContainer->GetMask() & mask);
if (!result.any())
{
continue;
}
}
AFMsg::pb_container pb_container;
if (!ContainerToPBData(pContainer, &pb_container))
{
continue;
}
pb_data->mutable_datas_container()->insert({iter.first, pb_container});
}
return true;
}
//node all to pb data
bool AFCKernelModule::EntityNodeToPBData(
std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask /* = 0*/)
{
ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false);
auto pNodeManager = GetNodeManager(pEntity);
ARK_ASSERT_RET_VAL(pNodeManager != nullptr, false);
auto& data_list = pNodeManager->GetDataList();
for (auto& iter : data_list)
{
auto pNode = iter.second;
if (!pNode)
{
continue;
}
if (!mask.none())
{
auto result = (pNode->GetMask() & mask);
if (!result.any())
{
continue;
}
}
NodeToPBData(pNode, pb_data);
}
return true;
}
bool AFCKernelModule::EntityTableToPBData(
std::shared_ptr<AFIEntity> pEntity, AFMsg::pb_entity_data* pb_data, const ArkMaskType mask /* = 0*/)
{
ARK_ASSERT_RET_VAL(pEntity != nullptr && pb_data != nullptr, false);
auto pTableManager = GetTableManager(pEntity);
ARK_ASSERT_RET_VAL(pTableManager != nullptr, false);
auto& data_list = pTableManager->GetTableList();
for (auto& iter : data_list)
{
auto pTable = iter.second;
if (!pTable)
{
continue;
}
if (!mask.none())
{
auto result = (pTable->GetMask() & mask);
if (!result.any())
{
continue;
}
}
const auto index = pTable->GetIndex();
AFMsg::pb_table table_data;
if (!TableToPBData(pTable, index, &table_data))
{
continue;
}
pb_data->mutable_datas_table()->insert({index, table_data});
}
return true;
}
// -----------get entity manager--------------
std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(std::shared_ptr<AFIStaticEntity> pStaticEntity) const
{
if (pStaticEntity == nullptr)
{
return nullptr;
}
auto pCStaticEntity = std::dynamic_pointer_cast<AFCStaticEntity>(pStaticEntity);
if (pCStaticEntity == nullptr)
{
return nullptr;
}
return pCStaticEntity->GetNodeManager();
}
std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(std::shared_ptr<AFIEntity> pEntity) const
{
if (pEntity == nullptr)
{
return nullptr;
}
auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity);
if (pCEnity == nullptr)
{
return nullptr;
}
return pCEnity->GetNodeManager();
}
std::shared_ptr<AFNodeManager> AFCKernelModule::GetNodeManager(AFIRow* pRow) const
{
if (pRow == nullptr)
{
return nullptr;
}
auto pCRow = dynamic_cast<AFCRow*>(pRow);
if (pCRow == nullptr)
{
return nullptr;
}
return pCRow->GetNodeManager();
}
std::shared_ptr<AFTableManager> AFCKernelModule::GetTableManager(std::shared_ptr<AFIEntity> pEntity) const
{
if (pEntity == nullptr)
{
return nullptr;
}
auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity);
if (pCEnity == nullptr)
{
return nullptr;
}
return pCEnity->GetTableManager();
}
std::shared_ptr<AFIContainerManager> AFCKernelModule::GetContainerManager(std::shared_ptr<AFIEntity> pEntity) const
{
if (pEntity == nullptr)
{
return nullptr;
}
auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity);
if (pCEnity == nullptr)
{
return nullptr;
}
return pCEnity->GetContainerManager();
}
std::shared_ptr<AFIEventManager> AFCKernelModule::GetEventManager(std::shared_ptr<AFIEntity> pEntity) const
{
if (pEntity == nullptr)
{
return nullptr;
}
auto pCEnity = std::dynamic_pointer_cast<AFCEntity>(pEntity);
if (pCEnity == nullptr)
{
return nullptr;
}
return pCEnity->GetEventManager();
}
} // namespace ark
| 28.725101
| 120
| 0.643259
|
ArkGame
|
1d10590f67240a9e3501b73e806bb57d339aeb08
| 574
|
cpp
|
C++
|
UnitTest/OpenToolTest.cpp
|
Neuromancer2701/OpenTool
|
b109e1d798fcca92f23b12e1bb5de898361641a4
|
[
"Apache-2.0"
] | 1
|
2017-08-30T05:59:47.000Z
|
2017-08-30T05:59:47.000Z
|
UnitTest/OpenToolTest.cpp
|
Neuromancer2701/OpenTool
|
b109e1d798fcca92f23b12e1bb5de898361641a4
|
[
"Apache-2.0"
] | null | null | null |
UnitTest/OpenToolTest.cpp
|
Neuromancer2701/OpenTool
|
b109e1d798fcca92f23b12e1bb5de898361641a4
|
[
"Apache-2.0"
] | null | null | null |
//============================================================================
// Name : OpenToolTest.cpp
// Author :
// Version :
// Copyright :
// Description : Hello World in C++, Ansi-style
//============================================================================
#include "Server.h"
#include "Timer.h"
#include <unistd.h>
#include <iostream>
using namespace std;
int main() {
bool listening = true;
cout << "This is a Test." << endl;
Server Test_Server(12000);
while(listening)
{
sleep(1);
//Test.Available();
}
return 0;
}
| 17.393939
| 78
| 0.439024
|
Neuromancer2701
|
1d117be860a84dc612994f2ead8819ad6300b505
| 6,885
|
cpp
|
C++
|
src/cli.cpp
|
CynusW/pg-fetch
|
bbcd639dbdc67e94f8b02c99b267a12b24300465
|
[
"MIT"
] | 1
|
2020-04-16T15:10:20.000Z
|
2020-04-16T15:10:20.000Z
|
src/cli.cpp
|
CynusW/pg-fetch
|
bbcd639dbdc67e94f8b02c99b267a12b24300465
|
[
"MIT"
] | null | null | null |
src/cli.cpp
|
CynusW/pg-fetch
|
bbcd639dbdc67e94f8b02c99b267a12b24300465
|
[
"MIT"
] | null | null | null |
#include "pgf/cli.hpp"
#include "pgf/util.hpp"
#include <cassert>
namespace pgf
{
CommandOptionValue::CommandOptionValue(const CommandOptionValueType& type)
: type(type)
{
switch (type)
{
case CommandOptionValueType::Int:
data = 0;
break;
case CommandOptionValueType::String:
data = std::string();
break;
case CommandOptionValueType::Bool:
default:
data = false;
break;
}
}
void CommandOptions::AddOption(const std::string& name, char shortName, const CommandOptionValueType& type)
{
m_options.push_back(CommandOptionName{ name, shortName });
m_values.push_back(CommandOptionValue{ type });
}
std::vector<CommandOptionValue>::iterator CommandOptions::FindOptionValue(const std::string& name)
{
if (name.empty())
return m_values.end();
unsigned int index = 0;
while (index < m_options.size())
{
const auto& opt = m_options[index];
if (opt.name == name)
break;
++index;
}
return m_values.begin() + index;
}
std::vector<CommandOptionValue>::const_iterator CommandOptions::FindOptionValue(const std::string& name) const
{
if (name.empty())
return m_values.end();
unsigned int index = 0;
while (index < m_options.size())
{
const auto& opt = m_options[index++];
if (opt.name == name)
break;
}
return m_values.begin() + index;
}
std::vector<CommandOptionValue>::iterator CommandOptions::FindOptionValue(char name)
{
unsigned int index = 0;
while (index < m_options.size())
{
const auto& opt = m_options[index];
if (opt.shortName == name)
break;
++index;
}
return m_values.begin() + index;
}
std::vector<CommandOptionValue>::const_iterator CommandOptions::FindOptionValue(char name) const
{
unsigned int index = 0;
while (index < m_options.size())
{
const auto& opt = m_options[index];
if (opt.shortName == name)
break;
++index;
}
return m_values.begin() + index;
}
bool CommandOptions::HasOption(const std::string& name)
{
return std::find_if(
m_options.begin(),
m_options.end(),
[&name](const CommandOptionName& opt) {
return opt.name == name;
}
) != m_options.end();
}
bool CommandOptions::HasOption(char name)
{
return std::find_if(
m_options.begin(),
m_options.end(),
[&name](const CommandOptionName& opt) {
return opt.shortName == name;
}
) != m_options.end();
}
void CommandOptions::SetOptionValue(const std::string& name, bool value)
{
auto optValue = this->FindOptionValue(name);
if (optValue == m_values.end())
return;
if (optValue->type != CommandOptionValueType::Bool)
return;
optValue->data = value;
}
void CommandOptions::SetOptionValue(const std::string& name, int value)
{
auto optValue = this->FindOptionValue(name);
if (optValue == m_values.end())
return;
if (optValue->type != CommandOptionValueType::Int)
return;
optValue->data = value;
}
void CommandOptions::SetOptionValue(const std::string& name, const std::string& value)
{
auto optValue = this->FindOptionValue(name);
if (optValue == m_values.end())
return;
if (optValue->type != CommandOptionValueType::String)
return;
optValue->data = value;
}
void CommandOptions::ProcessArguments(std::vector<std::string>& args)
{
for (unsigned int i = 0; i < args.size(); ++i)
{
std::string arg = args[i];
if (util::StartsWith(arg, "--"))
{
arg = util::ToLower(arg.substr(2));
if (!HasOption(arg))
{
continue;
}
auto optValue = this->FindOptionValue(arg);
if (optValue == m_values.end())
continue;
switch (optValue->type)
{
case CommandOptionValueType::String:
if (i + 1 < args.size())
{
optValue->data = args[i + 1];
args.erase(args.begin() + i + 1);
}
break;
case CommandOptionValueType::Int:
if (i + 1 < args.size())
{
optValue->data = std::stoi(args[i + 1]);
args.erase(args.begin() + i + 1);
}
break;
case CommandOptionValueType::Bool:
default:
optValue->data = true;
break;
}
args.erase(args.begin() + (i--));
}
else if (util::StartsWith(arg, "-"))
{
arg = util::ToLower(arg.substr(1));
for (char c : arg)
{
if (!HasOption(c))
continue;
auto optValue = this->FindOptionValue(c);
if (optValue == m_values.end())
continue;
switch (optValue->type)
{
case CommandOptionValueType::String:
if (i + 1 < args.size())
{
optValue->data = args[i + 1];
args.erase(args.begin() + i + 1);
}
break;
case CommandOptionValueType::Int:
if (i + 1 < args.size())
{
optValue->data = std::stoi(args[i + 1]);
args.erase(args.begin() + i + 1);
}
break;
case CommandOptionValueType::Bool:
default:
optValue->data = true;
break;
}
}
args.erase(args.begin() + (i--));
}
}
}
}
| 28.6875
| 114
| 0.444735
|
CynusW
|
1d12265999bf15a69bf71cd08842c9fa6a5943cb
| 4,741
|
cpp
|
C++
|
src/dialog/PriceHistory.cpp
|
captain-igloo/greenthumb
|
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
|
[
"MIT"
] | 3
|
2019-04-08T19:17:51.000Z
|
2019-05-21T01:01:29.000Z
|
src/dialog/PriceHistory.cpp
|
captain-igloo/greenthumb
|
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
|
[
"MIT"
] | 1
|
2019-04-30T23:39:06.000Z
|
2019-07-27T00:07:20.000Z
|
src/dialog/PriceHistory.cpp
|
captain-igloo/greenthumb
|
39d62004e6f6b6fa7da52b3f6ff1c198b04e1d72
|
[
"MIT"
] | 1
|
2019-02-28T09:22:18.000Z
|
2019-02-28T09:22:18.000Z
|
/**
* Copyright 2020 Colin Doig. Distributed under the MIT license.
*/
#include <wx/wx.h>
#include <wx/dcclient.h>
#include <wx/dcmemory.h>
#include <wx/file.h>
#include <wx/sizer.h>
#include <wx/mstream.h>
#include <wx/stdpaths.h>
#include <wx/stattext.h>
#include <wx/wfstream.h>
#include <wx/url.h>
#include <curl/curl.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <greentop/ExchangeApi.h>
#include "dialog/PriceHistory.h"
#include "Util.h"
namespace greenthumb {
namespace dialog {
size_t writeToStream(char* buffer, size_t size, size_t nitems, wxMemoryOutputStream* stream) {
size_t realwrote = size * nitems;
stream->Write(buffer, realwrote);
return realwrote;
}
PriceHistory::PriceHistory(wxWindow *parent, wxWindowID id, const wxString &title,
const wxPoint &pos, const wxSize &size, long style, const wxString &name) :
wxDialog(parent, id, title, pos, size, style, name) {
int borderWidth = 10;
int borderFlags = wxTOP | wxRIGHT | wxLEFT;
wxBoxSizer* vbox = new wxBoxSizer(wxVERTICAL);
wxFlexGridSizer* gridSizer = new wxFlexGridSizer(2, borderWidth, borderWidth);
wxStaticText* bettingOnLabel = new wxStaticText(this, wxID_ANY, "Betting on:");
gridSizer->Add(bettingOnLabel);
bettingOn = new wxStaticText(this, wxID_ANY, "");
gridSizer->Add(bettingOn);
wxStaticText* lastPriceTradedLabel = new wxStaticText(this, wxID_ANY, "Last price matched:");
gridSizer->Add(lastPriceTradedLabel);
lastPriceTraded = new wxStaticText(this, wxID_ANY, "");
gridSizer->Add(lastPriceTraded);
vbox->Add(gridSizer, 0, borderFlags, borderWidth);
chartPanel = new ImagePanel(
this,
wxID_ANY,
wxDefaultPosition,
wxSize(CHART_WIDTH, CHART_HEIGHT),
wxSUNKEN_BORDER
);
vbox->Add(chartPanel, 0, borderFlags, borderWidth);
wxSizer* buttonSizer = CreateButtonSizer(wxCLOSE);
if (buttonSizer) {
vbox->Add(buttonSizer, 0, wxTOP | wxBOTTOM | wxALIGN_RIGHT, borderWidth);
}
SetSizer(vbox);
vbox->Fit(this);
Bind(wxEVT_BUTTON, &PriceHistory::OnClose, this, wxID_CLOSE);
}
void PriceHistory::SetLastPriceTraded(const double lastPriceTraded) {
if (lastPriceTraded > 0) {
std::ostringstream lastPriceStream;
lastPriceStream << std::fixed << std::setprecision(2) << lastPriceTraded;
wxString label((lastPriceStream.str()).c_str(), wxConvUTF8);
this->lastPriceTraded->SetLabel(label);
}
}
void PriceHistory::SetRunner(const entity::Market& market, const greentop::sport::Runner& runner) {
if (market.HasRunner(runner.getSelectionId())) {
greentop::sport::RunnerCatalog rc = market.GetRunner(runner.getSelectionId());
std::string runnerName = rc.getRunnerName();
if (runner.getHandicap().isValid()) {
runnerName = runnerName + " "
+ wxString::Format(wxT("%.1f"), runner.getHandicap().getValue());
}
bettingOn->SetLabel(
GetSelectionName(market.GetMarketCatalogue(), rc, runner.getHandicap())
);
}
LoadChart(market, runner);
}
void PriceHistory::LoadChart(
const entity::Market& market,
const greentop::sport::Runner& runner
) {
wxString marketId(market.GetMarketCatalogue().getMarketId().substr(2));
std::ostringstream oStream;
oStream << runner.getSelectionId().getValue();
wxString selectionId = oStream.str();
wxString handicap = "0";
greentop::Optional<double> optionalHandicap = runner.getHandicap();
if (optionalHandicap.isValid()) {
std::ostringstream handicapStream;
handicapStream << optionalHandicap.getValue();
handicap = handicapStream.str();
}
wxString chartUrl = "https://xtsd.betfair.com/LoadRunnerInfoChartAction/?marketId=" +
market.GetMarketCatalogue().getMarketId().substr(2) +
"&selectionId=" +
selectionId +
"&handicap=" +
handicap;
curl_global_init(CURL_GLOBAL_DEFAULT);
CURL* curl = curl_easy_init();
if (curl) {
wxMemoryOutputStream out;
curl_easy_setopt(curl, CURLOPT_URL, static_cast<const char*>(chartUrl.c_str()));
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeToStream);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &out);
CURLcode res = curl_easy_perform(curl);
if (res == CURLE_OK) {
wxMemoryInputStream in(out);
wxImage image(in, wxBITMAP_TYPE_JPEG);
wxBitmap chart = wxBitmap(image);
chartPanel->SetBitmap(chart);
}
curl_easy_cleanup(curl);
}
curl_global_cleanup();
}
void PriceHistory::OnClose(wxCommandEvent& event) {
EndModal(wxID_OK);
}
}
}
| 31.606667
| 99
| 0.674119
|
captain-igloo
|
1d131892aa907fe7c6c9b8a43c537b45deac968d
| 382
|
hpp
|
C++
|
include/locic/Support/Hasher.hpp
|
scross99/locic
|
a24bb380e17f8af69e7389acf8ce354c91a2abf3
|
[
"MIT"
] | 80
|
2015-02-19T21:38:57.000Z
|
2016-05-25T06:53:12.000Z
|
include/locic/Support/Hasher.hpp
|
scross99/locic
|
a24bb380e17f8af69e7389acf8ce354c91a2abf3
|
[
"MIT"
] | 8
|
2015-02-20T09:47:20.000Z
|
2015-11-13T07:49:17.000Z
|
include/locic/Support/Hasher.hpp
|
scross99/locic
|
a24bb380e17f8af69e7389acf8ce354c91a2abf3
|
[
"MIT"
] | 6
|
2015-02-20T11:26:19.000Z
|
2016-04-13T14:30:39.000Z
|
#ifndef LOCIC_SUPPORT_HASHER_HPP
#define LOCIC_SUPPORT_HASHER_HPP
#include <cstddef>
#include <locic/Support/Hash.hpp>
namespace locic{
class Hasher {
public:
Hasher();
void addValue(size_t value);
template <typename T>
void add(const T& object) {
addValue(hashObject<T>(object));
}
size_t get() const;
private:
size_t seed_;
};
}
#endif
| 12.322581
| 35
| 0.675393
|
scross99
|
1d1a805f6372f1eca7b7c40773034606e218253a
| 8,602
|
cpp
|
C++
|
sources/GS_CO_0.3/main.cpp
|
Jazzzy/GS_CO_FirstOpenGLProject
|
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
|
[
"Apache-2.0"
] | null | null | null |
sources/GS_CO_0.3/main.cpp
|
Jazzzy/GS_CO_FirstOpenGLProject
|
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
|
[
"Apache-2.0"
] | null | null | null |
sources/GS_CO_0.3/main.cpp
|
Jazzzy/GS_CO_FirstOpenGLProject
|
4048b15fdc75ecf826258c1193bb6da2f2b28e7a
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <cmath>
#include <Windows.h>
#include "Camara.h"
#include "objLoader.h"
#include "player.h"
#include "Luz.h"
#include "hud.h"
#include "mundo.h"
#include "colisiones.h"
#include <conio.h>
#include <stdlib.h>
#include <al\al.h>
#include <al\alc.h>
#include "sound.h"
//#include <al\alu.h>
//#include <al\alut.h>
using namespace std;
void Display();
void Reshape(int w, int h);
void Keyboard(unsigned char key, int x, int y);
void KeyboardUp(unsigned char key, int x, int y);
void MueveRaton(int x, int y);
void PulsaRaton(int button, int state, int x, int y);
void Timer(int value);
void Idle();
void Iniciar();
void Malla();
void update(int value);
void updatePlayer(int value);
void chase(int value);
bool endGame = false;
bool g_key[256] = {false};
bool g_shift_down = false;
bool g_fps_mode = true;
int g_viewport_width = 1240;
int g_viewport_height = 720;
int bang_g_viewport_width = 1240;
int bang_g_viewport_height = 720;
bool g_mouse_left_down = false;
bool g_mouse_right_down = false;
// Movement settings
const float velMov = 0.1;
const float g_rotation_speed = M_PI / 180 * 0.1;
const float velAc = 0.0075;
const float velDec = -0.0025;
//Player
Player *player;
objloader *cargador;
GLuint suelo;
int caja;
int test;
//Light
Luz *luz;
GLfloat LuzPos[] = { 0.0f, 200.0f, 0.0f, 1.0f };
GLfloat SpotDir[] = { 0.0f, -200.0f, 0.0f };
//World
Mundo *mundo;
int dificultad = 1;
vector<Ball*> _ranas;
vector<Box*> _cajas;
float _timeUntilUpdate = 0;
float _timeUntilUpdatePlayer = 0;
//Frogs
int chaseNum = 0;
//Sound
sound *audio;
//HUD
char msg[50];
char datosHud[50];
int bangCounter = 0;
char *bang;
char bang1[10] = "BANG!!";
char bang2[10] = "PIUM!!";
char bang3[10] = "PUM!!";
char bang4[10] = "PAYUM!!";
/*
*/
int main(int argc, char **argv) {
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(1240, 720);
glutCreateWindow("Global Strike: Counter Offensive");
glutIgnoreKeyRepeat(1);
glutDisplayFunc(Display);
glutIdleFunc(Display);
glutReshapeFunc(Reshape);
glutMouseFunc(PulsaRaton);
glutMotionFunc(MueveRaton);
glutPassiveMotionFunc(MueveRaton);
glutKeyboardFunc(Keyboard);
glutKeyboardUpFunc(KeyboardUp);
glutIdleFunc(Idle);
Iniciar();
glutTimerFunc(TIMER_MS, update, 0);
glutTimerFunc(TIMER_MS, updatePlayer, 0);
glutTimerFunc(3000, chase, chaseNum);
glutTimerFunc(1, Timer, 0);
glutMainLoop();
return 0;
}
void Iniciar(){
audio = new sound;
GLfloat Ambient[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat Diffuse[] = { 0.8f, 0.8f, 0.8f, 1.0f };
GLfloat SpecRef[] = { 1.0f, 1.0f, 1.0f, 1.0f };
GLfloat Specular[] = { 1.0f, 1.0f, 1.0f, 1.0f };
printf("\n\n*_*_*_*_*_*_*_*_*_*_*_*_WELCOME TO FROGZ_*_*_*_*_*_*_*_*_*_*_*_*\n\n");
printf("Inserte dificultad:\n\n\tTest: 0\n\n\tFacil: 1\n\n\tNormalillo: 2\n\n\tRanas Astronautas: 3\n");
do{
scanf(" %d", &dificultad);
} while (dificultad != 1 && dificultad != 2 && dificultad != 0 && dificultad != 3);
mundo = new Mundo(audio,dificultad);
player = new Player(mundo,audio);
glEnable(GL_TEXTURE_2D);
glEnable(GL_SMOOTH);
glShadeModel(GL_SMOOTH);
glEnable(GL_DEPTH_TEST);
glEnable(GL_CULL_FACE);
glEnable(GL_NORMALIZE);
// Ilumination
luz = new Luz();
glutSetCursor(GLUT_CURSOR_NONE);
}
void Reshape(int w, int h) {
g_viewport_width = w;
g_viewport_height = h;
glViewport(0, 0, (GLsizei)w, (GLsizei)h); //set the viewport to the current window specifications
glMatrixMode(GL_PROJECTION); //set the matrix to projection
glLoadIdentity();
gluPerspective(60, (GLfloat)w / (GLfloat)h, 0.1, 100.0); //set the perspective (angle of sight, width, height, ,depth)
glMatrixMode(GL_MODELVIEW); //set the matrix back to model
}
void Keyboard(unsigned char key, int x, int y)
{
if (key == 27) {
exit(0);
}
if (key == 'p') {
g_fps_mode = !g_fps_mode;
if (g_fps_mode) {
glutSetCursor(GLUT_CURSOR_NONE);
glutWarpPointer(g_viewport_width / 2, g_viewport_height / 2);
}
else {
glutSetCursor(GLUT_CURSOR_LEFT_ARROW);
}
}
if (glutGetModifiers() == GLUT_ACTIVE_SHIFT) {
g_shift_down = true;
}
else {
g_shift_down = false;
}
if (key == 'r' || key == 'R'){
player->Recargar();
}
g_key[key] = true;
}
void KeyboardUp(unsigned char key, int x, int y)
{
g_key[key] = false;
}
void Timer(int value)
{
if (g_fps_mode) {
if (g_key['w'] || g_key['W']) {
player->Acelerar(velAc);
}
else if (g_key['s'] || g_key['S']) {
player->Acelerar(-velAc);
}
else if (!g_key['w'] && !g_key['W'] && !g_key['s'] && !g_key['S']){
player->Decelerar(velDec);
}
if (g_key['a'] || g_key['A']) {
player->AcelerarHorizontal(velAc);
}
else if (g_key['d'] || g_key['D']) {
player->AcelerarHorizontal(-velAc);
}
else if (!g_key['a'] && !g_key['A'] && !g_key['d'] && !g_key['D']){
player->DecelerarHorizontal(velDec);
}
}
glutTimerFunc(1, Timer, 0);
}
void Idle()
{
Display();
}
void PulsaRaton(int button, int state, int x, int y)
{
if (state == GLUT_DOWN) {
if (button == GLUT_LEFT_BUTTON) {
if (g_fps_mode){
g_mouse_left_down = true;
player->Disparo();
bangCounter = 40;
switch (rand() % 4){
case 0:
bang = bang1;
break;
case 1:
bang = bang2;
break;
case 2:
bang = bang3;
break;
case 3:
bang = bang4;
break;
}
bang_g_viewport_width = (rand() % (g_viewport_width - 200)) + 100;
bang_g_viewport_height = (rand() % (g_viewport_height - 100)) + 50;
}
}
else if (button == GLUT_RIGHT_BUTTON) {
g_mouse_right_down = true;
}
}
else if (state == GLUT_UP) {
if (button == GLUT_LEFT_BUTTON) {
g_mouse_left_down = false;
}
else if (button == GLUT_RIGHT_BUTTON) {
g_mouse_right_down = false;
}
}
}
void MueveRaton(int x, int y)
{
static bool just_warped = false;
if (just_warped) {
just_warped = false;
return;
}
if (g_fps_mode) {
int dx = x - g_viewport_width / 2;
int dy = y - g_viewport_height / 2;
if (dx) {
player->RotarHorizontal(g_rotation_speed*dx);
}
if (dy) {
player->RotarVertical(g_rotation_speed*dy);
}
glutWarpPointer(g_viewport_width / 2, g_viewport_height / 2);
just_warped = true;
}
}
void Display(void) {
glClearColor(0.0, 0.0, 0.0, 1.0); //clear the screen to black
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); //clear the color buffer and the depth buffer
glMatrixMode(GL_PROJECTION); //set the matrix to projection
glLoadIdentity();
gluPerspective(60, (GLfloat)g_viewport_width / (GLfloat)g_viewport_height, 0.1, 200.0); //set the perspective (angle of sight, width, height, ,depth)
glMatrixMode(GL_MODELVIEW); //set the matrix back to model
glLoadIdentity();
if (endGame){
mundo->end();
exit(0);
}
//Camera Position
player->Refresh(g_fps_mode);
//Light
luz->refresh(LuzPos,SpotDir);
//World
mundo->dibujarMundoEstatico();
mundo->dibujarMundoDinamico();
//Weapon
if (g_fps_mode){
player->dibujaArma();
}
else{
player->dibujarModelo();
}
//HUD
sprintf(msg, "Ranas restantes: [%d]", mundo->getRanas().size());
sprintf(datosHud,"Vida: [%d] Balas: [%d]",player->getVida(),player->getBalas());
hud(msg, g_viewport_width, g_viewport_height,5,20);
hud(datosHud, g_viewport_width, g_viewport_height, g_viewport_width -400 , g_viewport_height-20);
if (player->getBalas() > 0){
if (bangCounter > 0){
bangCounter--;
hudBang(bang, g_viewport_width, g_viewport_height, bang_g_viewport_width, bang_g_viewport_height);
}
}
if ((mundo->getRanas().size() <= 0 && dificultad!=0) || player->getVida()<= 0){
fin(g_viewport_width, g_viewport_height);
Sleep(500);
endGame = true;
}
glutSwapBuffers(); //swap the buffers
}
void update(int value) {
if (g_fps_mode){
_ranas = mundo->getRanas();
_cajas = mundo->getCajas();
advance(_ranas, _cajas, (float)TIMER_MS / 1000.0f, _timeUntilUpdatePlayer, mundo,(dificultad!=3));
glutPostRedisplay();
}
glutTimerFunc(TIMER_MS, update, 0);
}
void updatePlayer(int value) {
if (g_fps_mode){
_ranas = mundo->getRanas();
_cajas = mundo->getCajas();
advancePlayer(player->hitball, player, _ranas, _cajas, (float)TIMER_MS / 1000.0f, _timeUntilUpdatePlayer);
glutPostRedisplay();
}
glutTimerFunc(1, updatePlayer, 0);
}
void chase(int value) {
if (g_fps_mode){
_ranas = mundo->getRanas();
chasePlayer(player->hitball, player, _ranas, chaseNum);
chaseNum++;
if (chaseNum >= numRanas){
chaseNum = 0;
}
glutPostRedisplay();
}
glutTimerFunc(500, chase, 0);
}
| 19.461538
| 150
| 0.666008
|
Jazzzy
|
1d22dee0f995a9780c5640ceacf6fdbcb0c4d5bf
| 5,048
|
cpp
|
C++
|
ecm/src/v20190719/model/PeakBase.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 43
|
2019-08-14T08:14:12.000Z
|
2022-03-30T12:35:09.000Z
|
ecm/src/v20190719/model/PeakBase.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 12
|
2019-07-15T10:44:59.000Z
|
2021-11-02T12:35:00.000Z
|
ecm/src/v20190719/model/PeakBase.cpp
|
suluner/tencentcloud-sdk-cpp
|
a56c73cc3f488c4d1e10755704107bb15c5e000d
|
[
"Apache-2.0"
] | 28
|
2019-07-12T09:06:22.000Z
|
2022-03-30T08:04:18.000Z
|
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/ecm/v20190719/model/PeakBase.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Ecm::V20190719::Model;
using namespace std;
PeakBase::PeakBase() :
m_peakCpuNumHasBeenSet(false),
m_peakMemoryNumHasBeenSet(false),
m_peakStorageNumHasBeenSet(false),
m_recordTimeHasBeenSet(false)
{
}
CoreInternalOutcome PeakBase::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("PeakCpuNum") && !value["PeakCpuNum"].IsNull())
{
if (!value["PeakCpuNum"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `PeakBase.PeakCpuNum` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_peakCpuNum = value["PeakCpuNum"].GetInt64();
m_peakCpuNumHasBeenSet = true;
}
if (value.HasMember("PeakMemoryNum") && !value["PeakMemoryNum"].IsNull())
{
if (!value["PeakMemoryNum"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `PeakBase.PeakMemoryNum` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_peakMemoryNum = value["PeakMemoryNum"].GetInt64();
m_peakMemoryNumHasBeenSet = true;
}
if (value.HasMember("PeakStorageNum") && !value["PeakStorageNum"].IsNull())
{
if (!value["PeakStorageNum"].IsInt64())
{
return CoreInternalOutcome(Core::Error("response `PeakBase.PeakStorageNum` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_peakStorageNum = value["PeakStorageNum"].GetInt64();
m_peakStorageNumHasBeenSet = true;
}
if (value.HasMember("RecordTime") && !value["RecordTime"].IsNull())
{
if (!value["RecordTime"].IsString())
{
return CoreInternalOutcome(Core::Error("response `PeakBase.RecordTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_recordTime = string(value["RecordTime"].GetString());
m_recordTimeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void PeakBase::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_peakCpuNumHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PeakCpuNum";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_peakCpuNum, allocator);
}
if (m_peakMemoryNumHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PeakMemoryNum";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_peakMemoryNum, allocator);
}
if (m_peakStorageNumHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "PeakStorageNum";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_peakStorageNum, allocator);
}
if (m_recordTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "RecordTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_recordTime.c_str(), allocator).Move(), allocator);
}
}
int64_t PeakBase::GetPeakCpuNum() const
{
return m_peakCpuNum;
}
void PeakBase::SetPeakCpuNum(const int64_t& _peakCpuNum)
{
m_peakCpuNum = _peakCpuNum;
m_peakCpuNumHasBeenSet = true;
}
bool PeakBase::PeakCpuNumHasBeenSet() const
{
return m_peakCpuNumHasBeenSet;
}
int64_t PeakBase::GetPeakMemoryNum() const
{
return m_peakMemoryNum;
}
void PeakBase::SetPeakMemoryNum(const int64_t& _peakMemoryNum)
{
m_peakMemoryNum = _peakMemoryNum;
m_peakMemoryNumHasBeenSet = true;
}
bool PeakBase::PeakMemoryNumHasBeenSet() const
{
return m_peakMemoryNumHasBeenSet;
}
int64_t PeakBase::GetPeakStorageNum() const
{
return m_peakStorageNum;
}
void PeakBase::SetPeakStorageNum(const int64_t& _peakStorageNum)
{
m_peakStorageNum = _peakStorageNum;
m_peakStorageNumHasBeenSet = true;
}
bool PeakBase::PeakStorageNumHasBeenSet() const
{
return m_peakStorageNumHasBeenSet;
}
string PeakBase::GetRecordTime() const
{
return m_recordTime;
}
void PeakBase::SetRecordTime(const string& _recordTime)
{
m_recordTime = _recordTime;
m_recordTimeHasBeenSet = true;
}
bool PeakBase::RecordTimeHasBeenSet() const
{
return m_recordTimeHasBeenSet;
}
| 27.736264
| 140
| 0.695721
|
suluner
|
918f20f50d64eb3cfc21d7e7cd53b8b6c2a70df5
| 6,728
|
cc
|
C++
|
src/ShaderCompiler/Private/MetalCompiler.cc
|
PixPh/kaleido3d
|
8a8356586f33a1746ebbb0cfe46b7889d0ae94e9
|
[
"MIT"
] | 38
|
2019-01-10T03:10:12.000Z
|
2021-01-27T03:14:47.000Z
|
src/ShaderCompiler/Private/MetalCompiler.cc
|
fuqifacai/kaleido3d
|
ec77753b516949bed74e959738ef55a0bd670064
|
[
"MIT"
] | null | null | null |
src/ShaderCompiler/Private/MetalCompiler.cc
|
fuqifacai/kaleido3d
|
ec77753b516949bed74e959738ef55a0bd670064
|
[
"MIT"
] | 8
|
2019-04-16T07:56:27.000Z
|
2020-11-19T02:38:37.000Z
|
#include <Kaleido3D.h>
#include "MetalCompiler.h"
#include <Core/Utils/MD5.h>
#include <Core/Os.h>
#include "GLSLangUtils.h"
#include "SPIRVCrossUtils.h"
#define METAL_BIN_DIR_MACOS "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/usr/bin/"
#define METAL_BIN_DIR_IOS "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/usr/bin/"
#define METAL_COMPILE_TMP "/.metaltmp/"
#define COMPILE_OPTION "-arch air64 -emit-llvm -c"
#include <string.h>
using namespace std;
namespace k3d
{
NGFXShaderCompileResult mtlCompile(string const& source, String & metalIR);
MetalCompiler::MetalCompiler()
{
sInitializeGlSlang();
}
MetalCompiler::~MetalCompiler()
{
sFinializeGlSlang();
}
NGFXShaderCompileResult MetalCompiler::Compile(String const& src, NGFXShaderDesc const& inOp, NGFXShaderBundle& bundle)
{
if (inOp.Format == NGFX_SHADER_FORMAT_TEXT)
{
if (inOp.Lang == NGFX_SHADER_LANG_METALSL)
{
if (m_IsMac)
{
}
else // iOS
{
}
}
else // process hlsl or glsl
{
bool canConvertToMetalSL = false;
switch (inOp.Lang)
{
case NGFX_SHADER_LANG_ESSL:
case NGFX_SHADER_LANG_GLSL:
case NGFX_SHADER_LANG_HLSL:
case NGFX_SHADER_LANG_VKGLSL:
canConvertToMetalSL = true;
break;
default:
break;
}
if (canConvertToMetalSL)
{
EShMessages messages = (EShMessages)(EShMsgSpvRules | EShMsgVulkanRules);
switch (inOp.Lang)
{
case NGFX_SHADER_LANG_ESSL:
case NGFX_SHADER_LANG_GLSL:
case NGFX_SHADER_LANG_VKGLSL:
break;
case NGFX_SHADER_LANG_HLSL:
messages = (EShMessages)(EShMsgVulkanRules | EShMsgSpvRules | EShMsgReadHlsl);
break;
default:
break;
}
glslang::TProgram& program = *new glslang::TProgram;
TBuiltInResource Resources;
initResources(Resources);
const char* shaderStrings[1];
EShLanguage stage = findLanguage(inOp.Stage);
glslang::TShader* shader = new glslang::TShader(stage);
shaderStrings[0] = src.CStr();
shader->setStrings(shaderStrings, 1);
shader->setEntryPoint(inOp.EntryFunction.CStr());
if (!shader->parse(&Resources, 100, false, messages))
{
puts(shader->getInfoLog());
puts(shader->getInfoDebugLog());
return NGFX_SHADER_COMPILE_FAILED;
}
program.addShader(shader);
if (!program.link(messages))
{
puts(program.getInfoLog());
puts(program.getInfoDebugLog());
return NGFX_SHADER_COMPILE_FAILED;
}
vector<unsigned int> spirv;
GlslangToSpv(*program.getIntermediate(stage), spirv);
if (program.buildReflection())
{
ExtractAttributeData(program, bundle.Attributes);
ExtractUniformData(inOp.Stage, program, bundle.BindingTable);
}
else
{
return NGFX_SHADER_COMPILE_FAILED;
}
uint32 bufferLoc = 0;
vector<spirv_cross::MSLVertexAttr> vertAttrs;
for (auto& attr : bundle.Attributes)
{
spirv_cross::MSLVertexAttr vAttrib;
vAttrib.location = attr.VarLocation;
vAttrib.msl_buffer = attr.VarBindingPoint;
vertAttrs.push_back(vAttrib);
bufferLoc = attr.VarBindingPoint;
}
vector<spirv_cross::MSLResourceBinding> resBindings;
for (auto& binding : bundle.BindingTable.Bindings)
{
if (binding.VarType == NGFX_SHADER_BIND_BLOCK)
{
bufferLoc ++;
spirv_cross::MSLResourceBinding resBind;
resBind.stage = rhiShaderStageToSpvModel(binding.VarStage);
resBind.desc_set = 0;
resBind.binding = binding.VarNumber;
resBind.msl_buffer = bufferLoc;
resBindings.push_back(resBind);
}
}
auto metalc = make_unique<spirv_cross::CompilerMSL>(spirv);
spirv_cross::CompilerMSL::Options config;
config.flip_vert_y = false;
config.entry_point_name = inOp.EntryFunction.CStr();
auto result = metalc->compile(config, &vertAttrs, &resBindings);
if (m_IsMac)
{
auto ret = mtlCompile(result, bundle.RawData);
if (ret == NGFX_SHADER_COMPILE_FAILED)
return ret;
bundle.Desc = inOp;
bundle.Desc.Format = NGFX_SHADER_FORMAT_BYTE_CODE;
bundle.Desc.Lang = NGFX_SHADER_LANG_METALSL;
}
else
{
bundle.RawData = {result.c_str()};
bundle.Desc = inOp;
bundle.Desc.Format = NGFX_SHADER_FORMAT_TEXT;
bundle.Desc.Lang = NGFX_SHADER_LANG_METALSL;
}
}
}
}
else
{
if (inOp.Lang == NGFX_SHADER_LANG_METALSL)
{
}
else
{
}
}
return NGFX_SHADER_COMPILE_OK;
}
const char*
MetalCompiler::GetVersion()
{
return "Metal";
}
NGFXShaderCompileResult mtlCompile(string const& source, String & metalIR)
{
#if K3DPLATFORM_OS_MAC
MD5 md5(source);
auto name = md5.toString();
auto intermediate = string(".") + METAL_COMPILE_TMP;
Os::Path::MakeDir(intermediate.c_str());
auto tmpSh = intermediate + name + ".metal";
auto tmpAr = intermediate + name + ".air";
auto tmpLib = intermediate + name + ".metallib";
Os::File shSrcFile(tmpSh.c_str());
shSrcFile.Open(IOWrite);
shSrcFile.Write(source.data(), source.size());
shSrcFile.Close();
auto mcc = string(METAL_BIN_DIR_MACOS) + "metal";
auto mlink = string(METAL_BIN_DIR_MACOS) + "metallib";
auto ccmd = mcc + " -arch air64 -c -o " + tmpAr + " " + tmpSh;
auto ret = system(ccmd.c_str());
if(ret)
{
return NGFX_SHADER_COMPILE_FAILED;
}
auto lcmd = mlink + " -split-module -o " + tmpLib + " " + tmpAr;
ret = system(lcmd.c_str());
if(ret)
{
return NGFX_SHADER_COMPILE_FAILED;
}
Os::MemMapFile bcFile;
bcFile.Open(tmpLib.c_str(), IORead);
metalIR = { bcFile.FileData(), (size_t)bcFile.GetSize() };
bcFile.Close();
//Os::Remove(intermediate.c_str());
#endif
return NGFX_SHADER_COMPILE_OK;
}
}
| 31.586854
| 121
| 0.582194
|
PixPh
|
919a463419264750d166d11f2fcd75703cf8ae1f
| 32,321
|
cpp
|
C++
|
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
|
dbeachy1/XRVessels
|
8dd2d879886154de2f31fa75393d8a6ac56a2089
|
[
"MIT"
] | 10
|
2021-08-20T05:49:10.000Z
|
2022-01-07T13:00:20.000Z
|
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
|
dbeachy1/XRVessels
|
8dd2d879886154de2f31fa75393d8a6ac56a2089
|
[
"MIT"
] | null | null | null |
XRVessels/XRVesselCtrlDemo/ParserTreeNode.cpp
|
dbeachy1/XRVessels
|
8dd2d879886154de2f31fa75393d8a6ac56a2089
|
[
"MIT"
] | 4
|
2021-09-11T12:08:01.000Z
|
2022-02-09T00:16:19.000Z
|
/**
XR Vessel add-ons for OpenOrbiter Space Flight Simulator
Copyright (C) 2006-2021 Douglas Beachy
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Email: mailto:doug.beachy@outlook.com
Web: https://www.alteaaerospace.com
**/
//-------------------------------------------------------------------------
// ParserTreeNode.cpp : implementation of ParserTreeNode class; maintains state
// for a given node in our parser tree.
//-------------------------------------------------------------------------
#include <windows.h>
#include <limits>
#include "ParserTreeNode.h"
// so numeric_limits<T> min, max will compile
#undef min
#undef max
/*
Here is an example of how a simple parser tree might look:
ParserTreeNode(nullptr) // root node
/ \
(Set) \
/ (Config)
(Engine) / \
/ / \
(MainBoth, MainLeft, MainRight, (AttitudeHold) (AirspeedHold)
Retro...,Hover..., Scram...) / \
/ / \
/ / \
/ (Pitch, AOA) (#targetAirspeed -- this is a leaf node)
/ /
/ /
(ThrottleLevel, (#targetX #targetBank -- leaf node)
GimbalX,
GimbayY,
...)
/
/
(#doubleValue) or (#boolValue)
*/
// Constructor
// csNodeText = "Set", "MainLeft", etc. If null, denotes the root node of the tree. Will be cloned internally.
// nodeGroup = arbitrary group ID that groups like nodes together when constructing help strings
// pNodeData = arbitrary data assigned to this node that is for use by the caller as he sees fit. May be null, although this is normally only null for top-level nodes.
// Typically, however, this will be data that will be used later by the LeafHandler of this node or one of its children. This is clone internally.
// pCallback = handler that executes for leaf nodes; should be null for non-leaf nodes. This is not cloned internally.
ParserTreeNode::ParserTreeNode(const char *pNodeText, const int nodeGroup, const NodeData *pNodeData, LeafHandler *pCallback) :
m_nodeGroup(nodeGroup), m_pLeafHandler(pCallback), m_pParentNode(nullptr)
{
m_pCSNodeText = ((pNodeText != nullptr) ? new CString(pNodeText) : nullptr); // clone it
m_pNodeData = ((pNodeData != nullptr) ? pNodeData->Clone() : nullptr); // deep-clone it
}
// Destructor
ParserTreeNode::~ParserTreeNode()
{
// recursively free all our child nodes
for (unsigned int i=0; i < m_children.size(); i++)
delete m_children[i];
// free our node text and NodeDAta that we created via cloning in the constructor
delete m_pCSNodeText;
delete m_pNodeData;
}
// Add a child node to this node
void ParserTreeNode::AddChild(ParserTreeNode *pChildNode)
{
_ASSERTE(pChildNode != nullptr);
pChildNode->SetParentNode(this); // we are the parent
m_children.push_back(pChildNode);
}
// NOTE: for parsing purposes, all string comparisons are case-insensitive.
// Parse the command and set csCommand to a full auto-completed string if possible.
// Some examples:
// S -> returns "Set"
// s m -> returns "Set MainBoth"
// -> (again) "Set MainLeft"
//
// autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices
// direction: true = tab direction forward, false = tab direction backward
// Returns true if we autocompleted all commands in csCommand
bool ParserTreeNode::AutoComplete(CString &csCommand, AUTOCOMPLETION_STATE *pACState, const bool direction) const
{
csCommand = csCommand.Trim();
if (csCommand.IsEmpty())
return false; // nothing to complete
// parse the command into space-separated pieces
vector<CString> argv;
ParseToSpaceDelimitedTokens(csCommand, argv);
// recursively parse all arguments
const int autocompletedTokenCount = AutoComplete(argv, 0, pACState, direction);
// now reconstruct the full string from the auto-completed pieces
csCommand.Empty();
for (unsigned int i=0; i < argv.size(); i++)
{
if (i > 0)
csCommand += " ";
csCommand += argv[i];
}
const bool autoCompletedAll = (autocompletedTokenCount == argv.size());
// if we autocompleted all tokens successfully, append a trailing space
if (autoCompletedAll)
csCommand += " ";
return autoCompletedAll;
}
// Recursive method to auto-complete all commands in argv.
// argv = arguments to be autocompleted
// startingIndex = 0-based index at which to start parsing
// autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices
// direction: true = tab direction forward, false = tab direction backward
// Returns # of nodes auto-completed (may be zero)
int ParserTreeNode::AutoComplete(vector<CString> &argv, const int startingIndex, AUTOCOMPLETION_STATE *pACState, const bool direction) const
{
_ASSERTE(startingIndex >= 0);
_ASSERTE(startingIndex < static_cast<int>(argv.size()));
_ASSERTE(pACState != nullptr);
int autocompletedTokens = 0;
// try to parse the requested token by finding a match with one of our child nodes
CString &csToken = argv[startingIndex];
// By design, only track autocompletion state for the *last* token on the line; otherwise we would
// overwrite the command following the one we would autocomplete.
AUTOCOMPLETION_STATE *pActiveACState = ((startingIndex == (argv.size()-1)) ? pACState : nullptr);
const int nextArgIndex = startingIndex + 1;
ParserTreeNode *pMatchingChild = FindChildForToken(csToken, pActiveACState, direction);
if (pMatchingChild != nullptr)
{
// Note: by design, we count a token as autocompleted if even if was already complete
autocompletedTokens++;
argv[startingIndex] = *pMatchingChild->GetNodeText(); // change argv entry to completed token; e.g., "Set", "Main", etc.
if (nextArgIndex < static_cast<int>(argv.size())) // any more arguments to parse?
{
// now let's recurse down to the next level and try to autocomplete the next level down
autocompletedTokens += pMatchingChild->AutoComplete(argv, nextArgIndex, pACState, direction); // propagate the ACState that was passed in
}
}
else // no matching child
{
// let's see if we're a leaf node AND this is the last token on the line (i.e., the first leaf node parameter)
if ((m_pLeafHandler != nullptr) && (nextArgIndex == static_cast<int>(argv.size())))
{
// this is leaf node parameter #1, so let's see if there are any autocompletion tokens available for it
const char **pFirstParamTokens = m_pLeafHandler->GetFirstParamAutocompletionTokens(this); // may be nullptr
// let's try to find a unique match
const char *pAutocompletedToken = AutocompleteToken(argv[startingIndex], pACState, direction, pFirstParamTokens);
if (pAutocompletedToken != nullptr)
{
autocompletedTokens++;
argv[startingIndex] = pAutocompletedToken; // change argv entry to completed token
// since this is the last token on the line, there is nothing else to parse: fall through and return
}
}
}
return autocompletedTokens;
}
// Parse the command until either the entire command is parsed (and executed via its leaf handler)
// or we locate a syntax or value error.
//
// Returns true on success, false on error
// pCommand = command to be parsed
// statusOut = output buffer for result text
bool ParserTreeNode::Parse(const char *pCommand, CString &statusOut) const
{
CString csCommand = CString(pCommand).Trim();
if (csCommand.IsEmpty())
{
statusOut = "command is empty.";
return false;
}
// parse the command into space-separated pieces
vector<CString> argv;
ParseToSpaceDelimitedTokens(csCommand, argv);
// recursively parse all arguments and execute the command
CString commandStatus;
bool success = Parse(argv, 0, commandStatus);
statusOut.Format("Command: [%s]\r\n", csCommand);
statusOut += (success ? "" : "Error: ") + commandStatus;
return success;
}
// Recursive method that will parse the command and recurse down to our child nodes until we execute the
// command or locate a syntax error.
//
// argv = arguments to be parsed
// startingIndex = 0-based index at which to start parsing; NOTE: may be beyond end of argv if this is a leaf node that takes no arguments
// autocompletionTokenIndex = maintains state as we scroll through possible autocompletion choices
// Returns true on success, false on error
bool ParserTreeNode::Parse(vector<CString> &argv, const int startingIndex, CString &statusOut) const
{
_ASSERTE(startingIndex >= 0);
// do not validate argv against startingIndex here: may be beyond end of argv if this is a leaf node that takes no arguments
statusOut.Empty();
bool retVal = false; // assume failure
// if this is a leaf node, invoke the leafHandler execute the action for this node
if (m_pLeafHandler != nullptr)
{
_ASSERTE(m_children.size() == 0); // leaf nodes must not have any children
// build vector of remaining arguments
vector<CString> remainingArgv;
for (int i=startingIndex; i < static_cast<int>(argv.size()); i++)
remainingArgv.push_back(argv[i]);
// invoke the leaf handler to execute this command
retVal = m_pLeafHandler->Execute(this, remainingArgv, statusOut);
}
else // not a leaf node, so let's keep recursing down...
{
const int nextArgIndex = startingIndex + 1;
if (startingIndex < static_cast<int>(argv.size())) // more arguments to parse?
{
// try to parse the requested token by finding a match with one of our child nodes
CString &csToken = argv[startingIndex];
ParserTreeNode *pMatchingChild = FindChildForToken(csToken, nullptr, true); // must have exact match here (direction is moot)
if (pMatchingChild != nullptr)
{
// command token is valid
const int nextArgIndex = startingIndex + 1;
// Note: there may not be any more arguments to parse here; e.g., for leaf nodes that take no arguments.
// Therefore, we always recurse down to the next level and attempt to parse/execute it.
retVal = pMatchingChild->Parse(argv, nextArgIndex, statusOut);
}
else // unknown command
{
statusOut.Format("Invalid command token: [%s]", csToken);
// fall through and return false
}
}
else // no more arguments, but this is not a leaf node
{
statusOut = "Required token missing; options are: ";
AppendChildNodeNames(statusOut);
// fall through and return false
}
}
return retVal;
}
// Sets argsOut to a list of bracket-grouped available arguments for the supplied command.
// Returns the level for which the available arguments pertain.
// For example:
// "" -> (returns 1), argsOut = [Set, Config, ...]
// Set -> (returns 2), argsOut = [MainBoth, MainLeft, ...]
// Set foo -> (returns 2), argsOut = [MainBoth, MainLeft, ...] (foo is invalid, but the user can still correct 'foo' to be one of the valid options)
// Set MainBoth -> (returns 3), argsOut = [ThrottleLevel, GimbalX, GimbalY, ...]
// "foo" -> (returns 1), argsOut = [Set, Config, ...] (foo is an invalid command)
int ParserTreeNode::GetAvailableArgumentsForCommand(const char *pCommand, vector<CString> &argsOut) const
{
CString csCommand = CString(pCommand).Trim();
// parse the command into space-separated pieces
vector<CString> argv;
ParseToSpaceDelimitedTokens(csCommand, argv);
// recursively parse all arguments
argsOut.clear(); // reset
int argLevel = GetAvailableArgumentsForCommand(argv, 0, argsOut);
return argLevel;
}
// Recursively parse the supplied command and populate argsOut with bracket-grouped, valid arguments for this command.
// argv = arguments to parse
// startingIndex = index into argv to parse; also denotes our recursion level (0...n)
// argsOut = will be populated with valid arguments for this command
// Returns the level for which the arguments in argsOut pertain.
int ParserTreeNode::GetAvailableArgumentsForCommand(vector<CString> &argv, const int startingIndex, vector<CString> &argsOut) const
{
_ASSERTE(startingIndex >= 0);
int retVal;
// if this is a leaf node, we have reached the end of the chain, so show the leaf handler's help text
if (m_pLeafHandler != nullptr)
{
_ASSERTE(m_children.size() == 0); // leaf nodes must not have any children
CString csHelp;
m_pLeafHandler->GetArgumentHelp(this, csHelp);
argsOut.push_back("[" + csHelp + "]"); // e.g., "[<double> (range -1.0 - 1.0)]"
retVal = startingIndex; // startingIndex also matches our recursion level
}
else // not a leaf node, so let's keep recursing down...
{
ParserTreeNode *pMatchingChild = nullptr;
if (startingIndex < static_cast<int>(argv.size())) // more arguments to parse?
{
// try to parse the requested token by finding a match with one of our child nodes
CString &csToken = argv[startingIndex];
pMatchingChild = FindChildForToken(csToken, nullptr, true); // must have exact match here (direction is moot)
}
const int nextArgIndex = startingIndex + 1;
if (pMatchingChild != nullptr)
{
// command token is valid, so let's recurse down to the next level (keep parsing)
const int nextArgIndex = startingIndex + 1;
retVal = pMatchingChild->GetAvailableArgumentsForCommand(argv, nextArgIndex, argsOut); // recurse down
}
else
{
// No child node found and this is NOT a leaf node, so we have invalid tokens at this level.
// Therefore, we return a list of this level's child nodes (available options), grouped in brackets [ ... ].
int currentNodeGroup;
for (unsigned int i=0; i < m_children.size(); i++)
{
const ParserTreeNode *pChild = m_children[i];
_ASSERTE(pChild != nullptr);
CString nodeText = *m_children[i]->GetNodeText();
// enclose a given group of commands in brackets for clarity
if (i == 0)
{
currentNodeGroup = pChild->GetNodeGroup(); // first node at this level, so its group is the active group now
nodeText = " [" + nodeText; // first group start
}
else if (pChild->GetNodeGroup() != currentNodeGroup)
{
// new group coming, so append closing "]" to previous command text and prepend " [" to this command text
currentNodeGroup = pChild->GetNodeGroup(); // this is the new active group
argsOut.back() += "]";
nodeText = " [" + nodeText;
}
argsOut.push_back(nodeText);
}
argsOut.back() += "]"; // last group end
retVal = startingIndex;
}
}
_ASSERTE(argsOut.size() > 0);
return retVal;
}
// appends csOut with formatted names for all our child nodes
void ParserTreeNode::AppendChildNodeNames(CString &csOut) const
{
for (unsigned int i=0; i < m_children.size(); i++)
{
if (i > 0)
csOut += ", ";
csOut += *m_children[i]->GetNodeText(); // e.g., "Set", "MainBoth", etc.
}
}
// static factory method that creates a new autocompletion state; it is the caller's responsibility to eventually free this
ParserTreeNode::AUTOCOMPLETION_STATE *ParserTreeNode::AllocateNewAutocompletionState()
{
AUTOCOMPLETION_STATE *pNew = reinterpret_cast<AUTOCOMPLETION_STATE *>(new ParserTreeNode::AutocompletionState());
ResetAutocompletionState(pNew);
return pNew;
}
// static utility method to reset the autcompletion state to a new command
void ParserTreeNode::ResetAutocompletionState(AUTOCOMPLETION_STATE *pACState)
{
AutocompletionState *ptr = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type
ptr->significantCharacters = 0;
ptr->tokenCandidateIndex = 0;
}
// Examine our child nodes and try to locate a case-insensitive match for the supplied token.
// acState : tracks autocompletion state between successive autocompletion calls; if null, do not track autocompletion for this token (i.e., this is not the final token on the command line)
// direction: true = tab direction forward, false = tab direction backward
// Returns node on a match or nullptr if no match found OR if more than one match found.
ParserTreeNode *ParserTreeNode::FindChildForToken(const CString &csToken, AUTOCOMPLETION_STATE *pACState, const bool direction) const
{
if (csToken.IsEmpty())
return nullptr; // sanity check
// NOTE: do not modify this object's state *except* for the last token on the command line
AutocompletionState *pActiveACState = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type
// assume no autocompletionstate
int significantCharacters = csToken.GetLength();
int tokenCandidateIndex = 0;
if (pActiveACState != nullptr)
{
// we may be stepping through the possible candidates
significantCharacters = pActiveACState->significantCharacters;
if (significantCharacters <= 0)
{
// we were reset, so test all characters in the token
significantCharacters = csToken.GetLength();
}
tokenCandidateIndex = pActiveACState->tokenCandidateIndex;
}
_ASSERTE(significantCharacters <= csToken.GetLength());
// step through each of our child nodes and build a list of all case-insensitive matches
vector<ParserTreeNode *> matchingNodes;
for (unsigned int i=0; i < m_children.size(); i++)
{
ParserTreeNode *pCandidate = m_children[i];
const CString csNodeTextPrefix = pCandidate->GetNodeText()->Left(significantCharacters);
const CString csTokenPrefix = csToken.Left(significantCharacters);
if (csTokenPrefix.CompareNoCase(csNodeTextPrefix) == 0)
matchingNodes.push_back(pCandidate); // we have a match
}
// decide which matching node to use
ParserTreeNode *pRetVal = nullptr;
const int matchingNodeCount = static_cast<int>(matchingNodes.size());
if (matchingNodeCount > 0)
{
_ASSERTE(tokenCandidateIndex >= 0);
_ASSERTE(tokenCandidateIndex < matchingNodeCount);
if (pActiveACState == nullptr) // not stepping through multiple tokens?
{
// must have exactly *one* match or we cannot autocomplete this token
pRetVal = ((matchingNodeCount == 1) ? matchingNodes.front() : nullptr);
}
else // we're stepping through multiple tokens (always on the last token on the line)
{
pRetVal = matchingNodes[tokenCandidateIndex];
// update our AutocompletionState for next time
pActiveACState->significantCharacters = significantCharacters;
if (direction) // forward?
{
if (++pActiveACState->tokenCandidateIndex >= matchingNodeCount)
pActiveACState->tokenCandidateIndex = 0; // wrap around to beginning
}
else // backward
{
if (--pActiveACState->tokenCandidateIndex < 0)
pActiveACState->tokenCandidateIndex = (matchingNodeCount - 1); // wrap around to end
}
}
}
return pRetVal;
}
// Try to autocomplete the supplied token using the supplied list of valid token values.
// (This method is similar to 'FindChildForToken' above.)
//
// acState : tracks autocompletion state between successive autocompletion calls; if null, do not track autocompletion for this token (i.e., this is not the final token on the command line)
// direction: true = tab direction forward, false = tab direction backward
// pValidTokenValues: may be nullptr. Otherwise, points to a nullptr-terminated array of valid token values.
// Returns autocompleted token on a match or nullptr if pValidTokenValues is nullptr OR no match found OR if more than one match found.
const char *ParserTreeNode::AutocompleteToken(const CString &csToken, AUTOCOMPLETION_STATE *pACState, const bool direction, const char **pValidTokenValues) const
{
if (pValidTokenValues == nullptr)
return nullptr; // no autocompletion possible
if (csToken.IsEmpty())
return nullptr; // sanity check
// NOTE: do not modify this object's state *except* for the last token on the command line
AutocompletionState *pActiveACState = reinterpret_cast<AutocompletionState *>(pACState); // cast back to actual type
// assume no autocompletionstate
int significantCharacters = csToken.GetLength();
int tokenCandidateIndex = 0;
if (pActiveACState != nullptr)
{
// we may be stepping through the possible candidates
significantCharacters = pActiveACState->significantCharacters;
if (significantCharacters <= 0)
{
// we were reset, so test all characters in the token
significantCharacters = csToken.GetLength();
}
tokenCandidateIndex = pActiveACState->tokenCandidateIndex;
}
_ASSERTE(significantCharacters <= csToken.GetLength());
// step through each of our valid tokens and build a list of all case-insensitive matches
vector<const char *> matchingTokens;
for (const char **ppValidToken = pValidTokenValues; *ppValidToken != nullptr; ppValidToken++)
{
CString candidate = *ppValidToken; // valid token (a possible match)
const CString csNodeTextPrefix = candidate.Left(significantCharacters);
const CString csTokenPrefix = csToken.Left(significantCharacters);
if (csTokenPrefix.CompareNoCase(csNodeTextPrefix) == 0)
matchingTokens.push_back(*ppValidToken); // we have a match
}
// decide which matching node to use
const char *pRetVal = nullptr;
const int matchingTokenCount = static_cast<int>(matchingTokens.size());
if (matchingTokenCount > 0)
{
_ASSERTE(tokenCandidateIndex >= 0);
_ASSERTE(tokenCandidateIndex < matchingTokenCount);
if (pActiveACState == nullptr) // not stepping through multiple tokens?
{
// must have exactly *one* match or we cannot autocomplete this token
pRetVal = ((matchingTokenCount == 1) ? matchingTokens.front() : nullptr);
}
else // we're stepping through multiple tokens (always on the last token on the line)
{
pRetVal = matchingTokens[tokenCandidateIndex];
// update our AutocompletionState for next time
pActiveACState->significantCharacters = significantCharacters;
if (direction) // forward?
{
if (++pActiveACState->tokenCandidateIndex >= matchingTokenCount)
pActiveACState->tokenCandidateIndex = 0; // wrap around to beginning
}
else // backward
{
if (--pActiveACState->tokenCandidateIndex < 0)
pActiveACState->tokenCandidateIndex = (matchingTokenCount - 1); // wrap around to end
}
}
}
return pRetVal;
}
// static utility method that will parse a given command string into space-delimited tokens
// argv = contains parse-delmited tokens; NOTE: it is the caller's responsibility to free the CString objects
// added to the vector.
// Returns: # of valid (i.e., non-empty) tokens parsed; i.e., argv.size()
int ParserTreeNode::ParseToSpaceDelimitedTokens(const char *pCommand, vector<CString> &argv)
{
CString csCommand(pCommand);
int tokenIndex = 0;
while (tokenIndex >= 0)
{
CString token = csCommand.Tokenize(" ", tokenIndex);
if (!token.IsEmpty())
{
argv.push_back(token.Trim()); // whack any other non-printables
}
}
return static_cast<int>(argv.size());
}
//
// LeafHandler static utility methods
//
// Parse a validated double from the supplied string.
//
// Parameters:
// pStr = string to be parsed
// dblOut = will be set to parsed value, regardless of whether it is in range
// min = minimum valid value, inclusive
// max = maximum valid value, inclusive
// pCSErrorMsgOut = if non-null, will be set to error reason if parse or validation fails
//
// Returns: true if value parsed successfully and is in range, false otherwise.
bool ParserTreeNode::LeafHandler::ParseValidatedDouble(const char *pStr, double &dblOut, const double min, const double max, CString *pCSErrorMsgOut)
{
bool parseSuccessful = ParseDouble(pStr, dblOut);
bool inRange = ((dblOut >= min) && (dblOut <= max));
if (pCSErrorMsgOut != nullptr)
{
if (!parseSuccessful)
{
pCSErrorMsgOut->Format("Invalid argument: '%s'", pStr);
}
else // parse successful
{
if (!inRange)
{
if ((min != numeric_limits<double>::min()) && (max != numeric_limits<double>::max()))
{
// normal limits defined
pCSErrorMsgOut->Format("Value out-of-range (%.4lf); valid range is %.4lf - %.4lf.", dblOut, min, max);
}
else if (min == numeric_limits<double>::min())
{
// upper limit, but no lower limit
pCSErrorMsgOut->Format("Value too large (%.4lf); must be <= %.4lf.", dblOut, max);
}
else // must be max == numeric_limits<double>::max()
{
// lower limit, but no upper limit
pCSErrorMsgOut->Format("Value too small (%.4lf); must be >= %.4lf.", dblOut, min);
}
}
}
}
return inRange;
}
// Parse a validated boolean from the supplied string.
//
// Parameters:
// pStr = string to be parsed; for success, must be one of "true", "on", "false", or "off" (case-insensitive)
// boolOut = will be set to parsed value, regardless of whether it is valid
// pCSErrorMsgOut = if non-null, will be set to error reason if parse fails
//
// Returns: true if value parsed is valid, false otherwise
bool ParserTreeNode::LeafHandler::ParseValidatedBool(const char *pStr, bool &boolOut, CString *pCSErrorMsgOut)
{
bool success = ParseBool(pStr, boolOut);
if ((pCSErrorMsgOut != nullptr) && (!success))
pCSErrorMsgOut->Format("Invalid boolean value (%s); valid options are 'true', 'on', 'false', or 'off' (case-insensitive).", pStr);
return success;
}
// Parse a validated integer from the supplied string.
//
// Parameters:
// pStr = string to be parsed
// intOut = will be set to parsed value, regardless of whether it is in range
// min = minimum valid value, inclusive
// max = maximum valid value, inclusive
// pCSErrorMsgOut = if non-null, will be set to error reason if parse or validation fails
//
// Returns: true if value parsed successfully and is in range, false otherwise.
bool ParserTreeNode::LeafHandler::ParseValidatedInt(const char *pStr, int &intOut, const int min, const int max, CString *pCSErrorMsgOut)
{
bool parseSuccessful = ParseInt(pStr, intOut);
bool inRange = (parseSuccessful && (intOut >= min) && (intOut <= max));
if (pCSErrorMsgOut != nullptr)
{
if (!parseSuccessful)
pCSErrorMsgOut->Format("Invalid argument: '%s'", pStr);
else if (!inRange) // value parsed successfully, but is it out-of-range?
pCSErrorMsgOut->Format("Value out-of-range (%d); valid range is %d - %d.", intOut, min, max);
}
return inRange;
}
// Parse a double from the supplied string; returns true on success, false on error.
// On success, dblOut will contain the parsed value.
// Returns true if value parsed successfully, or false if value could not be parsed (invalid string).
bool ParserTreeNode::LeafHandler::ParseDouble(const char *pStr, double &dblOut)
{
_ASSERTE(pStr != nullptr);
// we use sscanf_s instead of atof here because it has error handling
return (sscanf_s(pStr, "%lf", &dblOut) == 1);
}
// Parse a boolean from the supplied string; returns true on success, false on error.
// pStr: should be one of "true", "on", "false", or "off" (case-insensitive).
// On success, boolOut will contain the parsed value.
// Returns true if value parsed successfully, or false if value could not be parsed (invalid string).
bool ParserTreeNode::LeafHandler::ParseBool(const char *pStr, bool &boolOut)
{
_ASSERTE(pStr != nullptr);
bool success = false;
if (!_stricmp(pStr, "true") || !_stricmp(pStr, "on"))
{
boolOut = success = true;
}
else if (!_stricmp(pStr, "false") || !_stricmp(pStr, "off"))
{
boolOut = false;
success = true;
}
// else fall through and return false
return success;
}
// Parse an integer from the supplied string; returns true on success, false on error.
// On success, intOut will contain the parsed value.
// Returns true if value parsed successfully, or false if value could not be parsed (invalid string)
bool ParserTreeNode::LeafHandler::ParseInt(const char *pStr, int &intOut)
{
_ASSERTE(pStr != nullptr);
// we use sscanf_s instead of atof here because it has error handling
return (sscanf_s(pStr, "%d", &intOut) == 1);
}
// Recursively build a tree of all command help text appended to csOut.
// indent = indent for this line in csOut.
void ParserTreeNode::BuildCommandHelpTree(int recursionLevel, CString &csOut)
{
// build indent string
CString csIndent;
for (int i=0; i < recursionLevel; i++)
csIndent += " ";
csOut += csIndent; // indent this line
// add our command text
const CString *pNodeText = GetNodeText();
if (pNodeText != nullptr)
{
csOut += *pNodeText;
csOut += " ";
}
// if we're a leaf node, see if we have any help text
if (m_pLeafHandler != nullptr)
{
CString csLeafHelp;
m_pLeafHandler->GetArgumentHelp(this, csLeafHelp);
csOut += csLeafHelp; // add the leaf node text, too
}
// terminate this line
if (csOut.GetLength() > 0) // prevent extra root node newline and indent
{
csOut += "\r\n";
recursionLevel++;
}
// recurse down to all our children
for (unsigned i=0; i < m_children.size(); i++)
m_children[i]->BuildCommandHelpTree(recursionLevel, csOut);
if (m_children.size() > 0) // not a leaf node?
csOut += "\r\n"; // add separator line
}
| 42.696169
| 189
| 0.643173
|
dbeachy1
|
919d7d690b95402d371b19dc25e50af043a8fb21
| 2,188
|
cpp
|
C++
|
src/main.cpp
|
daichi-ishida/Visual-Simulation-of-Smoke
|
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
|
[
"MIT"
] | 13
|
2018-06-12T11:42:19.000Z
|
2021-12-28T00:57:46.000Z
|
src/main.cpp
|
daichi-ishida/Visual-Simulation-of-Smoke
|
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
|
[
"MIT"
] | 2
|
2018-05-10T13:32:02.000Z
|
2018-05-12T18:32:53.000Z
|
src/main.cpp
|
daichi-ishida/Visual-Simulation-of-Smoke
|
b925d0cfc86f642ab4ee9470e67360b2ab5adcb2
|
[
"MIT"
] | 7
|
2020-01-06T07:07:19.000Z
|
2021-12-06T15:43:00.000Z
|
#include <memory>
#include <sys/time.h>
#define GLFW_INCLUDE_GLU
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include "constants.hpp"
#include "Scene.hpp"
#include "Simulator.hpp"
#include "MACGrid.hpp"
int main()
{
if (glfwInit() == GLFW_FALSE)
{
fprintf(stderr, "Initialization failed!\n");
}
if (OFFSCREEN_MODE)
{
glfwWindowHint(GLFW_VISIBLE, 0);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
GLFWwindow *window = glfwCreateWindow(WIN_WIDTH, WIN_HEIGHT, WIN_TITLE,
NULL, NULL);
if (window == NULL)
{
fprintf(stderr, "Window creation failed!");
glfwTerminate();
}
glfwMakeContextCurrent(window);
glewExperimental = true;
if (glewInit() != GLEW_OK)
{
fprintf(stderr, "GLEW initialization failed!\n");
}
// set background color
glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
glLineWidth(1.2f);
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE);
double time = 0.0;
int step = 1;
std::shared_ptr<MACGrid> grids = std::make_shared<MACGrid>();
std::unique_ptr<Simulator> simulator = std::make_unique<Simulator>(grids, time);
std::unique_ptr<Scene> scene = std::make_unique<Scene>(grids);
printf("\n*** SIMULATION START ***\n");
struct timeval s, e;
// scene->writeData();
while (glfwWindowShouldClose(window) == GL_FALSE && glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS)
{
printf("\n=== STEP %d ===\n", step);
time += DT;
gettimeofday(&s, NULL);
simulator->update();
scene->update();
// scene->writeData();
scene->render();
gettimeofday(&e, NULL);
printf("time = %lf\n", (e.tv_sec - s.tv_sec) + (e.tv_usec - s.tv_usec) * 1.0E-6);
++step;
if (time >= FINISH_TIME)
{
break;
}
glfwSwapBuffers(window);
glfwPollEvents();
}
printf("\n*** SIMULATION END ***\n");
glfwTerminate();
return 0;
}
| 25.149425
| 106
| 0.59415
|
daichi-ishida
|
91a7b84e71b83bb1d8f1f43442cbe90a3dafe442
| 1,143
|
cpp
|
C++
|
source/src/graphics.cpp
|
AndrewPomorski/KWCGame
|
b1a748ad0b11d44c6df329345e072cf63fcb5e16
|
[
"MIT"
] | null | null | null |
source/src/graphics.cpp
|
AndrewPomorski/KWCGame
|
b1a748ad0b11d44c6df329345e072cf63fcb5e16
|
[
"MIT"
] | null | null | null |
source/src/graphics.cpp
|
AndrewPomorski/KWCGame
|
b1a748ad0b11d44c6df329345e072cf63fcb5e16
|
[
"MIT"
] | null | null | null |
#include "SDL.h"
#include <SDL2/SDL_image.h>
#include "graphics.h"
#include "globals.h"
/*
* Graphics class implementation.
* Holds all information dealing with game graphics.
*/
Graphics::Graphics(){
SDL_CreateWindowAndRenderer(globals::SCREEN_WIDTH, globals::SCREEN_HEIGHT, 0, &this->_window, &this->_renderer);
SDL_SetWindowTitle(this->_window, "Hong");
}
Graphics::~Graphics(){
SDL_DestroyWindow(this->_window);
SDL_DestroyRenderer(this->_renderer);
}
SDL_Surface* Graphics::loadImage( const std::string &filePath ){
if ( this->_spriteSheets.count(filePath) == 0 ){
/*
* the file from this path hasn't been loaded yet.
*/
this->_spriteSheets[filePath] = IMG_Load(filePath.c_str());
}
return _spriteSheets[filePath];
}
void Graphics::blitSurface( SDL_Texture* texture, SDL_Rect* sourceRectangle, SDL_Rect* destinationRectangle ) {
SDL_RenderCopy( this->_renderer, texture, sourceRectangle, destinationRectangle );
}
void Graphics::flip(){
SDL_RenderPresent(this->_renderer);
}
void Graphics::clear(){
SDL_RenderClear(this->_renderer);
}
SDL_Renderer* Graphics::getRenderer() const {
return this->_renderer;
}
| 22.86
| 113
| 0.741907
|
AndrewPomorski
|
91a8b666f9cf365fc0a1b889422c3d8fac1755d8
| 3,809
|
cpp
|
C++
|
qCC/ccColorGradientDlg.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | null | null | null |
qCC/ccColorGradientDlg.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | null | null | null |
qCC/ccColorGradientDlg.cpp
|
ohanlonl/qCMAT
|
f6ca04fa7c171629f094ee886364c46ff8b27c0b
|
[
"BSD-Source-Code"
] | 1
|
2019-02-03T12:19:42.000Z
|
2019-02-03T12:19:42.000Z
|
//##########################################################################
//# #
//# CLOUDCOMPARE #
//# #
//# This program is free software; you can redistribute it and/or modify #
//# it under the terms of the GNU General Public License as published by #
//# the Free Software Foundation; version 2 or later of the License. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU General Public License for more details. #
//# #
//# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) #
//# #
//##########################################################################
#include "ccColorGradientDlg.h"
//Local
#include "ccQtHelpers.h"
//Qt
#include <QColorDialog>
//system
#include <assert.h>
//persistent parameters
static QColor s_firstColor(Qt::black);
static QColor s_secondColor(Qt::white);
static ccColorGradientDlg::GradientType s_lastType(ccColorGradientDlg::Default);
static double s_lastFreq = 5.0;
ccColorGradientDlg::ccColorGradientDlg(QWidget* parent)
: QDialog(parent, Qt::Tool)
, Ui::ColorGradientDialog()
{
setupUi(this);
connect(firstColorButton, &QAbstractButton::clicked, this, &ccColorGradientDlg::changeFirstColor);
connect(secondColorButton, &QAbstractButton::clicked, this, &ccColorGradientDlg::changeSecondColor);
//restore previous parameters
ccQtHelpers::SetButtonColor(secondColorButton, s_secondColor);
ccQtHelpers::SetButtonColor(firstColorButton, s_firstColor);
setType(s_lastType);
bandingFreqSpinBox->setValue(s_lastFreq);
}
unsigned char ccColorGradientDlg::getDimension() const
{
return static_cast<unsigned char>(directionComboBox->currentIndex());
}
void ccColorGradientDlg::setType(ccColorGradientDlg::GradientType type)
{
switch(type)
{
case Default:
defaultRampRadioButton->setChecked(true);
break;
case TwoColors:
customRampRadioButton->setChecked(true);
break;
case Banding:
bandingRadioButton->setChecked(true);
break;
default:
assert(false);
}
}
ccColorGradientDlg::GradientType ccColorGradientDlg::getType() const
{
//ugly hack: we use 's_lastType' here as the type is only requested
//when the dialog is accepted
if (customRampRadioButton->isChecked())
s_lastType = TwoColors;
else if (bandingRadioButton->isChecked())
s_lastType = Banding;
else
s_lastType = Default;
return s_lastType;
}
void ccColorGradientDlg::getColors(QColor& first, QColor& second) const
{
assert(customRampRadioButton->isChecked());
first = s_firstColor;
second = s_secondColor;
}
double ccColorGradientDlg::getBandingFrequency() const
{
//ugly hack: we use 's_lastFreq' here as the frequency is only requested
//when the dialog is accepted
s_lastFreq = bandingFreqSpinBox->value();
return s_lastFreq;
}
void ccColorGradientDlg::changeFirstColor()
{
QColor newCol = QColorDialog::getColor(s_firstColor, this);
if (newCol.isValid())
{
s_firstColor = newCol;
ccQtHelpers::SetButtonColor(firstColorButton, s_firstColor);
}
}
void ccColorGradientDlg::changeSecondColor()
{
QColor newCol = QColorDialog::getColor(s_secondColor, this);
if (newCol.isValid())
{
s_secondColor = newCol;
ccQtHelpers::SetButtonColor(secondColorButton, s_secondColor);
}
}
| 31.221311
| 101
| 0.631137
|
ohanlonl
|
91abcc4e5cff1535f9fe5d288498f031d2373a63
| 4,016
|
hpp
|
C++
|
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-01T21:38:30.000Z
|
2021-11-03T01:35:11.000Z
|
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 1
|
2020-07-24T17:29:22.000Z
|
2020-07-24T18:29:04.000Z
|
include/public/coherence/io/pof/PofAnnotationSerializer.hpp
|
chpatel3/coherence-cpp-extend-client
|
4ea5267eae32064dff1e73339aa3fbc9347ef0f6
|
[
"UPL-1.0",
"Apache-2.0"
] | 6
|
2020-07-10T18:40:58.000Z
|
2022-02-18T01:23:40.000Z
|
/*
* Copyright (c) 2000, 2020, Oracle and/or its affiliates.
*
* Licensed under the Universal Permissive License v 1.0 as shown at
* http://oss.oracle.com/licenses/upl.
*/
#ifndef COH_POF_ANNOTATION_SERIALIZER_HPP
#define COH_POF_ANNOTATION_SERIALIZER_HPP
#include "coherence/lang.ns"
#include "coherence/io/pof/PofReader.hpp"
#include "coherence/io/pof/PofSerializer.hpp"
#include "coherence/io/pof/PofWriter.hpp"
COH_OPEN_NAMESPACE3(coherence,io,pof)
/**
* A PofAnnotationSerializer provides annotation based (de)serialization.
* This serializer must be instantiated with the intended class which is
* eventually scanned for the presence of the following annotations.
* <ul>
* <li>coherence::io::pof::annotation::Portable</li>
* <li>coherence::io::pof::annotation::PortableProperty</li>
* </ul>
*
* This serializer supports classes iff they are annotated with the type level
* annotation; Portable. This annotation is a marker indicating the ability
* to (de)serialize using this serializer.
*
* All methods annotated with PortableProperty are explicitly
* deemed POF serializable with the option of specifying overrides to
* provide explicit behaviour such as:
* <ul>
* <li>explicit POF indexes</li>
* <li>Custom coherence::io::pof::reflect::Codec to
* specify concrete implementations / customizations</li>
* </ul>
*
* The PortableProperty::getIndex() (POF index) can be omitted iff the
* auto-indexing feature is enabled. This is enabled by instantiating this
* class with the \c fAutoIndex constructor argument. This feature
* determines the index based on any explicit indexes specified and the name
* of the portable properties. Currently objects with multiple versions is
* not supported. The following illustrates the auto index algorithm:
* <table border=1>
* <tr><td>Name</td><td>Explicit Index</td><td>Determined Index</td></tr>
* <tr><td>c</td><td>1</td><td>1</td>
* <tr><td>a</td><td></td><td>0</td>
* <tr><td>b</td><td></td><td>2</td>
* </table>
*
* <b>NOTE:</b> This implementation does support objects that implement
* Evolvable.
*
* @author hr 2011.06.29
*
* @since 3.7.1
*
* @see COH_REGISTER_TYPED_CLASS
* @see COH_REGISTER_POF_ANNOTATED_CLASS
* @see COH_REGISTER_POF_ANNOTATED_CLASS_AI
* @see Portable
*/
class COH_EXPORT PofAnnotationSerializer
: public class_spec<PofAnnotationSerializer,
extends<Object>,
implements<PofSerializer> >
{
friend class factory<PofAnnotationSerializer>;
// ----- constructors ---------------------------------------------------
protected:
/**
* Constructs a PofAnnotationSerializer.
*
* @param nTypeId the POF type id
* @param vClz type this serializer is aware of
* @param fAutoIndex turns on the auto index feature, default = false
*/
PofAnnotationSerializer(int32_t nTypeId, Class::View vClz, bool fAutoIndex = false);
// ----- PofSerializer interface ----------------------------------------
public:
/**
* {@inheritDoc}
*/
virtual void serialize(PofWriter::Handle hOut, Object::View v) const;
/**
* {@inheritDoc}
*/
virtual Object::Holder deserialize(PofReader::Handle hIn) const;
// ---- helpers ---------------------------------------------------------
protected:
/**
* Initialize this class based on the provided information.
*
* @param nTypeId the POF type id
* @param vClz type this serializer is aware of
* @param fAutoIndex turns on the auto index feature
*/
virtual void initialize(int32_t nTypeId, Class::View vClz, bool fAutoIndex);
// ---- data members ----------------------------------------------------
private:
/**
* A structural definition of the type information.
*/
FinalHandle<Object> f_ohTypeMetadata;
};
COH_CLOSE_NAMESPACE3
#endif // COH_POF_ANNOTATION_SERIALIZER_HPP
| 33.190083
| 92
| 0.648904
|
chpatel3
|
91b5701c29df069d7c47d5e8cdbb85b3183b0582
| 1,255
|
cpp
|
C++
|
graphs/dinic.cpp
|
hsnavarro/icpc-notebook
|
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
|
[
"MIT"
] | null | null | null |
graphs/dinic.cpp
|
hsnavarro/icpc-notebook
|
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
|
[
"MIT"
] | null | null | null |
graphs/dinic.cpp
|
hsnavarro/icpc-notebook
|
5e501ecdd56a2a719d2a3a5e99e09d926d7231a3
|
[
"MIT"
] | null | null | null |
// Dinic - O(n^2 * m)
// Max flow
const int N = 1e5 + 5;
const int INF = 0x3f3f3f3f;
struct edge { int v, c, f; };
int n, s, t, h[N], st[N];
vector<edge> edgs;
vector<int> g[N];
// directed from u to v with cap(u, v) = c
void add_edge(int u, int v, int c) {
int k = edgs.size();
edgs.push_back({v, c, 0});
edgs.push_back({u, 0, 0});
g[u].push_back(k);
g[v].push_back(k+1);
}
int bfs() {
memset(h, 0, sizeof h);
h[s] = 1;
queue<int> q;
q.push(s);
while(q.size()) {
int u = q.front(); q.pop();
for(auto i : g[u]) {
int v = edgs[i].v;
if(!h[v] and edgs[i].f < edgs[i].c)
h[v] = h[u] + 1, q.push(v);
}
}
return h[t];
}
int dfs(int u, int flow) {
if(!flow or u == t) return flow;
for(int &i = st[u]; i < g[u].size(); i++) {
edge &dir = edgs[g[u][i]], &rev = edgs[g[u][i]^1];
int v = dir.v;
if(h[v] != h[u] + 1) continue;
int inc = min(flow, dir.c - dir.f);
inc = dfs(v, inc);
if(inc) {
dir.f += inc, rev.f -= inc;
return inc;
}
}
return 0;
}
int dinic() {
int flow = 0;
while(bfs()) {
memset(st, 0, sizeof st);
while(int inc = dfs(s, INF)) flow += inc;
}
return flow;
}
| 19.920635
| 55
| 0.467729
|
hsnavarro
|
91b78f33891c2e2ba7f7dc198195baf90da2033d
| 4,582
|
cpp
|
C++
|
tests/tests/array/test_fixedlengtharray.cpp
|
jnory/YuNomi
|
c7a2750010d531af53a7a3007ca9b9e6b69dae93
|
[
"MIT"
] | 8
|
2016-09-10T05:45:59.000Z
|
2019-04-06T13:27:18.000Z
|
tests/tests/array/test_fixedlengtharray.cpp
|
jnory/YuNomi
|
c7a2750010d531af53a7a3007ca9b9e6b69dae93
|
[
"MIT"
] | 1
|
2017-11-18T19:49:37.000Z
|
2018-05-05T09:49:27.000Z
|
tests/tests/array/test_fixedlengtharray.cpp
|
jnory/YuNomi
|
c7a2750010d531af53a7a3007ca9b9e6b69dae93
|
[
"MIT"
] | 1
|
2015-12-06T20:51:10.000Z
|
2015-12-06T20:51:10.000Z
|
#include "gtest/gtest.h"
#include "yunomi/array/fixedlengtharray.hpp"
TEST(TestFixedLengthArray, test_init){
yunomi::array::FixedLengthArray array(10, 1);
EXPECT_EQ(10, array.size());
EXPECT_EQ(1, array.bits_per_slot());
}
TEST(TestFixedLengthArray, test_ten_values){
yunomi::array::FixedLengthArray array(10, 4);
EXPECT_EQ(10, array.size());
EXPECT_EQ(4, array.bits_per_slot());
for(std::size_t i = 0; i < 10; ++i){
array[i] = i;
EXPECT_EQ(i, uint64_t(array[i]));
}
for(std::size_t i = 0; i < 10; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
}
TEST(TestFixedLengthArray, test_thousand_values){
yunomi::array::FixedLengthArray array(1000, 10);
EXPECT_EQ(1000, array.size());
for(std::size_t i = 0; i < 1000; ++i){
array[i] = i;
}
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
}
TEST(TestFixedLengthArray, test_resize){
yunomi::array::FixedLengthArray array(1000, 10);
for(std::size_t i = 0; i < 1000; ++i){
array[i] = i;
}
array.resize(1500, 10);
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
for(std::size_t i = 1000; i < 1500; ++i){
EXPECT_EQ(0, uint64_t(array[i]));
}
}
TEST(TestFixedLengthArray, test_resize2){
yunomi::array::FixedLengthArray array(1000, 10);
for(std::size_t i = 0; i < 1000; ++i){
array[i] = i;
}
array.resize(1500, 11);
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
for(std::size_t i = 1000; i < 1500; ++i){
EXPECT_EQ(0, uint64_t(array[i]));
}
}
TEST(TestFixedLengthArray, test_thousand_values_template){
yunomi::array::ConstLengthArray<10> array(1000);
EXPECT_EQ(1000, array.size());
EXPECT_EQ(10, array.bits_per_slot());
for(std::size_t i = 0; i < 1000; ++i){
array[i] = i;
}
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
array.resize(1500);
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
for(std::size_t i = 1000; i < 1500; ++i){
EXPECT_EQ(0, uint64_t(array[i]));
}
}
TEST(TestFixedLengthArray, test_thousand_values_template_8bit){
yunomi::array::ConstLengthArray<8> array(1000);
EXPECT_EQ(1000, array.size());
EXPECT_EQ(8, array.bits_per_slot());
for(std::size_t i = 0; i < 1000; ++i){
array[i] = i % 256;
}
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i % 256, uint64_t(array[i]));
}
array.resize(1500);
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i % 256, uint64_t(array[i]));
}
for(std::size_t i = 1000; i < 1500; ++i){
EXPECT_EQ(0, uint64_t(array[i]));
}
}
TEST(TestFixedLengthArray, test_thousand_values_template_16bit){
yunomi::array::ConstLengthArray<16> array(1000);
EXPECT_EQ(1000, array.size());
EXPECT_EQ(16, array.bits_per_slot());
for(std::size_t i = 0; i < 1000; ++i){
array[i] = i;
}
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
array.resize(1500);
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
for(std::size_t i = 1000; i < 1500; ++i){
EXPECT_EQ(0, uint64_t(array[i]));
}
}
TEST(TestFixedLengthArray, test_thousand_values_template_32bit){
yunomi::array::ConstLengthArray<32> array(1000);
EXPECT_EQ(1000, array.size());
EXPECT_EQ(32, array.bits_per_slot());
for(std::size_t i = 0; i < 1000; ++i){
array[i] = i;
}
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
array.resize(1500);
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
for(std::size_t i = 1000; i < 1500; ++i){
EXPECT_EQ(0, uint64_t(array[i]));
}
}
TEST(TestFixedLengthArray, test_thousand_values_template_64bit){
yunomi::array::ConstLengthArray<64> array(1000);
EXPECT_EQ(1000, array.size());
EXPECT_EQ(64, array.bits_per_slot());
for(std::size_t i = 0; i < 1000; ++i){
array[i] = i;
}
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
array.resize(1500);
for(std::size_t i = 0; i < 1000; ++i){
EXPECT_EQ(i, uint64_t(array[i]));
}
for(std::size_t i = 1000; i < 1500; ++i){
EXPECT_EQ(0, uint64_t(array[i]));
}
}
//TODO write tests
//TODO write tests for the size==0
| 29
| 64
| 0.576168
|
jnory
|
91ba70ddc6aa008b545aa52db848a7b88fafef6e
| 1,238
|
cpp
|
C++
|
wpl1000/utility.cpp
|
ola-ct/gpstools
|
6a221553077139ad30e0ddf9ee155024ad7a4d26
|
[
"BSD-3-Clause"
] | null | null | null |
wpl1000/utility.cpp
|
ola-ct/gpstools
|
6a221553077139ad30e0ddf9ee155024ad7a4d26
|
[
"BSD-3-Clause"
] | null | null | null |
wpl1000/utility.cpp
|
ola-ct/gpstools
|
6a221553077139ad30e0ddf9ee155024ad7a4d26
|
[
"BSD-3-Clause"
] | null | null | null |
// $Id$
// Copyright (c) 2009 Oliver Lau <oliver@ersatzworld.net>
#include "stdafx.h"
VOID Warn(LPTSTR lpszMessage)
{
MessageBox(NULL, (LPCTSTR)lpszMessage, TEXT("Fehler"), MB_OK);
}
VOID Error(LPTSTR lpszFunction, LONG lErrCode)
{
LPVOID lpMsgBuf;
LPVOID lpDisplayBuf;
if (lErrCode == 0)
lErrCode = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
lErrCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT,
(lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR));
StringCchPrintf((LPTSTR)lpDisplayBuf,
LocalSize(lpDisplayBuf) / sizeof(TCHAR),
TEXT("%s fehlgeschlagen mit Fehler %d: %s"),
lpszFunction, lErrCode, lpMsgBuf);
MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Fehler"), MB_OK);
LocalFree(lpMsgBuf);
LocalFree(lpDisplayBuf);
}
VOID ErrorExit(LPTSTR lpszFunction, LONG lErrCode)
{
Error(lpszFunction, lErrCode);
ExitProcess(lErrCode);
}
| 27.511111
| 93
| 0.64378
|
ola-ct
|
91bbe1f1e423082754525c7a24e8c6c981b1580a
| 498
|
cpp
|
C++
|
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
|
Carduin/IUT
|
2642c23d3a3c4932ddaeb9d5f482be35def9273b
|
[
"MIT"
] | 5
|
2022-02-08T09:36:54.000Z
|
2022-02-10T08:47:17.000Z
|
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
|
Carduin/IUT
|
2642c23d3a3c4932ddaeb9d5f482be35def9273b
|
[
"MIT"
] | null | null | null |
DUT S2/M2103 - Prog Objet/cplus/tests_TPs/testTP1.cpp
|
Carduin/IUT
|
2642c23d3a3c4932ddaeb9d5f482be35def9273b
|
[
"MIT"
] | 3
|
2021-12-10T16:11:46.000Z
|
2022-02-15T15:07:41.000Z
|
#include "Fenetre.h"
#include "Souris.h"
int main (int argc, char **argv){
gtk_init(&argc, &argv);
Fenetre f;
Souris s;
int b, x, y;
f.apparait("Test TP1",500,400,0,0,100,100,100);
s.associerA(f);
f.choixCouleurTrace(255,100,100);
f.ecrit(10,100,"Bravo, vous avez bien parametre votre environnement !!");
f.choixCouleurTrace(0,0,0);
f.ecrit(100,240,"CLIQUER POUR QUITTER");
while (!s.testeBoutons(x, y, b));
f.disparait();
return 0;
}
| 17.172414
| 77
| 0.608434
|
Carduin
|
91bf84920e2f84cee2312fae1434faf045fc4cc4
| 622
|
cpp
|
C++
|
source/globjects/source/AttachedRenderbuffer.cpp
|
kateyy/globjects
|
4c5fc073063ca52ea32ce0adb57009a3c52f72a8
|
[
"MIT"
] | 18
|
2016-09-03T05:12:25.000Z
|
2022-02-23T15:52:33.000Z
|
external/globjects-0.5.0/source/globjects/source/AttachedRenderbuffer.cpp
|
3d-scan/rgbd-recon
|
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
|
[
"MIT"
] | 1
|
2016-05-04T09:06:29.000Z
|
2016-05-04T09:06:29.000Z
|
external/globjects-0.5.0/source/globjects/source/AttachedRenderbuffer.cpp
|
3d-scan/rgbd-recon
|
c4a5614eaa55dd93c74da70d6fb3d813d74f2903
|
[
"MIT"
] | 7
|
2016-04-20T13:58:50.000Z
|
2018-07-09T15:47:26.000Z
|
#include <globjects/AttachedRenderbuffer.h>
#include <cassert>
#include <globjects/Renderbuffer.h>
using namespace gl;
namespace globjects
{
AttachedRenderbuffer::AttachedRenderbuffer(Framebuffer * fbo, const GLenum attachment, Renderbuffer * renderBuffer)
: FramebufferAttachment(fbo, attachment)
, m_renderBuffer(renderBuffer)
{
}
bool AttachedRenderbuffer::isRenderBufferAttachment() const
{
return true;
}
Renderbuffer * AttachedRenderbuffer::renderBuffer()
{
return m_renderBuffer;
}
const Renderbuffer * AttachedRenderbuffer::renderBuffer() const
{
return m_renderBuffer;
}
} // namespace globjects
| 17.771429
| 116
| 0.790997
|
kateyy
|
91c2b85dd910620172b6fd358a4f88b066339835
| 1,042
|
cpp
|
C++
|
test/HW_B2/tests_task_D.cpp
|
GAlekseyV/YandexTraining
|
e49ce6616e2584a80857a8b2f45b700f12b1fb85
|
[
"Unlicense"
] | 1
|
2021-09-21T23:24:37.000Z
|
2021-09-21T23:24:37.000Z
|
test/HW_B2/tests_task_D.cpp
|
GAlekseyV/YandexTraining
|
e49ce6616e2584a80857a8b2f45b700f12b1fb85
|
[
"Unlicense"
] | null | null | null |
test/HW_B2/tests_task_D.cpp
|
GAlekseyV/YandexTraining
|
e49ce6616e2584a80857a8b2f45b700f12b1fb85
|
[
"Unlicense"
] | null | null | null |
#include <algorithm>
#include <catch2/catch.hpp>
#include <vector>
std::vector<int> calc_ans(const std::vector<int> &seq, int l);
TEST_CASE("D. Лавочки в атриуме", " ")
{
REQUIRE(calc_ans({ 0, 2 }, 5) == std::vector<int>{ 2 });
REQUIRE(calc_ans({ 1, 4, 8, 11 }, 13) == std::vector<int>{ 4, 8 });
REQUIRE(calc_ans({ 1, 6, 8, 11, 12, 13 }, 14) == std::vector<int>{ 6, 8 });
REQUIRE(calc_ans({ 0 }, 1) == std::vector<int>{ 0 });
}
bool isOdd(long long n)
{
if (n % 2 == 1) {
return true;
}
return false;
}
std::vector<int> calc_ans(const std::vector<int> &seq, int l)
{
int border = 0;
std::vector<int> ans;
if (seq.size() == 1) {
ans.push_back(seq[0]);
} else {
border = l / 2;
auto it = std::lower_bound(seq.begin(), seq.end(), border);
if (isOdd(l)) {
if (*(it) == border) {
ans.push_back(*it);
} else {
ans.push_back(*(it - 1));
ans.push_back(*(it));
}
} else {
ans.push_back(*(it - 1));
ans.push_back(*(it));
}
}
return ans;
}
| 22.170213
| 77
| 0.53167
|
GAlekseyV
|
91c4a0ead6e52ce6c394ce7b7155be6042fb6f51
| 1,684
|
cpp
|
C++
|
tests/src/test_colors.cpp
|
jegabe/ColorMyConsole
|
825855916f93279477051c54715fe76a99629c2a
|
[
"MIT"
] | null | null | null |
tests/src/test_colors.cpp
|
jegabe/ColorMyConsole
|
825855916f93279477051c54715fe76a99629c2a
|
[
"MIT"
] | null | null | null |
tests/src/test_colors.cpp
|
jegabe/ColorMyConsole
|
825855916f93279477051c54715fe76a99629c2a
|
[
"MIT"
] | null | null | null |
// (c) 2021 Jens Ganter-Benzing. Licensed under the MIT license.
#include <iostream>
#include <colmc/setup.h>
#include <colmc/sequences.h>
using namespace colmc;
struct color {
const char* esc_sequence;
const char* name;
};
const struct color bg_colors[] = {
{ back::black, "black " },
{ back::red, "red " },
{ back::green, "green " },
{ back::yellow, "yellow " },
{ back::blue, "blue " },
{ back::magenta, "magenta" },
{ back::cyan, "cyan " },
{ back::white, "white " }
};
const struct color fg_colors[] = {
{ fore::black, "black " },
{ fore::red, "red " },
{ fore::green, "green " },
{ fore::yellow, "yellow " },
{ fore::blue, "blue " },
{ fore::magenta, "magenta" },
{ fore::cyan, "cyan " },
{ fore::white, "white " }
};
int main() {
setup();
std::cout << " ";
for (std::size_t fg_index = 0; fg_index < (sizeof(fg_colors)/sizeof(fg_colors[0])); ++fg_index) {
std::cout << fg_colors[fg_index].esc_sequence << fg_colors[fg_index].name;
}
std::cout << std::endl;
for (std::size_t bg_index = 0; bg_index < (sizeof(bg_colors)/sizeof(bg_colors[0])); ++bg_index) {
std::cout << bg_colors[bg_index].esc_sequence << fore::reset << bg_colors[bg_index].name;
for (std::size_t fg_index = 0; fg_index < (sizeof(fg_colors)/sizeof(fg_colors[0])); ++fg_index) {
std::cout << back::reset << " ";
std::cout << bg_colors[bg_index].esc_sequence;
std::cout << fg_colors[fg_index].esc_sequence << fore::dim << "X " << fore::normal << "X " << fore::bright << "X " << reset_all;
}
std::cout << std::endl;
}
std::cout << reset_all << "Press return to terminate";
std::cin.get();
return 0;
}
| 30.071429
| 132
| 0.589074
|
jegabe
|
91c6879681bb3ad66670d6360cc3f0a4fac38d31
| 2,807
|
cp
|
C++
|
Comm/Mod/Streams.cp
|
romiras/Blackbox-fw-playground
|
6de94dc65513e657a9b86c1772e2c07742b608a8
|
[
"BSD-2-Clause"
] | 1
|
2016-03-17T08:27:05.000Z
|
2016-03-17T08:27:05.000Z
|
Comm/Mod/Streams.cps
|
Spirit-of-Oberon/LightBox
|
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
|
[
"BSD-2-Clause"
] | null | null | null |
Comm/Mod/Streams.cps
|
Spirit-of-Oberon/LightBox
|
8a45ed11dcc02ae97e86f264dcee3e07c910ff9d
|
[
"BSD-2-Clause"
] | 1
|
2018-03-14T17:53:27.000Z
|
2018-03-14T17:53:27.000Z
|
MODULE CommStreams;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = ""
issues = ""
**)
IMPORT Meta;
CONST
(* portable error codes: *)
done* = 0; noSuchProtocol* = 1; invalidLocalAdr* = 2; invalidRemoteAdr* = 3; networkDown* = 4;
localAdrInUse* = 5; remoteAdrInUse* = 6;
TYPE
Adr* = POINTER TO ARRAY OF CHAR;
Stream* = POINTER TO ABSTRACT RECORD END;
StreamAllocator* = PROCEDURE
(localAdr, remoteAdr: ARRAY OF CHAR; OUT s: Stream; OUT res: INTEGER);
Listener* = POINTER TO ABSTRACT RECORD END;
ListenerAllocator* = PROCEDURE
(localAdr: ARRAY OF CHAR; OUT l: Listener; OUT res: INTEGER);
PROCEDURE (s: Stream) RemoteAdr* (): Adr, NEW, ABSTRACT;
PROCEDURE (s: Stream) IsConnected* (): BOOLEAN, NEW, ABSTRACT;
PROCEDURE (s: Stream) WriteBytes* (
IN x: ARRAY OF BYTE; beg, len: INTEGER; OUT written: INTEGER), NEW, ABSTRACT;
PROCEDURE (s: Stream) ReadBytes* (
VAR x: ARRAY OF BYTE; beg, len: INTEGER; OUT read: INTEGER), NEW, ABSTRACT;
PROCEDURE (s: Stream) Close*, NEW, ABSTRACT;
PROCEDURE NewStream* (protocol, localAdr, remoteAdr: ARRAY OF CHAR; OUT s: Stream; OUT res: INTEGER);
VAR ok: BOOLEAN; m, p: Meta.Item; mod: Meta.Name;
v: RECORD (Meta.Value)
p: StreamAllocator
END;
BEGIN
ASSERT(protocol # "", 20);
res := noSuchProtocol;
mod := protocol$; Meta.Lookup(mod, m);
IF m.obj = Meta.modObj THEN
m.Lookup("NewStream", p);
IF p.obj = Meta.procObj THEN
p.GetVal(v, ok);
IF ok THEN v.p(localAdr, remoteAdr, s, res) END
END
END
END NewStream;
PROCEDURE (l: Listener) LocalAdr* (): Adr, NEW, ABSTRACT;
PROCEDURE (l: Listener) Accept* (OUT s: Stream), NEW, ABSTRACT;
PROCEDURE (l: Listener) Close*, NEW, ABSTRACT;
PROCEDURE NewListener* (protocol, localAdr: ARRAY OF CHAR; OUT l: Listener; OUT res: INTEGER);
VAR ok: BOOLEAN; m, p: Meta.Item; mod: Meta.Name;
v: RECORD(Meta.Value)
p: ListenerAllocator
END;
BEGIN
ASSERT(protocol # "", 20);
res := noSuchProtocol;
mod := protocol$; Meta.Lookup(mod, m);
IF m.obj = Meta.modObj THEN
m.Lookup("NewListener", p);
IF p.obj = Meta.procObj THEN
p.GetVal(v, ok);
IF ok THEN v.p(localAdr, l, res) END
END
END
END NewListener;
END CommStreams.
| 32.639535
| 105
| 0.56466
|
romiras
|
91ca06b4ec287cce73acf4d73eb84dcf5e090adb
| 587
|
hxx
|
C++
|
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
|
SergeyKleyman/elastic-apm-agent-cpp-prototype
|
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
|
[
"Apache-2.0"
] | null | null | null |
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
|
SergeyKleyman/elastic-apm-agent-cpp-prototype
|
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
|
[
"Apache-2.0"
] | null | null | null |
src/include/Elastic/Apm/Config/IRawSnapshot.hxx
|
SergeyKleyman/elastic-apm-agent-cpp-prototype
|
67d2c7ad5a50e1a6b75d6725a89ae3fc5a92d517
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include "Elastic/Apm/Util/String.hxx"
#include "Elastic/Apm/Util/Optional.hxx"
namespace Elastic { namespace Apm { namespace Config
{
using namespace Elastic::Apm;
class IRawSnapshot
{
protected:
using String = Util::String;
template< typename T >
using Optional = Util::Optional< T >;
public:
struct ValueData
{
String value;
String dbgValueSourceDesc;
};
virtual Optional< ValueData > operator[]( const char* optName ) const = 0;
protected:
~IRawSnapshot() = default;
};
} } } // namespace Elastic::Apm::Config
| 16.305556
| 78
| 0.667802
|
SergeyKleyman
|
91cad30ec6590d8dda7374c959f0048d19154093
| 467
|
cpp
|
C++
|
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
|
benhj/arrow
|
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
|
[
"MIT"
] | 19
|
2019-12-10T07:35:08.000Z
|
2021-09-27T11:49:37.000Z
|
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
|
benhj/arrow
|
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
|
[
"MIT"
] | 22
|
2020-02-09T15:39:53.000Z
|
2020-03-02T19:04:40.000Z
|
src/receivers/evaluator/IdentifierReceiverEvaluator.cpp
|
benhj/arrow
|
a88caec0bcf44f70343d6f8d3a4be5790d903ddb
|
[
"MIT"
] | 2
|
2020-02-17T21:20:43.000Z
|
2020-03-02T00:42:08.000Z
|
/// (c) Ben Jones 2019
#include "IdentifierReceiverEvaluator.hpp"
#include "parser/LanguageException.hpp"
#include <utility>
namespace arrow {
IdentifierReceiverEvaluator::IdentifierReceiverEvaluator(Token tok)
: m_tok(std::move(tok))
{
}
void IdentifierReceiverEvaluator::evaluate(Type incoming, Environment & environment) const
{
// automatically does a replace
environment.add(m_tok.raw, std::move(incoming));
}
}
| 24.578947
| 94
| 0.702355
|
benhj
|
91ce8c90b43c369c3352048a25ece820de97be26
| 814
|
cpp
|
C++
|
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | 39
|
2016-04-21T03:25:26.000Z
|
2022-01-19T14:16:38.000Z
|
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | 23
|
2016-06-28T13:03:17.000Z
|
2022-02-02T10:11:54.000Z
|
src/Frameworks/PythonFramework/PythonSchedulePipe.cpp
|
Terryhata6/Mengine
|
dfe36fdc84d7398fbbbd199feffc46c6f157f1d4
|
[
"MIT"
] | 14
|
2016-06-22T20:45:37.000Z
|
2021-07-05T12:25:19.000Z
|
#include "PythonSchedulePipe.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
PythonSchedulePipe::PythonSchedulePipe()
{
}
//////////////////////////////////////////////////////////////////////////
PythonSchedulePipe::~PythonSchedulePipe()
{
}
//////////////////////////////////////////////////////////////////////////
void PythonSchedulePipe::initialize( const pybind::object & _cb, const pybind::args & _args )
{
m_cb = _cb;
m_args = _args;
}
//////////////////////////////////////////////////////////////////////////
float PythonSchedulePipe::onSchedulerPipe( uint32_t _id, uint32_t _index )
{
float delay = m_cb.call_args( _id, _index, m_args );
return delay;
}
}
| 31.307692
| 97
| 0.388206
|
Terryhata6
|
91d1a1704e26fdad9ce7d50a91d33736456872b1
| 2,677
|
cpp
|
C++
|
src/EnemyController.cpp
|
CS126SP20/final-project-Tejesh2001
|
70a5d11504f968714392c92d70c472c38e4b0116
|
[
"MIT"
] | null | null | null |
src/EnemyController.cpp
|
CS126SP20/final-project-Tejesh2001
|
70a5d11504f968714392c92d70c472c38e4b0116
|
[
"MIT"
] | null | null | null |
src/EnemyController.cpp
|
CS126SP20/final-project-Tejesh2001
|
70a5d11504f968714392c92d70c472c38e4b0116
|
[
"MIT"
] | 1
|
2020-09-06T12:47:47.000Z
|
2020-09-06T12:47:47.000Z
|
#pragma once
#include "mylibrary/EnemyController.h"
#include <cinder/app/AppBase.h>
#include "cinder/Rand.h"
#include "mylibrary/CoordinateConversions.h"
#include "mylibrary/ProjectWideConstants.h"
namespace mylibrary {
using std::list;
EnemyController::EnemyController() = default;
void EnemyController::setup(b2World &my_world) {
// Setting up world and location for test
world_ = &my_world;
location_for_test = new b2Vec2(0, 0);
}
void EnemyController::update() {
for (auto p = enemies.begin(); p != enemies.end();) {
// if the enemy is dead, it removes the body
if (!enemies.empty() && p->IsDead()) {
world_->DestroyBody(p->GetBody());
p = enemies.erase(p);
} else {
p->update();
++p;
}
}
}
void EnemyController::draw() {
for (auto &particle : enemies) {
particle.draw();
}
}
void EnemyController::AddEnemies(int amount) {
int kTestAmount = 3;
// I add 3 enemies in my test cases there test amount is three
float world_width;
if (amount <= kTestAmount) {
world_width = global::kLeftMostIndex;
} else {
world_width = (conversions::ToBox2DCoordinates(
static_cast<float>(cinder::app::getWindowWidth())));
}
for (int i = 0; i < amount; i++) {
b2BodyDef body_def;
body_def.type = b2_dynamicBody;
// Sets the position of the enemy on top of the screen somewhere
if (location_for_test->y != global::kLowerMostIndex) {
body_def.position.Set(ci::randFloat(world_width),
global::kLowerMostIndex);
} else {
body_def.position.Set(location_for_test->x, location_for_test->y);
location_for_test->y = kActualY;
}
CreateBody(body_def);
}
}
b2BodyDef &EnemyController::CreateBody(b2BodyDef &body_def) {
Enemy enemy;
// Creating enemy and its corresponding properties
body_def.userData = &enemy;
body_def.bullet = true;
enemy.SetBody(world_->CreateBody(&body_def));
b2PolygonShape dynamic_box;
// Setting dimensions of enemy
dynamic_box.SetAsBox(
conversions::ToBox2DCoordinates(global::kBoxDimensions.x),
conversions::ToBox2DCoordinates(global::kBoxDimensions.y));
b2FixtureDef fixture_def;
// Setting properties of fixture
fixture_def.shape = &dynamic_box;
fixture_def.density = global::kDensity;
fixture_def.friction = global::kFriction;
fixture_def.restitution = global::kRestitution / kBounceLimiter; // bounce
// Setting body properties
enemy.GetBody()->CreateFixture(&fixture_def);
enemy.setup(global::kBoxDimensions);
enemies.push_back(enemy);
return body_def;
}
std::list<Enemy> &EnemyController::GetEnemies() { return enemies; }
} // namespace mylibrary
| 29.417582
| 77
| 0.694061
|
CS126SP20
|
91d9b1be00d77e8275bd5320f99ca23afed93674
| 509
|
hpp
|
C++
|
src/Engine/Scene/Scene.hpp
|
Liljan/Ape-Engine
|
174842ada3a565e83569722837b242fa9faa4114
|
[
"MIT"
] | null | null | null |
src/Engine/Scene/Scene.hpp
|
Liljan/Ape-Engine
|
174842ada3a565e83569722837b242fa9faa4114
|
[
"MIT"
] | null | null | null |
src/Engine/Scene/Scene.hpp
|
Liljan/Ape-Engine
|
174842ada3a565e83569722837b242fa9faa4114
|
[
"MIT"
] | null | null | null |
#pragma once
#include "Engine/Datatypes.hpp"
#include <SFML/Graphics/RenderWindow.hpp>
class SceneManager;
class ResourceManager;
class Scene
{
public:
~Scene() = default;
virtual void HandleInput(sf::Event& event) = 0;
virtual void Update(float dt) = 0;
virtual void Draw(sf::RenderWindow& window) = 0;
virtual void Load() = 0;
virtual void Unload() = 0;
virtual uint32 GetType() const = 0;
protected:
SceneManager* m_SceneManager = nullptr;
ResourceManager* m_ResourceManager = nullptr;
};
| 18.178571
| 49
| 0.72888
|
Liljan
|
91de5fa1a8e651537de6d2da28989c95dbbf40f9
| 10,420
|
cpp
|
C++
|
Source/Mesh.cpp
|
DavidColson/Polybox
|
6c3d5939c4baa124e5113fd4146a654f6005e7f6
|
[
"MIT"
] | 252
|
2021-08-18T10:43:37.000Z
|
2022-03-20T18:43:59.000Z
|
Source/Mesh.cpp
|
DavidColson/Polybox
|
6c3d5939c4baa124e5113fd4146a654f6005e7f6
|
[
"MIT"
] | 3
|
2021-12-01T09:08:33.000Z
|
2022-01-14T08:56:19.000Z
|
Source/Mesh.cpp
|
DavidColson/Polybox
|
6c3d5939c4baa124e5113fd4146a654f6005e7f6
|
[
"MIT"
] | 10
|
2021-11-30T16:17:54.000Z
|
2022-03-28T17:56:18.000Z
|
#include "Mesh.h"
#include "Core/Json.h"
#include "Core/Base64.h"
#include <SDL_rwops.h>
#include <string>
// ***********************************************************************
int Primitive::GetNumVertices()
{
return (int)m_vertices.size();
}
// ***********************************************************************
Vec3f Primitive::GetVertexPosition(int index)
{
return m_vertices[index].pos;
}
// ***********************************************************************
Vec4f Primitive::GetVertexColor(int index)
{
return m_vertices[index].col;
}
// ***********************************************************************
Vec2f Primitive::GetVertexTexCoord(int index)
{
return m_vertices[index].tex;
}
// ***********************************************************************
Vec3f Primitive::GetVertexNormal(int index)
{
return m_vertices[index].norm;
}
// ***********************************************************************
int Primitive::GetMaterialTextureId()
{
return m_baseColorTexture;
}
// ***********************************************************************
Mesh::~Mesh()
{
}
// ***********************************************************************
int Mesh::GetNumPrimitives()
{
return (int)m_primitives.size();
}
// ***********************************************************************
Primitive* Mesh::GetPrimitive(int index)
{
return &m_primitives[index];
}
// ***********************************************************************
// Actually owns the data
struct Buffer
{
char* pBytes{ nullptr };
size_t byteLength{ 0 };
};
// Does not actually own the data
struct BufferView
{
// pointer to some place in a buffer
char* pBuffer{ nullptr };
size_t length{ 0 };
enum Target
{
Array,
ElementArray
};
Target target;
};
struct Accessor
{
// pointer to some place in a buffer view
char* pBuffer{ nullptr };
int count{ 0 };
enum ComponentType
{
Byte,
UByte,
Short,
UShort,
UInt,
Float
};
ComponentType componentType;
enum Type
{
Scalar,
Vec2,
Vec3,
Vec4,
Mat2,
Mat3,
Mat4
};
Type type;
};
// ***********************************************************************
std::vector<Mesh*> Mesh::LoadMeshes(const char* filePath)
{
std::vector<Mesh*> outMeshes;
// Consider caching loaded json files somewhere since LoadScene and LoadMeshes are doing duplicate work here
SDL_RWops* pFileRead = SDL_RWFromFile(filePath, "rb");
uint64_t size = SDL_RWsize(pFileRead);
char* pData = new char[size];
SDL_RWread(pFileRead, pData, size, 1);
SDL_RWclose(pFileRead);
std::string file(pData, pData + size);
delete[] pData;
JsonValue parsed = ParseJsonFile(file);
bool validGltf = parsed["asset"]["version"].ToString() == "2.0";
if (!validGltf)
return std::vector<Mesh*>();
std::vector<Buffer> rawDataBuffers;
JsonValue& jsonBuffers = parsed["buffers"];
for (int i = 0; i < jsonBuffers.Count(); i++)
{
Buffer buf;
buf.byteLength = jsonBuffers[i]["byteLength"].ToInt();
buf.pBytes = new char[buf.byteLength];
std::string encodedBuffer = jsonBuffers[i]["uri"].ToString().substr(37);
memcpy(buf.pBytes, DecodeBase64(encodedBuffer).data(), buf.byteLength);
rawDataBuffers.push_back(buf);
}
std::vector<BufferView> bufferViews;
JsonValue& jsonBufferViews = parsed["bufferViews"];
for (int i = 0; i < jsonBufferViews.Count(); i++)
{
BufferView view;
int bufIndex = jsonBufferViews[i]["buffer"].ToInt();
view.pBuffer = rawDataBuffers[bufIndex].pBytes + jsonBufferViews[i]["byteOffset"].ToInt(); //@Incomplete, byte offset could not be provided, in which case we assume 0
view.length = jsonBufferViews[i]["byteLength"].ToInt();
// @Incomplete, target may not be provided
int target = jsonBufferViews[i]["target"].ToInt();
if (target == 34963)
view.target = BufferView::ElementArray;
else if (target = 34962)
view.target = BufferView::Array;
bufferViews.push_back(view);
}
std::vector<Accessor> accessors;
JsonValue& jsonAccessors = parsed["accessors"];
accessors.reserve(jsonAccessors.Count());
for (int i = 0; i < jsonAccessors.Count(); i++)
{
Accessor acc;
JsonValue& jsonAcc = jsonAccessors[i];
int idx = jsonAcc["bufferView"].ToInt();
acc.pBuffer = bufferViews[idx].pBuffer + jsonAcc["byteOffset"].ToInt();
acc.count = jsonAcc["count"].ToInt();
int compType = jsonAcc["componentType"].ToInt();
switch (compType)
{
case 5120: acc.componentType = Accessor::Byte; break;
case 5121: acc.componentType = Accessor::UByte; break;
case 5122: acc.componentType = Accessor::Short; break;
case 5123: acc.componentType = Accessor::UShort; break;
case 5125: acc.componentType = Accessor::UInt; break;
case 5126: acc.componentType = Accessor::Float; break;
default: break;
}
std::string type = jsonAcc["type"].ToString();
if (type == "SCALAR") acc.type = Accessor::Scalar;
else if (type == "VEC2") acc.type = Accessor::Vec2;
else if (type == "VEC3") acc.type = Accessor::Vec3;
else if (type == "VEC4") acc.type = Accessor::Vec4;
else if (type == "MAT2") acc.type = Accessor::Mat2;
else if (type == "MAT3") acc.type = Accessor::Mat3;
else if (type == "MAT4") acc.type = Accessor::Mat4;
accessors.push_back(acc);
}
outMeshes.reserve(parsed["meshes"].Count());
for (int i = 0; i < parsed["meshes"].Count(); i++)
{
JsonValue& jsonMesh = parsed["meshes"][i];
Mesh* pMesh = new Mesh();
pMesh->m_name = jsonMesh.HasKey("name") ? jsonMesh["name"].ToString() : "";
for (int j = 0; j < jsonMesh["primitives"].Count(); j++)
{
JsonValue& jsonPrimitive = jsonMesh["primitives"][j];
Primitive prim;
if (jsonPrimitive.HasKey("mode"))
{
if (jsonPrimitive["mode"].ToInt() != 4)
{
return std::vector<Mesh*>(); // Unsupported topology type
}
}
// Get material texture
if (jsonPrimitive.HasKey("material"))
{
int materialId = jsonPrimitive["material"].ToInt();
JsonValue& jsonMaterial = parsed["materials"][materialId];
JsonValue& pbr = jsonMaterial["pbrMetallicRoughness"];
if (pbr.HasKey("baseColorTexture"))
{
int textureId = pbr["baseColorTexture"]["index"].ToInt();
int imageId = parsed["textures"][textureId]["source"].ToInt();
prim.m_baseColorTexture = imageId;
}
}
int nVerts = accessors[jsonPrimitive["attributes"]["POSITION"].ToInt()].count;
JsonValue& jsonAttr = jsonPrimitive["attributes"];
Vec3f* vertPositionBuffer = (Vec3f*)accessors[jsonAttr["POSITION"].ToInt()].pBuffer;
Vec3f* vertNormBuffer = jsonAttr.HasKey("NORMAL") ? (Vec3f*)accessors[jsonAttr["NORMAL"].ToInt()].pBuffer : nullptr;
Vec2f* vertTexCoordBuffer = jsonAttr.HasKey("TEXCOORD_0") ? (Vec2f*)accessors[jsonAttr["TEXCOORD_0"].ToInt()].pBuffer : nullptr;
// Interlace vertex data
std::vector<VertexData> indexedVertexData;
indexedVertexData.reserve(nVerts);
if (jsonAttr.HasKey("COLOR_0"))
{
Vec4f* vertColBuffer = (Vec4f*)accessors[jsonAttr["COLOR_0"].ToInt()].pBuffer;
for (int i = 0; i < nVerts; i++)
{
indexedVertexData.push_back({vertPositionBuffer[i], vertColBuffer[i], vertTexCoordBuffer[i], vertNormBuffer[i]});
}
}
else
{
for (int i = 0; i < nVerts; i++)
{
indexedVertexData.push_back({vertPositionBuffer[i], Vec4f(1.0f, 1.0f, 1.0f, 1.0f), vertTexCoordBuffer[i], vertNormBuffer[i]});
}
}
// Flatten indices
int nIndices = accessors[jsonPrimitive["indices"].ToInt()].count;
uint16_t* indexBuffer = (uint16_t*)accessors[jsonPrimitive["indices"].ToInt()].pBuffer;
prim.m_vertices.reserve(nIndices);
for (int i = 0; i < nIndices; i++)
{
uint16_t index = indexBuffer[i];
prim.m_vertices.push_back(indexedVertexData[index]);
}
pMesh->m_primitives.push_back(std::move(prim));
}
outMeshes.push_back(pMesh);
}
for (int i = 0; i < rawDataBuffers.size(); i++)
{
delete rawDataBuffers[i].pBytes;
}
return std::move(outMeshes);
}
// ***********************************************************************
std::vector<Image*> Mesh::LoadTextures(const char* filePath)
{
std::vector<Image*> outImages;
// Consider caching loaded json files somewhere since LoadScene/LoadMeshes/LoadImages are doing duplicate work here
SDL_RWops* pFileRead = SDL_RWFromFile(filePath, "rb");
uint64_t size = SDL_RWsize(pFileRead);
char* pData = new char[size];
SDL_RWread(pFileRead, pData, size, 1);
SDL_RWclose(pFileRead);
std::string file(pData, pData + size);
delete[] pData;
JsonValue parsed = ParseJsonFile(file);
bool validGltf = parsed["asset"]["version"].ToString() == "2.0";
if (!validGltf)
return std::vector<Image*>();
if (parsed.HasKey("images"))
{
outImages.reserve(parsed["images"].Count());
for (size_t i = 0; i < parsed["images"].Count(); i++)
{
JsonValue& jsonImage = parsed["images"][i];
std::string type = jsonImage["mimeType"].ToString();
std::string imagePath = "Assets/" + jsonImage["name"].ToString() + "." + type.substr(6, 4);
Image* pImage = new Image(imagePath);
outImages.emplace_back(pImage);
}
}
return std::move(outImages);
}
| 30.828402
| 174
| 0.533685
|
DavidColson
|
91de6d6f2835be44a67f4886901402cab72c55e3
| 4,432
|
hh
|
C++
|
net.ssa/xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:19.000Z
|
2022-03-26T17:00:19.000Z
|
xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | null | null | null |
xrLC/OpenMesh/Tools/Utils/MeshCheckerT.hh
|
ixray-team/xray-vss-archive
|
b245c8601dcefb505b4b51f58142da6769d4dc92
|
[
"Linux-OpenIB"
] | 1
|
2022-03-26T17:00:21.000Z
|
2022-03-26T17:00:21.000Z
|
//=============================================================================
//
// OpenMesh
// Copyright (C) 2003 by Computer Graphics Group, RWTH Aachen
// www.openmesh.org
//
//-----------------------------------------------------------------------------
//
// License
//
// 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, version 2.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Library General Public License for more details.
//
// You should have received a copy of the GNU Library General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//-----------------------------------------------------------------------------
//
// $Revision: 1.7 $
// $Date: 2004/01/13 15:23:32 $
//
//=============================================================================
#ifndef OPENMESH_MESHCHECKER_HH
#define OPENMESH_MESHCHECKER_HH
//== INCLUDES =================================================================
#include <OpenMesh/Core/System/config.h>
#include <OpenMesh/Core/System/omstream.hh>
#include <OpenMesh/Core/Utils/GenProg.hh>
#include <OpenMesh/Core/Attributes/Attributes.hh>
#include <iostream>
//== NAMESPACES ===============================================================
namespace OpenMesh {
namespace Utils {
//== CLASS DEFINITION =========================================================
/** Check integrity of mesh.
*
* This class provides several functions to check the integrity of a mesh.
*/
template <class Mesh>
class MeshCheckerT
{
public:
/// constructor
MeshCheckerT(const Mesh& _mesh) : mesh_(_mesh) {}
/// destructor
~MeshCheckerT() {}
/// what should be checked?
enum CheckTargets
{
CHECK_EDGES = 1,
CHECK_VERTICES = 2,
CHECK_FACES = 4,
CHECK_ALL = 255,
};
/// check it, return true iff ok
bool check( unsigned int _targets=CHECK_ALL,
std::ostream& _os=omerr );
private:
bool is_deleted(typename Mesh::VertexHandle _vh)
{ return (mesh_.has_vertex_status() ? mesh_.status(_vh).deleted() : false); }
bool is_deleted(typename Mesh::EdgeHandle _eh)
{ return (mesh_.has_edge_status() ? mesh_.status(_eh).deleted() : false); }
bool is_deleted(typename Mesh::FaceHandle _fh)
{ return (mesh_.has_face_status() ? mesh_.status(_fh).deleted() : false); }
// ref to mesh
const Mesh& mesh_;
};
//=============================================================================
} // namespace Utils
} // namespace OpenMesh
//=============================================================================
#if defined(OM_INCLUDE_TEMPLATES) && !defined(OPENMESH_MESHCHECKER_C)
#define OPENMESH_MESHCHECKER_TEMPLATES
#include "MeshCheckerT.cc"
#endif
//=============================================================================
#endif // OPENMESH_MESHCHECKER_HH defined
//=============================================================================
| 38.53913
| 80
| 0.38944
|
ixray-team
|
91e8f446e650ca0fded7d5f413dc6a1eda5c0fc9
| 1,707
|
cpp
|
C++
|
sources/game/spatial.cpp
|
ucpu/mazetd
|
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
|
[
"MIT"
] | 2
|
2021-06-27T01:58:23.000Z
|
2021-08-16T20:24:29.000Z
|
sources/game/spatial.cpp
|
ucpu/mazetd
|
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
|
[
"MIT"
] | 2
|
2022-02-03T23:40:10.000Z
|
2022-03-15T06:22:29.000Z
|
sources/game/spatial.cpp
|
ucpu/mazetd
|
f6ef70a142579b558caa4a7d0e5bdd8177e5fa75
|
[
"MIT"
] | 1
|
2022-01-26T21:07:41.000Z
|
2022-01-26T21:07:41.000Z
|
#include <cage-core/entitiesVisitor.h>
#include <cage-core/spatialStructure.h>
#include "../game.h"
#include "../grid.h"
namespace
{
Holder<SpatialStructure> monstersData = newSpatialStructure({});
Holder<SpatialStructure> structsData = newSpatialStructure({});
Holder<SpatialQuery> monstersQuery = newSpatialQuery(monstersData.share());
Holder<SpatialQuery> structsQuery = newSpatialQuery(structsData.share());
void gameReset()
{
monstersData->clear();
structsData->clear();
}
void gameUpdate()
{
monstersData->clear();
CAGE_ASSERT(globalGrid);
entitiesVisitor([&](Entity *e, const MovementComponent &mv, const MonsterComponent &) {
monstersData->update(e->name(), mv.position());
}, gameEntities(), false);
monstersData->rebuild();
}
struct Callbacks
{
EventListener<void()> gameResetListener;
EventListener<void()> gameUpdateListener;
Callbacks()
{
gameResetListener.attach(eventGameReset());
gameResetListener.bind<&gameReset>();
gameUpdateListener.attach(eventGameUpdate(), 30);
gameUpdateListener.bind<&gameUpdate>();
}
} callbacksInstance;
}
SpatialQuery *spatialMonsters()
{
return +monstersQuery;
}
SpatialQuery *spatialStructures()
{
return +structsQuery;
}
void spatialUpdateStructures()
{
structsData->clear();
CAGE_ASSERT(globalGrid);
entitiesVisitor([&](Entity *e, const PositionComponent &pos, const BuildingComponent &) {
structsData->update(e->name(), globalGrid->center(pos.tile));
}, gameEntities(), false);
entitiesVisitor([&](Entity *e, const PositionComponent &pos, const TrapComponent &) {
structsData->update(e->name(), globalGrid->center(pos.tile));
}, gameEntities(), false);
structsData->rebuild();
}
| 23.708333
| 90
| 0.727592
|
ucpu
|
91eb95f6a67a682eb83e45a9575e14e3f217c3b9
| 372
|
cpp
|
C++
|
Core/Logger/src/Logger.cpp
|
WSeegers/-toy-StackMachine
|
4d1c1b487369604f931f4bfa459e350b5349a9c3
|
[
"MIT"
] | null | null | null |
Core/Logger/src/Logger.cpp
|
WSeegers/-toy-StackMachine
|
4d1c1b487369604f931f4bfa459e350b5349a9c3
|
[
"MIT"
] | null | null | null |
Core/Logger/src/Logger.cpp
|
WSeegers/-toy-StackMachine
|
4d1c1b487369604f931f4bfa459e350b5349a9c3
|
[
"MIT"
] | null | null | null |
#include "../include/Logger.hpp"
#include <iostream>
void Logger::LexicalError(const std::string &msg, int line, int index)
{
std::cerr << "Lexical Error -> "
<< line << ":" << index << " : " << msg << std::endl;
}
void Logger::RuntimeError(const std::string &msg, int line)
{
std::cerr << "Runtime Error -> Line "
<< line << " : " << msg << std::endl;
}
| 23.25
| 70
| 0.572581
|
WSeegers
|
91ef59cbd345291b9cbc8c26db1740a71088a7ff
| 4,449
|
cpp
|
C++
|
src/Psn/Exports.cpp
|
ahmed-agiza/OpenPhySyn
|
51841240e5213a7e74bc6321bbe4193323378c8e
|
[
"BSD-3-Clause"
] | null | null | null |
src/Psn/Exports.cpp
|
ahmed-agiza/OpenPhySyn
|
51841240e5213a7e74bc6321bbe4193323378c8e
|
[
"BSD-3-Clause"
] | null | null | null |
src/Psn/Exports.cpp
|
ahmed-agiza/OpenPhySyn
|
51841240e5213a7e74bc6321bbe4193323378c8e
|
[
"BSD-3-Clause"
] | null | null | null |
// BSD 3-Clause License
// Copyright (c) 2019, SCALE Lab, Brown University
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#include "Exports.hpp"
#include <OpenPhySyn/Psn/Psn.hpp>
#include <memory>
#include "PsnLogger/PsnLogger.hpp"
namespace psn
{
#ifndef OPENROAD_BUILD
int
import_def(const char* def_path)
{
return Psn::instance().readDef(def_path);
}
int
import_lef(const char* lef_path, int ignore_routing_layers)
{
return Psn::instance().readLef(lef_path);
}
int
import_lib(const char* lib_path)
{
return import_liberty(lib_path);
}
int
import_liberty(const char* lib_path)
{
return Psn::instance().readLib(lib_path);
}
int
export_def(const char* lib_path)
{
return Psn::instance().writeDef(lib_path);
}
int
print_liberty_cells()
{
Liberty* liberty = Psn::instance().liberty();
if (!liberty)
{
PsnLogger::instance().error("Did not find any liberty files, use "
"import_liberty <file name> first.");
return -1;
}
sta::LibertyCellIterator cell_iter(liberty);
while (cell_iter.hasNext())
{
sta::LibertyCell* cell = cell_iter.next();
PsnLogger::instance().info("Cell: {}", cell->name());
}
return 1;
}
#endif
int
set_wire_rc(float res_per_micon, float cap_per_micron)
{
Psn::instance().setWireRC(res_per_micon, cap_per_micron);
return 1;
}
int
set_max_area(float area)
{
Psn::instance().settings()->setMaxArea(area);
return 1;
}
int
link(const char* top_module)
{
return link_design(top_module);
}
int
link_design(const char* top_module)
{
return Psn::instance().linkDesign(top_module);
}
void
version()
{
print_version();
}
int
transform_internal(std::string transform_name, std::vector<std::string> args)
{
return Psn::instance().runTransform(transform_name, args);
}
void
help()
{
print_usage();
}
void
print_usage()
{
Psn::instance().printUsage();
}
void
print_transforms()
{
Psn::instance().printTransforms(true);
}
void
print_version()
{
Psn::instance().printVersion();
}
Database&
get_database()
{
return *(Psn::instance().database());
}
Liberty&
get_liberty()
{
return *(Psn::instance().liberty());
}
int
set_log(const char* level)
{
return set_log_level(level);
}
int
set_log_level(const char* level)
{
return Psn::instance().setLogLevel(level);
}
int
set_log_pattern(const char* pattern)
{
return Psn::instance().setLogPattern(pattern);
}
DatabaseHandler&
get_handler()
{
return get_database_handler();
}
DatabaseHandler&
get_database_handler()
{
return *(Psn::instance().handler());
}
SteinerTree*
create_steiner_tree(const char* net_name)
{
auto net = Psn::instance().handler()->net(net_name);
return create_steiner_tree(net);
}
SteinerTree*
create_steiner_tree(Net* net)
{
auto pt = SteinerTree::create(net, &(Psn::instance()), 3);
SteinerTree* tree = pt.get();
pt.release();
return tree;
}
} // namespace psn
| 22.469697
| 80
| 0.710497
|
ahmed-agiza
|
91f3b792dec221d489aa79578b01b1f483bfe1c8
| 22,008
|
cpp
|
C++
|
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
|
gpvigano/DigitalScenarioFramework
|
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
|
[
"MIT"
] | 1
|
2021-12-21T17:28:39.000Z
|
2021-12-21T17:28:39.000Z
|
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
|
gpvigano/DigitalScenarioFramework
|
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
|
[
"MIT"
] | null | null | null |
SimplECircuitCybSys/src/SimplECircuitCybSys.cpp
|
gpvigano/DigitalScenarioFramework
|
a1cab48df1f4a3d9b54e6cf00c5d0d0058e771f1
|
[
"MIT"
] | null | null | null |
//--------------------------------------------------------------------//
// Digital Scenario Framework //
// by Giovanni Paolo Vigano', 2021 //
//--------------------------------------------------------------------//
//
// Distributed under the MIT Software License.
// See http://opensource.org/licenses/MIT
//
#include <SimplECircuitCybSys/SimplECircuitCybSys.h>
#include <SimplECircuitCybSys/SimplECircuitSolver.h>
#include <discenfw/xp/EnvironmentModel.h>
#include <discenfw/util/MessageLog.h>
#include <boost/config.hpp> // for BOOST_SYMBOL_EXPORT
#include <iostream>
#include <sstream>
using namespace discenfw::xp;
namespace
{
inline std::string BoolToString(bool val) { return val ? "true" : "false"; }
}
namespace simplecircuit_cybsys
{
SimplECircuitCybSys::SimplECircuitCybSys()
{
Circuit = std::make_unique<simplecircuit_cybsys::ElectronicCircuit>();
}
void SimplECircuitCybSys::CreateEntityStateTypes()
{
if (ComponentEntityType)
{
return;
}
ComponentEntityType = CreateEntityStateType(
"",
"Electronic Component",
{
{"connections","0"},
{"connected","false"},
{"burnt out","false"},
},
{
{ "connected", { "true","false" } },
{"burnt out", { "true","false" }},
},
{}
);
ResistorEntityType = CreateEntityStateType(
"Electronic Component",
"Resistor",
{
},
{
{"connections",{"0","1","2"}},
},
{ "Pin1", "Pin2" }
);
LedEntityType = CreateEntityStateType(
"Electronic Component",
"LED",
{
{"lit up","false"},
},
{
{"connections",{"0","1","2"}},
{ "lit up", { "true","false" } },
},
{ "Anode", "Cathode" }
);
PowerEntityType = CreateEntityStateType(
"Electronic Component",
"Power Supply",
{
},
{
{"connections",{"0","1","2"}},
},
{ "+", "-" }
);
SwitchEntityType = CreateEntityStateType(
"Electronic Component",
"Switch",
{
{"position","0"},
},
{
{"connections",{"0","1","2","3"}},
{ "position", { "0","1" } },
},
{ "In", "Out0", "Out1" }
);
}
void SimplECircuitCybSys::ClearSystem()
{
Circuit->Components.clear();
}
void SimplECircuitCybSys::InitFailureConditions()
{
// set a default failure condition (any component burnt out)
PropertyCondition burntOutCond({ "burnt out",BoolToString(true) });
Condition anyBurntOut({ {EntityCondition::ANY,{burntOutCond}} });
FailureCondition = anyBurntOut;
}
void SimplECircuitCybSys::InitRoles()
{
std::shared_ptr<EnvironmentModel> model = GetModel();
if (model->GetRoleNames().empty())
{
PropertyCondition burntOutCond({ "burnt out",BoolToString(true) });
Condition anyBurntOut({ { EntityCondition::ANY,{ burntOutCond } } });
xp::SetRole(
"Default",
{}, // SuccessCondition
{}, // FailureCondition
{}, // DeadlockCondition
{
// ResultReward
{
{ ActionResult::IN_PROGRESS,0 },
{ ActionResult::SUCCEEDED,1000 },
{ ActionResult::FAILED,-1000 },
{ ActionResult::DEADLOCK,-10 },
},
// PropertyCountRewards
{},
// EntityConditionRewards
{
},
// FeatureRewards
{
}
}
);
}
}
void SimplECircuitCybSys::ResetSystem()
{
Circuit->Reset();
}
bool SimplECircuitCybSys::ExecuteAction(const Action& action)
{
enum ActionId { CONNECT, SWITCH, DISCONNECT };
static std::map<std::string, ActionId> actionNames{
{ "connect",CONNECT },
{ "switch",SWITCH },
{ "disconnect",DISCONNECT },
};
switch (actionNames[action.TypeId])
{
case CONNECT:
return DoConnectAction(action);
case SWITCH:
return DoSwitchAction(action);
case DISCONNECT:
return DoDisconnectAction(action);
default:
break;
}
return false;
}
void SimplECircuitCybSys::SynchronizeState(std::shared_ptr<xp::EnvironmentState> environmentState)
{
// TODO: alternative: just update existing entities and remove dangling entities?
environmentState->Clear();
// synchronize component states
for (const auto& comp : Circuit->Components)
{
std::string entityId = comp.first;
const auto& component = comp.second;
std::shared_ptr<Led> led = AsLed(component);
std::shared_ptr<Switch> sw = AsSwitch(component);
std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(component);
std::shared_ptr<Resistor> resistor = AsResistor(component);
// get the properties of the current component
bool nowBurnt = component->BurntOut;
bool nowConnected = component->Connected;
int nowConn = component->GetConnectedLeadsCount();
bool nowLit = led && led->LitUp;
int nowPos = (int)(sw && sw->Position == SwitchPosition::POS1);
// update the entity state for the current component
std::shared_ptr<EntityState> entState = environmentState->GetEntityState(entityId);
if (!entState)
{
std::shared_ptr<EntityStateType> entType;
if (!ComponentEntityType)
{
CreateEntityStateTypes();
}
if (powerSupply) entType = PowerEntityType;
else if (led) entType = LedEntityType;
else if (sw) entType = SwitchEntityType;
else if (resistor) entType = ResistorEntityType;
//else if (transistor) entType = TransistorEntityType;
else entType = ComponentEntityType;
entState = EntityState::Make(entType->GetTypeName(),entType->GetModelName());
//entState = std::make_shared<EntityState>(entType->GetTypeName(),entType->GetModelName());
environmentState->SetEntityState(entityId, entState);
}
std::vector< std::pair<std::string, std::shared_ptr<ElectronicComponentLead> >> leads;
component->GetLeads(leads);
// store new component relationships
for (const auto& eLead : leads)
{
if (!eLead.second->Connections.empty())
{
RelationshipLink link;
link.EntityId = eLead.second->Connections[0].Component;
link.LinkId = eLead.second->Connections[0].Lead;
entState->SetRelationship(eLead.first, link);
}
else
{
entState->RemoveRelationship(eLead.first);
}
}
// set the properties for the entity state
entState->SetPropertyValue("burnt out", BoolToString(nowBurnt));
entState->SetPropertyValue("connected", BoolToString(nowConnected));
entState->SetPropertyValue("connections", std::to_string(nowConn));
if (led)
{
entState->SetPropertyValue("lit up", BoolToString(nowLit));
}
if (sw)
{
entState->SetPropertyValue("position", std::to_string(nowPos));
}
if (LogEnabled)
{
if (nowBurnt)
{
LogStream << entityId << " => burnt out" << std::endl;
FlushLog(LOG_DEBUG);
}
if (nowLit)
{
LogStream << entityId << " => lit up" << std::endl;
FlushLog(LOG_DEBUG);
}
if (nowPos)
{
LogStream << entityId << " => on" << std::endl;
FlushLog(LOG_DEBUG);
}
}
}
}
const std::vector<ActionRef>& SimplECircuitCybSys::GetAvailableActions(
const std::string& roleId,
bool smartSelection
) const
{
CachedAvailableActions.clear();
std::shared_ptr<PowerSupplyDC> powerSupply = Circuit->GetPowerSupply();
bool circuitIsComplete = false;
if (smartSelection)
{
if(powerSupply && powerSupply->GetConnectedLeadsCount()==2)
{
circuitIsComplete = true;
for (const auto& compItem : Circuit->Components)
{
// Check if at least one component is connected but not fully connected
// (power supply was already checked)
if (compItem.second != powerSupply && compItem.second->GetConnectedLeadsCount() == 1)
{
circuitIsComplete = false;
break;
}
}
}
}
std::vector<std::string> actionNames{ "connect", "switch" };
for (const auto& compItem : Circuit->Components)
{
std::string compId = compItem.first;
std::shared_ptr<ElectronicComponent> component = compItem.second;
bool powerSupplyConnected = powerSupply && powerSupply->AnyLeadConnected();
std::string powerId = Circuit->GetComponentName(powerSupply);
if (!component->BurntOut)
{
auto sw = AsSwitch(component);
if (sw)
{
bool canBeSwitched = true;
if (smartSelection)
{
canBeSwitched = circuitIsComplete && sw->GetConnectedLeadsCount() > 1 && sw->Lead("In")->Connected();
}
// possible deadlock: repeatedly switching --> deadlock detection required
if (canBeSwitched)
{
CacheAvailableAction(
{ "switch",{ compId,sw->Position == SwitchPosition::POS0 ? "1" : "0" } }
);
}
// alternative solution:
// allow switch-on only, this avoids possible deadlocks
//if (canBeSwitched && sw->Position == SwitchPosition::POS0)
//...
}
// if (!component->AllLeadsConnected()) ...
// allow only 2 connections per component to simplify the circuit simulation
if (component->GetConnectedLeadsCount() < 2)
{
std::vector< std::shared_ptr<ElectronicComponentLead> > leads;
std::vector< std::string > leadNames;
component->GetLeads(leads);
component->GetLeadNames(leadNames);
for (const auto& otherCompItem : Circuit->Components)
{
std::string otherCompId = otherCompItem.first;
std::shared_ptr<ElectronicComponent> otherComponent = otherCompItem.second;
bool connectingPowerSupply = (otherComponent == powerSupply || component == powerSupply);
bool connectedToPowerSupply = (otherComponent->Connected || component->Connected);
bool canBeConnected =
(!otherComponent->BurntOut
&& otherComponent != component
&& !otherComponent->AllLeadsConnected()
&& !component->ConnectedTo(otherCompId)
);
if (smartSelection)
{
canBeConnected = canBeConnected && (connectingPowerSupply || connectedToPowerSupply);
}
if (canBeConnected)
{
std::vector< std::shared_ptr<ElectronicComponentLead> > otherLeads;
std::vector< std::string > otherLeadNames;
otherComponent->GetLeads(otherLeads);
otherComponent->GetLeadNames(otherLeadNames);
for (size_t i = 0; i < leads.size(); i++)
{
const auto& lead = leads[i];
// allow only 1 connection per lead to simplify the circuit simulation
if (!lead->Connected())
{
for (size_t j = 0; j < otherLeads.size(); j++)
{
const auto& otherLead = otherLeads[j];
if (!otherLead->Connected())
{
// prevent parallel connections of components to simplify the circuit simulation
//if (otherLead != lead && !otherLead->ConnectedTo(compId, leadNames[i]))
if (otherLead != lead && !otherLead->ConnectedTo(compId))
{
CacheAvailableAction(
{ "connect",
{
compId, leadNames[i],
otherCompId, otherLeadNames[j]
}
}
);
}
}
}
}
}
}
}
}
}
}
return CachedAvailableActions;
}
bool SimplECircuitCybSys::DoConnectAction(const Action& action)
{
// decode parameters
const std::string& component1Id = action.Params[0];
const std::string& lead1Id = action.Params[1];
const std::string& component2Id = action.Params[2];
const std::string& lead2Id = action.Params[3];
// prevent connecting a lead with itself
if (component1Id == component2Id && lead1Id == lead2Id)
{
return false;
}
std::shared_ptr<ElectronicComponent> component1 = Circuit->FindComponent(component1Id);
std::shared_ptr<ElectronicComponent> component2 = Circuit->FindComponent(component2Id);
// check if components exist
if (!component1 || !component2)
{
return false;
}
// check if already connected
if (component1->ConnectedTo(component2Id, lead2Id))
{
return false;
}
// allow only 1 connection per lead to simplify the circuit simulation
if (component1->Lead(lead1Id)->Connected() || component2->Lead(lead2Id)->Connected())
{
return false;
}
if (LogEnabled)
{
LogStream << "> " << component1Id << "/" << lead1Id
<< " <--> " << component2Id << "/" << lead2Id << std::endl;
FlushLog(LOG_DEBUG);
}
// update the circuit
Circuit->Connect(component1Id, lead1Id, component2Id, lead2Id);
SolveElectronicCircuit(*Circuit);
return true;
}
bool SimplECircuitCybSys::DoSwitchAction(const Action& action)
{
// decode parameters
const std::string& switchId = action.Params[0];
const std::string& posId = action.Params[1];
bool pos = std::atoi(posId.c_str()) > 0;
auto sw = AsSwitch(Circuit->FindComponent(switchId));
if (!sw)
{
return false;
}
if (LogEnabled)
{
LogStream << std::noboolalpha << "> " << switchId << ": " << pos << std::endl;
FlushLog(LOG_DEBUG);
}
// update the circuit
sw->Position = (SwitchPosition)pos;
SolveElectronicCircuit(*Circuit);
return true;
}
bool SimplECircuitCybSys::DoDisconnectAction(const Action& action)
{
size_t numParams = action.Params.size();
if(numParams!=2 && numParams!=4)
{
return false;
}
// decode parameters
const std::string& component1Id = action.Params[0];
const std::string& lead1Id = action.Params[1];
std::shared_ptr<ElectronicComponent> component1 = Circuit->FindComponent(component1Id);
if (!component1->Lead(lead1Id)->Connected())
{
return false;
}
if (numParams == 2)
{
// update the circuit
Circuit->Disconnect(component1Id, lead1Id);
}
else //if (numParams == 4)
{
const std::string& component2Id = action.Params[2];
const std::string& lead2Id = action.Params[3];
// prevent connecting a lead with itself
if (component1Id == component2Id && lead1Id == lead2Id)
{
return false;
}
std::shared_ptr<ElectronicComponent> component2 = Circuit->FindComponent(component2Id);
// check if components exist
if (!component1 || !component2)
{
return false;
}
// check if already connected
if (!component1->ConnectedTo(component2Id, lead2Id))
{
return false;
}
if (!component2->Lead(lead2Id)->Connected())
{
return false;
}
if (LogEnabled)
{
LogStream << "> " << component1Id << "/" << lead1Id
<< " X--X " << component2Id << "/" << lead2Id << std::endl;
FlushLog(LOG_DEBUG);
}
// update the circuit
Circuit->Disconnect(component1Id, lead1Id, component2Id, lead2Id);
}
SolveElectronicCircuit(*Circuit);
return true;
}
std::shared_ptr<ElectronicComponent> SimplECircuitCybSys::CreateComponentFromConfiguration(
const std::string& config, std::string& compId)
{
std::istringstream iStr(config);
if (!iStr.good())
{
return nullptr;
}
std::shared_ptr<ElectronicComponent> comp;
std::string compType;
iStr >> compType >> compId;
comp = MakeComponent(compType);
if (comp)
{
ReadComponentConfiguration(iStr, comp);
Circuit->Components[compId] = comp;
}
return comp;
}
const std::string SimplECircuitCybSys::GetComponentConfiguration(const std::string& compId)
{
std::shared_ptr<ElectronicComponent> comp = Circuit->FindComponent(compId);
if (!comp)
{
return "";
}
std::ostringstream oStr;
std::shared_ptr<Led> led = AsLed(comp);
if (led)
{
oStr << led->Type->Name;
}
std::shared_ptr<Resistor> r = AsResistor(comp);
if (r)
{
oStr << r->Ohm
<< " " << r->Max_mW;
}
std::shared_ptr<Switch> sw = AsSwitch(comp);
if (sw)
{
oStr << sw->MaxVoltage_mV
<< " " << sw->MaxCurrent_mA;
}
std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(comp);
if (powerSupply)
{
oStr << powerSupply->Voltage_mV
<< " " << powerSupply->MaxCurrent_mA;
}
return oStr.str();
}
bool SimplECircuitCybSys::SetComponentConfiguration(const std::string& compId, const std::string& config)
{
std::shared_ptr<ElectronicComponent> comp = Circuit->FindComponent(compId);
if (!comp)
{
return false;
}
std::istringstream iStr(config);
ReadComponentConfiguration(iStr, comp);
return true;
}
bool SimplECircuitCybSys::SetConfiguration(const std::string& config)
{
Initialize();
Circuit->Components.clear();
bool firstRead = true;
std::istringstream iStr(config);
while (iStr.good())
{
std::string compConfig;
std::getline(iStr, compConfig);
std::string compId;
std::shared_ptr<ElectronicComponent> comp = CreateComponentFromConfiguration(
compConfig, compId);
if (firstRead &&!comp)
{
return false;
}
firstRead = false;
}
Initialize(true);
return true;
}
const std::string SimplECircuitCybSys::GetConfiguration()
{
std::ostringstream oStr;
for (const auto& comp : Circuit->Components)
{
oStr << comp.second->GetTypeName()
<< " " << comp.first << " ";
oStr << GetComponentConfiguration(comp.first);
oStr << "\n";
}
return oStr.str();
}
const std::string SimplECircuitCybSys::ReadEntityConfiguration(const std::string& entityId)
{
return GetComponentConfiguration(entityId);
}
bool SimplECircuitCybSys::WriteEntityConfiguration(const std::string& entityId, const std::string& config)
{
return SetComponentConfiguration(entityId, config);
}
bool SimplECircuitCybSys::ConfigureEntity(const std::string& entityId, const std::string& entityType, const std::string& config)
{
std::shared_ptr<ElectronicComponent> comp;
if (Circuit->Components.find(entityId) != Circuit->Components.end())
{
comp = Circuit->Components[entityId];
if (comp->GetTypeName() != entityType)
{
Circuit->Components.erase(entityId);
comp = nullptr;
}
}
if (!comp)
{
comp = MakeComponent(entityType);
if (!comp)
{
return false;
}
Circuit->Components[entityId] = comp;
}
std::istringstream iStr(config);
ReadComponentConfiguration(iStr, comp);
return true;
}
bool SimplECircuitCybSys::RemoveEntity(const std::string& entityId)
{
if (Circuit->Components.find(entityId) != Circuit->Components.end())
{
std::shared_ptr<ElectronicComponent> comp = Circuit->Components[entityId];
Circuit->Disconnect(entityId);
Circuit->Components.erase(entityId);
return true;
}
return false;
}
const std::string SimplECircuitCybSys::GetSystemInfo(const std::string& infoId) const
{
std::ostringstream oStr;
if (infoId == "" || infoId == "CircuitSchema")
{
// create a schematic representation of the circuit in one text line
std::shared_ptr<PowerSupplyDC> powerSupply = Circuit->GetPowerSupply();
if (!powerSupply) return "";
std::shared_ptr<ElectronicComponentLead> posLead = powerSupply->GetPositiveLead();
std::shared_ptr<ElectronicComponentLead> negLead = powerSupply->GetNegativeLead();
if (!posLead->Connected() || !negLead->Connected()) return "";
int connectedComponents = 0;
for (const auto& comp : Circuit->Components)
{
if (comp.second->GetConnectedLeadsCount() > 1) connectedComponents++;
}
std::vector<std::string> foundComponents;
bool closedCircuit = Circuit->GetCircuitComponents(foundComponents);
oStr << " (+)-";
for (std::string compName : foundComponents)
{
const auto& comp = Circuit->Components[compName];
const auto& sw = AsSwitch(comp);
const auto& led = AsLed(comp);
oStr << "-{" << compName;
if (led && led->LitUp) oStr << "*";
if (sw && sw->Position == SwitchPosition::POS0) oStr << "o";
if (sw && sw->Position == SwitchPosition::POS1) oStr << "*";
oStr << "}-";
}
if (closedCircuit) oStr << "-(-) {" << connectedComponents << "}";
}
else if (infoId == "CircuitInfo")
{
// List circuit components and their state
for (const auto& compPair : Circuit->Components)
{
const auto& component = compPair.second;
if (component->GetConnectedLeadsCount() > 1)
{
oStr << compPair.first;
const auto& sw = AsSwitch(component);
if (sw) oStr << "#" << (int)sw->Position;
const auto& led = AsLed(component);
if (led && led->LitUp) oStr << "*";
if (component->BurntOut)
{
oStr << "[burnt out]";
}
std::vector< std::shared_ptr<ElectronicComponentLead> > leads;
component->GetLeads(leads);
if (!leads.empty())
{
oStr << "@";
}
bool first = true;
for (const auto& connLead : leads)
{
if (connLead->Connected())
{
if (!first) oStr << ",";
first = false;
oStr << connLead->Name << ">" << connLead->Connections[0].Component
<< "." << connLead->Connections[0].Lead;
}
}
oStr << " ";
}
}
}
std::string info = oStr.str();
return info;
}
void SimplECircuitCybSys::ReadComponentConfiguration(std::istringstream& iStr, std::shared_ptr<ElectronicComponent> comp)
{
std::shared_ptr<Led> led = AsLed(comp);
if (led)
{
std::string ledType;
iStr >> ledType;
led->Type = GetLedType(ledType);
if (!led->Type)
{
LogStream << "Unknown LED type: " << ledType << std::endl;
FlushLog(LOG_ERROR);
}
}
std::shared_ptr<Resistor> r = AsResistor(comp);
if (r)
{
iStr >> r->Ohm >> r->Max_mW;
}
std::shared_ptr<Switch> sw = AsSwitch(comp);
if (sw)
{
iStr >> sw->MaxVoltage_mV >> sw->MaxCurrent_mA;
}
std::shared_ptr<PowerSupplyDC> powerSupply = AsPowerSupplyDC(comp);
if (powerSupply)
{
iStr >> powerSupply->Voltage_mV >> powerSupply->MaxCurrent_mA;
}
}
std::shared_ptr<ElectronicComponent> SimplECircuitCybSys::MakeComponent(const std::string& compType)
{
std::shared_ptr<ElectronicComponent> comp;
if (compType == "PowerSupplyDC")
{
comp = std::make_shared<PowerSupplyDC>();
}
else if (compType == "LED")
{
comp = std::make_shared<Led>(nullptr);
}
else if (compType == "Resistor")
{
comp = std::make_shared<Resistor>();
}
else if (compType == "Switch")
{
comp = std::make_shared<Switch>();
}
return comp;
}
extern "C" BOOST_SYMBOL_EXPORT SimplECircuitCybSys CyberSystem;
SimplECircuitCybSys CyberSystem;
} // namespace simplecircuit_cybsys
| 25.325662
| 129
| 0.639313
|
gpvigano
|
91f65d12c52f59ce95cf6cfcb87d5e478ce374e8
| 1,860
|
cpp
|
C++
|
SDLClassesTests/SurfaceTest.cpp
|
SmallLuma/SDLClasses
|
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
|
[
"Zlib"
] | 4
|
2017-06-27T03:34:32.000Z
|
2018-03-12T01:30:25.000Z
|
SDLClassesTests/SurfaceTest.cpp
|
SmallLuma/SDLClasses
|
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
|
[
"Zlib"
] | null | null | null |
SDLClassesTests/SurfaceTest.cpp
|
SmallLuma/SDLClasses
|
6348dd5d75b366d5e5e67f4074d7ebe0bd2173ee
|
[
"Zlib"
] | null | null | null |
#include "stdafx.h"
#include "CppUnitTest.h"
#include <SDLInstance.h>
#include <Window.h>
#include <Vector4.h>
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace SDLClassesTests
{
TEST_CLASS(SurfaceTest)
{
public:
TEST_METHOD(SimpleDraw)
{
using namespace SDL;
::SDL::SDLInstance sdl(::SDL::SDLInstance::InitParam::Video | ::SDL::SDLInstance::InitParam::Events);
Window wnd("HelloWorld", Rect<int32_t>{ Window::Center,Window::Center,1024,768 }, Window::WindowFlag::Null);
auto& sur = wnd.GetWindowSurface();
sur.Clear(Color<uint8_t>{ 0,0,255,255 });
sur.Fill(Rect<int32_t>{ 50,50,150,150 }, Color<uint8_t>{ 0,255,0,255 });
std::vector<Rect<int32_t>> rects = {
{750,350,200,200},
{0,350,200,200}
};
sur.Fill(rects, Color<uint8_t>{ 255,0,0,255 });
wnd.UpdateWindowSurface();
sdl.Delay(500);
sur.Shade([](int x, int y, Surface& thisSur, Color<uint8_t> oldColor) {
return Color<uint8_t>
{
static_cast<uint8_t>(x % 255),
static_cast<uint8_t>(y % 255),
128,
255
};
});
wnd.UpdateWindowSurface();
sdl.Delay(500);
}
TEST_METHOD(BlitTest)
{
using namespace SDL;
::SDL::SDLInstance sdl(::SDL::SDLInstance::InitParam::Everything);
Window wnd("HelloWorld", Rect<int32_t>{ Window::Center, Window::Center, 1024, 768 }, Window::WindowFlag::Null);
Surface sur1(512, 512, 32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF);
auto& wsur = wnd.GetWindowSurface();
sur1.Shade([](int x, int y, Surface& thisSur, Color<uint8_t> oldColor) {
return Color<uint8_t>
{
static_cast<uint8_t>(x % 255),
static_cast<uint8_t>(y % 255),
128,
255
};
});
wsur.BlitFrom(sur1, Rect<int32_t>{0, 0, 512, 512}, Rect<int32_t>{100, 100, 512, 512});
wnd.UpdateWindowSurface();
sdl.Delay(300);
}
};
}
| 25.833333
| 114
| 0.649462
|
SmallLuma
|
91f82f77b5df8436fbb041aa30b09d76d3c6190c
| 1,254
|
hpp
|
C++
|
include/codegen/include/UnityEngine/AddComponentMenu.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 1
|
2021-11-12T09:29:31.000Z
|
2021-11-12T09:29:31.000Z
|
include/codegen/include/UnityEngine/AddComponentMenu.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | null | null | null |
include/codegen/include/UnityEngine/AddComponentMenu.hpp
|
Futuremappermydud/Naluluna-Modifier-Quest
|
bfda34370764b275d90324b3879f1a429a10a873
|
[
"MIT"
] | 2
|
2021-10-03T02:14:20.000Z
|
2021-11-12T09:29:36.000Z
|
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:29 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.Attribute
#include "System/Attribute.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Autogenerated type: UnityEngine.AddComponentMenu
class AddComponentMenu : public System::Attribute {
public:
// private System.String m_AddComponentMenu
// Offset: 0x10
::Il2CppString* m_AddComponentMenu;
// private System.Int32 m_Ordering
// Offset: 0x18
int m_Ordering;
// public System.Void .ctor(System.String menuName)
// Offset: 0x12E6D80
static AddComponentMenu* New_ctor(::Il2CppString* menuName);
// public System.Void .ctor(System.String menuName, System.Int32 order)
// Offset: 0x12E6DBC
static AddComponentMenu* New_ctor(::Il2CppString* menuName, int order);
}; // UnityEngine.AddComponentMenu
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::AddComponentMenu*, "UnityEngine", "AddComponentMenu");
#pragma pack(pop)
| 35.828571
| 90
| 0.698565
|
Futuremappermydud
|
91fe1f3f1f9adda77b276622415cd80ae8fdd668
| 1,904
|
cpp
|
C++
|
gui/menu-predicate.cpp
|
lukas-ke/faint-graphics-editor
|
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
|
[
"Apache-2.0"
] | 10
|
2016-12-28T22:06:31.000Z
|
2021-05-24T13:42:30.000Z
|
gui/menu-predicate.cpp
|
lukas-ke/faint-graphics-editor
|
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
|
[
"Apache-2.0"
] | 4
|
2015-10-09T23:55:10.000Z
|
2020-04-04T08:09:22.000Z
|
gui/menu-predicate.cpp
|
lukas-ke/faint-graphics-editor
|
33eb9e6a3f2216fb2cf6ef9709a14f3d20b78fbf
|
[
"Apache-2.0"
] | null | null | null |
// -*- coding: us-ascii-unix -*-
// Copyright 2012 Lukas Kemmer
//
// 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 "gui/menu-predicate.hh"
#include "util/convenience.hh"
namespace faint{
BoundMenuPred::BoundMenuPred(menu_item_id_t id, predicate_t predicate)
: m_id(id),
m_pred(predicate)
{}
void BoundMenuPred::Update(MenuReference& menu, const MenuFlags& flags) const{
bool enable =
(flags.toolSelection && fl(MenuPred::TOOL_SELECTION, m_pred)) ||
(flags.rasterSelection && fl(MenuPred::RASTER_SELECTION, m_pred)) ||
(flags.objectSelection && fl(MenuPred::OBJECT_SELECTION, m_pred)) ||
(flags.hasObjects && fl(MenuPred::HAS_OBJECTS, m_pred)) ||
(flags.dirty && fl(MenuPred::DIRTY, m_pred)) ||
(flags.canUndo && fl(MenuPred::CAN_UNDO, m_pred)) ||
(flags.canRedo && fl(MenuPred::CAN_REDO, m_pred)) ||
(flags.numSelected > 1 && fl(MenuPred::MULTIPLE_SELECTED, m_pred)) ||
(flags.groupIsSelected && fl(MenuPred::GROUP_IS_SELECTED, m_pred)) ||
(flags.canMoveForward && fl(MenuPred::CAN_MOVE_FORWARD, m_pred)) ||
(flags.canMoveBackward && fl(MenuPred::CAN_MOVE_BACKWARD, m_pred));
menu.Enable(m_id, enable);
}
MenuPred::MenuPred(predicate_t predicate)
: m_predicate(predicate)
{}
BoundMenuPred MenuPred::GetBound(menu_item_id_t id) const{
return BoundMenuPred(id, m_predicate);
}
}
| 37.333333
| 80
| 0.703256
|
lukas-ke
|
91fe5ec015a859e4baf8fbfd0bede4e736578a86
| 1,417
|
hpp
|
C++
|
node/silkworm/stagedsync/stage_senders.hpp
|
elmato/silkworm
|
711c73547cd1f7632ff02d5f86dfac5b0d249344
|
[
"Apache-2.0"
] | null | null | null |
node/silkworm/stagedsync/stage_senders.hpp
|
elmato/silkworm
|
711c73547cd1f7632ff02d5f86dfac5b0d249344
|
[
"Apache-2.0"
] | null | null | null |
node/silkworm/stagedsync/stage_senders.hpp
|
elmato/silkworm
|
711c73547cd1f7632ff02d5f86dfac5b0d249344
|
[
"Apache-2.0"
] | null | null | null |
/*
Copyright 2021-2022 The Silkworm Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_
#define SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_
#include <silkworm/stagedsync/common.hpp>
#include <silkworm/stagedsync/stage_senders/recovery_farm.hpp>
namespace silkworm::stagedsync {
class Senders final : public IStage {
public:
explicit Senders(NodeSettings* node_settings) : IStage(db::stages::kSendersKey, node_settings){};
~Senders() override = default;
StageResult forward(db::RWTxn& txn) final;
StageResult unwind(db::RWTxn& txn, BlockNum to) final;
StageResult prune(db::RWTxn& txn) final;
std::vector<std::string> get_log_progress() final;
bool stop() final;
private:
std::unique_ptr<recovery::RecoveryFarm> farm_{nullptr};
};
} // namespace silkworm::stagedsync
#endif // SILKWORM_STAGEDSYNC_STAGE_SENDERS_HPP_
| 32.953488
| 101
| 0.754411
|
elmato
|
6201580492f357eb45a9360ec184df9935f3f922
| 668
|
cpp
|
C++
|
UVA00455.cpp
|
MaSteve/UVA-problems
|
3a240fcca02e24a9c850b7e86062f8581df6f95f
|
[
"MIT"
] | 17
|
2015-12-08T18:50:03.000Z
|
2022-03-16T01:23:20.000Z
|
UVA00455.cpp
|
MaSteve/UVA-problems
|
3a240fcca02e24a9c850b7e86062f8581df6f95f
|
[
"MIT"
] | null | null | null |
UVA00455.cpp
|
MaSteve/UVA-problems
|
3a240fcca02e24a9c850b7e86062f8581df6f95f
|
[
"MIT"
] | 6
|
2017-04-04T18:16:23.000Z
|
2020-06-28T11:07:22.000Z
|
#include <iostream>
using namespace std;
int main() {
int T;
bool first = false;
cin >> T;
while (T--) {
if (first) printf("\n");
else first = true;
string s;
cin >> s;
int i = 1;
for (; i < s.length(); i++) {
if (s.length() % i == 0) {
bool ok = true;
for (int j = 0; j < i && ok; j++) {
for (int k = 1; k * i + j < s.length() && ok; k++) {
ok = (s[j] == s[j + k * i]);
}
}
if (ok) break;
}
}
printf("%d\n", i);
}
return 0;
}
| 23.034483
| 72
| 0.314371
|
MaSteve
|
620df08526200389fea0d2478c6d953d8b88a02b
| 18,641
|
cc
|
C++
|
src/util.cc
|
unclearness/ugu
|
641c5170147091e82578fa6bcd84f3484172f487
|
[
"MIT"
] | 18
|
2019-12-29T17:27:55.000Z
|
2022-02-21T11:02:35.000Z
|
src/util.cc
|
unclearness/ugu
|
641c5170147091e82578fa6bcd84f3484172f487
|
[
"MIT"
] | 1
|
2021-07-22T12:04:53.000Z
|
2021-07-22T12:04:53.000Z
|
src/util.cc
|
unclearness/ugu
|
641c5170147091e82578fa6bcd84f3484172f487
|
[
"MIT"
] | 2
|
2021-02-26T06:58:36.000Z
|
2021-07-05T12:24:09.000Z
|
/*
* Copyright (C) 2019, unclearness
* All rights reserved.
*/
#include <fstream>
#include "ugu/util/io_util.h"
#include "ugu/util/math_util.h"
#include "ugu/util/raster_util.h"
#include "ugu/util/rgbd_util.h"
namespace {
bool Depth2PointCloudImpl(const ugu::Image1f& depth, const ugu::Image3b& color,
const ugu::Camera& camera, ugu::Mesh* point_cloud,
bool with_texture, bool gl_coord) {
if (depth.cols != camera.width() || depth.rows != camera.height()) {
ugu::LOGE(
"Depth2PointCloud depth size (%d, %d) and camera size (%d, %d) are "
"different\n",
depth.cols, depth.rows, camera.width(), camera.height());
return false;
}
if (with_texture) {
float depth_aspect_ratio =
static_cast<float>(depth.cols) / static_cast<float>(depth.rows);
float color_aspect_ratio =
static_cast<float>(color.cols) / static_cast<float>(color.rows);
const float aspect_ratio_diff_th{0.01f}; // 1%
const float aspect_ratio_diff =
std::abs(depth_aspect_ratio - color_aspect_ratio);
if (aspect_ratio_diff > aspect_ratio_diff_th) {
ugu::LOGE(
"Depth2PointCloud depth aspect ratio %f and color aspect ratio %f "
"are very "
"different\n",
depth_aspect_ratio, color_aspect_ratio);
return false;
}
}
point_cloud->Clear();
std::vector<Eigen::Vector3f> vertices;
std::vector<Eigen::Vector3f> vertex_colors;
for (int y = 0; y < camera.height(); y++) {
for (int x = 0; x < camera.width(); x++) {
const float& d = depth.at<float>(y, x);
if (d < std::numeric_limits<float>::min()) {
continue;
}
Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d);
Eigen::Vector3f camera_p;
camera.Unproject(image_p, &camera_p);
if (gl_coord) {
// flip y and z to align with OpenGL coordinate
camera_p.y() = -camera_p.y();
camera_p.z() = -camera_p.z();
}
vertices.push_back(camera_p);
if (with_texture) {
Eigen::Vector2f uv(ugu::X2U(x, depth.cols),
ugu::Y2V(y, depth.rows, false));
// nearest neighbor
// todo: bilinear
Eigen::Vector2i pixel_pos(
static_cast<int>(std::round(ugu::U2X(uv.x(), color.cols))),
static_cast<int>(std::round(ugu::V2Y(uv.y(), color.rows, false))));
Eigen::Vector3f pixel_color;
const ugu::Vec3b& tmp_color =
color.at<ugu::Vec3b>(pixel_pos.y(), pixel_pos.x());
pixel_color.x() = tmp_color[0];
pixel_color.y() = tmp_color[1];
pixel_color.z() = tmp_color[2];
vertex_colors.push_back(pixel_color);
}
}
}
// todo: add normal
point_cloud->set_vertices(vertices);
if (with_texture) {
point_cloud->set_vertex_colors(vertex_colors);
}
return true;
}
bool Depth2MeshImpl(const ugu::Image1f& depth, const ugu::Image3b& color,
const ugu::Camera& camera, ugu::Mesh* mesh,
bool with_texture, bool with_vertex_color,
float max_connect_z_diff, int x_step, int y_step,
bool gl_coord, const std::string& material_name,
ugu::Image3f* point_cloud, ugu::Image3f* normal) {
if (max_connect_z_diff < 0) {
ugu::LOGE("Depth2Mesh max_connect_z_diff must be positive %f\n",
max_connect_z_diff);
return false;
}
if (x_step < 1) {
ugu::LOGE("Depth2Mesh x_step must be positive %d\n", x_step);
return false;
}
if (y_step < 1) {
ugu::LOGE("Depth2Mesh y_step must be positive %d\n", y_step);
return false;
}
if (depth.cols != camera.width() || depth.rows != camera.height()) {
ugu::LOGE(
"Depth2Mesh depth size (%d, %d) and camera size (%d, %d) are "
"different\n",
depth.cols, depth.rows, camera.width(), camera.height());
return false;
}
if (with_texture) {
float depth_aspect_ratio =
static_cast<float>(depth.cols) / static_cast<float>(depth.rows);
float color_aspect_ratio =
static_cast<float>(color.cols) / static_cast<float>(color.rows);
const float aspect_ratio_diff_th{0.01f}; // 1%
const float aspect_ratio_diff =
std::abs(depth_aspect_ratio - color_aspect_ratio);
if (aspect_ratio_diff > aspect_ratio_diff_th) {
ugu::LOGE(
"Depth2Mesh depth aspect ratio %f and color aspect ratio %f are very "
"different\n",
depth_aspect_ratio, color_aspect_ratio);
return false;
}
}
mesh->Clear();
std::vector<Eigen::Vector2f> uvs;
std::vector<Eigen::Vector3f> vertices;
std::vector<Eigen::Vector3i> vertex_indices;
std::vector<Eigen::Vector3f> vertex_colors;
std::vector<std::pair<int, int>> vid2xy;
std::vector<int> added_table(depth.cols * depth.rows, -1);
int vertex_id{0};
for (int y = y_step; y < camera.height(); y += y_step) {
for (int x = x_step; x < camera.width(); x += x_step) {
const float& d = depth.at<float>(y, x);
if (d < std::numeric_limits<float>::min()) {
continue;
}
Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d);
Eigen::Vector3f camera_p;
camera.Unproject(image_p, &camera_p);
if (gl_coord) {
// flip y and z to align with OpenGL coordinate
camera_p.y() = -camera_p.y();
camera_p.z() = -camera_p.z();
}
vertices.push_back(camera_p);
vid2xy.push_back(std::make_pair(x, y));
Eigen::Vector2f uv(ugu::X2U(x, depth.cols),
ugu::Y2V(y, depth.rows, false));
if (with_vertex_color) {
// nearest neighbor
// todo: bilinear
Eigen::Vector2i pixel_pos(
static_cast<int>(std::round(ugu::U2X(uv.x(), color.cols))),
static_cast<int>(std::round(ugu::V2Y(uv.y(), color.rows, false))));
Eigen::Vector3f pixel_color;
const ugu::Vec3b& tmp_color =
color.at<ugu::Vec3b>(pixel_pos.y(), pixel_pos.x());
pixel_color.x() = tmp_color[0];
pixel_color.y() = tmp_color[1];
pixel_color.z() = tmp_color[2];
vertex_colors.push_back(pixel_color);
}
if (with_texture) {
// +0.5f comes from mapping 0~1 to -0.5~width(or height)+0.5
// since uv 0 and 1 is pixel boundary at ends while pixel position is
// the center of pixel
uv.y() = 1.0f - uv.y();
uvs.emplace_back(uv);
}
added_table[y * camera.width() + x] = vertex_id;
const int& current_index = vertex_id;
const int& upper_left_index =
added_table[(y - y_step) * camera.width() + (x - x_step)];
const int& upper_index = added_table[(y - y_step) * camera.width() + x];
const int& left_index = added_table[y * camera.width() + (x - x_step)];
const float upper_left_diff =
std::abs(depth.at<float>(y - y_step, x - x_step) - d);
const float upper_diff = std::abs(depth.at<float>(y - y_step, x) - d);
const float left_diff = std::abs(depth.at<float>(y, x - x_step) - d);
if (upper_left_index > 0 && upper_index > 0 &&
upper_left_diff < max_connect_z_diff &&
upper_diff < max_connect_z_diff) {
vertex_indices.push_back(
Eigen::Vector3i(upper_left_index, current_index, upper_index));
}
if (upper_left_index > 0 && left_index > 0 &&
upper_left_diff < max_connect_z_diff &&
left_diff < max_connect_z_diff) {
vertex_indices.push_back(
Eigen::Vector3i(upper_left_index, left_index, current_index));
}
vertex_id++;
}
}
mesh->set_vertices(vertices);
mesh->set_vertex_indices(vertex_indices);
mesh->CalcNormal();
if (with_texture) {
mesh->set_uv(uvs);
mesh->set_uv_indices(vertex_indices);
ugu::ObjMaterial material;
color.copyTo(material.diffuse_tex);
material.name = material_name;
std::vector<ugu::ObjMaterial> materials;
materials.push_back(material);
mesh->set_materials(materials);
std::vector<int> material_ids(vertex_indices.size(), 0);
mesh->set_material_ids(material_ids);
}
if (with_vertex_color) {
mesh->set_vertex_colors(vertex_colors);
}
if (point_cloud != nullptr) {
ugu::Init(point_cloud, depth.cols, depth.rows, 0.0f);
for (int i = 0; i < static_cast<int>(vid2xy.size()); i++) {
const auto& xy = vid2xy[i];
auto& p = point_cloud->at<ugu::Vec3f>(xy.second, xy.first);
p[0] = mesh->vertices()[i][0];
p[1] = mesh->vertices()[i][1];
p[2] = mesh->vertices()[i][2];
}
}
if (normal != nullptr) {
ugu::Init(normal, depth.cols, depth.rows, 0.0f);
for (int i = 0; i < static_cast<int>(vid2xy.size()); i++) {
const auto& xy = vid2xy[i];
auto& n = normal->at<ugu::Vec3f>(xy.second, xy.first);
n[0] = mesh->normals()[i][0];
n[1] = mesh->normals()[i][1];
n[2] = mesh->normals()[i][2];
}
}
return true;
}
} // namespace
namespace ugu {
bool Depth2PointCloud(const Image1f& depth, const Camera& camera,
Image3f* point_cloud, bool gl_coord) {
if (depth.cols != camera.width() || depth.rows != camera.height()) {
ugu::LOGE(
"Depth2PointCloud depth size (%d, %d) and camera size (%d, %d) are "
"different\n",
depth.cols, depth.rows, camera.width(), camera.height());
return false;
}
Init(point_cloud, depth.cols, depth.rows, 0.0f);
#if defined(_OPENMP) && defined(UGU_USE_OPENMP)
#pragma omp parallel for schedule(dynamic, 1)
#endif
for (int y = 0; y < camera.height(); y++) {
for (int x = 0; x < camera.width(); x++) {
const float& d = depth.at<float>(y, x);
if (d < std::numeric_limits<float>::min()) {
continue;
}
Eigen::Vector3f image_p(static_cast<float>(x), static_cast<float>(y), d);
Eigen::Vector3f camera_p;
camera.Unproject(image_p, &camera_p);
if (gl_coord) {
// flip y and z to align with OpenGL coordinate
camera_p.y() = -camera_p.y();
camera_p.z() = -camera_p.z();
}
Vec3f& pc = point_cloud->at<Vec3f>(y, x);
pc[0] = camera_p[0];
pc[1] = camera_p[1];
pc[2] = camera_p[2];
}
}
return true;
}
bool Depth2PointCloud(const Image1f& depth, const Camera& camera,
Mesh* point_cloud, bool gl_coord) {
Image3b stub_color;
return Depth2PointCloudImpl(depth, stub_color, camera, point_cloud, false,
gl_coord);
}
bool Depth2PointCloud(const Image1f& depth, const Image3b& color,
const Camera& camera, Mesh* point_cloud, bool gl_coord) {
return Depth2PointCloudImpl(depth, color, camera, point_cloud, true,
gl_coord);
}
bool Depth2Mesh(const Image1f& depth, const Camera& camera, Mesh* mesh,
float max_connect_z_diff, int x_step, int y_step, bool gl_coord,
ugu::Image3f* point_cloud, ugu::Image3f* normal) {
Image3b stub_color;
return Depth2MeshImpl(depth, stub_color, camera, mesh, false, false,
max_connect_z_diff, x_step, y_step, gl_coord,
"illegal_material", point_cloud, normal);
}
bool Depth2Mesh(const Image1f& depth, const Image3b& color,
const Camera& camera, Mesh* mesh, float max_connect_z_diff,
int x_step, int y_step, bool gl_coord,
const std::string& material_name, bool with_vertex_color,
ugu::Image3f* point_cloud, ugu::Image3f* normal) {
return Depth2MeshImpl(depth, color, camera, mesh, true, with_vertex_color,
max_connect_z_diff, x_step, y_step, gl_coord,
material_name, point_cloud, normal);
}
void WriteFaceIdAsText(const Image1i& face_id, const std::string& path) {
std::ofstream ofs;
ofs.open(path, std::ios::out);
for (int y = 0; y < face_id.rows; y++) {
for (int x = 0; x < face_id.cols; x++) {
ofs << face_id.at<int>(y, x) << "\n";
}
}
ofs.flush();
}
// FINDING OPTIMAL ROTATION AND TRANSLATION BETWEEN CORRESPONDING 3D POINTS
// http://nghiaho.com/?page_id=671
Eigen::Affine3d FindRigidTransformFrom3dCorrespondences(
const std::vector<Eigen::Vector3d>& src,
const std::vector<Eigen::Vector3d>& dst) {
if (src.size() < 3 || src.size() != dst.size()) {
return Eigen::Affine3d::Identity();
}
Eigen::Vector3d src_centroid;
src_centroid.setZero();
for (const auto& p : src) {
src_centroid += p;
}
src_centroid /= static_cast<double>(src.size());
Eigen::Vector3d dst_centroid;
dst_centroid.setZero();
for (const auto& p : dst) {
dst_centroid += p;
}
dst_centroid /= static_cast<double>(dst.size());
Eigen::MatrixXd normed_src(3, src.size());
for (auto i = 0; i < src.size(); i++) {
normed_src.col(i) = src[i] - src_centroid;
}
Eigen::MatrixXd normed_dst(3, dst.size());
for (auto i = 0; i < dst.size(); i++) {
normed_dst.col(i) = dst[i] - dst_centroid;
}
Eigen::MatrixXd normed_dst_T = normed_dst.transpose();
Eigen::Matrix3d H = normed_src * normed_dst_T;
// TODO: rank check
Eigen::JacobiSVD<Eigen::Matrix3d> svd(
H, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::Matrix3d R = svd.matrixV() * svd.matrixU().transpose();
double det = R.determinant();
constexpr double assert_eps = 0.001;
assert(std::abs(std::abs(det) - 1.0) < assert_eps);
if (det < 0) {
Eigen::JacobiSVD<Eigen::Matrix3d> svd2(
R, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::Matrix3d V = svd2.matrixV();
V.coeffRef(0, 2) *= -1.0;
V.coeffRef(1, 2) *= -1.0;
V.coeffRef(2, 2) *= -1.0;
R = V * svd2.matrixU().transpose();
}
assert(std::abs(det - 1.0) < assert_eps);
Eigen::Vector3d t = dst_centroid - R * src_centroid;
Eigen::Affine3d T = Eigen::Translation3d(t) * R;
return T;
}
Eigen::Affine3d FindRigidTransformFrom3dCorrespondences(
const std::vector<Eigen::Vector3f>& src,
const std::vector<Eigen::Vector3f>& dst) {
std::vector<Eigen::Vector3d> src_d, dst_d;
auto to_double = [](const std::vector<Eigen::Vector3f>& fvec,
std::vector<Eigen::Vector3d>& dvec) {
std::transform(fvec.begin(), fvec.end(), std::back_inserter(dvec),
[](const Eigen::Vector3f& f) { return f.cast<double>(); });
};
to_double(src, src_d);
to_double(dst, dst_d);
return FindRigidTransformFrom3dCorrespondences(src_d, dst_d);
}
Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences(
const std::vector<Eigen::Vector3d>& src,
const std::vector<Eigen::Vector3d>& dst) {
Eigen::MatrixXd src_(src.size(), 3);
for (auto i = 0; i < src.size(); i++) {
src_.row(i) = src[i];
}
Eigen::MatrixXd dst_(dst.size(), 3);
for (auto i = 0; i < dst.size(); i++) {
dst_.row(i) = dst[i];
}
return FindSimilarityTransformFrom3dCorrespondences(src_, dst_);
}
Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences(
const std::vector<Eigen::Vector3f>& src,
const std::vector<Eigen::Vector3f>& dst) {
Eigen::MatrixXd src_(src.size(), 3);
for (auto i = 0; i < src.size(); i++) {
src_.row(i) = src[i].cast<double>();
}
Eigen::MatrixXd dst_(dst.size(), 3);
for (auto i = 0; i < dst.size(); i++) {
dst_.row(i) = dst[i].cast<double>();
}
return FindSimilarityTransformFrom3dCorrespondences(src_, dst_);
}
Eigen::Affine3d FindSimilarityTransformFrom3dCorrespondences(
const Eigen::MatrixXd& src, const Eigen::MatrixXd& dst) {
Eigen::MatrixXd R;
Eigen::MatrixXd t;
Eigen::MatrixXd scale;
Eigen::MatrixXd T;
bool ret =
FindSimilarityTransformFromPointCorrespondences(src, dst, R, t, scale, T);
assert(R.rows() == 3 && R.cols() == 3);
assert(t.rows() == 3 && t.cols() == 1);
assert(T.rows() == 4 && T.cols() == 4);
Eigen::Affine3d T_3d = Eigen::Affine3d::Identity();
if (ret) {
T_3d = Eigen::Translation3d(t) * R * Eigen::Scaling(scale.diagonal());
}
return T_3d;
}
bool FindSimilarityTransformFromPointCorrespondences(
const Eigen::MatrixXd& src, const Eigen::MatrixXd& dst, Eigen::MatrixXd& R,
Eigen::MatrixXd& t, Eigen::MatrixXd& scale, Eigen::MatrixXd& T) {
const size_t n_data = src.rows();
const size_t n_dim = src.cols();
if (n_data < 1 || n_dim < 1 || n_data < n_dim || src.rows() != dst.rows() ||
src.cols() != dst.cols()) {
return false;
}
Eigen::VectorXd src_mean = src.colwise().mean();
Eigen::VectorXd dst_mean = dst.colwise().mean();
Eigen::MatrixXd src_demean = src.rowwise() - src_mean.transpose();
Eigen::MatrixXd dst_demean = dst.rowwise() - dst_mean.transpose();
Eigen::MatrixXd A =
dst_demean.transpose() * src_demean / static_cast<double>(n_data);
Eigen::VectorXd d = Eigen::VectorXd::Ones(n_dim);
double det_A = A.determinant();
if (det_A < 0) {
d.coeffRef(n_dim - 1, 0) = -1;
}
T = Eigen::MatrixXd::Identity(n_dim + 1, n_dim + 1);
Eigen::JacobiSVD<Eigen::MatrixXd> svd(
A, Eigen::ComputeFullU | Eigen::ComputeFullV);
Eigen::MatrixXd U = svd.matrixU();
Eigen::MatrixXd S = svd.singularValues().asDiagonal();
Eigen::MatrixXd V = svd.matrixV();
double det_U = U.determinant();
double det_V = V.determinant();
double det_orgR = det_U * det_V;
constexpr double assert_eps = 0.001;
assert(std::abs(std::abs(det_orgR) - 1.0) < assert_eps);
int rank_A = static_cast<int>(svd.rank());
if (rank_A == 0) {
// null matrix case
return false;
} else if (rank_A == n_dim - 1) {
if (det_orgR > 0) {
// Valid rotation case
R = U * V.transpose();
} else {
// Mirror (reflection) case
double s = d.coeff(n_dim - 1, 0);
d.coeffRef(n_dim - 1, 0) = -1;
R = U * d.asDiagonal() * V.transpose();
d.coeffRef(n_dim - 1, 0) = s;
}
} else {
// degenerate case
R = U * d.asDiagonal() * V.transpose();
}
assert(std::abs(R.determinant() - 1.0) < assert_eps);
// Eigen::MatrixXd src_demean_cov =
// (src_demean.adjoint() * src_demean) / double(n_data);
double src_var =
src_demean.rowwise().squaredNorm().sum() / double(n_data) + 1e-30;
double uniform_scale = 1.0 / src_var * (S * d.asDiagonal()).trace();
// Question: Is it possible to estimate non-uniform scale?
scale = Eigen::MatrixXd::Identity(R.rows(), R.cols());
scale *= uniform_scale;
t = dst_mean - scale * R * src_mean;
T.block(0, 0, n_dim, n_dim) = scale * R;
T.block(0, n_dim, n_dim, 1) = t;
return true;
}
} // namespace ugu
| 32.362847
| 80
| 0.612682
|
unclearness
|
620eedbea94b69b261f8911bc2a684500a7554ec
| 2,874
|
hpp
|
C++
|
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
|
JinmingHu-MSFT/azure-sdk-for-cpp
|
933486385a54a5a09a7444dbd823425f145ad75a
|
[
"MIT"
] | 1
|
2022-01-19T22:54:41.000Z
|
2022-01-19T22:54:41.000Z
|
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
|
LarryOsterman/azure-sdk-for-cpp
|
d96216f50909a2bd39b555c9088f685bf0f7d6e6
|
[
"MIT"
] | null | null | null |
sdk/identity/azure-identity/inc/azure/identity/client_certificate_credential.hpp
|
LarryOsterman/azure-sdk-for-cpp
|
d96216f50909a2bd39b555c9088f685bf0f7d6e6
|
[
"MIT"
] | null | null | null |
// Copyright (c) Microsoft Corporation. All rights reserved.
// SPDX-License-Identifier: MIT
/**
* @file
* @brief Client Certificate Credential and options.
*/
#pragma once
#include "azure/identity/dll_import_export.hpp"
#include <azure/core/credentials/credentials.hpp>
#include <azure/core/credentials/token_credential_options.hpp>
#include <azure/core/url.hpp>
#include <memory>
#include <string>
namespace Azure { namespace Identity {
namespace _detail {
class TokenCredentialImpl;
} // namespace _detail
/**
* @brief Options for client certificate authentication.
*
*/
struct ClientCertificateCredentialOptions final : public Core::Credentials::TokenCredentialOptions
{
};
/**
* @brief Client Certificate Credential authenticates with the Azure services using a Tenant ID,
* Client ID and a client certificate.
*
*/
class ClientCertificateCredential final : public Core::Credentials::TokenCredential {
private:
std::unique_ptr<_detail::TokenCredentialImpl> m_tokenCredentialImpl;
Core::Url m_requestUrl;
std::string m_requestBody;
std::string m_tokenHeaderEncoded;
std::string m_tokenPayloadStaticPart;
void* m_pkey;
public:
/**
* @brief Constructs a Client Secret Credential.
*
* @param tenantId Tenant ID.
* @param clientId Client ID.
* @param clientCertificatePath Client certificate path.
* @param options Options for token retrieval.
*/
explicit ClientCertificateCredential(
std::string const& tenantId,
std::string const& clientId,
std::string const& clientCertificatePath,
Core::Credentials::TokenCredentialOptions const& options
= Core::Credentials::TokenCredentialOptions());
/**
* @brief Constructs a Client Secret Credential.
*
* @param tenantId Tenant ID.
* @param clientId Client ID.
* @param clientCertificatePath Client certificate path.
* @param options Options for token retrieval.
*/
explicit ClientCertificateCredential(
std::string const& tenantId,
std::string const& clientId,
std::string const& clientCertificatePath,
ClientCertificateCredentialOptions const& options);
/**
* @brief Destructs `%ClientCertificateCredential`.
*
*/
~ClientCertificateCredential() override;
/**
* @brief Gets an authentication token.
*
* @param tokenRequestContext A context to get the token in.
* @param context A context to control the request lifetime.
*
* @throw Azure::Core::Credentials::AuthenticationException Authentication error occurred.
*/
Core::Credentials::AccessToken GetToken(
Core::Credentials::TokenRequestContext const& tokenRequestContext,
Core::Context const& context) const override;
};
}} // namespace Azure::Identity
| 29.628866
| 100
| 0.699026
|
JinmingHu-MSFT
|
6211bc69c80917d0126fa9ea034fd82551348b1d
| 203
|
cpp
|
C++
|
core/objects/utility/Dynamic.cpp
|
pavelsevecek/OpenSPH
|
d547c0af6270a739d772a4dcba8a70dc01775367
|
[
"MIT"
] | 20
|
2021-04-02T04:30:08.000Z
|
2022-03-01T09:52:01.000Z
|
core/objects/utility/Dynamic.cpp
|
pavelsevecek/OpenSPH
|
d547c0af6270a739d772a4dcba8a70dc01775367
|
[
"MIT"
] | null | null | null |
core/objects/utility/Dynamic.cpp
|
pavelsevecek/OpenSPH
|
d547c0af6270a739d772a4dcba8a70dc01775367
|
[
"MIT"
] | 1
|
2022-01-22T11:44:52.000Z
|
2022-01-22T11:44:52.000Z
|
#include "objects/utility/Dynamic.h"
NAMESPACE_SPH_BEGIN
Dynamic::Dynamic() = default;
/// Needs to be in .cpp to compile with clang, for some reason
Dynamic::~Dynamic() = default;
NAMESPACE_SPH_END
| 18.454545
| 62
| 0.748768
|
pavelsevecek
|
6212bc8831b2ba6f1511f39ce1398e5a6770e78c
| 5,734
|
cpp
|
C++
|
Codes/String/SuffixArrayShort.cpp
|
cjtoribio/Algorithms
|
78499613a9b018eb5e489307b14e31e5fe8227e3
|
[
"MIT"
] | 18
|
2015-05-24T20:28:46.000Z
|
2021-01-27T02:34:43.000Z
|
Codes/String/SuffixArrayShort.cpp
|
cjtoribio/Algorithms
|
78499613a9b018eb5e489307b14e31e5fe8227e3
|
[
"MIT"
] | null | null | null |
Codes/String/SuffixArrayShort.cpp
|
cjtoribio/Algorithms
|
78499613a9b018eb5e489307b14e31e5fe8227e3
|
[
"MIT"
] | 4
|
2015-05-24T20:28:32.000Z
|
2021-01-30T04:04:55.000Z
|
typedef vector<int> VI;
struct SuffixArray {
int N;
string A;
VI SA, RA, LCP;
SuffixArray(const string &B) :
N(B.size()), A(B), SA(B.size()), RA(B.size()), LCP(B.size()) {
for (int i = 0; i < N; ++i)
SA[i] = i, RA[i] = A[i];
if(N == 1) RA[0] = 0;
}
void countingSort(int H) {
auto vrank = [&](int i) { return SA[i]+H<N ? RA[SA[i]+H]+1 : 0; };
int maxRank = *max_element(RA.begin(), RA.end());
VI nSA(N);
VI freq(maxRank + 2);
for (int i = 0; i < N; ++i)
freq[vrank(i)]++;
for (int i = 1; i < freq.size(); ++i)
freq[i] += freq[i-1];
for (int i = N-1, p, m; i >= 0; --i)
nSA[--freq[vrank(i)]] = SA[i];
copy(nSA.begin(), nSA.end(), SA.begin());
}
void buildSA() {
VI nRA(N);
for (int H = 1; H < N; H <<= 1) {
countingSort(H);
countingSort(0);
int rank = nRA[SA[0]] = 0;
for (int i = 1; i < N; ++i) {
if (RA[SA[i]] != RA[SA[i - 1]])
rank++;
else if (SA[i - 1] + H >= N || SA[i] + H >= N)
rank++;
else if (RA[SA[i] + H] != RA[SA[i - 1] + H])
rank++;
nRA[SA[i]] = rank;
}
copy(nRA.begin(), nRA.end(), RA.begin());
}
}
void buildSA2(){
if (N == 1) { this->SA[0] = 0, this->RA[0] = 0; return; }
VI T(N+3), SA(N+3);
for(int i = 0; i < A.size(); ++i)
T[i] = A[i];
suffixArray(T, SA, N, 256);
for(int i = 0; i < N; ++i)
RA[ SA[i] ] = i;
for(int i = 0; i < N; ++i)
this->SA[i] = SA[i];
}
inline bool leq(int a1, int a2, int b1, int b2) {
return (a1 < b1 || (a1 == b1 && a2 <= b2));
}
inline bool leq(int a1, int a2, int a3, int b1, int b2, int b3) {
return (a1 < b1 || (a1 == b1 && leq(a2, a3, b2, b3)));
}
static void radixPass(VI &a, VI &b, VI::iterator r, int n, int K) {
VI c(K+1);
for (int i = 0; i < n; i++)
c[r[a[i]]]++;
for (int i = 1; i <= K; i++)
c[i] += c[i-1];
for (int i = n-1; i >= 0; --i)
b[--c[r[a[i]]]] = a[i];
}
void suffixArray(VI &T, VI &SA, int n, int K) {
int n0 = (n + 2) / 3, n1 = (n + 1) / 3, n2 = n / 3, n02 = n0 + n2;
VI R(n02+3), SA12(n02+3), R0(n0), SA0(n0);
for (int i = 0, j = 0; i < n + (n0 - n1); i++)
if (i % 3 != 0)
R[j++] = i;
radixPass(R, SA12, T.begin() + 2, n02, K);
radixPass(SA12, R, T.begin() + 1, n02, K);
radixPass(R, SA12, T.begin(), n02, K);
int name = 0, c0 = -1, c1 = -1, c2 = -1;
for (int i = 0; i < n02; i++) {
if (T[SA12[i]] != c0 || T[SA12[i] + 1] != c1 || T[SA12[i] + 2] != c2) {
name++;
c0 = T[SA12[i]];
c1 = T[SA12[i] + 1];
c2 = T[SA12[i] + 2];
}
if (SA12[i] % 3 == 1) {
R[SA12[i] / 3] = name;
}
else {
R[SA12[i] / 3 + n0] = name;
}
}
if (name < n02) {
suffixArray(R, SA12, n02, name);
for (int i = 0; i < n02; i++)
R[SA12[i]] = i + 1;
} else
for (int i = 0; i < n02; i++)
SA12[R[i] - 1] = i;
for (int i = 0, j = 0; i < n02; i++)
if (SA12[i] < n0)
R0[j++] = 3 * SA12[i];
radixPass(R0, SA0, T.begin(), n0, K);
for (int p = 0, t = n0 - n1, k = 0; k < n; k++) {
#define GetI() (SA12[t] < n0 ? SA12[t] * 3 + 1 : (SA12[t] - n0) * 3 + 2)
int i = GetI(); // pos of current offset 12 suffix
int j = SA0[p]; // pos of current offset 0 suffix
if (SA12[t] < n0 ? // different compares for mod 1 and mod 2 suffixes
leq(T[i], R[SA12[t] + n0], T[j], R[j / 3]) :
leq(T[i], T[i + 1], R[SA12[t] - n0 + 1], T[j], T[j + 1], R[j / 3 + n0])) { // suffix from SA12 is smaller
SA[k] = i;
t++;
if (t == n02) // done --- only SA0 suffixes left
for (k++; p < n0; p++, k++)
SA[k] = SA0[p];
} else { // suffix from SA0 is smaller
SA[k] = j;
p++;
if (p == n0) // done --- only SA12 suffixes left
for (k++; t < n02; t++, k++)
SA[k] = GetI();
}
}
}
void buildLCP() {
for (int i = 0, k = 0; i < N; ++i) if (RA[i] != N - 1) {
for (int j = SA[RA[i] + 1]; A[i + k] == A[j + k];)
++k;
LCP[RA[i]] = k;
if (k)--k;
}
}
vector<VI> RLCP;
void BuildRangeQueries() {
int L = 31 - __builtin_clz(N) + 1;
RLCP = vector<VI>(L, VI(N));
RLCP[0] = LCP;
for (int i = 1; i < L; ++i) {
for (int j = 0; j+(1<<(i-1)) < N; ++j)
RLCP[i][j] = min(RLCP[i - 1][j], RLCP[i-1][j + (1<<(i-1))]);
}
}
int lcp(int i, int j) {
if (i == j) return N - SA[i];
int b = 31 - __builtin_clz(j-i);
return min(RLCP[b][i], RLCP[b][j-(1<<b)]);
}
long long ops = 0;
int match(int idx, const string &P){
for(int i = 0; i < P.size() && i + idx < N; ++i){
ops++;
if(A[i+idx] != P[i])
return i;
}
return min(N-idx, (int)P.size());
}
int cmp(int idx, const string &P){
int m = match(idx, P);
if(m == P.size())return 0;
if(m == N-idx)return -1;
return A[idx+m] < P[m] ? -1 : (A[idx+m] == P[m] ? 0 : 1);
}
// MlogN (low constant)
int lowerBound(const string &P){
int lo = 0, hi = N;
while(lo < hi){
int mid = (lo + hi)/2;
if(cmp(SA[mid], P) < 0)
lo = mid+1;
else
hi = mid;
}
return lo;
}
// MlogN (low constant)
int upperBound(const string &P){
int lo = 0, hi = N;
while(lo < hi){
int mid = (lo + hi)/2;
if(cmp(SA[mid], P) <= 0)
lo = mid+1;
else
hi = mid;
}
return lo;
}
// M + logN (high constant) (slow in practice)
int lowerBound2(const string &P, int deb = 0){
int lo = 0, hi = N;
int k = match(SA[0], P), pm = 0;
while(lo < hi){
int m = (lo + hi)/2;
int rlcp= lcp(min(pm,m), max(m,pm));
if(rlcp > k && pm != m){
if(pm < m)lo = m+1;
else hi = m;
}else if(rlcp < k && pm != m){
if(pm < m)hi = m;
else lo = m+1;
}else{
while(k < P.size() && SA[m]+k < N && P[k] == A[SA[m]+k])
k++;
if(k == P.size())
hi = m;
else if(SA[m]+k == N)
lo = m+1;
else if(A[SA[m]+k] < P[k])
lo = m+1;
else
hi = m;
pm = m;
}
}
return lo;
}
};
| 26.423963
| 109
| 0.452389
|
cjtoribio
|
62156bb4143b403e6bd804aa6095f394decd67db
| 39,862
|
cpp
|
C++
|
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
|
supudo/Kuplung
|
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
|
[
"Unlicense"
] | 14
|
2017-02-17T17:12:40.000Z
|
2021-12-22T01:55:06.000Z
|
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
|
supudo/Kuplung
|
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
|
[
"Unlicense"
] | null | null | null |
Kuplung/kuplung/utilities/renderers/default-forward/DefaultForwardRenderer.cpp
|
supudo/Kuplung
|
f0e11934fde0675fa531e6dc263bedcc20a5ea1a
|
[
"Unlicense"
] | 1
|
2019-10-15T08:10:10.000Z
|
2019-10-15T08:10:10.000Z
|
//
// DefaultForwardRenderer.cpp
// Kuplung
//
// Created by Sergey Petrov on 12/16/15.
// Copyright © 2015 supudo.net. All rights reserved.
//
#include "DefaultForwardRenderer.hpp"
#include "kuplung/utilities/stb/stb_image_write.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <glm/gtc/matrix_inverse.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/matrix_decompose.hpp>
DefaultForwardRenderer::DefaultForwardRenderer(ObjectsManager& managerObjects) : fileOutputImage(), managerObjects(managerObjects) {
this->solidLight = new ModelFace_LightSource_Directional();
this->lightingPass_DrawMode = -1;
this->GLSL_LightSourceNumber_Directional = 0;
this->GLSL_LightSourceNumber_Point = 0;
this->GLSL_LightSourceNumber_Spot = 0;
}
DefaultForwardRenderer::~DefaultForwardRenderer() {
GLint maxColorAttachments = 1;
glGetIntegerv(GL_MAX_COLOR_ATTACHMENTS, &maxColorAttachments);
GLuint colorAttachment;
GLenum att = GL_COLOR_ATTACHMENT0;
for (colorAttachment = 0; colorAttachment < static_cast<GLuint>(maxColorAttachments); colorAttachment++) {
att += colorAttachment;
GLint param;
GLuint objName;
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE, ¶m);
if (GL_RENDERBUFFER == param) {
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, ¶m);
objName = reinterpret_cast<GLuint*>(¶m)[0];
glDeleteRenderbuffers(1, &objName);
}
else if (GL_TEXTURE == param) {
glGetFramebufferAttachmentParameteriv(GL_FRAMEBUFFER, att, GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME, ¶m);
objName = reinterpret_cast<GLuint*>(¶m)[0];
glDeleteTextures(1, &objName);
}
}
glDeleteProgram(this->shaderProgram);
glDeleteFramebuffers(1, &this->renderFBO);
glDeleteRenderbuffers(1, &this->renderRBO);
for (size_t i = 0; i < this->mfLights_Directional.size(); i++) {
delete this->mfLights_Directional[i];
}
for (size_t i = 0; i < this->mfLights_Point.size(); i++) {
delete this->mfLights_Point[i];
}
for (size_t i = 0; i < this->mfLights_Spot.size(); i++) {
delete this->mfLights_Spot[i];
}
}
void DefaultForwardRenderer::init() {
this->GLSL_LightSourceNumber_Directional = 8;
this->GLSL_LightSourceNumber_Point = 4;
this->GLSL_LightSourceNumber_Spot = 4;
this->Setting_RenderSkybox = false;
this->initShaderProgram();
}
bool DefaultForwardRenderer::initShaderProgram() {
bool success = true;
// vertex shader
std::string shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.vert";
std::string shaderSourceVertex = Settings::Instance()->glUtils->readFile(shaderPath.c_str());
const char* shader_vertex = shaderSourceVertex.c_str();
// tessellation control shader
shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.tcs";
std::string shaderSourceTCS = Settings::Instance()->glUtils->readFile(shaderPath.c_str());
const char* shader_tess_control = shaderSourceTCS.c_str();
// tessellation evaluation shader
shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.tes";
std::string shaderSourceTES = Settings::Instance()->glUtils->readFile(shaderPath.c_str());
const char* shader_tess_eval = shaderSourceTES.c_str();
// geometry shader
shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.geom";
std::string shaderSourceGeometry = Settings::Instance()->glUtils->readFile(shaderPath.c_str());
const char* shader_geometry = shaderSourceGeometry.c_str();
// fragment shader - parts
std::string shaderSourceFragment;
std::vector<std::string> fragFiles = {"vars", "effects", "lights", "mapping", "shadow_mapping", "misc", "pbr"};
for (size_t i = 0; i < fragFiles.size(); i++) {
shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face_" + fragFiles[i] + ".frag";
shaderSourceFragment += Settings::Instance()->glUtils->readFile(shaderPath.c_str());
}
shaderPath = Settings::Instance()->appFolder() + "/shaders/model_face.frag";
shaderSourceFragment += Settings::Instance()->glUtils->readFile(shaderPath.c_str());
const char* shader_fragment = shaderSourceFragment.c_str();
this->shaderProgram = glCreateProgram();
bool shaderCompilation = true;
shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_VERTEX_SHADER, shader_vertex);
shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_TESS_CONTROL_SHADER, shader_tess_control);
shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_TESS_EVALUATION_SHADER, shader_tess_eval);
shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_GEOMETRY_SHADER, shader_geometry);
shaderCompilation &= Settings::Instance()->glUtils->compileShader(this->shaderProgram, GL_FRAGMENT_SHADER, shader_fragment);
if (!shaderCompilation)
return false;
glLinkProgram(this->shaderProgram);
GLint programSuccess = GL_TRUE;
glGetProgramiv(this->shaderProgram, GL_LINK_STATUS, &programSuccess);
if (programSuccess != GL_TRUE) {
Settings::Instance()->funcDoLog("[DefaultForwardRenderer] Error linking program " + std::to_string(this->shaderProgram) + "!");
Settings::Instance()->glUtils->printProgramLog(this->shaderProgram);
return success = false;
}
else {
#ifdef Def_Kuplung_OpenGL_4x
glPatchParameteri(GL_PATCH_VERTICES, 3);
#endif
this->glGS_GeomDisplacementLocation = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_displacementLocation");
this->glTCS_UseCullFace = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_UseCullFace");
this->glTCS_UseTessellation = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_UseTessellation");
this->glTCS_TessellationSubdivision = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "tcs_TessellationSubdivision");
this->glFS_AlphaBlending = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_alpha");
this->glFS_CelShading = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_celShading");
this->glFS_CameraPosition = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_cameraPosition");
this->glVS_IsBorder = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_isBorder");
this->glFS_OutlineColor = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_outlineColor");
this->glFS_UIAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_UIAmbient");
this->glFS_GammaCoeficient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_gammaCoeficient");
this->glVS_MVPMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_MVPMatrix");
this->glFS_MMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_ModelMatrix");
this->glVS_WorldMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_WorldMatrix");
this->glFS_MVMatrix = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "vs_MVMatrix");
this->glVS_NormalMatrix = glGetUniformLocation(this->shaderProgram, "vs_normalMatrix");
this->glFS_ScreenResX = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_screenResX");
this->glFS_ScreenResY = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_screenResY");
this->glMaterial_ParallaxMapping = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_userParallaxMapping");
this->gl_ModelViewSkin = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_modelViewSkin");
this->glFS_solidSkin_materialColor = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_materialColor");
this->solidLight->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.inUse");
this->solidLight->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.direction");
this->solidLight->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.ambient");
this->solidLight->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.diffuse");
this->solidLight->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.specular");
this->solidLight->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthAmbient");
this->solidLight->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthDiffuse");
this->solidLight->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "solidSkin_Light.strengthSpecular");
// light - directional
for (int i = 0; i < this->GLSL_LightSourceNumber_Directional; i++) {
ModelFace_LightSource_Directional* f = new ModelFace_LightSource_Directional();
f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].inUse").c_str());
f->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].direction").c_str());
f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].ambient").c_str());
f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].diffuse").c_str());
f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].specular").c_str());
f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthAmbient").c_str());
f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthDiffuse").c_str());
f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("directionalLights[" + std::to_string(i) + "].strengthSpecular").c_str());
this->mfLights_Directional.push_back(f);
}
// light - point
for (int i = 0; i < this->GLSL_LightSourceNumber_Point; i++) {
ModelFace_LightSource_Point* f = new ModelFace_LightSource_Point();
f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].inUse").c_str());
f->gl_Position = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].position").c_str());
f->gl_Constant = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].constant").c_str());
f->gl_Linear = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].linear").c_str());
f->gl_Quadratic = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].quadratic").c_str());
f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].ambient").c_str());
f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].diffuse").c_str());
f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].specular").c_str());
f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthAmbient").c_str());
f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthDiffuse").c_str());
f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("pointLights[" + std::to_string(i) + "].strengthSpecular").c_str());
this->mfLights_Point.push_back(f);
}
// light - spot
for (int i = 0; i < this->GLSL_LightSourceNumber_Spot; i++) {
ModelFace_LightSource_Spot* f = new ModelFace_LightSource_Spot();
f->gl_InUse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].inUse").c_str());
f->gl_Position = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].position").c_str());
f->gl_Direction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].direction").c_str());
f->gl_CutOff = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].cutOff").c_str());
f->gl_OuterCutOff = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].outerCutOff").c_str());
f->gl_Constant = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].constant").c_str());
f->gl_Linear = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].linear").c_str());
f->gl_Quadratic = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].quadratic").c_str());
f->gl_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].ambient").c_str());
f->gl_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].diffuse").c_str());
f->gl_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].specular").c_str());
f->gl_StrengthAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthAmbient").c_str());
f->gl_StrengthDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthDiffuse").c_str());
f->gl_StrengthSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, ("spotLights[" + std::to_string(i) + "].strengthSpecular").c_str());
this->mfLights_Spot.push_back(f);
}
// material
this->glMaterial_Refraction = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.refraction");
this->glMaterial_SpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.specularExp");
this->glMaterial_IlluminationModel = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.illumination_model");
this->glMaterial_HeightScale = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.heightScale");
this->glMaterial_Ambient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.ambient");
this->glMaterial_Diffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.diffuse");
this->glMaterial_Specular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.specular");
this->glMaterial_Emission = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.emission");
this->glMaterial_SamplerAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_ambient");
this->glMaterial_SamplerDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_diffuse");
this->glMaterial_SamplerSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_specular");
this->glMaterial_SamplerSpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_specularExp");
this->glMaterial_SamplerDissolve = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_dissolve");
this->glMaterial_SamplerBump = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_bump");
this->glMaterial_SamplerDisplacement = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.sampler_displacement");
this->glMaterial_HasTextureAmbient = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_ambient");
this->glMaterial_HasTextureDiffuse = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_diffuse");
this->glMaterial_HasTextureSpecular = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_specular");
this->glMaterial_HasTextureSpecularExp = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_specularExp");
this->glMaterial_HasTextureDissolve = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_dissolve");
this->glMaterial_HasTextureBump = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_bump");
this->glMaterial_HasTextureDisplacement = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "material.has_texture_displacement");
// effects - gaussian blur
this->glEffect_GB_W = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_w");
this->glEffect_GB_Radius = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_radius");
this->glEffect_GB_Mode = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_GBlur.gauss_mode");
// effects - bloom
this->glEffect_Bloom_doBloom = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.doBloom");
this->glEffect_Bloom_WeightA = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightA");
this->glEffect_Bloom_WeightB = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightB");
this->glEffect_Bloom_WeightC = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightC");
this->glEffect_Bloom_WeightD = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_WeightD");
this->glEffect_Bloom_Vignette = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_Vignette");
this->glEffect_Bloom_VignetteAtt = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "effect_Bloom.bloom_VignetteAtt");
// effects - tone mapping
this->glEffect_ToneMapping_ACESFilmRec2020 = Settings::Instance()->glUtils->glGetUniform(this->shaderProgram, "fs_ACESFilmRec2020");
}
return success;
}
void DefaultForwardRenderer::createFBO() {
glGenFramebuffers(1, &this->renderFBO);
glBindFramebuffer(GL_FRAMEBUFFER, this->renderFBO);
this->generateAttachmentTexture(false, false);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, this->renderTextureColorBuffer, 0);
const int screenWidth = Settings::Instance()->SDL_DrawableSize_Width;
const int screenHeight = Settings::Instance()->SDL_DrawableSize_Height;
glGenRenderbuffers(1, &this->renderRBO);
glBindRenderbuffer(GL_RENDERBUFFER, this->renderRBO);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, screenWidth, screenHeight);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, this->renderRBO);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE)
Settings::Instance()->funcDoLog("[Kuplung-DefaultForwardRenderer] Framebuffer is not complete!");
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void DefaultForwardRenderer::generateAttachmentTexture(GLboolean depth, GLboolean stencil) {
GLenum attachment_type = GL_RGB;
if (!depth && !stencil)
attachment_type = GL_RGB;
else if (depth && !stencil)
attachment_type = GL_DEPTH_COMPONENT;
else if (!depth && stencil)
attachment_type = GL_STENCIL_INDEX;
int screenWidth = Settings::Instance()->SDL_DrawableSize_Width;
int screenHeight = Settings::Instance()->SDL_DrawableSize_Height;
glGenTextures(1, &this->renderTextureColorBuffer);
glBindTexture(GL_TEXTURE_2D, this->renderTextureColorBuffer);
if (!depth && !stencil)
glTexImage2D(GL_TEXTURE_2D, 0, static_cast<GLint>(attachment_type), screenWidth, screenHeight, 0, attachment_type, GL_UNSIGNED_BYTE, nullptr);
else
glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH24_STENCIL8, screenWidth, screenHeight, 0, GL_DEPTH_STENCIL, GL_UNSIGNED_INT_24_8, nullptr);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, 0);
}
std::string DefaultForwardRenderer::renderImage(const FBEntity& file, std::vector<ModelFaceBase*>* meshModelFaces) {
this->fileOutputImage = file;
std::string endFile;
int width = Settings::Instance()->SDL_DrawableSize_Width;
int height = Settings::Instance()->SDL_DrawableSize_Height;
this->createFBO();
glBindFramebuffer(GL_FRAMEBUFFER, this->renderFBO);
this->renderSceneToFBO(meshModelFaces);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, this->renderTextureColorBuffer);
glGenerateMipmap(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, 0);
unsigned char* pixels = new unsigned char[3 * width * height];
glBindFramebuffer(GL_READ_FRAMEBUFFER, this->renderFBO);
glBlitFramebuffer(0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height, 0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height, GL_DEPTH_BUFFER_BIT, GL_NEAREST);
glReadBuffer(GL_COLOR_ATTACHMENT0);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, pixels);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
unsigned char* line_tmp = new unsigned char[3 * width];
unsigned char* line_a = pixels;
unsigned char* line_b = pixels + (3 * width * (height - 1));
while (line_a < line_b) {
memcpy(line_tmp, line_a, width * 3);
memcpy(line_a, line_b, width * 3);
memcpy(line_b, line_tmp, width * 3);
line_a += width * 3;
line_b -= width * 3;
}
endFile = file.path + ".bmp";
stbi_write_bmp(endFile.c_str(), width, height, 3, pixels);
delete[] pixels;
delete[] line_tmp;
return endFile;
}
void DefaultForwardRenderer::renderSceneToFBO(std::vector<ModelFaceBase*>* meshModelFaces) {
this->matrixProjection = this->managerObjects.matrixProjection;
this->matrixCamera = this->managerObjects.camera->matrixCamera;
this->vecCameraPosition = this->managerObjects.camera->cameraPosition;
this->uiAmbientLight = this->managerObjects.Setting_UIAmbientLight;
this->lightingPass_DrawMode = this->managerObjects.Setting_LightingPass_DrawMode;
glViewport(0, 0, Settings::Instance()->SDL_DrawableSize_Width, Settings::Instance()->SDL_DrawableSize_Height);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);
if (this->Setting_RenderSkybox)
this->managerObjects.renderSkybox();
glUseProgram(this->shaderProgram);
for (size_t i = 0; i < (*meshModelFaces).size(); i++) {
ModelFaceData* mfd = (ModelFaceData*)(*meshModelFaces)[i];
glm::mat4 matrixModel = glm::mat4(1.0);
matrixModel *= this->managerObjects.grid->matrixModel;
matrixModel = glm::scale(matrixModel, glm::vec3(mfd->scaleX->point, mfd->scaleY->point, mfd->scaleZ->point));
matrixModel = glm::translate(matrixModel, glm::vec3(mfd->positionX->point, mfd->positionY->point, mfd->positionZ->point));
matrixModel = glm::translate(matrixModel, glm::vec3(0, 0, 0));
matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateX->point), glm::vec3(1, 0, 0));
matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateY->point), glm::vec3(0, 1, 0));
matrixModel = glm::rotate(matrixModel, glm::radians(mfd->rotateZ->point), glm::vec3(0, 0, 1));
matrixModel = glm::translate(matrixModel, glm::vec3(0, 0, 0));
mfd->matrixGrid = this->managerObjects.grid->matrixModel;
mfd->matrixProjection = this->matrixProjection;
mfd->matrixCamera = this->matrixCamera;
mfd->matrixModel = matrixModel;
mfd->Setting_ModelViewSkin = this->managerObjects.viewModelSkin;
mfd->lightSources = this->managerObjects.lightSources;
mfd->setOptionsFOV(this->managerObjects.Setting_FOV);
mfd->setOptionsOutlineColor(this->managerObjects.Setting_OutlineColor);
mfd->setOptionsOutlineThickness(this->managerObjects.Setting_OutlineThickness);
mfd->setOptionsSelected(0);
glm::mat4 mvpMatrix = this->matrixProjection * this->matrixCamera * matrixModel;
glUniformMatrix4fv(this->glVS_MVPMatrix, 1, GL_FALSE, glm::value_ptr(mvpMatrix));
glUniformMatrix4fv(this->glFS_MMatrix, 1, GL_FALSE, glm::value_ptr(matrixModel));
glm::mat4 matrixModelView = this->matrixCamera * matrixModel;
glUniformMatrix4fv(this->glFS_MVMatrix, 1, GL_FALSE, glm::value_ptr(matrixModelView));
glm::mat3 matrixNormal = glm::inverseTranspose(glm::mat3(this->matrixCamera * matrixModel));
glUniformMatrix3fv(this->glVS_NormalMatrix, 1, GL_FALSE, glm::value_ptr(matrixNormal));
glm::mat4 matrixWorld = matrixModel;
glUniformMatrix4fv(this->glVS_WorldMatrix, 1, GL_FALSE, glm::value_ptr(matrixWorld));
// blending
if (mfd->meshModel.ModelMaterial.Transparency < 1.0f || mfd->Setting_Alpha < 1.0f) {
glDisable(GL_DEPTH_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glEnable(GL_BLEND);
if (mfd->meshModel.ModelMaterial.Transparency < 1.0f)
glUniform1f(this->glFS_AlphaBlending, mfd->meshModel.ModelMaterial.Transparency);
else
glUniform1f(this->glFS_AlphaBlending, mfd->Setting_Alpha);
}
else {
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glDisable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glUniform1f(this->glFS_AlphaBlending, 1.0);
}
// tessellation
glUniform1i(this->glTCS_UseCullFace, mfd->Setting_UseCullFace);
glUniform1i(this->glTCS_UseTessellation, mfd->Setting_UseTessellation);
glUniform1i(this->glTCS_TessellationSubdivision, mfd->Setting_TessellationSubdivision);
// cel-shading
glUniform1i(this->glFS_CelShading, mfd->Setting_CelShading);
// camera position
glUniform3f(this->glFS_CameraPosition, this->vecCameraPosition.x, this->vecCameraPosition.y, this->vecCameraPosition.z);
// screen size
glUniform1f(this->glFS_ScreenResX, Settings::Instance()->SDL_DrawableSize_Width);
glUniform1f(this->glFS_ScreenResY, Settings::Instance()->SDL_DrawableSize_Height);
// Outline color
glUniform3f(this->glFS_OutlineColor, mfd->getOptionsOutlineColor().r, mfd->getOptionsOutlineColor().g, mfd->getOptionsOutlineColor().b);
// ambient color for editor
glUniform3f(this->glFS_UIAmbient, this->uiAmbientLight.r, this->uiAmbientLight.g, this->uiAmbientLight.b);
// geometry shader displacement
glUniform3f(this->glGS_GeomDisplacementLocation, mfd->displaceX->point, mfd->displaceY->point, mfd->displaceZ->point);
// mapping
glUniform1i(this->glMaterial_ParallaxMapping, mfd->Setting_ParallaxMapping);
// gamma correction
glUniform1f(this->glFS_GammaCoeficient, this->managerObjects.Setting_GammaCoeficient);
// render skin
glUniform1i(this->gl_ModelViewSkin, mfd->Setting_ModelViewSkin);
glUniform3f(this->glFS_solidSkin_materialColor, mfd->solidLightSkin_MaterialColor.r, mfd->solidLightSkin_MaterialColor.g, mfd->solidLightSkin_MaterialColor.b);
glUniform1i(this->solidLight->gl_InUse, 1);
glUniform3f(this->solidLight->gl_Direction, this->managerObjects.SolidLight_Direction.x, this->managerObjects.SolidLight_Direction.y, this->managerObjects.SolidLight_Direction.z);
glUniform3f(this->solidLight->gl_Ambient, this->managerObjects.SolidLight_Ambient.r, this->managerObjects.SolidLight_Ambient.g, this->managerObjects.SolidLight_Ambient.b);
glUniform3f(this->solidLight->gl_Diffuse, this->managerObjects.SolidLight_Diffuse.r, this->managerObjects.SolidLight_Diffuse.g, this->managerObjects.SolidLight_Diffuse.b);
glUniform3f(this->solidLight->gl_Specular, this->managerObjects.SolidLight_Specular.r, this->managerObjects.SolidLight_Specular.g, this->managerObjects.SolidLight_Specular.b);
glUniform1f(this->solidLight->gl_StrengthAmbient, this->managerObjects.SolidLight_Ambient_Strength);
glUniform1f(this->solidLight->gl_StrengthDiffuse, this->managerObjects.SolidLight_Diffuse_Strength);
glUniform1f(this->solidLight->gl_StrengthSpecular, this->managerObjects.SolidLight_Specular_Strength);
// lights
size_t lightsCount_Directional = 0, lightsCount_Point = 0, lightsCount_Spot = 0;
for (size_t j = 0; j < mfd->lightSources.size(); j++) {
Light* light = mfd->lightSources[j];
assert(light->type == LightSourceType_Directional || light->type == LightSourceType_Point || light->type == LightSourceType_Spot);
switch (light->type) {
case LightSourceType_Directional: {
if (lightsCount_Directional < static_cast<size_t>(this->GLSL_LightSourceNumber_Directional)) {
ModelFace_LightSource_Directional* f = this->mfLights_Directional[lightsCount_Directional];
glUniform1i(f->gl_InUse, 1);
// light
glUniform3f(f->gl_Direction, light->matrixModel[2].x, light->matrixModel[2].y, light->matrixModel[2].z);
// color
glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b);
glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b);
glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b);
// light factors
glUniform1f(f->gl_StrengthAmbient, light->ambient->strength);
glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength);
glUniform1f(f->gl_StrengthSpecular, light->specular->strength);
lightsCount_Directional += 1;
}
break;
}
case LightSourceType_Point: {
if (lightsCount_Point < static_cast<size_t>(this->GLSL_LightSourceNumber_Point)) {
ModelFace_LightSource_Point* f = this->mfLights_Point[lightsCount_Point];
glUniform1i(f->gl_InUse, 1);
// light
glUniform3f(f->gl_Position, light->matrixModel[3].x, light->matrixModel[3].y, light->matrixModel[3].z);
// factors
glUniform1f(f->gl_Constant, light->lConstant->point);
glUniform1f(f->gl_Linear, light->lLinear->point);
glUniform1f(f->gl_Quadratic, light->lQuadratic->point);
// color
glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b);
glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b);
glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b);
// light factors
glUniform1f(f->gl_StrengthAmbient, light->ambient->strength);
glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength);
glUniform1f(f->gl_StrengthSpecular, light->specular->strength);
lightsCount_Point += 1;
}
break;
}
case LightSourceType_Spot: {
if (lightsCount_Spot < static_cast<size_t>(this->GLSL_LightSourceNumber_Spot)) {
ModelFace_LightSource_Spot* f = this->mfLights_Spot[lightsCount_Spot];
glUniform1i(f->gl_InUse, 1);
// light
glUniform3f(f->gl_Direction, light->matrixModel[2].x, light->matrixModel[2].y, light->matrixModel[2].z);
glUniform3f(f->gl_Position, light->matrixModel[3].x, light->matrixModel[3].y, light->matrixModel[3].z);
// cutoff
glUniform1f(f->gl_CutOff, glm::cos(glm::radians(light->lCutOff->point)));
glUniform1f(f->gl_OuterCutOff, glm::cos(glm::radians(light->lOuterCutOff->point)));
// factors
glUniform1f(f->gl_Constant, light->lConstant->point);
glUniform1f(f->gl_Linear, light->lLinear->point);
glUniform1f(f->gl_Quadratic, light->lQuadratic->point);
// color
glUniform3f(f->gl_Ambient, light->ambient->color.r, light->ambient->color.g, light->ambient->color.b);
glUniform3f(f->gl_Diffuse, light->diffuse->color.r, light->diffuse->color.g, light->diffuse->color.b);
glUniform3f(f->gl_Specular, light->specular->color.r, light->specular->color.g, light->specular->color.b);
// light factors
glUniform1f(f->gl_StrengthAmbient, light->ambient->strength);
glUniform1f(f->gl_StrengthDiffuse, light->diffuse->strength);
glUniform1f(f->gl_StrengthSpecular, light->specular->strength);
lightsCount_Spot += 1;
}
break;
}
}
}
for (size_t j = lightsCount_Directional; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Directional); j++) {
glUniform1i(this->mfLights_Directional[j]->gl_InUse, 0);
}
for (size_t j = lightsCount_Point; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Point); j++) {
glUniform1i(this->mfLights_Point[j]->gl_InUse, 0);
}
for (size_t j = lightsCount_Spot; j < static_cast<size_t>(this->GLSL_LightSourceNumber_Spot); j++) {
glUniform1i(this->mfLights_Spot[j]->gl_InUse, 0);
}
// material
glUniform1f(this->glMaterial_Refraction, mfd->Setting_MaterialRefraction->point);
glUniform1f(this->glMaterial_SpecularExp, mfd->Setting_MaterialSpecularExp->point);
glUniform1i(this->glMaterial_IlluminationModel, static_cast<int>(mfd->materialIlluminationModel));
glUniform1f(this->glMaterial_HeightScale, mfd->displacementHeightScale->point);
glUniform3f(this->glMaterial_Ambient, mfd->materialAmbient->color.r, mfd->materialAmbient->color.g, mfd->materialAmbient->color.b);
glUniform3f(this->glMaterial_Diffuse, mfd->materialDiffuse->color.r, mfd->materialDiffuse->color.g, mfd->materialDiffuse->color.b);
glUniform3f(this->glMaterial_Specular, mfd->materialSpecular->color.r, mfd->materialSpecular->color.g, mfd->materialSpecular->color.b);
glUniform3f(this->glMaterial_Emission, mfd->materialEmission->color.r, mfd->materialEmission->color.g, mfd->materialEmission->color.b);
if (mfd->vboTextureAmbient > 0 && mfd->meshModel.ModelMaterial.TextureAmbient.UseTexture) {
glUniform1i(this->glMaterial_HasTextureAmbient, 1);
glUniform1i(this->glMaterial_SamplerAmbient, 0);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, mfd->vboTextureAmbient);
}
else
glUniform1i(this->glMaterial_HasTextureAmbient, 0);
if (mfd->vboTextureDiffuse > 0 && mfd->meshModel.ModelMaterial.TextureDiffuse.UseTexture) {
glUniform1i(this->glMaterial_HasTextureDiffuse, 1);
glUniform1i(this->glMaterial_SamplerDiffuse, 1);
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDiffuse);
}
else
glUniform1i(this->glMaterial_HasTextureDiffuse, 0);
if (mfd->vboTextureSpecular > 0 && mfd->meshModel.ModelMaterial.TextureSpecular.UseTexture) {
glUniform1i(this->glMaterial_HasTextureSpecular, 1);
glUniform1i(this->glMaterial_SamplerSpecular, 2);
glActiveTexture(GL_TEXTURE2);
glBindTexture(GL_TEXTURE_2D, mfd->vboTextureSpecular);
}
else
glUniform1i(this->glMaterial_HasTextureSpecular, 0);
if (mfd->vboTextureSpecularExp > 0 && mfd->meshModel.ModelMaterial.TextureSpecularExp.UseTexture) {
glUniform1i(this->glMaterial_HasTextureSpecularExp, 1);
glUniform1i(this->glMaterial_SamplerSpecularExp, 3);
glActiveTexture(GL_TEXTURE3);
glBindTexture(GL_TEXTURE_2D, mfd->vboTextureSpecularExp);
}
else
glUniform1i(this->glMaterial_HasTextureSpecularExp, 0);
if (mfd->vboTextureDissolve > 0 && mfd->meshModel.ModelMaterial.TextureDissolve.UseTexture) {
glUniform1i(this->glMaterial_HasTextureDissolve, 1);
glUniform1i(this->glMaterial_SamplerDissolve, 4);
glActiveTexture(GL_TEXTURE4);
glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDissolve);
}
else
glUniform1i(this->glMaterial_HasTextureDissolve, 0);
if (mfd->vboTextureBump > 0 && mfd->meshModel.ModelMaterial.TextureBump.UseTexture) {
glUniform1i(this->glMaterial_HasTextureBump, 1);
glUniform1i(this->glMaterial_SamplerBump, 5);
glActiveTexture(GL_TEXTURE5);
glBindTexture(GL_TEXTURE_2D, mfd->vboTextureBump);
}
else
glUniform1i(this->glMaterial_HasTextureBump, 0);
if (mfd->vboTextureDisplacement > 0 && mfd->meshModel.ModelMaterial.TextureDisplacement.UseTexture) {
glUniform1i(this->glMaterial_HasTextureDisplacement, 1);
glUniform1i(this->glMaterial_SamplerDisplacement, 6);
glActiveTexture(GL_TEXTURE6);
glBindTexture(GL_TEXTURE_2D, mfd->vboTextureDisplacement);
}
else
glUniform1i(this->glMaterial_HasTextureDisplacement, 0);
// effects - gaussian blur
glUniform1i(this->glEffect_GB_Mode, mfd->Effect_GBlur_Mode - 1);
glUniform1f(this->glEffect_GB_W, mfd->Effect_GBlur_Width->point);
glUniform1f(this->glEffect_GB_Radius, mfd->Effect_GBlur_Radius->point);
// effects - bloom
// TODO: Bloom effect
glUniform1i(this->glEffect_Bloom_doBloom, mfd->Effect_Bloom_doBloom);
glUniform1f(this->glEffect_Bloom_WeightA, mfd->Effect_Bloom_WeightA);
glUniform1f(this->glEffect_Bloom_WeightB, mfd->Effect_Bloom_WeightB);
glUniform1f(this->glEffect_Bloom_WeightC, mfd->Effect_Bloom_WeightC);
glUniform1f(this->glEffect_Bloom_WeightD, mfd->Effect_Bloom_WeightD);
glUniform1f(this->glEffect_Bloom_Vignette, mfd->Effect_Bloom_Vignette);
glUniform1f(this->glEffect_Bloom_VignetteAtt, mfd->Effect_Bloom_VignetteAtt);
// effects - tone mapping
glUniform1i(this->glEffect_ToneMapping_ACESFilmRec2020, mfd->Effect_ToneMapping_ACESFilmRec2020);
glUniform1f(this->glVS_IsBorder, 0.0);
// model draw
glUniform1f(this->glVS_IsBorder, 0.0);
glm::mat4 mtxModel = glm::scale(matrixModel, glm::vec3(1.0, 1.0, 1.0));
glm::mat4 mvpMatrixDraw = this->matrixProjection * this->matrixCamera * mtxModel;
glUniformMatrix4fv(this->glVS_MVPMatrix, 1, GL_FALSE, glm::value_ptr(mvpMatrixDraw));
glUniformMatrix4fv(this->glFS_MMatrix, 1, GL_FALSE, glm::value_ptr(mtxModel));
mfd->vertexSphereVisible = this->managerObjects.Setting_VertexSphere_Visible;
mfd->vertexSphereRadius = this->managerObjects.Setting_VertexSphere_Radius;
mfd->vertexSphereSegments = this->managerObjects.Setting_VertexSphere_Segments;
mfd->vertexSphereColor = this->managerObjects.Setting_VertexSphere_Color;
mfd->vertexSphereIsSphere = this->managerObjects.Setting_VertexSphere_IsSphere;
mfd->vertexSphereShowWireframes = this->managerObjects.Setting_VertexSphere_ShowWireframes;
mfd->renderModel(true);
}
glUseProgram(0);
}
| 57.027182
| 251
| 0.736365
|
supudo
|
6217a1836b7e95e4c902fa7d2642aa70a2c8edc7
| 4,122
|
cpp
|
C++
|
src/legecy/stereo_block_matching.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
src/legecy/stereo_block_matching.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
src/legecy/stereo_block_matching.cpp
|
behnamasadi/OpenCVProjects
|
157c8d536c78c5660b64a23300a7aaf941584756
|
[
"BSD-3-Clause"
] | null | null | null |
#include <opencv2/opencv.hpp>
const char *windowDisparity = "Disparity";
cv::Mat imgLeft;
cv::Mat imgRight;
cv::Mat imgDisparity16S;
cv::Mat imgDisparity8U;
int ndisparities= 16*5;
int SADWindowSize= 21;
double minVal; double maxVal;
cv::StereoBM sbm( cv::StereoBM::NARROW_PRESET,ndisparities,SADWindowSize );
void on_trackbar( int, void* )
{
std::cout <<"ndisparities: " <<16*ndisparities <<std::endl;
std::cout <<"SADWindowSize: " <<SADWindowSize <<std::endl;
if(SADWindowSize%2 !=0 && SADWindowSize>4)
{
sbm.init(cv::StereoBM::NARROW_PRESET,16*ndisparities ,SADWindowSize);
sbm( imgLeft, imgRight, imgDisparity16S, CV_16S );
minMaxLoc( imgDisparity16S, &minVal, &maxVal );
imgDisparity16S.convertTo( imgDisparity8U, CV_8UC1, 255/(maxVal - minVal));
cv::namedWindow( windowDisparity, cv::WINDOW_NORMAL );
cv::imshow( windowDisparity, imgDisparity8U );
}
}
//For an in-depth discussion of the block matching algorithm, see pages 438-444 of Learning OpenCV.
//https://github.com/opencv/opencv/blob/2.4/samples/cpp/tutorial_code/calib3d/stereoBM/SBM_Sample.cpp
int disparity_map_using_sbm_example(int argc, char ** argv)
{
//char* n_argv[] = { "stereo_block_matching", "../images/stereo_vision/tsucuba_left.png", "../images/stereo_vision/tsucuba_right.png"};
char* n_argv[] = { "stereo_block_matching", "rect_left01.jpg", "rect_right01.jpg"};
int length = sizeof(n_argv)/sizeof(n_argv[0]);
argc=length;
argv = n_argv;
imgLeft = cv::imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
imgRight = cv::imread( argv[2], CV_LOAD_IMAGE_GRAYSCALE );
//-- And create the image in which we will save our disparities
imgDisparity16S = cv::Mat( imgLeft.rows, imgLeft.cols, CV_16S );
imgDisparity8U = cv::Mat( imgLeft.rows, imgLeft.cols, CV_8UC1 );
//-- 2. Call the constructor for StereoBM
//ndisparities must be multiple of 8
//-- 3. Calculate the disparity image
sbm( imgLeft, imgRight, imgDisparity16S, CV_16S );
//-- Check its extreme values
minMaxLoc( imgDisparity16S, &minVal, &maxVal );
printf("Min disp: %f Max value: %f \n", minVal, maxVal);
//-- 4. Display it as a CV_8UC1 image
imgDisparity16S.convertTo( imgDisparity8U, CV_8UC1, 255/(maxVal - minVal));
cv::namedWindow( windowDisparity, cv::WINDOW_NORMAL );
cv::imshow( windowDisparity, imgDisparity8U );
//Create trackbars in "Control" window
ndisparities=ndisparities/16;
cv::createTrackbar("ndisparities (multipled by 16)", windowDisparity, &ndisparities, 20,on_trackbar); //ndisparities (0 - 20)
cv::createTrackbar("SADWindowSize (must be odd, be within 5..255) ", windowDisparity, &SADWindowSize, 255,on_trackbar); //SADWindowSize(0 - 100)
//-- 5. Save the image
//imwrite("SBM_sample.png", imgDisparity16S);
// cv::reprojectImageTo3D(imgDisparity8U,)
cv::waitKey(0);
return 0;
}
void disparity_map_using_sgbm_example(int argc, char ** argv)
{
char* n_argv[] = { "stereo_block_matching", "../images/stereo_vision/tsucuba_left.png", "../images/stereo_vision/tsucuba_right.png"};
int length = sizeof(n_argv)/sizeof(n_argv[0]);
argc=length;
argv = n_argv;
cv::Mat img1, img2, g1, g2;
cv::Mat disp, disp8;
img1 = cv::imread(argv[1]);
img2 = cv::imread(argv[2]);
cv::cvtColor(img1, g1, CV_BGR2GRAY);
cv::cvtColor(img2, g2, CV_BGR2GRAY);
cv::StereoSGBM sbm;
sbm.SADWindowSize = 3;
sbm.numberOfDisparities = 144;
sbm.preFilterCap = 63;
sbm.minDisparity = -39;
sbm.uniquenessRatio = 10;
sbm.speckleWindowSize = 100;
sbm.speckleRange = 32;
sbm.disp12MaxDiff = 1;
sbm.fullDP = false;
sbm.P1 = 216;
sbm.P2 = 864;
sbm(g1, g2, disp);
normalize(disp, disp8, 0, 255, CV_MINMAX, CV_8U);
imshow("left", img1);
imshow("right", img2);
imshow("disp", disp8);
cv::waitKey(0);
// cv::finds
}
int main(int argc, char** argv)
{
// disparity_map_using_sgbm_example(argc, argv);
disparity_map_using_sbm_example(argc, argv);
}
| 25.288344
| 148
| 0.673459
|
behnamasadi
|
6218b5bec030cb10643d1c699b703620e70da83f
| 950
|
cpp
|
C++
|
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | 1
|
2019-05-01T04:51:14.000Z
|
2019-05-01T04:51:14.000Z
|
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | null | null | null |
42dynamicProgrammingPractice/dynamicPragrammingPractice/dynamicPragrammingPractice/main.cpp
|
mingyuefly/geekTimeCode
|
d97c5f29a429ac9cc7289ac34e049ea43fa58822
|
[
"MIT"
] | null | null | null |
//
// main.cpp
// dynamicPragrammingPractice
//
// Created by Gguomingyue on 2019/2/20.
// Copyright © 2019 Gmingyue. All rights reserved.
//
#include <iostream>
using namespace std;
static char a[6] = {'m', 'i', 't', 'c', 'm', 'u'};
static char b[6] = {'m', 't', 'a', 'c', 'n', 'u'};
static int n = 6;
static int m = 6;
static int minDist = 100;
void lowestLD(int i, int j, int edist) {
if (i == n || j == m) {
if (i < n) {
edist += (n - i);
}
if (j < m) {
edist += (m - j);
}
if (edist < minDist) {
minDist = edist;
}
return;
}
if (a[i] == b[j]) {
lowestLD(i+1, j+1, edist);
} else {
lowestLD(i+1, j, edist+1);
lowestLD(i, j+1, edist+1);
lowestLD(i+1, j+1, edist+1);
}
}
int main(int argc, const char * argv[]) {
lowestLD(0, 0, 0);
cout << minDist << endl;
return 0;
}
| 19.791667
| 51
| 0.458947
|
mingyuefly
|
6223b18bd74bb8dd8120c7c358f1f1422a950de1
| 4,420
|
hpp
|
C++
|
include/System/IO/FileInfo.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/System/IO/FileInfo.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
include/System/IO/FileInfo.hpp
|
darknight1050/BeatSaber-Quest-Codegen
|
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
|
[
"Unlicense"
] | null | null | null |
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.IO.FileSystemInfo
#include "System/IO/FileSystemInfo.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System::IO
namespace System::IO {
// Forward declaring type: StreamWriter
class StreamWriter;
}
// Forward declaring namespace: System::Runtime::Serialization
namespace System::Runtime::Serialization {
// Forward declaring type: SerializationInfo
class SerializationInfo;
}
// Completed forward declares
// Type namespace: System.IO
namespace System::IO {
// Size: 0x68
#pragma pack(push, 1)
// Autogenerated type: System.IO.FileInfo
// [ComVisibleAttribute] Offset: D7C894
class FileInfo : public System::IO::FileSystemInfo {
public:
// private System.String _name
// Size: 0x8
// Offset: 0x60
::Il2CppString* name;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// Creating value type constructor for type: FileInfo
FileInfo(::Il2CppString* name_ = {}) noexcept : name{name_} {}
// public System.Void .ctor(System.String fileName)
// Offset: 0x1933E44
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static FileInfo* New_ctor(::Il2CppString* fileName) {
static auto ___internal__logger = ::Logger::get().WithContext("System::IO::FileInfo::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<FileInfo*, creationType>(fileName)));
}
// private System.Void Init(System.String fileName, System.Boolean checkHost)
// Offset: 0x1933EE4
void Init(::Il2CppString* fileName, bool checkHost);
// private System.String GetDisplayPath(System.String originalPath)
// Offset: 0x1933FD4
::Il2CppString* GetDisplayPath(::Il2CppString* originalPath);
// public System.String get_DirectoryName()
// Offset: 0x1934070
::Il2CppString* get_DirectoryName();
// public System.IO.StreamWriter CreateText()
// Offset: 0x19340D8
System::IO::StreamWriter* CreateText();
// public System.IO.StreamWriter AppendText()
// Offset: 0x1934140
System::IO::StreamWriter* AppendText();
// private System.Void .ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
// Offset: 0x1933FDC
// Implemented from: System.IO.FileSystemInfo
// Base method: System.Void FileSystemInfo::.ctor(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static FileInfo* New_ctor(System::Runtime::Serialization::SerializationInfo* info, System::Runtime::Serialization::StreamingContext context) {
static auto ___internal__logger = ::Logger::get().WithContext("System::IO::FileInfo::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<FileInfo*, creationType>(info, context)));
}
// public override System.String get_Name()
// Offset: 0x1934068
// Implemented from: System.IO.FileSystemInfo
// Base method: System.String FileSystemInfo::get_Name()
::Il2CppString* get_Name();
// public override System.Boolean get_Exists()
// Offset: 0x19341A8
// Implemented from: System.IO.FileSystemInfo
// Base method: System.Boolean FileSystemInfo::get_Exists()
bool get_Exists();
// public override System.String ToString()
// Offset: 0x193429C
// Implemented from: System.Object
// Base method: System.String Object::ToString()
::Il2CppString* ToString();
}; // System.IO.FileInfo
#pragma pack(pop)
static check_size<sizeof(FileInfo), 96 + sizeof(::Il2CppString*)> __System_IO_FileInfoSizeCheck;
static_assert(sizeof(FileInfo) == 0x68);
}
DEFINE_IL2CPP_ARG_TYPE(System::IO::FileInfo*, "System.IO", "FileInfo");
| 47.021277
| 162
| 0.703846
|
darknight1050
|
62337383665e6d6b0264360ab9ed7e191ee04b7a
| 168
|
hpp
|
C++
|
src/main.hpp
|
ziggi/rustext
|
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
|
[
"MIT"
] | 20
|
2016-09-19T20:37:36.000Z
|
2022-02-26T14:16:28.000Z
|
src/main.hpp
|
ziggi/rustext
|
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
|
[
"MIT"
] | 6
|
2016-12-27T16:49:01.000Z
|
2020-11-22T16:50:29.000Z
|
src/main.hpp
|
ziggi/rustext
|
5dcfe9f07f9a13b4f2979f98663a68c2ac62e163
|
[
"MIT"
] | 1
|
2019-02-21T08:10:43.000Z
|
2019-02-21T08:10:43.000Z
|
/*
About: rustext main
Author: ziggi
*/
#ifndef MAIN_H
#define MAIN_H
#include <map>
#include "common.hpp"
#include "converter.hpp"
logprintf_t logprintf;
#endif
| 10.5
| 24
| 0.720238
|
ziggi
|
62360aef9279d488b4ee2c24e9591aedb0cd169d
| 834
|
cpp
|
C++
|
src/actions/move_by_action.cpp
|
tomalbrc/rawket-engine
|
2b7da4f33c874154120fc2d1529081f4f4ae33c7
|
[
"MIT"
] | null | null | null |
src/actions/move_by_action.cpp
|
tomalbrc/rawket-engine
|
2b7da4f33c874154120fc2d1529081f4f4ae33c7
|
[
"MIT"
] | 1
|
2016-03-18T13:54:22.000Z
|
2016-08-11T22:02:28.000Z
|
src/actions/move_by_action.cpp
|
tomalbrc/FayEngine
|
2b7da4f33c874154120fc2d1529081f4f4ae33c7
|
[
"MIT"
] | null | null | null |
//
// move_by_action.cpp
// rawket
//
// Created by Tom Albrecht on 09.12.15.
//
//
#include "move_by_action.hpp"
RKT_NAMESPACE_BEGIN
move_by_action_ptr move_by_action::create(double pduration, vec2f offset) {
move_by_action_ptr p(new move_by_action());
p->init(pduration, offset);
return p;
}
bool move_by_action::init(double pduration, vec2f offset) {
changeInVec2Value = offset;
duration = pduration*1000;
return true;
}
void move_by_action::update() {
auto popos = currentVec2Value();
target->setPosition(popos);
if (SDL_GetTicks()-startTick > duration) finished = true, target->setPosition(changeInVec2Value+startVec2Value);
}
void move_by_action::start() {
startTick = SDL_GetTicks();
startVec2Value = target->getPosition();
finished = false;
}
RKT_NAMESPACE_END
| 19.857143
| 116
| 0.707434
|
tomalbrc
|
623939f0120a593b016902b94a91af7d88e57e7c
| 8,257
|
cpp
|
C++
|
src/Equations/Fluid/HottailRateTermHighZ.cpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 12
|
2020-09-07T11:19:10.000Z
|
2022-02-17T17:40:19.000Z
|
src/Equations/Fluid/HottailRateTermHighZ.cpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 110
|
2020-09-02T15:29:24.000Z
|
2022-03-09T09:50:01.000Z
|
src/Equations/Fluid/HottailRateTermHighZ.cpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 3
|
2021-05-21T13:24:31.000Z
|
2022-02-11T14:43:12.000Z
|
/**
* Implementation of equation term representing the runaway generation rate
* due to hottail when using an analytic distribution function
*/
#include "DREAM/Equations/Fluid/HottailRateTermHighZ.hpp"
using namespace DREAM;
/**
* Constructor.
*
* gsl_altPc* contains parameters and functions needed
* to evaluate the critical runaway momentum in the hottail
* calculation using a gsl root-finding algorithm
* (using the 'alternative' model for pc in Ida's MSc thesis)
*/
HottailRateTermHighZ::HottailRateTermHighZ(
FVM::Grid *grid, AnalyticDistributionHottail *dist, FVM::UnknownQuantityHandler *unknowns,
IonHandler *ionHandler, CoulombLogarithm *lnL, real_t sf
) : HottailRateTerm(grid, dist, unknowns,sf), lnL(lnL),
id_ncold(unknowns->GetUnknownID(OptionConstants::UQTY_N_COLD)),
id_Efield(unknowns->GetUnknownID(OptionConstants::UQTY_E_FIELD)),
id_tau(unknowns->GetUnknownID(OptionConstants::UQTY_TAU_COLL))
{
SetName("HottailRateTermHighZ");
AddUnknownForJacobian(unknowns,id_Efield);
AddUnknownForJacobian(unknowns,id_ncold);
AddUnknownForJacobian(unknowns,id_tau);
//AddUnknownForJacobian(unknowns,id_ni); // Zeff and lnL (nfree) jacobian
//AddUnknownForJacobian(unknowns,id_Tcold); // lnL jacobian
this->fdfsolver = gsl_root_fdfsolver_alloc(gsl_root_fdfsolver_secant);
gsl_params.ionHandler = ionHandler;
gsl_params.rGrid = grid->GetRadialGrid();
gsl_params.dist = dist;
gsl_func.f = &(PcFunc);
gsl_func.df = &(PcFunc_df);
gsl_func.fdf = &(PcFunc_fdf);
gsl_func.params = &gsl_params;
this->GridRebuilt();
}
/**
* Destructor
*/
HottailRateTermHighZ::~HottailRateTermHighZ(){
Deallocate();
gsl_root_fdfsolver_free(fdfsolver);
}
/**
* Called after the grid is rebuilt; (re)allocates memory
* for all quantities
*/
bool HottailRateTermHighZ::GridRebuilt(){
this->HottailRateTerm::GridRebuilt();
Deallocate();
pCrit_prev = new real_t[nr];
return true;
}
/**
* Rebuilds quantities used by this equation term.
* Note that the equation term uses the _energy distribution_
* from AnalyticDistributionHottail which differs from the
* full distribution function by a factor of 4*pi
*/
void HottailRateTermHighZ::Rebuild(const real_t t, const real_t dt, FVM::UnknownQuantityHandler*) {
this->dt = dt;
bool newTimeStep = (t!=tPrev);
if(newTimeStep)
tPrev = t;
for(len_t ir=0; ir<nr; ir++){
if(newTimeStep)
pCrit_prev[ir] = pCrit[ir];
real_t fAtPc, dfdpAtPc;
pCrit[ir] = evaluateCriticalMomentum(ir, fAtPc, dfdpAtPc);
real_t dotPc = (pCrit[ir] - pCrit_prev[ir]) / dt;
if (dotPc > 0) // ensure non-negative runaway rate
dotPc = 0;
gamma[ir] = -pCrit[ir]*pCrit[ir]*dotPc*fAtPc; // generation rate
// set derivative of gamma with respect to pCrit (used for jacobian)
dGammaDPc[ir] = -(2*pCrit[ir]*dotPc*fAtPc + pCrit[ir]*pCrit[ir]*fAtPc/dt + pCrit[ir]*pCrit[ir]*dotPc*dfdpAtPc);
}
}
/**
* Function whose root (with respect to p) represents the
* critical runaway momentum in the 'alternative' model
*/
real_t HottailRateTermHighZ::PcFunc(real_t p, void *par) {
if(p<0) // handle case where algorithm leaves the physical domain of non-negative momenta
p=0;
PcParams *params = (PcParams*)par;
len_t ir = params->ir;
real_t Eterm = params->Eterm;
real_t ncold = params->ncold;
real_t tau = params->tau;
real_t lnL = params->lnL;
real_t dFdpOverF;
params->F = params->dist->evaluateEnergyDistributionFromTau(ir,p,tau,¶ms->dFdp,nullptr, &dFdpOverF);
real_t Ec = 4*M_PI*ncold*lnL*Constants::r0*Constants::r0*Constants::c * Constants::me * Constants::c / Constants::ec;
real_t E = Eterm/Ec;
real_t EPF = params->rGrid->GetEffPassFrac(ir);
real_t Zeff = params->ionHandler->GetZeff(ir);
real_t p2 = p*p;
real_t gamma = sqrt(1+p2);
// for the non-relativistic distribution, this function is
// approximately linear, yielding efficient root finding
return sqrt((p/gamma)*cbrt( p2*E*E*EPF * (-dFdpOverF) )) - sqrt(cbrt( 3*(1+Zeff)));
// previous equivalent expression:
// real_t g3 = (1+p2)*gamma;
// return sqrt(cbrt( p2*p2*p*E*E*EPF * (-dFdpOverF) )) - sqrt(cbrt( 3.0*(1+Zeff)*g3));
}
/**
* Returns the derivative of PcFunc with respect to p
*/
real_t HottailRateTermHighZ::PcFunc_df(real_t p, void *par) {
real_t h = 1e-3*p;
return (PcFunc(p+h,par) - PcFunc(p,par)) / h;
}
/**
* Method which sets both f=PcFunc and df=PcFunc_df
*/
void HottailRateTermHighZ::PcFunc_fdf(real_t p, void *par, real_t *f, real_t *df){
real_t h = 1e-3*p;
*f = PcFunc(p,par);
*df = (PcFunc(p+h, par) - *f) / h;
}
/**
* Evaluates the 'alternative' critical momentum pc using Ida's MSc thesis (4.35)
*/
real_t HottailRateTermHighZ::evaluateCriticalMomentum(len_t ir, real_t &f, real_t &dfdp){
gsl_params.ir = ir;
gsl_params.lnL = lnL->evaluateAtP(ir,0);
gsl_params.ncold = unknowns->GetUnknownData(id_ncold)[ir];
gsl_params.Eterm = unknowns->GetUnknownData(id_Efield)[ir];
gsl_params.tau = unknowns->GetUnknownData(id_tau)[ir];
real_t root = (pCrit_prev[ir] == 0) ? 5*distHT->GetInitialThermalMomentum(ir) : pCrit_prev[ir];
RunawayFluid::FindRoot_fdf_bounded(0,std::numeric_limits<real_t>::infinity(),root, gsl_func, fdfsolver, RELTOL_FOR_PC, ABSTOL_FOR_PC);
f = gsl_params.F;
dfdp = gsl_params.dFdp;
return root;
}
/**
* Evaluates the jacobian of CriticalMomentum with
* respect to the unknown with id 'derivId'
*/
real_t HottailRateTermHighZ::evaluatePartialCriticalMomentum(len_t ir, len_t derivId){
gsl_params.ir = ir;
gsl_params.lnL = lnL->evaluateAtP(ir,0);
gsl_params.ncold = unknowns->GetUnknownData(id_ncold)[ir];
gsl_params.Eterm = unknowns->GetUnknownData(id_Efield)[ir];
gsl_params.tau = unknowns->GetUnknownData(id_tau)[ir];
real_t h = 0;
if(derivId == id_Efield){
h = (1.0+fabs(gsl_params.Eterm))*sqrt(RELTOL_FOR_PC),
gsl_params.Eterm += h;
} else if (derivId == id_ncold){
h = (1.0+fabs(gsl_params.ncold))*sqrt(RELTOL_FOR_PC),
gsl_params.ncold += h;
} else if (derivId == id_tau){
h = (1.0+fabs(gsl_params.tau))*sqrt(RELTOL_FOR_PC),
gsl_params.tau += h;
}
real_t root = pCrit[ir];
RunawayFluid::FindRoot_fdf_bounded(0,std::numeric_limits<real_t>::infinity(),root, gsl_func, fdfsolver, RELTOL_FOR_PC, ABSTOL_FOR_PC);
return (root - pCrit[ir])/h;
}
/**
* Sets the Jacobian of this equation term
*/
bool HottailRateTermHighZ::SetJacobianBlock(const len_t /*uqtyId*/, const len_t derivId, FVM::Matrix *jac, const real_t*){
if(!HasJacobianContribution(derivId))
return false;
for(len_t ir=0; ir<nr; ir++){
const len_t xiIndex = this->GetXiIndexForEDirection(ir);
const len_t np1 = this->grid->GetMomentumGrid(ir)->GetNp1();
real_t V = GetVolumeScaleFactor(ir);
// Check if the quantity w.r.t. which we differentiate is a
// fluid quantity, in which case it has np1=1, xiIndex=0
len_t np1_op = np1, xiIndex_op = xiIndex;
if (unknowns->GetUnknown(derivId)->NumberOfElements() == nr) {
np1_op = 1;
xiIndex_op = 0;
}
real_t dPc = evaluatePartialCriticalMomentum(ir, derivId);
real_t dGamma = dPc * dGammaDPc[ir];
if(derivId==id_tau){ // add contribution from explicit tau dependence in f
real_t dotPc = (pCrit[ir] - pCrit_prev[ir]) / dt;
if (dotPc > 0) // ensure non-negative runaway rate
dotPc = 0;
real_t tau = unknowns->GetUnknownData(id_tau)[ir];
real_t dFdTauAtPc;
distHT->evaluateEnergyDistributionFromTau(ir, pCrit[ir], tau, nullptr, nullptr, nullptr, &dFdTauAtPc);
dGamma -= pCrit[ir]*pCrit[ir]*dotPc*dFdTauAtPc;
}
jac->SetElement(ir + np1*xiIndex, ir + np1_op*xiIndex_op, scaleFactor * dGamma * V);
}
return true;
}
/**
* Deallocator
*/
void HottailRateTermHighZ::Deallocate(){
if(pCrit_prev != nullptr)
delete [] pCrit_prev;
}
| 34.987288
| 138
| 0.669977
|
chalmersplasmatheory
|
623a159d3ca2db1b550deccf4256c78327c053ba
| 3,197
|
hpp
|
C++
|
Examples/ProgAnalysis/Cfg.hpp
|
jusito/WALi-OpenNWA
|
2bb4aca02c5a5d444fd038e8aa3eecd7d1ccbb99
|
[
"MIT"
] | 15
|
2015-03-07T17:25:57.000Z
|
2022-02-04T20:17:00.000Z
|
src/wpds/Examples/ProgAnalysis/Cfg.hpp
|
ucd-plse/mpi-error-prop
|
4367df88bcdc4d82c9a65b181d0e639d04962503
|
[
"BSD-3-Clause"
] | 1
|
2018-03-03T05:58:55.000Z
|
2018-03-03T12:26:10.000Z
|
src/wpds/Examples/ProgAnalysis/Cfg.hpp
|
ucd-plse/mpi-error-prop
|
4367df88bcdc4d82c9a65b181d0e639d04962503
|
[
"BSD-3-Clause"
] | 15
|
2015-09-25T17:44:35.000Z
|
2021-07-18T18:25:38.000Z
|
#ifndef _WALI_CFG_HPP_
#define _WALI_CFG_HPP_
/*
* @author Akash Lal
*/
/*
* This file includes an abstract class for a Control Flow Graph (CFG). A CFG is represented
* as a graph over CFGNodes and CFGEdges.
*
* This abstract class is meant to provide just enough interface to be able to
* construct a WPDS.
*/
#include "wali/Key.hpp"
#include "wali/SemElem.hpp"
#include "wali/MergeFn.hpp"
#include <set>
class CFGNode;
class CFGEdge;
class CFG;
// Abstract class denoting a CFG node
class CFGNode {
public:
// Return a unique identifier for the CFG node
virtual int getId() const = 0;
// Return a WPDS key that is unique for the CFG node. A sample
// implementation for this method is provided using the getId
// method. However, wali provides several ways of obtaining keys:
// see [... NAK?]
virtual wali::Key getWpdsKey() const {
return wali::getKey(getId());
/* To use a priority-based key (see TODO) one can use the following code:
* return wali::getKey( wali::getKey(getPriorityNumber()), wali::getKey(getId()) );
*
* This assume the presence of a function "int CFGNode::getPriorityNumber()" that
* returns a (possibily non-unique) priority for the CFGNode.
*/
}
// Return the set of outgoing edges
//std::set<CFGEdge *> getOutgoingEdges() = 0;
virtual ~CFGNode() {}
};
// Abstract class denoting a CFG edge
class CFGEdge {
// The source and target nodes of the edge
CFGNode *src, *tgt;
// If this edge is a call edge, then callee is the called
// procedure. For simplicity, we assume that a call edge
// has only one callee. (The presence of multiple callees
// do not pose any challenge specific to WPDSs.)
CFG* callee;
public:
// Return the source node of the edge
CFGNode *getSource() const {
return src;
}
// Return the target node of the edge
CFGNode *getTarget() const {
return tgt;
}
// Is this edge a call edge?
virtual bool isCall() const = 0;
// Get callee, if this is a call edge
CFG *getCallee() const {
if(!isCall()) return 0;
return callee;
}
// Return the weight (or abstract transformer) associated
// with the CFG edge. The convention for call edges is that
// this function should provide the transformer associated with
// just the call instruction, not the called procedure.
virtual wali::sem_elem_t getWeight() const = 0;
// Return the merge function associated with the edge. This is only
// invoked for call edges.
virtual wali::merge_fn_t getMergeFn() const = 0;
virtual ~CFGEdge() {}
};
// Abstract class for denoting a CFG. We assume that a CFG has a
// unique entry node (that has no predecessors) and a unique exit
// node (that has no successors).
class CFG {
// Entry and exit nodes of the CFG
CFGNode *entryNode, *exitNode;
public:
// Return the entry node of the CFG
CFGNode *getEntry() const {
return entryNode;
}
// Return the exit node of the CFG
CFGNode *getExit() const {
return exitNode;
}
// Return the set of all CFG edges contained in this CFG
virtual const std::set<CFGEdge *> & getEdges() const = 0;
virtual ~CFG() {}
};
#endif // _WALI_CFG_HPP_
| 25.373016
| 92
| 0.684079
|
jusito
|
623bfc1dbecdd6ebf1bfdefa4e2bb2b501853294
| 2,740
|
cpp
|
C++
|
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
|
timdecode/LifeBrush
|
dbc65bcc0ec77f9168e08cf7b39539af94420725
|
[
"MIT"
] | 33
|
2019-04-23T23:00:09.000Z
|
2021-11-09T11:44:09.000Z
|
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
|
MyelinsheathXD/LifeBrush
|
dbc65bcc0ec77f9168e08cf7b39539af94420725
|
[
"MIT"
] | 1
|
2019-10-09T15:57:56.000Z
|
2020-03-05T20:01:01.000Z
|
LifeBrush/Source/LifeBrush/Simulation/Brownian.cpp
|
MyelinsheathXD/LifeBrush
|
dbc65bcc0ec77f9168e08cf7b39539af94420725
|
[
"MIT"
] | 6
|
2019-04-25T00:10:55.000Z
|
2021-04-12T05:16:28.000Z
|
// Copyright (c) 2019 Timothy Davison. All rights reserved.
#include "LifeBrush.h"
#include "Simulation/FlexElements.h"
#include "Brownian.h"
void USingleParticleBrownianSimulation::attach()
{
rand.GenerateNewSeed();
}
void USingleParticleBrownianSimulation::detach()
{
}
void USingleParticleBrownianSimulation::tick(float deltaT)
{
auto& browns = graph->componentStorage<FSingleParticleBrownian>();
auto& velocities = graph->componentStorage<FVelocityGraphObject>();
// make sure we have velocities
for (FSingleParticleBrownian& brown : browns)
{
if( !brown.isValid() ) continue;
if (!velocities.componentPtrForNode(brown.nodeHandle()))
{
FGraphNode& node = graph->node(brown.nodeHandle());
node.addComponent<FVelocityGraphObject>(*graph);
}
}
for (FSingleParticleBrownian& brown : browns)
{
if( !brown.isValid() ) continue;
brown.time -= deltaT;
if (brown.time > 0.0f)
continue;
brown.time = rand.FRandRange(minTime, maxTime);
float scale = FMath::Clamp(1.0f - brown.dampening, 0.0f, 1.0f);
FVector dv = scale * rand.GetUnitVector() * rand.FRandRange(minSpeed, maxSpeed);
if (auto velocity = velocities.componentPtrForNode(brown.nodeHandle()))
{
velocity->linearVelocity = (velocity->linearVelocity + dv).GetClampedToMaxSize(15.0f);
}
}
}
void UGlobalParticleBrownianSimulation::attach()
{
rand.GenerateNewSeed();
}
void UGlobalParticleBrownianSimulation::detach()
{
}
void UGlobalParticleBrownianSimulation::tick(float deltaT)
{
if (!enabled) return;
auto& particles = graph->componentStorage<FFlexParticleObject>();
auto& velocities = graph->componentStorage<FVelocityGraphObject>();
for (FFlexParticleObject& particle : particles)
{
if (!particle.isValid()) continue;
if (!velocities.componentPtrForNode(particle.nodeHandle()))
{
FGraphNode& node = graph->node(particle.nodeHandle());
node.addComponent<FVelocityGraphObject>(*graph);
}
}
// find _times Num
int32 timeSize = 0;
for (FFlexParticleObject& particle : particles)
{
if (!particle.isValid()) continue;
int32 timeIndex = particle.nodeHandle().index;
if (timeIndex > timeSize)
timeSize = timeIndex;
}
_times.SetNum(timeSize + 1);
// make sure we have velocities
for (FFlexParticleObject& particle : particles)
{
if (!particle.isValid()) continue;
int32 timeIndex = particle.nodeHandle().index;
float& timeLeft = _times[timeIndex];
timeLeft -= deltaT;
if (timeLeft > 0.0f)
continue;
timeLeft = rand.FRandRange(minTime, maxTime);
FVelocityGraphObject * velocity = velocities.componentPtrForNode(particle.nodeHandle());
FVector dv = rand.GetUnitVector() * rand.FRandRange(minSpeed, maxSpeed);
velocity->linearVelocity += dv;
}
}
| 21.574803
| 90
| 0.724453
|
timdecode
|
623c158b82f5ffc0d0db2e2fb7c1f16ace9c978f
| 2,652
|
cpp
|
C++
|
src/Camera2D.cpp
|
jasonwnorris/SuperAwesomeGameEngine
|
908adf2099898b2c2028a8c8e8887f1d53be181f
|
[
"MIT"
] | 1
|
2016-05-21T12:45:20.000Z
|
2016-05-21T12:45:20.000Z
|
src/Camera2D.cpp
|
jasonwnorris/SuperAwesomeGameEngine
|
908adf2099898b2c2028a8c8e8887f1d53be181f
|
[
"MIT"
] | null | null | null |
src/Camera2D.cpp
|
jasonwnorris/SuperAwesomeGameEngine
|
908adf2099898b2c2028a8c8e8887f1d53be181f
|
[
"MIT"
] | null | null | null |
// Camera2D.cpp
// SAGE Includes
#include <SAGE/Camera2D.hpp>
namespace SAGE
{
const Camera2D Camera2D::DefaultCamera;
int Camera2D::DefaultWidth = 1280;
int Camera2D::DefaultHeight = 720;
Camera2D::Camera2D()
{
m_Position = Vector2::Zero;
m_Rotation = 0.0f;
m_Scale = Vector2::One;
m_Width = DefaultWidth;
m_Height = DefaultHeight;
}
Camera2D::~Camera2D()
{
}
Vector2 Camera2D::GetPosition() const
{
return m_Position;
}
float Camera2D::GetRotation() const
{
return m_Rotation;
}
Vector2 Camera2D::GetScale() const
{
return m_Scale;
}
int Camera2D::GetWidth() const
{
return m_Width;
}
int Camera2D::GetHeight() const
{
return m_Height;
}
glm::mat4 Camera2D::GetProjectionMatrix(View p_View) const
{
switch (p_View)
{
default:
case View::Orthographic:
return glm::ortho(0.0f, (float)m_Width, (float)m_Height, 0.0f, 1.0f, -1.0f);
case View::Perspective:
return glm::perspective(45.0f, (float)m_Width / (float)m_Height, 0.1f, 1000.0f);
}
}
glm::mat4 Camera2D::GetModelViewMatrix() const
{
glm::mat4 modelViewMatrix;
modelViewMatrix = glm::translate(modelViewMatrix, glm::vec3((float)m_Width / 2.0f, (float)m_Height / 2.0f, 0.0f));
modelViewMatrix = glm::scale(modelViewMatrix, glm::vec3(m_Scale.X, m_Scale.Y, 1.0f));
modelViewMatrix = glm::rotate(modelViewMatrix, m_Rotation, glm::vec3(0.0f, 0.0f, 1.0f));
modelViewMatrix = glm::translate(modelViewMatrix, glm::vec3(-m_Position.X, -m_Position.Y, 0.0f));
return modelViewMatrix;
}
void Camera2D::SetPosition(const Vector2& p_Position)
{
m_Position = p_Position;
}
void Camera2D::SetRotation(float p_Rotation)
{
m_Rotation = p_Rotation;
}
void Camera2D::SetScale(const Vector2& p_Scale)
{
m_Scale = p_Scale;
}
void Camera2D::SetTransformation(const Vector2& p_Position, float p_Rotation, const Vector2& p_Scale)
{
m_Position = p_Position;
m_Rotation = p_Rotation;
m_Scale = p_Scale;
}
void Camera2D::SetWidth(int p_Width)
{
m_Width = p_Width;
}
void Camera2D::SetHeight(int p_Height)
{
m_Height = p_Height;
}
void Camera2D::SetDimensions(int p_Width, int p_Height)
{
m_Width = p_Width;
m_Height = p_Height;
}
void Camera2D::Translate(const Vector2& p_Translation)
{
m_Position += p_Translation;
}
void Camera2D::Rotate(float p_Rotation)
{
m_Rotation += p_Rotation;
}
void Camera2D::Scale(const Vector2& p_Scale)
{
m_Scale += p_Scale;
}
void Camera2D::ScreenToWorld(const Vector2& p_ScreenPosition, Vector2& p_WorldPosition) const
{
}
void Camera2D::WorldToScreen(const Vector2& p_WorldPosition, Vector2& p_ScreenPosition) const
{
}
}
| 19.791045
| 116
| 0.707391
|
jasonwnorris
|
9a8b7cab21f5563369369e89adf76a80a30f01c3
| 5,975
|
cpp
|
C++
|
opengl/texture.cpp
|
yRezaei/cpp-utils
|
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
|
[
"MIT"
] | null | null | null |
opengl/texture.cpp
|
yRezaei/cpp-utils
|
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
|
[
"MIT"
] | null | null | null |
opengl/texture.cpp
|
yRezaei/cpp-utils
|
3e1ba264bdb6e2339b7b5f2c4e5c3ab7d8097332
|
[
"MIT"
] | null | null | null |
#include "../rendering/gl_utility.hpp"
#include "texture.h"
namespace gl
{
int format_to_texture(image::Format format)
{
switch (format)
{
case image::ALPHA:
case image::GRAYSCALE:
return GL_RED;
case image::GRAYSCALE_ALPHA:
ASSERT("Unkown format 'GRAYSCALE_ALPHA'!!!!");
case image::RGB:
return GL_RGB;
case image::BGR:
return GL_BGR;
case image::RGBA:
return GL_RGBA;
case image::BGRA:
return GL_BGRA;
default:
ASSERT("Unkown format '" + image::FormatStrings[format] + "'.");
}
}
int internal_texture_format(image::Format format)
{
switch (format)
{
case image::ALPHA:
case image::GRAYSCALE:
return GL_RED;
case image::GRAYSCALE_ALPHA:
ASSERT("Unkown format 'GRAYSCALE_ALPHA'!!!!");
case image::RGB:
case image::BGR:
return GL_RGB;
case image::RGBA:
return GL_RGBA;
case image::BGRA:
return GL_BGRA;
default:
ASSERT("Unkown format '" + image::FormatStrings[format] + "'.");
}
}
Texture::Texture(image::Format format, const glm::ivec2 & size, TextureFilter texture_filter, TextureWrapping texture_wrapping) :
id_(0u), format_(format), size_(size)
{
GL_CHECK(glGenTextures(1, &id_));
ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id.");
GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_));
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping);
std::vector<uint8_t> pixels(size_.x * size_.y * format_size(format_), 0);
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, pixels.data()));
}
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture::Texture(image::Bitmap const & bitmap, TextureFilter texture_filter, TextureWrapping texture_wrapping) :
id_(0u), format_(bitmap.format), size_(bitmap.size)
{
GL_CHECK(glGenTextures(1, &id_));
ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id.");
GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_));
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping);
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, bitmap.buffer.data()));
}
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture::Texture(image::Format format, const glm::ivec2 & size, const std::vector<uint8_t>& pixels, TextureFilter texture_filter, TextureWrapping texture_wrapping) :
id_(0u), format_(format), size_(size)
{
if (id_ != 0)
glDeleteTextures(1, &id_);
GL_CHECK(glGenTextures(1, &id_));
ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id.");
GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_));
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping);
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, pixels.data()));
}
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture::Texture(image::Format format, const glm::ivec2 & size, const uint8_t * data, TextureFilter texture_filter, TextureWrapping texture_wrapping) :
id_(0u), format_(format), size_(size)
{
if (id_ != 0)
glDeleteTextures(1, &id_);
GL_CHECK(glGenTextures(1, &id_));
ASSERT_IF_FALSE(id_, "glGenTextures() failed to generate texture id.");
GL_CHECK(glBindTexture(GL_TEXTURE_2D, id_));
{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, texture_filter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, texture_wrapping);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, texture_wrapping);
GL_CHECK(glTexImage2D(GL_TEXTURE_2D, 0, format_to_texture(format_), size_.x, size_.y, 0, internal_texture_format(format_), GL_UNSIGNED_BYTE, data));
}
glBindTexture(GL_TEXTURE_2D, 0);
}
Texture::~Texture()
{
if (id_ != 0)
glDeleteTextures(1, &id_);
}
const glm::ivec2 & Texture::size()
{
return size_;
}
void Texture::set_data(const std::vector<uint8_t>& data)
{
glBindTexture(GL_TEXTURE_2D, id_);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size_.x, size_.y, internal_texture_format(format_), GL_UNSIGNED_BYTE, data.data()));
}
void Texture::set_data(const glm::ivec4 & rect, const std::vector<uint8_t>& data)
{
glBindTexture(GL_TEXTURE_2D, id_);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, rect[0], rect[1], rect[2], rect[3], internal_texture_format(format_), GL_UNSIGNED_BYTE, data.data()));
}
void Texture::set_data(const std::uint8_t* data)
{
glBindTexture(GL_TEXTURE_2D, id_);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, size_.x, size_.y, internal_texture_format(format_), GL_UNSIGNED_BYTE, data));
}
void Texture::set_data(const glm::ivec4 & rect, const std::uint8_t* data)
{
glBindTexture(GL_TEXTURE_2D, id_);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
GL_CHECK(glTexSubImage2D(GL_TEXTURE_2D, 0, rect[0], rect[1], rect[2], rect[3], internal_texture_format(format_), GL_UNSIGNED_BYTE, data));
}
void Texture::bind()
{
glBindTexture(GL_TEXTURE_2D, id_);
}
void Texture::unbind()
{
glBindTexture(GL_TEXTURE_2D, 0);
}
}
| 33.757062
| 167
| 0.743096
|
yRezaei
|
9a90a34a50edc5648df12b76cb1b02e0be8f77fc
| 737
|
cpp
|
C++
|
InfoX/lungimea_coordonate_segment.cpp
|
jbara2002/Informatica_LCIB
|
ff9db6d7d6119ba835750cc2d408079f76b852df
|
[
"CC0-1.0"
] | 1
|
2022-03-31T21:45:03.000Z
|
2022-03-31T21:45:03.000Z
|
InfoX/lungimea_coordonate_segment.cpp
|
jbara2002/Informatica_LCIB
|
ff9db6d7d6119ba835750cc2d408079f76b852df
|
[
"CC0-1.0"
] | null | null | null |
InfoX/lungimea_coordonate_segment.cpp
|
jbara2002/Informatica_LCIB
|
ff9db6d7d6119ba835750cc2d408079f76b852df
|
[
"CC0-1.0"
] | null | null | null |
// Citesc coordonatele A(x1,y1), B(x2,y2).
// Afiseaza lungimea AB si coordonatele mijlocului segmentului AB.
#include <iostream>
#include <math.h>
using namespace std;
int main(){
float x1, y1, x2, y2, ab, c1, c2;
cout << "Introdu coordonata punctului A - x1: "; cin >> x1;
cout << "Introdu coordonata punctului A - y1: "; cin >> y1;
cout << "Introdu coordonata punctului B - x2: "; cin >> x2;
cout << "Introdu coordonata punctului B - y2: "; cin >> y2;
ab=sqrt(pow((x1-x2),2)+pow((y1-y2),2));
c1=(x1+x2)/2;
c2=(y1+y2)/2;
cout << "Lungimea segmentului AB: " << ab << endl;
cout << "Coordonatele mijlocului segmentului: " << "A(" << x1+c1 << ")" << " , " << "B(" << y1+c2 << ")" << endl;
}
| 29.48
| 117
| 0.573948
|
jbara2002
|
9a92781c5880a10d8cbdff21bdb1f9650bb73f75
| 12,314
|
cpp
|
C++
|
cmd_vcf_sample_summary.cpp
|
Yichen-Si/cramore
|
18ed327c2bb9deb6c2ec4243d259b93142304719
|
[
"Apache-2.0"
] | 2
|
2019-03-04T23:08:17.000Z
|
2021-08-24T08:10:03.000Z
|
cmd_vcf_sample_summary.cpp
|
Yichen-Si/cramore
|
18ed327c2bb9deb6c2ec4243d259b93142304719
|
[
"Apache-2.0"
] | 2
|
2018-09-19T05:16:20.000Z
|
2020-10-01T18:28:36.000Z
|
cmd_vcf_sample_summary.cpp
|
Yichen-Si/cramore
|
18ed327c2bb9deb6c2ec4243d259b93142304719
|
[
"Apache-2.0"
] | 3
|
2018-09-06T22:04:40.000Z
|
2019-08-19T16:55:42.000Z
|
#include "bcf_filter_arg.h"
#include "cramore.h"
#include "bcf_ordered_reader.h"
int32_t cmdVcfSampleSummary(int32_t argc, char** argv) {
std::string inVcf;
std::string out;
std::string reg;
std::vector<std::string> sumFields;
int32_t minDistBp = 0;
int32_t verbose = 1000;
bool countVariants = false; // count variants by variant type, allele type, and genotypes
bcf_vfilter_arg vfilt;
bcf_gfilter_arg gfilt;
std::vector<int32_t> acThres;
std::vector<double> afThres;
bool posOnly = false;
paramList pl;
BEGIN_LONG_PARAMS(longParameters)
LONG_PARAM_GROUP("Input Sites", NULL)
LONG_STRING_PARAM("in-vcf",&inVcf, "Input VCF/BCF file")
LONG_STRING_PARAM("region",®,"Genomic region to focus on")
LONG_PARAM("pos-only",&posOnly,"Consider POS field only (not REF field) when determining --region option. This will exclude >1bp variants outside of the region included")
LONG_PARAM_GROUP("Analysis Options", NULL)
LONG_MULTI_STRING_PARAM("sum-field",&sumFields, "Field values to calculate the sums")
LONG_PARAM("count-variants",&countVariants, "Flag to turn on counting variants")
LONG_PARAM_GROUP("Variant Filtering Options", NULL)
LONG_INT_PARAM("min-dist-bp",&minDistBp, "Minimum distance from the previous variant in base-position")
LONG_MULTI_STRING_PARAM("apply-filter",&vfilt.required_filters, "Require at least one of the listed FILTER strings")
LONG_STRING_PARAM("include-expr",&vfilt.include_expr, "Include sites for which expression is true")
LONG_STRING_PARAM("exclude-expr",&vfilt.exclude_expr, "Exclude sites for which expression is true")
LONG_PARAM_GROUP("Genotype Filtering Options", NULL)
LONG_MULTI_INT_PARAM("ac",&acThres,"Allele count threshold to count rare/common variants")
LONG_MULTI_DOUBLE_PARAM("af",&afThres,"Allele frequency threshold to count rare/common variants")
LONG_INT_PARAM("minDP",&gfilt.minDP,"Minimum depth threshold for counting genotypes")
LONG_INT_PARAM("minGQ",&gfilt.minGQ,"Minimum depth threshold for counting genotypes")
LONG_PARAM_GROUP("Output Options", NULL)
LONG_STRING_PARAM("out", &out, "Output VCF file name")
LONG_INT_PARAM("verbose",&verbose,"Frequency of verbose output (1/n)")
END_LONG_PARAMS();
pl.Add(new longParams("Available Options", longParameters));
pl.Read(argc, argv);
pl.Status();
// sanity check of input arguments
if ( inVcf.empty() || out.empty() ) {
error("[E:%s:%d %s] --in-vcf, --out are required parameters",__FILE__,__LINE__,__FUNCTION__);
}
std::vector<GenomeInterval> intervals;
if ( !reg.empty() ) {
parse_intervals(intervals, "", reg);
}
BCFOrderedReader odr(inVcf, intervals);
bcf1_t* iv = bcf_init();
// handle filter string
std::string filter_str;
int32_t filter_logic = 0;
if ( vfilt.include_expr.empty() ) {
if ( vfilt.exclude_expr.empty() ) {
// do nothing
}
else {
filter_str = vfilt.exclude_expr;
filter_logic |= FLT_EXCLUDE;
}
}
else {
if ( vfilt.exclude_expr.empty() ) {
filter_str = vfilt.include_expr;
filter_logic |= FLT_INCLUDE;
}
else {
error("[E:%s:%d %s] Cannot use both --include-expr and --exclude-expr options",__FILE__,__LINE__,__FUNCTION__);
}
}
filter_t* filt = NULL;
if ( filter_logic != 0 )
filter_init(odr.hdr, filter_str.c_str());
// handle --apply-filtrs
std::vector<int32_t> req_flt_ids;
if ( !vfilt.required_filters.empty() ) {
for(int32_t i=0; i < (int32_t)vfilt.required_filters.size(); ++i) {
req_flt_ids.push_back(bcf_hdr_id2int(odr.hdr, BCF_DT_ID, vfilt.required_filters[i].c_str()));
}
}
notice("Started Reading site information from VCF file");
std::map< std::string, std::vector<int64_t> > mapFieldSums;
std::map< std::string, std::vector<int64_t> > mapFieldVars;
int32_t nVariant = 0;
int32_t nsamples = bcf_hdr_nsamples(odr.hdr);
for(int32_t i=0; i < (int32_t)sumFields.size(); ++i)
mapFieldSums[sumFields[i]].resize(nsamples, (int64_t)0);
std::vector<std::string> varFields;
varFields.push_back("ALL.SNP");
varFields.push_back("ALL.OTH");
varFields.push_back("NREF.SNP");
varFields.push_back("NREF.OTH");
varFields.push_back("REF.SNP");
varFields.push_back("REF.OTH");
varFields.push_back("HET.SNP");
varFields.push_back("HET.OTH");
varFields.push_back("ALT.SNP");
varFields.push_back("ALT.OTH");
varFields.push_back("MISS.SNP");
varFields.push_back("MISS.OTH");
std::sort(acThres.begin(), acThres.end());
for(int32_t i=0; i < (int32_t)acThres.size(); ++i) {
char buf[255];
sprintf(buf, "AC_%d_%d.SNP", i == 0 ? 1 : acThres[i-1]+1, acThres[i]);
varFields.push_back(buf);
sprintf(buf, "AC_%d_%d.OTH", i == 0 ? 1 : acThres[i-1]+1, acThres[i]);
varFields.push_back(buf);
}
std::sort(afThres.begin(), afThres.end());
for(int32_t i=0; i < (int32_t)afThres.size(); ++i) {
char buf[255];
sprintf(buf, "AF_%f_%f.SNP", i == 0 ? 0 : afThres[i-1], afThres[i]);
varFields.push_back(buf);
sprintf(buf, "AF_%f_%f.OTH", i == 0 ? 0 : afThres[i-1], afThres[i]);
varFields.push_back(buf);
}
for(int32_t i=0; i < (int32_t)varFields.size(); ++i) {
mapFieldVars[varFields[i]].resize(nsamples, (int64_t)0);
}
std::vector<int32_t> varMasks(varFields.size());
int32_t* p_gt = NULL;
int32_t n_gt = 0;
int32_t* p_fld = NULL;
int32_t n_fld = 0;
int32_t prev_rid = -1, prev_pos = -1;
int32_t nskip = 0;
int32_t an = 0, ac_alloc = 0, non_ref_ac = 0;
int32_t* ac = NULL;
for(int32_t k=0; odr.read(iv); ++k) { // read marker
if ( k % verbose == 0 )
notice("Processing %d markers at %s:%d. Skipped %d markers within %d-bp from the previous marker", k, bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1, nskip, minDistBp);
// if minimum distance is specified, skip the variant
if ( ( prev_rid == iv->rid ) && ( iv->pos - prev_pos < minDistBp ) ) {
++nskip;
continue;
}
if ( ( !reg.empty() ) && posOnly && ( ( intervals[0].start1 > iv->pos+1 ) || ( intervals[0].end1 < iv->pos+1 ) ) ) {
notice("With --pos-only option, skipping variant at %s:%d", bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1);
++nskip;
continue;
}
bcf_unpack(iv, BCF_UN_FLT);
// check --apply-filters
bool has_filter = req_flt_ids.empty() ? true : false;
if ( ! has_filter ) {
//notice("%d %d", iv->d.n_flt, (int32_t)req_flt_ids.size());
for(int32_t i=0; i < iv->d.n_flt; ++i) {
for(int32_t j=0; j < (int32_t)req_flt_ids.size(); ++j) {
if ( req_flt_ids[j] == iv->d.flt[i] )
has_filter = true;
}
}
}
//if ( k % 1000 == 999 ) abort();
if ( ! has_filter ) { ++nskip; continue; }
// check filter logic
if ( filt != NULL ) {
int32_t ret = filter_test(filt, iv, NULL);
if ( filter_logic == FLT_INCLUDE ) { if ( !ret) has_filter = false; }
else if ( ret ) { has_filter = false; }
}
if ( ! has_filter ) { ++nskip; continue; }
++nVariant;
if ( countVariants ) {
// calculate AC
if ( acThres.size() + afThres.size() > 0 ) {
hts_expand(int, iv->n_allele, ac_alloc, ac);
an = 0;
non_ref_ac = 0;
bcf_calc_ac(odr.hdr, iv, ac, BCF_UN_INFO|BCF_UN_FMT); // get original AC and AN values from INFO field if available, otherwise calculate
for (int32_t i=1; i<iv->n_allele; i++)
non_ref_ac += ac[i];
for (int32_t i=0; i<iv->n_allele; i++)
an += ac[i];
}
// determine variant type : flags are MISSING HOMALT HET HOMREF
std::fill(varMasks.begin(), varMasks.end(), 0);
if ( bcf_is_snp(iv) ) {
varMasks[0] = MASK_GT_ALL;
varMasks[2] = MASK_GT_NONREF;
varMasks[4] = MASK_GT_HOMREF;
varMasks[6] = MASK_GT_HET;
varMasks[8] = MASK_GT_HOMALT;
varMasks[10] = MASK_GT_MISS;
} // for non-ref genotypes
else {
varMasks[1] = MASK_GT_ALL;
varMasks[3] = MASK_GT_NONREF;
varMasks[5] = MASK_GT_HOMREF;
varMasks[7] = MASK_GT_HET;
varMasks[9] = MASK_GT_HOMALT;
varMasks[11] = MASK_GT_MISS;
} // for non-ref genotypes
for(int32_t i=0, j=12; i < (int32_t)acThres.size(); ++i, j += 2) {
if ( ( non_ref_ac > (i == 0 ? 0 : acThres[i-1]) ) && ( non_ref_ac <= acThres[i] ) ) {
if ( bcf_is_snp(iv) ) {
varMasks[j] = MASK_GT_NONREF;
}
else {
varMasks[j+1] = MASK_GT_NONREF;
}
}
}
for(int32_t i=0, j=12 + 2*acThres.size(); i < (int32_t)afThres.size(); ++i, j += 2) {
if ( ( non_ref_ac > (i == 0 ? 0 : afThres[i-1]*an) ) && ( non_ref_ac <= afThres[i]*an ) ) {
if ( bcf_is_snp(iv) ) {
varMasks[j] = MASK_GT_NONREF;
}
else {
varMasks[j+1] = MASK_GT_NONREF;
}
}
}
// extract genotype and apply genotype level filter
if ( bcf_get_genotypes(odr.hdr, iv, &p_gt, &n_gt) < 0 ) {
error("[E:%s:%d %s] Cannot find the field GT from the VCF file at position %s:%d",__FILE__,__LINE__,__FUNCTION__, bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1);
}
for(int32_t i=0; i < nsamples; ++i) {
int32_t g1 = p_gt[2*i];
int32_t g2 = p_gt[2*i+1];
int32_t geno;
if ( bcf_gt_is_missing(g1) || bcf_gt_is_missing(g2) ) {
geno = 0;
}
else {
geno = ((bcf_gt_allele(g1) > 0) ? 1 : 0) + ((bcf_gt_allele(g2) > 0) ? 1 : 0) + 1;
//if ( i == 0 )
//notice("g1 = %d, g2 = %d, geno = %d", g1,g2,geno);
}
p_gt[i] = geno;
}
if ( gfilt.minDP > 0 ) {
if ( bcf_get_format_int32(odr.hdr, iv, "DP", &p_fld, &n_fld) < 0 ) {
error("[E:%s:%d %s] Cannot find the field DP from the VCF file at position %s:%d",__FILE__,__LINE__,__FUNCTION__, bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1);
}
for(int32_t i=0; i < nsamples; ++i) {
if ( p_fld[i] < gfilt.minDP ) p_gt[i] = 0;
}
}
if ( gfilt.minGQ > 0 ) {
if ( bcf_get_format_int32(odr.hdr, iv, "GQ", &p_fld, &n_fld) < 0 ) {
error("[E:%s:%d %s] Cannot find the field GQ from the VCF file at position %s:%d",__FILE__,__LINE__,__FUNCTION__, bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1);
}
for(int32_t i=0; i < nsamples; ++i) {
if ( p_fld[i] < gfilt.minGQ ) p_gt[i] = 0;
}
}
// update the maps
for(int32_t i=0; i < (int32_t)varFields.size(); ++i) {
std::vector<int64_t>& v = mapFieldVars[varFields[i]];
for(int32_t j=0; j < nsamples; ++j) {
if ( varMasks[i] & ( 0x01 << p_gt[j] ) ) {
//if ( j == 0 ) notice("VarMask[i] = %d, p_gt[j] = %d", varMasks[i], p_gt[j]);
++v[j];
}
}
}
//if ( rand() % 100 == 0 ) abort();
}
// perform sumField tasks
for(int32_t i=0; i < (int32_t)sumFields.size(); ++i) {
if ( bcf_get_format_int32(odr.hdr, iv, sumFields[i].c_str(), &p_fld, &n_fld) < 0 ) {
error("[E:%s:%d %s] Cannot find the field %s from the VCF file at position %s:%d",__FILE__,__LINE__,__FUNCTION__, sumFields[i].c_str(), bcf_hdr_id2name(odr.hdr, iv->rid), iv->pos+1);
}
if ( nsamples != n_fld )
error("[E:%s:%d %s] Field %s has multiple elements",__FILE__,__LINE__,__FUNCTION__,sumFields[i].c_str());
std::vector<int64_t>& v = mapFieldSums[sumFields[i]];
if ( (int32_t)v.size() != nsamples )
error("[E:%s:%d %s] mapFieldSums object does not have %s as key",__FILE__,__LINE__,__FUNCTION__,sumFields[i].c_str());
for(int32_t j=0; j < nsamples; ++j) {
//if ( p_fld[j] != bcf_int32_missing ) {
v[j] += p_fld[j];
//}
}
}
prev_rid = iv->rid;
prev_pos = iv->pos;
}
htsFile* wf = hts_open(out.c_str(), "w");
hprintf(wf, "ID\tN.VAR");
for(int32_t i=0; i < (int32_t)varFields.size(); ++i) {
hprintf(wf, "\t%s",varFields[i].c_str());
}
for(int32_t i=0; i < (int32_t)sumFields.size(); ++i) {
hprintf(wf, "\tSUM.%s",sumFields[i].c_str());
}
hprintf(wf,"\n");
for(int32_t i=0; i < nsamples; ++i) {
hprintf(wf, "%s", odr.hdr->id[BCF_DT_SAMPLE][i].key);
hprintf(wf, "\t%d", nVariant);
for(int32_t j=0; j < (int32_t)varFields.size(); ++j) {
hprintf(wf, "\t%lld", mapFieldVars[varFields[j]][i]);
}
for(int32_t j=0; j < (int32_t)sumFields.size(); ++j) {
hprintf(wf, "\t%lld", mapFieldSums[sumFields[j]][i]);
}
hprintf(wf, "\n");
}
hts_close(wf);
odr.close();
return 0;
}
| 33.82967
| 183
| 0.617265
|
Yichen-Si
|
9a96b1ef62c7fd3cd7363e2485646d7bc9ee2186
| 589
|
cpp
|
C++
|
volume2/1161_10May2006_1186596.cpp
|
andriybuday/timus
|
a5cdc03f3ca8e7878220b8e0a0c72343f98ee1eb
|
[
"MIT"
] | null | null | null |
volume2/1161_10May2006_1186596.cpp
|
andriybuday/timus
|
a5cdc03f3ca8e7878220b8e0a0c72343f98ee1eb
|
[
"MIT"
] | null | null | null |
volume2/1161_10May2006_1186596.cpp
|
andriybuday/timus
|
a5cdc03f3ca8e7878220b8e0a0c72343f98ee1eb
|
[
"MIT"
] | null | null | null |
//1161
#include <stdio.h>
#include <math.h>
int arr[107];
double res = 0;
void Sq(int* a, int n){
int p = a[n>>1];
int i = 0 , j = n;
int temp;
do{
while(a[i] < p)i++;
while(a[j] > p)j--;
if(i <= j){
temp = a[i];
a[i] = a[j];
a[j] = temp;
i++;
j--;
}
}while(i <= j);
if(j > 0)Sq(a, j);
if(i < n)Sq(a + i, n-i);
}
int main(){
int n;
scanf("%d", &n);
int i;
for(i = 0;i < n; i++)
scanf("%d", &arr[i]);
Sq(arr, n-1);
res = arr[n-1];
for(i = n-2; i >= 0; i--)
{
res = 2*sqrt(arr[i]*res);
}
printf("%.2f", res);
return 0;
}
| 12.270833
| 27
| 0.419355
|
andriybuday
|
9a989fbef319496656a1b096f8e75ab1160136fc
| 4,103
|
cpp
|
C++
|
src/solver.cpp
|
oygx210/dmsc-visualizer
|
c0d571beb5dc6a4c76ef27b9d57139cb48376756
|
[
"MIT"
] | null | null | null |
src/solver.cpp
|
oygx210/dmsc-visualizer
|
c0d571beb5dc6a4c76ef27b9d57139cb48376756
|
[
"MIT"
] | null | null | null |
src/solver.cpp
|
oygx210/dmsc-visualizer
|
c0d571beb5dc6a4c76ef27b9d57139cb48376756
|
[
"MIT"
] | 1
|
2021-12-13T02:28:00.000Z
|
2021-12-13T02:28:00.000Z
|
#include "dmsc/solver.hpp"
#include "dmsc/glm_include.hpp"
#include <cmath>
#include <ctime>
#include <fstream>
#include <random>
namespace dmsc {
float Solver::nextCommunication(const InterSatelliteLink& edge, const float time_0) {
// edge is never visible?
float t_visible = nextVisibility(edge, time_0);
if (t_visible >= INFINITY) {
return INFINITY;
}
// get current orientation of both satellites
TimelineEvent<glm::vec3> sat1 = satellite_orientation[&edge.getV1()];
TimelineEvent<glm::vec3> sat2 = satellite_orientation[&edge.getV2()];
// edge can be scanned directly?
if (edge.canAlign(sat1, sat2, t_visible)) {
return t_visible;
}
// satellites can't align => search for a time where they can
// max time to align ==> time for a 180 deg turn
float t_max = std::max(static_cast<float>(M_PI) / edge.getV1().getRotationSpeed(),
static_cast<float>(M_PI) / edge.getV2().getRotationSpeed());
t_max += edge.getPeriod();
for (float t = t_visible; t <= time_0 + t_max; t += step_size) {
if (edge.isBlocked(t)) { // skip time where edge is blocked
// find next slot where edge is visible
float t_relative = fmodf(t, edge.getPeriod());
auto search = edge_time_slots.find(&edge);
float t_next = 0.0f;
if (search != edge_time_slots.end()) {
t_next = search->second.nextTimeWithEvent(t_relative, true);
}
if (t_next < t_relative) { // loop applied
t += t_next + edge.getPeriod() - t_relative;
} else { // loop not applied
t += t_next - t_relative;
}
}
if (edge.canAlign(sat1, sat2, t)) { // edge can be scanned
if (!edge.isBlocked(t)) {
return t;
}
}
}
// communication is never possible
return INFINITY;
}
// ------------------------------------------------------------------------------------------------
void Solver::createCache() {
for (const auto& edge : instance.getISLs()) {
for (float t = 0.0f; t < edge.getPeriod(); t += step_size) {
// TODO getPERIOD IS INFINIT if cm.gp = 0
float t_next = findNextVisiblity(edge, t);
if (t_next == INFINITY || t_next >= edge.getPeriod()) {
break;
}
float t_end = findLastVisible(edge, t_next);
if (t_end == INFINITY || t_end >= edge.getPeriod()) {
t_end = edge.getPeriod();
}
TimelineEvent<> slot(t_next, t_end);
edge_time_slots[&edge].insert(slot);
t = slot.t_end;
}
}
}
// ------------------------------------------------------------------------------------------------
float Solver::nextVisibility(const InterSatelliteLink& edge, const float t0) {
if (edge_time_slots[&edge].size() == 0) {
return INFINITY;
}
float t = std::fmod(t0, edge.getPeriod());
float n_periods = edge.getPeriod() * (int)(t0 / edge.getPeriod());
float t_next = edge_time_slots[&edge].nextTimeWithEvent(t, true);
if (t_next < t) { // loop applied
n_periods += edge.getPeriod();
}
return t_next + n_periods;
}
// ------------------------------------------------------------------------------------------------
float Solver::findNextVisiblity(const InterSatelliteLink& edge, const float t0) const {
for (float t = t0; t <= t0 + edge.getPeriod(); t += step_size) {
if (!edge.isBlocked(t)) {
return t;
}
}
// edge is never visible
return INFINITY;
}
// ------------------------------------------------------------------------------------------------
float Solver::findLastVisible(const InterSatelliteLink& edge, const float t0) const {
for (float t = t0; t <= t0 + edge.getPeriod(); t += step_size) {
if (edge.isBlocked(t)) {
return t - step_size;
}
}
// edge is never visible
return INFINITY;
}
} // namespace dmsc
| 32.307087
| 99
| 0.520107
|
oygx210
|
9a9ea4fd5b4657ee6f817ddef3d9c02f4b17b117
| 674
|
cpp
|
C++
|
solution.cpp
|
kylianlee/acmicpc_11000
|
df4fc833ee5aef7385250683d69405400557687e
|
[
"MIT"
] | null | null | null |
solution.cpp
|
kylianlee/acmicpc_11000
|
df4fc833ee5aef7385250683d69405400557687e
|
[
"MIT"
] | null | null | null |
solution.cpp
|
kylianlee/acmicpc_11000
|
df4fc833ee5aef7385250683d69405400557687e
|
[
"MIT"
] | null | null | null |
//
// Created by Kylian Lee on 2021/09/18.
//
#include <iostream>
#include <vector>
#include <queue>
#include <utility>
using namespace std;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;
int main(){
int class_num;
scanf("%d", &class_num);
for (int i = 0; i < class_num; ++i) {
int start, end;
scanf("%d %d", &start, &end);
pq.push({start, end});
}
priority_queue<int, vector<int>, greater<>> answer;
answer.push(pq.top().second);
pq.pop();
while(!pq.empty()){
if(answer.top() <= pq.top().first)
answer.pop();
answer.push(pq.top().second);
pq.pop();
}
cout << answer.size() << endl;
return 0;
}
| 19.823529
| 69
| 0.591988
|
kylianlee
|
9a9fffcd98f63cbc05284239b58ae4182f83c68b
| 3,301
|
cpp
|
C++
|
addons/ofxKinectForWindows2/example/src/ofApp.cpp
|
syeminpark/openFrame
|
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
|
[
"MIT"
] | null | null | null |
addons/ofxKinectForWindows2/example/src/ofApp.cpp
|
syeminpark/openFrame
|
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
|
[
"MIT"
] | null | null | null |
addons/ofxKinectForWindows2/example/src/ofApp.cpp
|
syeminpark/openFrame
|
2d117bf86ae58dbc2d5d0ddc6727f14e5627e6e6
|
[
"MIT"
] | null | null | null |
#include "ofApp.h"
int previewWidth = 512;
int previewHeight = 424;
//--------------------------------------------------------------
void ofApp::setup(){
kinect.open();
kinect.initDepthSource();
kinect.initColorSource();
kinect.initInfraredSource();
kinect.initBodySource();
kinect.initBodyIndexSource();
ofSetWindowShape(previewWidth * 2, previewHeight * 2);
}
//--------------------------------------------------------------
void ofApp::update(){
kinect.update();
//--
//Getting joint positions (skeleton tracking)
//--
//
{
auto bodies = kinect.getBodySource()->getBodies();
for (auto body : bodies) {
for (auto joint : body.joints) {
//now do something with the joints
}
}
}
//
//--
//--
//Getting bones (connected joints)
//--
//
{
// Note that for this we need a reference of which joints are connected to each other.
// We call this the 'boneAtlas', and you can ask for a reference to this atlas whenever you like
auto bodies = kinect.getBodySource()->getBodies();
auto boneAtlas = ofxKinectForWindows2::Data::Body::getBonesAtlas();
for (auto body : bodies) {
for (auto bone : boneAtlas) {
auto firstJointInBone = body.joints[bone.first];
auto secondJointInBone = body.joints[bone.second];
//now do something with the joints
}
}
}
//
//--
}
//--------------------------------------------------------------
void ofApp::draw(){
kinect.getDepthSource()->draw(0, 0, previewWidth, previewHeight); // note that the depth texture is RAW so may appear dark
// Color is at 1920x1080 instead of 512x424 so we should fix aspect ratio
float colorHeight = previewWidth * (kinect.getColorSource()->getHeight() / kinect.getColorSource()->getWidth());
float colorTop = (previewHeight - colorHeight) / 2.0;
kinect.getColorSource()->draw(previewWidth, 0 + colorTop, previewWidth, colorHeight);
kinect.getBodySource()->drawProjected(previewWidth, 0 + colorTop, previewWidth, colorHeight);
kinect.getInfraredSource()->draw(0, previewHeight, previewWidth, previewHeight);
kinect.getBodyIndexSource()->draw(previewWidth, previewHeight, previewWidth, previewHeight);
kinect.getBodySource()->drawProjected(previewWidth, previewHeight, previewWidth, previewHeight, ofxKFW2::ProjectionCoordinates::DepthCamera);
}
//--------------------------------------------------------------
void ofApp::keyPressed(int key){
}
//--------------------------------------------------------------
void ofApp::keyReleased(int key){
}
//--------------------------------------------------------------
void ofApp::mouseMoved(int x, int y){
}
//--------------------------------------------------------------
void ofApp::mouseDragged(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mousePressed(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::mouseReleased(int x, int y, int button){
}
//--------------------------------------------------------------
void ofApp::windowResized(int w, int h){
}
//--------------------------------------------------------------
void ofApp::gotMessage(ofMessage msg){
}
//--------------------------------------------------------------
void ofApp::dragEvent(ofDragInfo dragInfo){
}
| 27.057377
| 142
| 0.541351
|
syeminpark
|
9aa057125e59591d9eef384321180649580e4163
| 17,493
|
cpp
|
C++
|
application_sandbox/stencil_export/main.cpp
|
apazylbe/vulkan_test_applications
|
250bb3d371e3c587a8d1ceb5f9187a960b61d63f
|
[
"Apache-2.0"
] | null | null | null |
application_sandbox/stencil_export/main.cpp
|
apazylbe/vulkan_test_applications
|
250bb3d371e3c587a8d1ceb5f9187a960b61d63f
|
[
"Apache-2.0"
] | null | null | null |
application_sandbox/stencil_export/main.cpp
|
apazylbe/vulkan_test_applications
|
250bb3d371e3c587a8d1ceb5f9187a960b61d63f
|
[
"Apache-2.0"
] | null | null | null |
// Copyright 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "application_sandbox/sample_application_framework/sample_application.h"
#include "support/entry/entry.h"
#include "vulkan_helpers/buffer_frame_data.h"
#include "vulkan_helpers/helper_functions.h"
#include "vulkan_helpers/vulkan_application.h"
#include "vulkan_helpers/vulkan_model.h"
#include <chrono>
#include "mathfu/matrix.h"
#include "mathfu/vector.h"
using Mat44 = mathfu::Matrix<float, 4, 4>;
using Vector4 = mathfu::Vector<float, 4>;
namespace x_model {
const struct {
size_t num_vertices;
float positions[24];
float uv[16];
float normals[24];
size_t num_indices;
uint32_t indices[12];
} model = {8,
/*positions*/
{1.5f, 1.5f, 0.0f, 1.5f, 1.5f, 0.0f, -1.5f, -1.5f,
0.0f, -1.5f, -1.5f, 0.0f, -1.5f, 1.5f, 0.0f, -1.5f,
1.5f, 0.0f, 1.5f, -1.5f, 0.0f, 1.5f, -1.5f, 0.0f},
/*texture_coords*/
{},
/*normals*/
{-1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f, 1.0f,
1.0f, 1.0f, -1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, 1.0f, 1.0f, 1.0f, -1.0f, -1.0f, -1.0f},
12,
/*indices*/
{0, 2, 1, 1, 2, 3, 4, 5, 6, 6, 5, 7}};
} // namespace x_model
const auto& x_cross_data = x_model::model;
uint32_t line_vertex_shader[] =
#include "line.vert.spv"
;
uint32_t line_fragment_shader[] =
#include "line.frag.spv"
;
struct StencilExportFrameData {
containers::unique_ptr<vulkan::VkCommandBuffer> command_buffer_;
containers::unique_ptr<vulkan::VkFramebuffer> framebuffer_;
containers::unique_ptr<vulkan::DescriptorSet> line_descriptor_set_;
vulkan::ImagePointer stencil_;
containers::unique_ptr<vulkan::VkImageView> stencil_view_;
};
// This creates an application with 16MB of image memory, and defaults
// for host, and device buffer sizes.
class StencilExportSample
: public sample_application::Sample<StencilExportFrameData> {
public:
StencilExportSample(const entry::EntryData* data)
: data_(data),
Sample<StencilExportFrameData>(
data->allocator(), data, 1, 512, 1, 1,
sample_application::SampleOptions().EnableMultisampling(), {}, {},
{VK_EXT_SHADER_STENCIL_EXPORT_EXTENSION_NAME}),
x_cross_(data->allocator(), data->logger(), x_cross_data) {}
virtual void InitializeApplicationData(
vulkan::VkCommandBuffer* initialization_buffer,
size_t num_swapchain_images) override {
x_cross_.InitializeData(app(), initialization_buffer);
line_descriptor_set_layouts_[0] = {
0, // binding
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
1, // descriptorCount
VK_SHADER_STAGE_VERTEX_BIT, // stageFlags
nullptr // pImmutableSamplers
};
line_descriptor_set_layouts_[1] = {
1, // binding
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
1, // descriptorCount
VK_SHADER_STAGE_VERTEX_BIT, // stageFlags
nullptr // pImmutableSamplers
};
pipeline_layout_ = containers::make_unique<vulkan::PipelineLayout>(
data_->allocator(),
app()->CreatePipelineLayout({{line_descriptor_set_layouts_[0],
line_descriptor_set_layouts_[1]}}));
VkAttachmentReference color_attachment = {
0, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL};
VkAttachmentReference stencil_attachment = {
1, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL};
render_pass_ = containers::make_unique<vulkan::VkRenderPass>(
data_->allocator(),
app()->CreateRenderPass(
{{
0, // flags
render_format(), // format
num_samples(), // samples
VK_ATTACHMENT_LOAD_OP_CLEAR, // loadOp
VK_ATTACHMENT_STORE_OP_STORE, // storeOp
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // stenilLoadOp
VK_ATTACHMENT_STORE_OP_DONT_CARE, // stenilStoreOp
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, // initialLayout
VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL // finalLayout
},
{
0, // flags
VK_FORMAT_D24_UNORM_S8_UINT, // format
num_samples(), // samples
VK_ATTACHMENT_LOAD_OP_DONT_CARE, // loadOp
VK_ATTACHMENT_STORE_OP_DONT_CARE, // storeOp
VK_ATTACHMENT_LOAD_OP_CLEAR, // stenilLoadOp
VK_ATTACHMENT_STORE_OP_DONT_CARE, // stenilStoreOp
VK_IMAGE_LAYOUT_UNDEFINED, // initialLayout
VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL // finalLayout
}}, // AttachmentDescriptions
{{
0, // flags
VK_PIPELINE_BIND_POINT_GRAPHICS, // pipelineBindPoint
0, // inputAttachmentCount
nullptr, // pInputAttachments
1, // colorAttachmentCount
&color_attachment, // colorAttachment
nullptr, // pResolveAttachments
&stencil_attachment, // pDepthStencilAttachment
0, // preserveAttachmentCount
nullptr // pPreserveAttachments
}}, // SubpassDescriptions
{} // SubpassDependencies
));
VkStencilOpState stencilOpState{VK_STENCIL_OP_KEEP,
VK_STENCIL_OP_REPLACE,
VK_STENCIL_OP_KEEP,
VK_COMPARE_OP_GREATER,
UINT32_MAX,
UINT32_MAX,
0};
line_pipeline_ = containers::make_unique<vulkan::VulkanGraphicsPipeline>(
data_->allocator(), app()->CreateGraphicsPipeline(
pipeline_layout_.get(), render_pass_.get(), 0));
line_pipeline_->AddShader(VK_SHADER_STAGE_VERTEX_BIT, "main",
line_vertex_shader);
line_pipeline_->AddShader(VK_SHADER_STAGE_FRAGMENT_BIT, "main",
line_fragment_shader);
line_pipeline_->SetTopology(VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST);
line_pipeline_->SetInputStreams(&x_cross_);
line_pipeline_->SetViewport(viewport());
line_pipeline_->SetScissor(scissor());
line_pipeline_->SetSamples(num_samples());
line_pipeline_->AddAttachment();
line_pipeline_->DepthStencilState().depthTestEnable = false;
line_pipeline_->DepthStencilState().stencilTestEnable = true;
line_pipeline_->DepthStencilState().front = stencilOpState;
line_pipeline_->Commit();
camera_data_ = containers::make_unique<vulkan::BufferFrameData<CameraData>>(
data_->allocator(), app(), num_swapchain_images,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
model_data_ = containers::make_unique<vulkan::BufferFrameData<ModelData>>(
data_->allocator(), app(), num_swapchain_images,
VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT);
float aspect =
(float)app()->swapchain().width() / (float)app()->swapchain().height();
camera_data_->data().projection_matrix =
Mat44::FromScaleVector(mathfu::Vector<float, 3>{1.0f, -1.0f, 1.0f}) *
Mat44::Perspective(1.5708f, aspect, 0.1f, 100.0f);
model_data_->data().transform = Mat44::FromTranslationVector(
mathfu::Vector<float, 3>{0.0f, 0.0f, -3.0f});
}
virtual void InitializeFrameData(
StencilExportFrameData* frame_data,
vulkan::VkCommandBuffer* initialization_buffer,
size_t frame_index) override {
frame_data->command_buffer_ =
containers::make_unique<vulkan::VkCommandBuffer>(
data_->allocator(), app()->GetCommandBuffer());
frame_data->line_descriptor_set_ =
containers::make_unique<vulkan::DescriptorSet>(
data_->allocator(),
app()->AllocateDescriptorSet({line_descriptor_set_layouts_[0],
line_descriptor_set_layouts_[1]}));
VkDescriptorBufferInfo buffer_infos[2] = {
{
camera_data_->get_buffer(), // buffer
camera_data_->get_offset_for_frame(frame_index), // offset
camera_data_->size(), // range
},
{
model_data_->get_buffer(), // buffer
model_data_->get_offset_for_frame(frame_index), // offset
model_data_->size(), // range
}};
VkWriteDescriptorSet write{
VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, // sType
nullptr, // pNext
*frame_data->line_descriptor_set_, // dstSet
0, // dstbinding
0, // dstArrayElement
2, // descriptorCount
VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, // descriptorType
nullptr, // pImageInfo
buffer_infos, // pBufferInfo
nullptr, // pTexelBufferView
};
app()->device()->vkUpdateDescriptorSets(app()->device(), 1, &write, 0,
nullptr);
VkImageCreateInfo image_create_info{
/* sType = */
VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO,
/* pNext = */ nullptr,
/* flags = */ 0,
/* imageType = */ VK_IMAGE_TYPE_2D,
/* format = */ VK_FORMAT_D24_UNORM_S8_UINT,
/* extent = */
{
/* width = */ app()->swapchain().width(),
/* height = */ app()->swapchain().height(),
/* depth = */ app()->swapchain().depth(),
},
/* mipLevels = */ 1,
/* arrayLayers = */ 1,
/* samples = */ num_samples(),
/* tiling = */
VK_IMAGE_TILING_OPTIMAL,
/* usage = */
VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT,
/* sharingMode = */
VK_SHARING_MODE_EXCLUSIVE,
/* queueFamilyIndexCount = */ 0,
/* pQueueFamilyIndices = */ nullptr,
/* initialLayout = */
VK_IMAGE_LAYOUT_UNDEFINED,
};
VkImageViewCreateInfo view_create_info = {
VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
VK_NULL_HANDLE, // image
VK_IMAGE_VIEW_TYPE_2D, // viewType
VK_FORMAT_D24_UNORM_S8_UINT, // format
{VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B,
VK_COMPONENT_SWIZZLE_A},
{VK_IMAGE_ASPECT_STENCIL_BIT, 0, 1, 0, 1}};
::VkImageView raw_views[2] = {color_view(frame_data), VK_NULL_HANDLE};
frame_data->stencil_ = app()->CreateAndBindImage(&image_create_info);
view_create_info.image = *frame_data->stencil_;
app()->device()->vkCreateImageView(app()->device(), &view_create_info,
nullptr, &raw_views[1]);
frame_data->stencil_view_ = containers::make_unique<vulkan::VkImageView>(
data_->allocator(),
vulkan::VkImageView(raw_views[1], nullptr, &app()->device()));
// Create a framebuffer with depth and image attachments
VkFramebufferCreateInfo framebuffer_create_info{
VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, // sType
nullptr, // pNext
0, // flags
*render_pass_, // renderPass
2, // attachmentCount
raw_views, // attachments
app()->swapchain().width(), // width
app()->swapchain().height(), // height
1 // layers
};
::VkFramebuffer raw_framebuffer;
app()->device()->vkCreateFramebuffer(
app()->device(), &framebuffer_create_info, nullptr, &raw_framebuffer);
frame_data->framebuffer_ = containers::make_unique<vulkan::VkFramebuffer>(
data_->allocator(),
vulkan::VkFramebuffer(raw_framebuffer, nullptr, &app()->device()));
(*frame_data->command_buffer_)
->vkBeginCommandBuffer((*frame_data->command_buffer_),
&sample_application::kBeginCommandBuffer);
vulkan::VkCommandBuffer& cmdBuffer = (*frame_data->command_buffer_);
VkClearValue clear[2];
vulkan::MemoryClear(&clear[0]);
vulkan::MemoryClear(&clear[1]);
VkRenderPassBeginInfo pass_begin = {
VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, // sType
nullptr, // pNext
*render_pass_, // renderPass
*frame_data->framebuffer_, // framebuffer
{{0, 0},
{app()->swapchain().width(),
app()->swapchain().height()}}, // renderArea
2, // clearValueCount
clear // clears
};
cmdBuffer->vkCmdBeginRenderPass(cmdBuffer, &pass_begin,
VK_SUBPASS_CONTENTS_INLINE);
cmdBuffer->vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
*line_pipeline_);
cmdBuffer->vkCmdBindDescriptorSets(
cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS,
::VkPipelineLayout(*pipeline_layout_), 0, 1,
&frame_data->line_descriptor_set_->raw_set(), 0, nullptr);
x_cross_.Draw(&cmdBuffer);
cmdBuffer->vkCmdEndRenderPass(cmdBuffer);
(*frame_data->command_buffer_)
->vkEndCommandBuffer(*frame_data->command_buffer_);
}
virtual void Update(float time_since_last_render) override {
model_data_->data().transform = model_data_->data().transform *
Mat44::FromRotationMatrix(Mat44::RotationZ(
3.14f * time_since_last_render));
}
virtual void Render(vulkan::VkQueue* queue, size_t frame_index,
StencilExportFrameData* frame_data) override {
// Update our uniform buffers.
camera_data_->UpdateBuffer(queue, frame_index);
model_data_->UpdateBuffer(queue, frame_index);
VkSubmitInfo init_submit_info{
VK_STRUCTURE_TYPE_SUBMIT_INFO, // sType
nullptr, // pNext
0, // waitSemaphoreCount
nullptr, // pWaitSemaphores
nullptr, // pWaitDstStageMask,
1, // commandBufferCount
&(frame_data->command_buffer_->get_command_buffer()),
0, // signalSemaphoreCount
nullptr // pSignalSemaphores
};
app()->render_queue()->vkQueueSubmit(app()->render_queue(), 1,
&init_submit_info,
static_cast<VkFence>(VK_NULL_HANDLE));
}
private:
struct CameraData {
Mat44 projection_matrix;
};
struct ModelData {
Mat44 transform;
};
const entry::EntryData* data_;
containers::unique_ptr<vulkan::PipelineLayout> pipeline_layout_;
containers::unique_ptr<vulkan::VulkanGraphicsPipeline> line_pipeline_;
containers::unique_ptr<vulkan::VkRenderPass> render_pass_;
VkDescriptorSetLayoutBinding line_descriptor_set_layouts_[2];
vulkan::VulkanModel x_cross_;
containers::unique_ptr<vulkan::BufferFrameData<CameraData>> camera_data_;
containers::unique_ptr<vulkan::BufferFrameData<ModelData>> model_data_;
};
int main_entry(const entry::EntryData* data) {
data->logger()->LogInfo("Application Startup");
StencilExportSample sample(data);
sample.Initialize();
while (!sample.should_exit() && !data->WindowClosing()) {
sample.ProcessFrame();
}
sample.WaitIdle();
data->logger()->LogInfo("Application Shutdown");
return 0;
}
| 42.980344
| 81
| 0.565998
|
apazylbe
|
9aa44ab013d4ea06a37dab5fec1871e02da1e5f3
| 2,639
|
hpp
|
C++
|
src/dwalker/include/PEManager.hpp
|
shmmsra/dwalker
|
4996adcec11bb92ad6d67a8d2e79bd5b022cb67f
|
[
"MIT"
] | null | null | null |
src/dwalker/include/PEManager.hpp
|
shmmsra/dwalker
|
4996adcec11bb92ad6d67a8d2e79bd5b022cb67f
|
[
"MIT"
] | null | null | null |
src/dwalker/include/PEManager.hpp
|
shmmsra/dwalker
|
4996adcec11bb92ad6d67a8d2e79bd5b022cb67f
|
[
"MIT"
] | null | null | null |
#pragma once
#include <string>
#include <vector>
#include <memory>
#include <PHLib.hpp>
#include <PE.hpp>
#include <ApiSet.hpp>
struct PeImport {
unsigned short Hint;
unsigned short Ordinal;
std::string Name;
std::string ModuleName;
bool ImportByOrdinal;
bool DelayImport;
PeImport(const PPH_MAPPED_IMAGE_IMPORT_DLL importDll, size_t Index);
PeImport(const PeImport& other);
~PeImport();
};
struct PeImportDll {
public:
long Flags;
std::string Name;
long NumberOfEntries;
std::vector<PeImport> ImportList;
// constructors
PeImportDll(const PPH_MAPPED_IMAGE_IMPORTS& PvMappedImports, size_t ImportDllIndex);
PeImportDll(const PeImportDll& other);
// destructors
~PeImportDll();
// getters
bool IsDelayLoad();
private:
PPH_MAPPED_IMAGE_IMPORT_DLL ImportDll;
};
struct PeProperties {
short Machine;
// DateTime^ Time;
short Magic;
long ImageBase;
int SizeOfImage;
long EntryPoint;
int Checksum;
bool CorrectChecksum;
short Subsystem;
std::pair<short, short>* SubsystemVersion;
short Characteristics;
short DllCharacteristics;
unsigned long FileSize;
};
class PEManager {
public:
PEManager(const std::wstring& filepath);
~PEManager();
// Mapped the PE in memory and init infos
bool Load();
// Unmapped the PE from memory
void Unload();
// Check if the PE is 32-bit
bool IsWow64Dll();
// Return the ApiSetSchemaBase
std::unique_ptr<ApiSetSchemaBase> GetApiSetSchema();
// Return the list of functions exported by the PE
// List<PeExport ^>^ GetExports();
// Return the list of functions imported by the PE, bundled by Dll name
std::vector<PeImportDll> GetImports();
// Retrieve the manifest embedded within the PE
// Return an empty string if there is none.
// NOTE: Currently only support reading normal string (not wstring)
// because Xerces library doesn't seem to support that either
std::string GetManifest();
// PE properties parsed from the NT header
PeProperties* properties;
// Check if the specified file has been successfully parsed as a PE file.
bool loadSuccessful;
// Path to PE file.
std::wstring filepath;
protected:
// Initalize PeProperties struct once the PE has been loaded into memory
bool InitProperties();
private:
// C++ part interfacing with phlib
PE* m_Impl;
// local cache for imports and exports list
std::vector<PeImportDll> m_Imports;
// List<PeExport ^>^ m_Exports;
bool m_ExportsInit;
bool m_ImportsInit;
};
| 22.176471
| 88
| 0.685866
|
shmmsra
|
9aaa7871a9043ee5b33360e07308437e026f85f4
| 2,746
|
cpp
|
C++
|
openbr/plugins/gui/drawgridlines.cpp
|
gaatyin/openbr
|
a55fa7bd0038b323ade2340c69f109146f084218
|
[
"Apache-2.0"
] | 1
|
2021-04-26T12:53:42.000Z
|
2021-04-26T12:53:42.000Z
|
openbr/plugins/gui/drawgridlines.cpp
|
William-New/openbr
|
326f9bbb84de35586e57b1b0449c220726571c6c
|
[
"Apache-2.0"
] | null | null | null |
openbr/plugins/gui/drawgridlines.cpp
|
William-New/openbr
|
326f9bbb84de35586e57b1b0449c220726571c6c
|
[
"Apache-2.0"
] | null | null | null |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* Copyright 2012 The MITRE Corporation *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#include <openbr/plugins/openbr_internal.h>
#include <opencv2/imgproc.hpp>
using namespace cv;
namespace br
{
/*!
* \ingroup transforms
* \brief Draws a grid on the image
* \author Josh Klontz \cite jklontz
*/
class DrawGridLinesTransform : public UntrainableTransform
{
Q_OBJECT
Q_PROPERTY(int rows READ get_rows WRITE set_rows RESET reset_rows STORED false)
Q_PROPERTY(int columns READ get_columns WRITE set_columns RESET reset_columns STORED false)
Q_PROPERTY(int r READ get_r WRITE set_r RESET reset_r STORED false)
Q_PROPERTY(int g READ get_g WRITE set_g RESET reset_g STORED false)
Q_PROPERTY(int b READ get_b WRITE set_b RESET reset_b STORED false)
BR_PROPERTY(int, rows, 0)
BR_PROPERTY(int, columns, 0)
BR_PROPERTY(int, r, 196)
BR_PROPERTY(int, g, 196)
BR_PROPERTY(int, b, 196)
void project(const Template &src, Template &dst) const
{
Mat m = src.m().clone();
float rowStep = 1.f * m.rows / (rows+1);
float columnStep = 1.f * m.cols / (columns+1);
int thickness = qMin(m.rows, m.cols) / 256;
for (float row = rowStep/2; row < m.rows; row += rowStep)
line(m, Point(0, row), Point(m.cols, row), Scalar(r, g, b), thickness, LINE_AA);
for (float column = columnStep/2; column < m.cols; column += columnStep)
line(m, Point(column, 0), Point(column, m.rows), Scalar(r, g, b), thickness, LINE_AA);
dst = m;
}
};
BR_REGISTER(Transform, DrawGridLinesTransform)
} // namespace br
#include "gui/drawgridlines.moc"
| 42.90625
| 98
| 0.545157
|
gaatyin
|
9aae4ee0b7a4aa188f2e2316079f4f471f1c8a5a
| 3,416
|
cpp
|
C++
|
51nod/1037.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | 3
|
2017-09-17T09:12:50.000Z
|
2018-04-06T01:18:17.000Z
|
51nod/1037.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
51nod/1037.cpp
|
swwind/code
|
25c4c5ca2f8578ba792b44cbdf44286d39dfb7e0
|
[
"WTFPL"
] | null | null | null |
#pragma GCC optimize 2
#include <bits/stdc++.h>
#define N 100020
#define ll long long
using namespace std;
inline ll read(){
ll x=0,f=1;char ch=getchar();
while(ch>'9'||ch<'0')ch=='-'&&(f=0)||(ch=getchar());
while(ch<='9'&&ch>='0')x=(x<<3)+(x<<1)+ch-'0',ch=getchar();
return f?x:-x;
}
inline ll rand(ll mx) {
return (ll) rand() * rand() % mx + 1;
}
inline ll safe_mul(ll x, ll y, ll p) {
ll z = 0 % p;
for (; y; y >>= 1, x = (x + x) % p) {
if (y & 1) {
z = (z + x) % p;
}
}
return z;
}
inline ll fast_pow(ll x, ll y, ll p) {
ll z = 1 % p;
for (; y; y >>= 1, x = safe_mul(x, x, p)) {
if (y & 1) {
z = safe_mul(z, x, p);
}
}
return z;
}
int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37 };
bool isPrime(ll n) {
if (n == 2) return true;
if (n <= 1) return false;
if (!(n & 1)) return false;
ll m = n - 1, k = 0;
while (!(m & 1)) {
++ k;
m >>= 1;
}
for (int i = 0; i < 12; ++ i) {
ll a = primes[i];
if (n == a) return true;
ll x = fast_pow(a, m, n), y;
for (int j = 1; j <= k; ++ j) {
y = safe_mul(x, x, n);
if (y == 1 && x != 1 && x != n - 1) {
return false;
}
x = y;
}
if (y != 1) {
return false;
}
}
return true;
}
inline ll F(ll x, ll p) {
return (safe_mul(x, x, p) + rand(p)) % p;
}
ll rho(ll n) {
// printf("rho %lld\n", n);
if (rand() % 3 != 0) {
for (ll a = rand(n), d = 1, k = 1; d == 1; a = F(a, n), ++ k) {
// printf("gcd(%lld, %lld)\n", a, n);
d = __gcd(a, n);
if (d > 1) {
if (d == n) return rho(n);
else return d;
}
if (k == 10) {
k = 0;
a = rand(n);
}
}
} else {
for (ll a = rand(n), d = 1, k = 1, s = 1; d == 1; a = F(a, n), ++ k) {
// printf("gcd(%lld, %lld)\n", a, n);
d = __gcd(a, n);
if (d > 1) {
if (d == n) return rho(n);
else return d;
}
if (k == s) {
a = rand(n);
s <<= 1;
}
}
}
return 1;
}
vector<ll> ps, vs, cs;
void resolve(ll n) {
// printf("resolving %lld\n", n);
if (n <= 1) return;
if (isPrime(n)) {
ps.push_back(n);
return;
}
// printf("%lld is not prime\n", n);
ll d = rho(n);
resolve(d);
resolve(n / d);
}
void decompose(ll n) {
ps.clear();
vs.clear();
cs.clear();
resolve(n);
sort(ps.begin(), ps.end());
for (size_t i = 0; i < ps.size(); ++ i) {
if (!i || ps[i] != ps[i - 1]) {
vs.push_back(ps[i]);
cs.push_back(1);
} else {
++ *cs.rbegin();
}
}
}
vector<ll> ds;
void dfs_ds(ll x, int d) {
ds.push_back(x);
if (d == vs.size()) return;
for (int i = 0; i <= cs[d]; ++ i) {
dfs_ds(x, d + 1);
x *= vs[d];
}
}
bool check(ll n) {
if (!isPrime(n)) return false;
ll m = n - 1;
decompose(m);
dfs_ds(1, 0);
sort(ds.begin(), ds.end());
for (ll d : ds) {
// printf("enum %lld...\n", d);
if (fast_pow(10, d, n) == 1) {
return d == n - 1;
}
}
return false;
}
int main(int argc, char const *argv[]) {
// freopen("../tmp/.in", "r", stdin);
for (ll n = read(); n; -- n) {
if (n == 928098230207300044ll) return puts("928098230207299891"), 0;
srand(n);
if (check(n)) {
return printf("%lld\n", n), 0;
} else {
// printf("%lld is not what i am fucking want.\n", n);
}
}
// puts("zyy AK IOI 9102");
return 0;
}
| 19.52
| 74
| 0.43589
|
swwind
|
9aae8cf1d38d195dab8f63a67a3e221bba43032a
| 4,484
|
cpp
|
C++
|
src/ProvisioningCipher.cpp
|
yorickdewid/Signalpp
|
c66d7455f46b883caf61cabd0dd01d3eb0839515
|
[
"BSD-3-Clause"
] | 1
|
2017-07-08T12:36:01.000Z
|
2017-07-08T12:36:01.000Z
|
src/ProvisioningCipher.cpp
|
yorickdewid/Signalpp
|
c66d7455f46b883caf61cabd0dd01d3eb0839515
|
[
"BSD-3-Clause"
] | null | null | null |
src/ProvisioningCipher.cpp
|
yorickdewid/Signalpp
|
c66d7455f46b883caf61cabd0dd01d3eb0839515
|
[
"BSD-3-Clause"
] | null | null | null |
#include "Logger.h"
#include "Helper.h"
#include "Base64.h"
#include "CryptoProvider.h"
#include "ProvisioningCipher.h"
#include "KeyHelper.h"
#include "DeviceMessages.pb.h"
#include <hkdf.h>
using namespace signalpp;
ProvisioningCipher::ProvisioningCipher() {
signal_context_create(&context, 0);//TODO: move
CryptoProvider::hook(context);
}
ProvisioningCipher::~ProvisioningCipher() {
// SIGNAL_UNREF(key_pair);
signal_context_destroy(context);//TODO: move
}
ec_public_key *ProvisioningCipher::getPublicKey() {
int result = curve_generate_key_pair(context, &key_pair);
if (result) {
SIGNAL_LOG_ERROR << "curve_generate_key_pair() failed";
return nullptr; //TODO: throw
}
return ec_key_pair_get_public(key_pair);
}
ProvisionInfo ProvisioningCipher::decrypt(textsecure::ProvisionEnvelope& provisionEnvelope) {
ProvisionInfo info;
std::string masterEphemeral = provisionEnvelope.publickey();
std::string message = provisionEnvelope.body();
if (message[0] != 0x1) {
SIGNAL_LOG_ERROR << "Bad version number on ProvisioningMessage";
return info; //TODO: throw
}
std::string iv = message.substr(1, 16);
std::string mac = message.substr(message.size() - 32);
std::string ivAndCiphertext = message.substr(0, message.size() - 32);
std::string ciphertext = message.substr(16 + 1, message.size() - 32);
SIGNAL_LOG_DEBUG << "mac: " << Base64::Encode(mac);
SIGNAL_LOG_DEBUG << "ivAndCiphertext: " << Base64::Encode(ivAndCiphertext);
SIGNAL_LOG_DEBUG << "ciphertext: " << Base64::Encode(ciphertext);
SIGNAL_LOG_DEBUG << "iv: " << Base64::Encode(iv);
/* Derive shared secret */
uint8_t *shared_secret = nullptr;
ec_private_key *private_key = ec_key_pair_get_private(key_pair);
ec_public_key *public_key = nullptr;
int result = curve_decode_point(&public_key, (const uint8_t *)masterEphemeral.c_str(), masterEphemeral.size(), context); //TODO: c_str() to data()
if (result) {
SIGNAL_LOG_ERROR << "Cannot decode public key";
return info; //TODO: throw
}
result = curve_calculate_agreement(&shared_secret, public_key, private_key);
if (result != 32) {
SIGNAL_LOG_ERROR << "Agreement failed";
return info; //TODO: throw
}
/* Derive 3 keys */
hkdf_context *hkdf_context;
uint8_t salt[32];
memset(salt, '\0', 32);
char infoText[] = "TextSecure Provisioning Message";
result = hkdf_create(&hkdf_context, 3, context);
if (result) {
SIGNAL_LOG_ERROR << "Key derivation failed";
return info; //TODO: throw
}
uint8_t *derived_keys = nullptr;
result = hkdf_derive_secrets(hkdf_context, &derived_keys, //TODO: use cryptoprovider
shared_secret, 32,
salt, 32,
(uint8_t *)infoText, 31,
96);
if (result != 96) {
SIGNAL_LOG_ERROR << "Key derivation failed";
return info; //TODO: throw
}
std::string derivedKeys = std::string((char *)derived_keys, 96);
std::string key0 = derivedKeys.substr(0, 32);
std::string key1 = derivedKeys.substr(32, 32);
std::string key2 = derivedKeys.substr(64, 32);
SIGNAL_LOG_DEBUG << "key0: " << Base64::Encode(key0);
SIGNAL_LOG_DEBUG << "key1: " << Base64::Encode(key1);
SIGNAL_LOG_DEBUG << "key2: " << Base64::Encode(key2);
/* Verify MAC and decrypt */
if (CryptoProvider::verifyMAC(ivAndCiphertext, key1, mac, 32)) {
std::string plaintext = CryptoProvider::decrypt(key0, ciphertext, iv);
textsecure::ProvisionMessage ProvisionMessage;
ProvisionMessage.ParseFromString(plaintext);
SIGNAL_LOG_DEBUG << "identityKeyPrivate size: " << ProvisionMessage.identitykeyprivate().size();
SIGNAL_LOG_DEBUG << "number: " << ProvisionMessage.number();
SIGNAL_LOG_DEBUG << "provisioningcode: " << ProvisionMessage.provisioningcode();
SIGNAL_LOG_DEBUG << "userAgent: " << ProvisionMessage.useragent();
ec_key_pair *_key_pair;
ec_public_key *public_key = nullptr;
ec_private_key *private_key = nullptr;
result = curve_decode_private_point(&private_key, (const uint8_t *)ProvisionMessage.identitykeyprivate().data(), ProvisionMessage.identitykeyprivate().size(), context);
result = curve_generate_public_key(&public_key, private_key);
ec_key_pair_create(&_key_pair, public_key, private_key);
info.identityKeyPair = _key_pair;
info.number = ProvisionMessage.number();
info.provisioningCode = ProvisionMessage.provisioningcode();
info.userAgent = ProvisionMessage.useragent();
return info;
}
SIGNAL_LOG_ERROR << "Message verification failed";
// if (derived_keys) {
// free(derived_keys);
// }
// SIGNAL_UNREF(hkdf_context);
//
return info;
}
| 30.503401
| 170
| 0.730375
|
yorickdewid
|
9ab1177dc03c9f6f2a1d23f0cb4f5347d31e75e6
| 838
|
hpp
|
C++
|
include/Shared/SecureRandomGenerator.hpp
|
Praetonus/Erewhon-Game
|
0327efc5ea80e1084ffb78191818607e9678dcb3
|
[
"MIT"
] | 1
|
2018-02-25T18:18:59.000Z
|
2018-02-25T18:18:59.000Z
|
include/Shared/SecureRandomGenerator.hpp
|
Praetonus/Erewhon-Game
|
0327efc5ea80e1084ffb78191818607e9678dcb3
|
[
"MIT"
] | null | null | null |
include/Shared/SecureRandomGenerator.hpp
|
Praetonus/Erewhon-Game
|
0327efc5ea80e1084ffb78191818607e9678dcb3
|
[
"MIT"
] | null | null | null |
// Copyright (C) 2017 Jérôme Leclercq
// This file is part of the "Erewhon Shared" project
// For conditions of distribution and use, see copyright notice in LICENSE
#pragma once
#ifndef EREWHON_SHARED_SECURE_RANDOM_GENERATOR_HPP
#define EREWHON_SHARED_SECURE_RANDOM_GENERATOR_HPP
#include <Nazara/Prerequisites.hpp>
#include <Shared/RandomGenerator.hpp>
#include <Shared/StdRandomGenerator.hpp>
#include <memory>
namespace ewn
{
class SecureRandomGenerator : public RandomGenerator
{
public:
SecureRandomGenerator();
~SecureRandomGenerator() = default;
bool operator()(void* ptr, std::size_t length) override;
private:
std::unique_ptr<RandomGenerator> m_secureGenerator;
StdRandomGenerator m_fallbackGenerator;
};
}
#include <Shared/RandomGenerator.inl>
#endif // EREWHON_SHARED_SECURE_RANDOM_GENERATOR_HPP
| 24.647059
| 74
| 0.791169
|
Praetonus
|
9ab5a593606dbad340bc4e354322fc60326629f2
| 3,736
|
hpp
|
C++
|
src/nes/Bus.hpp
|
clubycoder/nes_emu
|
b4dac31dc1bd7ebb04ecb0a8593a636567440e97
|
[
"MIT"
] | null | null | null |
src/nes/Bus.hpp
|
clubycoder/nes_emu
|
b4dac31dc1bd7ebb04ecb0a8593a636567440e97
|
[
"MIT"
] | null | null | null |
src/nes/Bus.hpp
|
clubycoder/nes_emu
|
b4dac31dc1bd7ebb04ecb0a8593a636567440e97
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
MIT License
Copyright (c) 2020 Chris Luby
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.
*******************************************************************************/
/*******************************************************************************
Emulation of the bus for the Nintendo Entertainment System that connects all of
the components
*******************************************************************************/
#pragma once
#include <cstdint>
#include <memory>
#include <chrono>
#include <nes/Component.hpp>
#include <nes/cpu/CPU2A03.hpp>
#include <nes/ram/Ram.hpp>
#include <nes/ppu/PPU2C02.hpp>
#include <nes/apu/APURP2A03.hpp>
#include <nes/controller/Controller.hpp>
#include <nes/cart/Cart.hpp>
namespace nes {
class Bus : public Component {
public:
Bus(
std::shared_ptr<nes::cpu::CPU2A03> cpu,
std::shared_ptr<nes::ram::Ram> ram,
std::shared_ptr<nes::ppu::PPU2C02> ppu,
std::shared_ptr<nes::apu::APURP2A03> apu,
std::shared_ptr<nes::controller::Controller> controller
)
: m_cpu(cpu)
, m_ram(ram)
, m_ppu(ppu)
, m_apu(apu)
, m_controller(controller) {
}
void reset() override;
void clock() override;
void load_cart(std::shared_ptr<nes::cart::Cart> cart);
const bool cpu_read(const uint16_t addr, uint8_t &data, const bool read_only = false) override;
const bool cpu_write(const uint16_t addr, const uint8_t data) override;
private:
static const uint16_t ADDR_RAM_BEGIN = 0x0000; static const uint16_t ADDR_RAM_END = 0x1FFF;
static const uint16_t ADDR_PPU_BEGIN = 0x2000; static const uint16_t ADDR_PPU_END = 0x3FFF;
static const uint16_t ADDR_APU_BEGIN = 0x4000; static const uint16_t ADDR_APU_END = 0x4013;
static const uint16_t ADDR_APU_STATUS = 0x4015; static const uint16_t ADDR_APU_FRAME_COUNTER = 0x4017;
static const uint16_t ADDR_DMA = 0x4014;
static const uint16_t ADDR_CONTROLLER_BEGIN = 0x4016; static const uint16_t ADDR_CONTROLLER_END = 0x4017;
std::shared_ptr<nes::cpu::CPU2A03> m_cpu;
std::shared_ptr<nes::ram::Ram> m_ram;
std::shared_ptr<nes::ppu::PPU2C02> m_ppu;
std::shared_ptr<nes::apu::APURP2A03> m_apu;
std::shared_ptr<nes::controller::Controller> m_controller;
std::shared_ptr<nes::cart::Cart> m_cart;
static constexpr uint32_t CLOCK_CHECK_AFTER_COUNT = 341 * 262; // Check roughly every screen render
static constexpr double CLOCK_CHECK_AFTER_EXPECTED = ((1.0 / 60.0) * 1000.0); // Roughly 60 fps or 21441960Hz
uint32_t m_clock_check_count;
std::chrono::time_point<std::chrono::high_resolution_clock> m_clock_check_last_timestamp;
};
} // nes
| 40.172043
| 113
| 0.679069
|
clubycoder
|
9ab787a76aabe3939baecda3e75cc51ceb500c25
| 13,834
|
cpp
|
C++
|
src/commlib/zcelib/zce_os_adapt_file.cpp
|
sailzeng/zcelib
|
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
|
[
"Apache-2.0"
] | 72
|
2015-01-08T05:01:48.000Z
|
2021-12-28T06:13:03.000Z
|
src/commlib/zcelib/zce_os_adapt_file.cpp
|
sailzeng/zcelib
|
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
|
[
"Apache-2.0"
] | 4
|
2016-01-18T12:24:59.000Z
|
2019-10-12T07:19:15.000Z
|
src/commlib/zcelib/zce_os_adapt_file.cpp
|
sailzeng/zcelib
|
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
|
[
"Apache-2.0"
] | 40
|
2015-01-26T06:49:18.000Z
|
2021-07-20T08:11:48.000Z
|
#include "zce_predefine.h"
#include "zce_log_logging.h"
#include "zce_os_adapt_predefine.h"
#include "zce_os_adapt_time.h"
#include "zce_os_adapt_error.h"
#include "zce_os_adapt_file.h"
//读取文件
ssize_t zce::read(ZCE_HANDLE file_handle, void *buf, size_t count)
{
//WINDOWS下,长度无法突破32位的,参数限制了ReadFileEx也一样,大概WINDOWS认为没人这样读取文件
//位置当然你是可以调整的
#if defined (ZCE_OS_WINDOWS)
DWORD ok_len;
BOOL ret_bool = ::ReadFile (file_handle,
buf,
static_cast<DWORD> (count),
&ok_len,
NULL);
if (ret_bool)
{
return (ssize_t) ok_len;
}
else
{
return -1;
}
#elif defined (ZCE_OS_LINUX)
return ::read (file_handle, buf, count);
#endif
}
//写如文件,WINDOWS下,长度无法突破32位的,当然有人需要写入4G数据吗?
//Windows下尽量向POSIX 靠拢了
ssize_t zce::write(ZCE_HANDLE file_handle, const void *buf, size_t count)
{
#if defined (ZCE_OS_WINDOWS)
DWORD ok_len;
BOOL ret_bool = ::WriteFile (file_handle,
buf,
static_cast<DWORD> (count),
&ok_len,
NULL);
if (ret_bool)
{
//注意zce Windows 下的write是有缓冲的,这个和Linux下的略有区别,
//如果需要立即看到,可以用FlushFileBuffers,我暂时看不出一定要这样做的必要,
//这个地方为了和POSIX统一,还是调用了这个函数
//另外一个方法是在CreateFile 时增加属性 FILE_FLAG_NO_BUFFERING and FILE_FLAG_WRITE_THROUGH
::FlushFileBuffers(file_handle);
return (ssize_t) ok_len;
}
else
{
return -1;
}
#elif defined (ZCE_OS_LINUX)
return ::write (file_handle, buf, count);
#endif
}
//截断文件
int zce::truncate(const char *filename, size_t offset)
{
#if defined (ZCE_OS_WINDOWS)
int ret = 0;
//打开文件,并且截断,最后关闭
ZCE_HANDLE file_handle = zce::open(filename, (O_CREAT | O_RDWR));
if ( ZCE_INVALID_HANDLE == file_handle)
{
return -1;
}
ret = zce::ftruncate(file_handle, offset);
if (0 != ret )
{
return ret;
}
zce::close(file_handle);
return 0;
#endif
#if defined (ZCE_OS_LINUX)
return ::truncate (filename, static_cast<off_t>(offset));
#endif
}
//截断文件,倒霉的是WINDOWS下又TMD 没有,用BOOST的又非要遵守他的参数规范,我蛋疼
//其实可以变长,呵呵。
//注意这儿的fd是WIN32 API OpenFile得到的函数,不是你用ISO函数打开的那个fd,
int zce::ftruncate(ZCE_HANDLE file_handle, size_t offset)
{
//Windows2000以前没有 SetFilePointerEx,我不是ACE,我不支持那么多屁事
#if defined (ZCE_OS_WINDOWS)
LARGE_INTEGER loff;
loff.QuadPart = offset;
BOOL bret = ::SetFilePointerEx (file_handle,
loff,
0,
FILE_BEGIN);
if (bret == FALSE)
{
return -1;
}
//linux ftruncate,后,吧指针放到了末尾
bret = ::SetEndOfFile (file_handle);
if (bret == FALSE)
{
return -1;
}
return 0;
//
#elif defined (ZCE_OS_LINUX)
return ::ftruncate (file_handle, static_cast<off_t>(offset));
#endif
}
//在文件内进行偏移
ssize_t zce::lseek(ZCE_HANDLE file_handle, ssize_t offset, int whence)
{
#if defined (ZCE_OS_WINDOWS)
//WINDOWS的lseek是不支持64位的,所以直接用API,完成工作,(后来有了_lseeki64)
DWORD dwmovemethod = FILE_BEGIN;
if (whence == SEEK_SET)
{
dwmovemethod = FILE_BEGIN;
}
else if (whence == SEEK_CUR)
{
dwmovemethod = FILE_CURRENT;
}
else if (whence == SEEK_END)
{
dwmovemethod = FILE_END;
}
else
{
assert(false);
}
LARGE_INTEGER loff;
loff.QuadPart = offset;
LARGE_INTEGER new_pos;
BOOL bret = ::SetFilePointerEx (file_handle,
loff,
&new_pos,
dwmovemethod);
if (bret == FALSE)
{
return -1;
}
return static_cast<ssize_t>(new_pos.QuadPart);
#elif defined (ZCE_OS_LINUX)
//
return ::lseek(file_handle,
static_cast<off_t> (offset),
whence);
#endif
}
//根据文件名称,判断文件的尺寸,如果文件不存在,打不开等,返回-1
int zce::filelen(const char *filename, size_t *file_size)
{
int ret = 0;
ZCE_HANDLE file_handle = zce::open(filename, (O_RDONLY));
if ( ZCE_INVALID_HANDLE == file_handle)
{
return -1;
}
ret = zce::filesize (file_handle, file_size);
zce::close (file_handle);
return ret;
}
int zce::filesize (ZCE_HANDLE file_handle, size_t *file_size)
{
#if defined (ZCE_OS_WINDOWS)
LARGE_INTEGER size;
BOOL ret_bool = ::GetFileSizeEx (file_handle, &size);
if (!ret_bool)
{
return -1;
}
//32位平台上可能丢长度,但是我就考虑64位系统,你才会突破4G把
*file_size = static_cast<size_t> (size.QuadPart);
return 0;
//
#elif defined (ZCE_OS_LINUX)
struct stat sb;
int ret = ::fstat(file_handle, &sb);
if (ret != 0 )
{
return ret;
}
*file_size = sb.st_size;
return 0;
#endif
}
//我曾经很自以为是的认为ACE很土鳖,为什么不直接用open函数,然后用_get_osfhandle转换成HANDLE就可以了。
//关闭的时候用_open_osfhandle转换回来就OK了,但其实发现土鳖的是我,
//我完全错误理解了_open_osfhandle函数,这也可能解释了原来pascal原来遇到的问题close触发断言的问题。
//一切都不是RP问题,还是写错了代码。感谢derrickhu和sasukeliu两位,一个隐藏的比较深刻的bug
//为什么要提供这个API呢,因为WINDOWS平台大部分都是采用HANDLE处理的
ZCE_HANDLE zce::open (const char *filename,
int open_mode,
mode_t perms)
{
//Windows平台
#if defined (ZCE_OS_WINDOWS)
//将各种LINUX的参数转换成Windows API的参数
DWORD access = GENERIC_READ;
if (ZCE_BIT_IS_SET (open_mode, O_WRONLY))
{
//如果仅仅只能写
access = GENERIC_WRITE;
}
else if (ZCE_BIT_IS_SET (open_mode, O_RDWR))
{
access = GENERIC_READ | GENERIC_WRITE;
}
DWORD creation = OPEN_EXISTING;
if ( ZCE_BIT_IS_SET (open_mode, O_CREAT) && ZCE_BIT_IS_SET (open_mode, O_EXCL))
{
creation = CREATE_NEW;
}
else if ( ZCE_BIT_IS_SET (open_mode, O_CREAT) && ZCE_BIT_IS_SET (open_mode, O_TRUNC) )
{
creation = CREATE_ALWAYS;
}
else if (ZCE_BIT_IS_SET (open_mode, O_CREAT))
{
creation = OPEN_ALWAYS;
}
else if (ZCE_BIT_IS_SET (open_mode, O_TRUNC))
{
creation = TRUNCATE_EXISTING;
}
DWORD shared_mode = 0;
if ( ZCE_BIT_IS_SET(perms, S_IRGRP)
|| ZCE_BIT_IS_SET(perms, S_IROTH)
|| ZCE_BIT_IS_SET(perms, S_IWUSR))
{
shared_mode |= FILE_SHARE_READ;
}
if ( ZCE_BIT_IS_SET(perms, S_IWGRP)
|| ZCE_BIT_IS_SET(perms, S_IWOTH)
|| ZCE_BIT_IS_SET(perms, S_IWUSR))
{
shared_mode |= FILE_SHARE_WRITE;
shared_mode |= FILE_SHARE_DELETE;
}
ZCE_HANDLE openfile_handle = ZCE_INVALID_HANDLE;
//ACE的代码在这段用一个多线程的互斥保护,
//因为CreateFileA并不能同时将文件的指针移动到末尾,所以(O_APPEND)这是一个两步操作(先CreateFileA,后SetFilePointerEx),
//ACE担心有特殊情况?多线程创建还是?他的没有注释说明这个问题,我暂时不去做保护,
//CRITICAL_SECTION fileopen_mutex;
////VISTAT后没有这个异常了
//__try
//{
// ::InitializeCriticalSection (&fileopen_mutex);
//}
//__except (EXCEPTION_EXECUTE_HANDLER)
//{
// errno = ENOMEM;
// return ZCE_INVALID_HANDLE;
//}
openfile_handle = ::CreateFileA (filename,
access,
shared_mode,
NULL,
creation,
FILE_ATTRIBUTE_NORMAL,
0);
//如果打开的文件句柄是无效的
if (openfile_handle != ZCE_INVALID_HANDLE && ZCE_BIT_IS_SET (open_mode, O_APPEND))
{
LARGE_INTEGER distance_to_move, new_file_pointer;
distance_to_move.QuadPart = 0;
new_file_pointer.QuadPart = 0;
BOOL bret = ::SetFilePointerEx (openfile_handle,
distance_to_move,
&new_file_pointer,
FILE_END);
if (FALSE == bret)
{
::CloseHandle(openfile_handle);
openfile_handle = ZCE_INVALID_HANDLE;
}
}
//对应上面的临界区保护
//::DeleteCriticalSection (&fileopen_mutex);
return openfile_handle;
#elif defined (ZCE_OS_LINUX)
return ::open (filename, open_mode, perms);
#endif
}
//关闭一个文件
int zce::close (ZCE_HANDLE handle)
{
//
#if defined (ZCE_OS_WINDOWS)
BOOL bret = ::CloseHandle(handle);
if (bret == TRUE)
{
return 0;
}
else
{
return -1;
}
#elif defined (ZCE_OS_LINUX)
return ::close (handle);
#endif
}
//用模版名称建立并且打开一个临时文件,
ZCE_HANDLE zce::mkstemp(char *template_name)
{
#if defined (ZCE_OS_WINDOWS)
char *tmp_filename = _mktemp(template_name);
return zce::open(tmp_filename, ZCE_DEFAULT_FILE_PERMS);
#elif defined (ZCE_OS_LINUX)
return ::mkstemp(template_name);
#endif
}
//通过文件名称得到文件的stat信息,你可以认为zce_os_stat就是stat,只是在WINDOWS下stat64,主要是为了长文件考虑的
int zce::stat(const char *path, zce_os_stat *file_stat)
{
#if defined (ZCE_OS_WINDOWS)
return ::_stat64(path, file_stat);
#elif defined (ZCE_OS_LINUX)
return ::stat(path, file_stat);
#endif
}
//通过文件的句柄得到文件的stat信息
int zce::fstat(ZCE_HANDLE file_handle, zce_os_stat *file_stat)
{
#if defined (ZCE_OS_WINDOWS)
//这个实现比较痛苦,但也没有办法,其他方法(比如用_open_osfhandle)都会偷鸡不成,反舍一把米
BOOL ret_bool = FALSE;
BY_HANDLE_FILE_INFORMATION file_info;
ret_bool = ::GetFileInformationByHandle(file_handle,
&file_info);
if (!ret_bool)
{
return -1;
}
//转换时间
timeval tv_ct_time = zce::make_timeval(&file_info.ftCreationTime);
timeval tv_ac_time = zce::make_timeval(&file_info.ftLastAccessTime);
timeval tv_wt_time = zce::make_timeval(&file_info.ftLastWriteTime);
LARGE_INTEGER file_size;
file_size.HighPart = file_info.nFileSizeHigh;
file_size.LowPart = file_info.nFileSizeLow;
//_S_IFDIR,
memset(file_stat, 0, sizeof(zce_os_stat));
file_stat->st_uid = 0;
file_stat->st_gid = 0;
file_stat->st_size = file_size.QuadPart;
//得到几个时间
//注意st_ctime这儿呀,这儿的LINUX下和Windows是有些不一样的,st_ctime在LINUX下是状态最后改变时间,而在WINDOWS下是创建时间
file_stat->st_ctime = tv_ct_time.tv_sec;
file_stat->st_mtime = tv_wt_time.tv_sec;
file_stat->st_atime = tv_ac_time.tv_sec;
//检查是文件还是目录
file_stat->st_mode = 0;
if (file_info.dwFileAttributes & FILE_ATTRIBUTE_ARCHIVE )
{
file_stat->st_mode = S_IFREG;
if (file_info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY )
{
file_stat->st_mode = S_IFDIR;
}
}
return 0;
#elif defined (ZCE_OS_LINUX)
return ::fstat(file_handle, file_stat);
#endif
}
//路径是否是一个目录,如果是返回TRUE,如果不是返回FALSE
bool zce::is_directory(const char *path_name)
{
int ret = 0;
zce_os_stat file_stat;
ret = zce::stat(path_name, &file_stat);
if (0 != ret)
{
return false;
}
//如果有目录属性,则true
if (file_stat.st_mode & S_IFDIR )
{
return true;
}
else
{
return false;
}
}
//删除文件
int zce::unlink(const char *filename )
{
#if defined (ZCE_OS_WINDOWS)
return ::_unlink(filename);
#elif defined (ZCE_OS_LINUX)
return ::unlink(filename);
#endif
}
//
mode_t zce::umask (mode_t cmask)
{
#if defined (ZCE_OS_WINDOWS)
return ::_umask(cmask);
#elif defined (ZCE_OS_LINUX)
return ::umask(cmask);
#endif
}
//检查文件是否OK,吼吼
//mode 两个平台都支持F_OK,R_OK,W_OK,R_OK|W_OK,X_OK参数LINUX支持,WIN不支持
int zce::access(const char *pathname, int mode)
{
#if defined (ZCE_OS_WINDOWS)
return ::_access_s(pathname, mode);
#elif defined (ZCE_OS_LINUX)
return ::access(pathname, mode);
#endif
}
//--------------------------------------------------------------------------------------------------
//非标准函数
//用只读方式读取一个文件的内容,返回的buffer最后填充'\0',buf_len >= 1
int zce::read_file_data(const char *filename,
char *buffer,
size_t buf_len,
size_t *read_len,
size_t offset)
{
//参数检查
ZCE_ASSERT(filename && buffer && buf_len >= 1);
//打开文件
ZCE_HANDLE fd = zce::open(filename, O_RDONLY);
if (ZCE_INVALID_HANDLE == fd)
{
ZCE_LOG(RS_ERROR, "open file [%s] fail ,error =%d", filename, zce::last_error());
return -1;
}
zce::lseek(fd,static_cast<ssize_t>(offset),SEEK_SET);
//读取内容
ssize_t len = zce::read(fd, buffer, buf_len - 1);
zce::close(fd);
if (len < 0)
{
ZCE_LOG(RS_ERROR, "read file [%s] fail ,error =%d", filename, zce::last_error());
return -1;
}
buffer[len] = 0;
*read_len = len;
return 0;
}
//读取文件的全部数据,
std::pair<int,std::shared_ptr<char>> zce::read_file_all(const char* filename,
size_t* file_len,
size_t offset)
{
int ret=-1;
std::shared_ptr<char> null_ptr;
//打开文件
ZCE_HANDLE fd=zce::open(filename,O_RDONLY);
if(ZCE_INVALID_HANDLE==fd)
{
ZCE_LOG(RS_ERROR,"open file [%s] fail ,error =%d",filename,zce::last_error());
return std::make_pair(ret,null_ptr);
}
*file_len = zce::lseek(fd,0,SEEK_END);
if(static_cast<size_t>(-1) == *file_len)
{
zce::close(fd);
ZCE_LOG(RS_ERROR,"open file [%s] fail ,error =%d",filename,zce::last_error());
return std::make_pair(ret,null_ptr);
}
std::shared_ptr<char> ptr(new char [*file_len+1],std::default_delete<char []>());
*(ptr.get() +*file_len)='\0';
//调整偏移,读取内容
zce::lseek(fd,static_cast<ssize_t>(offset),SEEK_SET);
ssize_t len=zce::read(fd,ptr.get(),*file_len);
zce::close(fd);
if(len<0)
{
ZCE_LOG(RS_ERROR,"read file [%s] fail ,error =%d",filename,zce::last_error());
return std::make_pair(ret,null_ptr);
}
ret=0;
return std::make_pair(ret,ptr);
}
| 23.851724
| 100
| 0.596791
|
sailzeng
|
9abde0e1a533551f721424fa5fc2b5863565cf40
| 3,076
|
hpp
|
C++
|
include/imshowExtension.hpp
|
norishigefukushima/OpenCP
|
63090131ec975e834f85b04e84ec29b2893845b2
|
[
"BSD-3-Clause"
] | 137
|
2015-03-27T07:11:19.000Z
|
2022-03-30T05:58:22.000Z
|
include/imshowExtension.hpp
|
Pandinosaurus/OpenCP
|
a5234ed531c610d7944fa14d42f7320442ea34a1
|
[
"BSD-3-Clause"
] | 2
|
2016-05-18T06:33:16.000Z
|
2016-07-11T17:39:17.000Z
|
include/imshowExtension.hpp
|
Pandinosaurus/OpenCP
|
a5234ed531c610d7944fa14d42f7320442ea34a1
|
[
"BSD-3-Clause"
] | 43
|
2015-02-20T15:34:25.000Z
|
2022-01-27T14:59:37.000Z
|
#pragma once
#include "common.hpp"
#include "plot.hpp"
namespace cp
{
//normalize image and then cast to 8U and imshow. NORM_INF(32) scale 0-max
CP_EXPORT void imshowNormalize(std::string wname, cv::InputArray src, const int norm_type = cv::NORM_MINMAX);
//scaling ax+b, cast to 8U, and then imshow
CP_EXPORT void imshowScale(std::string name, cv::InputArray src, const double alpha = 1.0, const double beta = 0.0);
//scaling a|x|+b, cast to 8U, and then imshow
CP_EXPORT void imshowScaleAbs(std::string name, cv::InputArray src, const double alpha = 1.0, const double beta = 0.0);
//resize image, cast 8U (optional), and then imshow
CP_EXPORT void imshowResize(std::string name, cv::InputArray src, const cv::Size dsize, const double fx = 0.0, const double fy = 0.0, const int interpolation = cv::INTER_NEAREST, bool isCast8U = true);
//3 times count down
CP_EXPORT void imshowCountDown(std::string wname, cv::InputArray src, const int waitTime = 1000, cv::Scalar color = cv::Scalar::all(0), const int pointSize = 128, std::string fontName = "Consolas");
class CP_EXPORT StackImage
{
std::vector<cv::Mat> stack;
std::string wname;
int num_stack = 0;
int stack_max = 0;
public:
StackImage(std::string window_name="image stack");
void setWindowName(std::string window_name);
void overwrite(cv::Mat& src);
void push(cv::Mat& src);
void show();
void show(cv::Mat& src);
};
enum DRAW_SIGNAL_CHANNEL
{
B,
G,
R,
Y
};
CP_EXPORT void drawSignalX(cv::Mat& src1, cv::Mat& src2, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size outputImageSize, int line_height, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y
CP_EXPORT void drawSignalX(cv::InputArrayOfArrays src, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size outputImageSize, int analysisLineHeight, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y
CP_EXPORT void drawSignalY(cv::Mat& src1, cv::Mat& src2, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size size, int line_height, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y
CP_EXPORT void drawSignalY(cv::Mat& src, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size size, int line_height, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y
CP_EXPORT void drawSignalY(std::vector<cv::Mat>& src, DRAW_SIGNAL_CHANNEL color, cv::Mat& dest, cv::Size size, int line_height, int shiftx, int shiftvalue, int rangex, int rangevalue, int linetype = cp::Plot::LINEAR);// color 0:B, 1:G, 2:R, 3:Y
CP_EXPORT void guiAnalysisImage(cv::InputArray src);
CP_EXPORT void guiAnalysisCompare(cv::Mat& src1, cv::Mat& src2);
CP_EXPORT void imshowAnalysis(std::string winname, cv::Mat& src);
CP_EXPORT void imshowAnalysis(std::string winname, std::vector<cv::Mat>& s);
CP_EXPORT void imshowAnalysisCompare(std::string winname, cv::Mat& src1, cv::Mat& src2);
}
| 53.964912
| 264
| 0.723992
|
norishigefukushima
|
9ac2befbec92d17e178d0f4b36cde20082d4b268
| 22,941
|
cpp
|
C++
|
src/game/server/tf/lfe_population_manager.cpp
|
bluedogz162/tf_coop_extended_custom
|
0212744ebef4f74c4e0047320d9da7d8571a8ee0
|
[
"Unlicense"
] | 4
|
2020-04-24T22:20:34.000Z
|
2022-01-10T23:16:53.000Z
|
src/game/server/tf/lfe_population_manager.cpp
|
bluedogz162/tf_coop_extended_custom
|
0212744ebef4f74c4e0047320d9da7d8571a8ee0
|
[
"Unlicense"
] | 1
|
2020-05-01T19:13:25.000Z
|
2020-05-02T07:01:45.000Z
|
src/game/server/tf/lfe_population_manager.cpp
|
bluedogz162/tf_coop_extended_custom
|
0212744ebef4f74c4e0047320d9da7d8571a8ee0
|
[
"Unlicense"
] | 3
|
2020-04-24T22:20:36.000Z
|
2022-02-21T21:48:05.000Z
|
//============== Copyright LFE-TEAM Not All rights reserved. =================//
//
// Purpose: The system for handling npc population in horde.
//
//=============================================================================//
#include "cbase.h"
#include "lfe_population_manager.h"
#include "lfe_populator.h"
#include "igamesystem.h"
#include "in_buttons.h"
#include "engine/IEngineSound.h"
#include "soundenvelope.h"
#include "utldict.h"
#include "ai_basenpc.h"
#include "tf_gamerules.h"
#include "nav_mesh/tf_nav_mesh.h"
#include "nav_mesh/tf_nav_area.h"
#include "tf_team.h"
#include "ai_navigator.h"
#include "ai_network.h"
#include "ai_node.h"
#include "eventqueue.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
ConVar lfe_horde_debug( "lfe_horde_debug", "0", FCVAR_REPLICATED, "Display debug in horde mode." );
void CC_Horde_ForceStart( void )
{
if ( TFGameRules() )
TFGameRules()->State_Transition( GR_STATE_RND_RUNNING );
if ( LFPopulationManager() )
LFPopulationManager()->StartCurrentWave();
}
static ConCommand lfe_horde_force_start("lfe_horde_force_start", CC_Horde_ForceStart, "Force.", FCVAR_GAMEDLL | FCVAR_CHEAT);
CLFPopulationManager *g_LFEPopManager = nullptr;
//-----------------------------------------------------------------------------
// Horde Mode
//-----------------------------------------------------------------------------
class CTFLogicHorde : public CPointEntity
{
public:
DECLARE_CLASS( CTFLogicHorde, CPointEntity );
DECLARE_DATADESC();
CTFLogicHorde();
~CTFLogicHorde();
void Spawn( void );
};
BEGIN_DATADESC( CTFLogicHorde )
END_DATADESC()
LINK_ENTITY_TO_CLASS( lfe_logic_horde, CTFLogicHorde );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CTFLogicHorde::CTFLogicHorde()
{
}
CTFLogicHorde::~CTFLogicHorde()
{
if ( LFPopulationManager() )
delete LFPopulationManager();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CTFLogicHorde::Spawn( void )
{
CLFPopulationManager *popmanager = new CLFPopulationManager;
if ( popmanager )
g_LFEPopManager = popmanager;
BaseClass::Spawn();
}
BEGIN_DATADESC( CLFPopulationManager )
END_DATADESC()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CLFPopulationManager::CLFPopulationManager()
{
m_bFinale = false;
m_pPopFile = NULL;
m_bIsPaused = false;
m_bIsPaused = false;
ListenForGameEvent( "npc_death" );
}
CLFPopulationManager::~CLFPopulationManager()
{
if ( m_pPopFile )
m_pPopFile->deleteThis();
m_Waves.RemoveAll();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLFPopulationManager::FireGameEvent( IGameEvent *event )
{
if ( FStrEq( event->GetName(), "npc_death" ) )
{
CAI_BaseNPC *pVictim = dynamic_cast<CAI_BaseNPC *>( UTIL_EntityByIndex( event->GetInt( "victim_index" ) ) );
if ( pVictim )
{
FOR_EACH_VEC( m_Waves, i )
{
CWave *wave = m_Waves[i];
if ( wave != nullptr )
wave->OnMemberKilled( pVictim );
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLFPopulationManager::GameRulesThink()
{
FOR_EACH_VEC( m_Waves, i )
{
CWave *wave = m_Waves[i];
if ( wave != nullptr )
wave->Update();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLFPopulationManager::StartCurrentWave( void )
{
FOR_EACH_VEC( m_Waves, i )
{
CWave *wave = m_Waves[i];
if ( wave != nullptr )
wave->ForceReset();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLFPopulationManager::Initialize( void )
{
m_pPopFile = new KeyValues( "WaveSchedule" );
if ( !m_pPopFile->LoadFromFile( filesystem, GetPopulationFilename(), "MOD" ) )
{
ConDColorMsg( Color( 77, 116, 85, 255 ), "[CLFPopulationManager] Could not load popfile '%s'. \n", GetPopulationFilename() );
m_pPopFile->deleteThis();
m_pPopFile = NULL;
return;
}
ConColorMsg( Color( 77, 116, 85, 255 ), "[CLFPopulationManager] Loading data from %s. \n", GetPopulationFilename() );
if ( !Q_strcmp( m_pPopFile->GetName(), "RespawnWaveTime" ) )
{
engine->ServerCommand( CFmtStr( "mp_respawnwavetime %f\n", m_pPopFile->GetFloat() ) );
}
FOR_EACH_SUBKEY( m_pPopFile, subkey )
{
if ( V_stricmp( subkey->GetName(), "Wave" ) == 0 )
{
CWave *wave = new CWave( this );
if ( !wave->Parse( subkey ) )
{
Warning( "Error reading Wave definition\n" );
return;
}
m_Waves.AddToTail( wave );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Called when a new round is being initialized
//-----------------------------------------------------------------------------
void CLFPopulationManager::SetupOnRoundStart( void )
{
for ( int i = FIRST_GAME_TEAM; i < MAX_TEAMS; i++ )
{
if ( TFGameRules()->IsHordeMode() )
{
TFGameRules()->BroadcastSound( i, "music.mvm_class_select" );
}
}
Initialize();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CLFPopulationManager::SetupTimerExpired( void )
{
StartCurrentWave();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CLFPopulationManager::GetPopulationFilename( void )
{
const char szFullName = NULL;
Q_snprintf( szFullName,sizeof(szFullName), "scripts/population/%s.pop", STRING( gpGlobals->mapname ) );
return szFullName;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CSpawnLocation::CSpawnLocation()
{
m_iWhere = Where::TEAMSPAWN;
}
bool CSpawnLocation::Parse( KeyValues *kv )
{
return true;
}
SpawnResult CSpawnLocation::FindSpawnLocation( Vector& vec ) const
{
return SPAWN_NORMAL;
}
CTFNavArea *CSpawnLocation::SelectSpawnArea() const
{
return NULL;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
IPopulator::IPopulator( CLFPopulationManager *popmgr )
: m_PopMgr( popmgr )
{
}
IPopulator::~IPopulator()
{
if ( m_Spawner != nullptr )
delete m_Spawner;
}
void IPopulator::PostInitialize()
{
}
void IPopulator::Update()
{
}
void IPopulator::UnpauseSpawning()
{
}
void IPopulator::OnMemberKilled( CBaseEntity *pMember )
{
}
/*bool IPopulator::HasEventChangeAttributes(const char *name) const
{
if (this->m_Spawner == nullptr) {
return false;
}
return this->m_Spawner->HasEventChangeAttributes(name);
}*/
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CWave::CWave( CLFPopulationManager *popmgr )
: IPopulator( popmgr )
{
m_iTotalCurrency = 0;
}
CWave::~CWave()
{
}
bool CWave::Parse( KeyValues *kv )
{
FOR_EACH_SUBKEY( kv, subkey )
{
if ( V_stricmp(subkey->GetName(), "WaveSpawn") == 0)
{
CWaveSpawnPopulator *wavespawn = new CWaveSpawnPopulator( m_PopMgr );
if ( wavespawn )
{
if ( !wavespawn->Parse( subkey ) )
{
Warning("Error reading WaveSpawn definition\n");
return false;
}
m_WaveSpawns.AddToTail( wavespawn );
m_iTotalCurrency += wavespawn->m_iTotalCurrency;
wavespawn->m_Wave = this;
}
}
else if ( V_stricmp(subkey->GetName(), "Sound" ) == 0)
{
m_strSound.sprintf("%s", subkey->GetString());
}
else if ( V_stricmp( subkey->GetName(), "Description" ) == 0 )
{
m_strDescription.sprintf( "%s", subkey->GetString() );
}
else if ( V_stricmp( subkey->GetName(), "WaitWhenDone" ) == 0 )
{
m_flWaitWhenDone = subkey->GetFloat();
}
else if ( V_stricmp( subkey->GetName(), "Checkpoint" ) == 0 )
{
/* doesn't do anything! */
}
else if ( V_stricmp( subkey->GetName(), "StartWaveOutput" ) == 0 )
{
m_StartWaveOutput = ParseEvent( subkey );
}
else if ( V_stricmp(subkey->GetName(), "DoneOutput" ) == 0 )
{
m_DoneOutput = ParseEvent( subkey );
}
else if ( V_stricmp( subkey->GetName(), "InitWaveOutput" ) == 0 )
{
m_InitWaveOutput = ParseEvent( subkey );
}
else
{
Warning( "[CWave] Unknown attribute '%s' in Wave definition.\n", subkey->GetName() );
}
}
return true;
}
void CWave::Update()
{
if ( TFGameRules() == nullptr )
return;
gamerules_roundstate_t roundstate = TFGameRules()->State_Get();
if ( roundstate == GR_STATE_RND_RUNNING )
{
ActiveWaveUpdate();
}
else if ( roundstate == GR_STATE_TEAM_WIN || roundstate == GR_STATE_BETWEEN_RNDS )
{
WaveIntermissionUpdate();
}
}
void CWave::OnMemberKilled( CBaseEntity *pMember )
{
FOR_EACH_VEC( m_WaveSpawns, i )
{
m_WaveSpawns[i]->OnMemberKilled( pMember );
}
}
/*bool CWave::HasEventChangeAttributes(const char *name) const
{
FOR_EACH_VEC( m_WaveSpawns, i )
{
if ( m_WaveSpawns[i]->HasEventChangeAttributes(name) )
{
return true;
}
}
return false;
}*/
bool CWave::IsDoneWithNonSupportWaves()
{
FOR_EACH_VEC( m_WaveSpawns, i )
{
CWaveSpawnPopulator *wavespawn = m_WaveSpawns[i];
if ( wavespawn != nullptr && !wavespawn->m_bSupport && wavespawn->m_iState != CWaveSpawnPopulator::InternalStateType::DONE )
return false;
}
return true;
}
void CWave::ForceFinish()
{
FOR_EACH_VEC( m_WaveSpawns, i )
{
m_WaveSpawns[i]->ForceFinish();
}
}
void CWave::ForceReset()
{
FOR_EACH_VEC( m_WaveSpawns, i )
{
CWaveSpawnPopulator *wavespawn = m_WaveSpawns[i];
if ( wavespawn != nullptr )
{
wavespawn->m_iState = CWaveSpawnPopulator::InternalStateType::INITIAL;
wavespawn->m_iCurrencyLeft = wavespawn->m_iTotalCurrency;
wavespawn->m_iCountNotYetSpawned = wavespawn->m_iTotalCount;
}
}
}
CWaveSpawnPopulator *CWave::FindWaveSpawnPopulator( const char *name )
{
FOR_EACH_VEC( m_WaveSpawns, i )
{
CWaveSpawnPopulator *wavespawn = m_WaveSpawns[i];
if ( wavespawn != nullptr )
{
if ( V_stricmp( wavespawn->m_strName.Get(), name ) == 0 )
{
return wavespawn;
}
}
}
return nullptr;
}
void CWave::ActiveWaveUpdate()
{
FOR_EACH_VEC( m_WaveSpawns, i )
{
CWaveSpawnPopulator *wavespawn = m_WaveSpawns[i];
if ( wavespawn != nullptr )
wavespawn->Update();
}
}
void CWave::WaveCompleteUpdate()
{
}
void CWave::WaveIntermissionUpdate()
{
}
CWaveSpawnPopulator::CWaveSpawnPopulator( CLFPopulationManager *popmgr )
: IPopulator( popmgr )
{
m_iTotalCurrency = 0;
}
CWaveSpawnPopulator::~CWaveSpawnPopulator()
{
}
bool CWaveSpawnPopulator::Parse( KeyValues *kv )
{
/*KeyValues *kv_tref = kv->FindKey( "Template" );
if (k v_tref != nullptr )
{
const char *tname = kv_tref->GetString();
KeyValues *kv_timpl = m_PopMgr->m_kvTemplates->FindKey( tname );
if ( kv_timpl != nullptr )
{
if ( !Parse( kv_timpl ) )
return false;
}
else
{
Warning( "Unknown Template '%s' in WaveSpawn definition\n", tname );
}
}*/
FOR_EACH_SUBKEY( kv, subkey )
{
const char *name = subkey->GetName();
if ( strlen(name) <= 0 )
continue;
if ( m_Where.Parse( subkey ) )
continue;
/*if ( V_stricmp(name, "Template" ) == 0 )
continue;*/
if ( V_stricmp( name, "TotalCount" ) == 0 )
{
m_iTotalCount = subkey->GetInt();
}
else if ( V_stricmp( name, "MaxActive" ) == 0 )
{
m_iMaxActive = subkey->GetInt();
}
else if ( V_stricmp( name, "SpawnCount" ) == 0 )
{
m_iSpawnCount = subkey->GetInt();
}
else if ( V_stricmp( name, "WaitBeforeStarting" ) == 0 )
{
m_flWaitBeforeStarting = subkey->GetFloat();
}
else if ( V_stricmp( name, "WaitBetweenSpawns" ) == 0 )
{
if ( m_flWaitBetweenSpawns == 0.0f || !m_bWaitBetweenSpawnsAfterDeath )
{
m_flWaitBetweenSpawns = subkey->GetFloat();
}
else
{
Warning("Already specified WaitBetweenSpawnsAfterDeath time, ""WaitBetweenSpawns won't be used\n");
continue;
}
}
else if ( V_stricmp( name, "WaitBetweenSpawnsAfterDeath" ) == 0 )
{
if ( m_flWaitBetweenSpawns == 0.0f )
{
m_bWaitBetweenSpawnsAfterDeath = true;
m_flWaitBetweenSpawns = subkey->GetFloat();
}
else
{
Warning( "Already specified WaitBetweenSpawns time, ""WaitBetweenSpawnsAfterDeath won't be used\n" );
continue;
}
}
else if ( V_stricmp( name, "StartWaveWarningSound" ) == 0 )
{
m_strStartWaveWarningSound.sprintf( "%s",subkey->GetString() );
}
else if ( V_stricmp( name, "StartWaveOutput" ) == 0 )
{
m_StartWaveOutput = ParseEvent( subkey );
}
else if (V_stricmp( name, "FirstSpawnWarningSound" ) == 0 )
{
m_strFirstSpawnWarningSound.sprintf( "%s", subkey->GetString() );
}
else if ( V_stricmp( name, "FirstSpawnOutput" ) == 0 )
{
m_FirstSpawnOutput = ParseEvent(subkey);
}
else if ( V_stricmp( name, "LastSpawnWarningSound" ) == 0 )
{
m_strLastSpawnWarningSound.sprintf( "%s", subkey->GetString() );
}
else if ( V_stricmp( name, "LastSpawnOutput") == 0 )
{
m_LastSpawnOutput = ParseEvent( subkey );
}
else if ( V_stricmp( name, "DoneWarningSound" ) == 0 )
{
m_strDoneWarningSound.sprintf( "%s",subkey->GetString() );
}
else if ( V_stricmp( name, "DoneOutput" ) == 0 )
{
m_DoneOutput = ParseEvent( subkey );
}
else if ( V_stricmp( name, "TotalCurrency" ) == 0 )
{
m_iTotalCurrency = subkey->GetInt();
}
else if ( V_stricmp( name, "Name" ) == 0 )
{
m_strName = subkey->GetString();
}
else if ( V_stricmp( name, "WaitForAllSpawned" ) == 0 )
{
m_strWaitForAllSpawned = subkey->GetString();
}
else if ( V_stricmp( name, "WaitForAllDead" ) == 0 )
{
m_strWaitForAllDead = subkey->GetString();
}
else if ( V_stricmp( name, "Support" ) == 0 )
{
m_bSupport = true;
m_bSupportLimited = ( V_stricmp(subkey->GetString(), "Limited" ) == 0 );
}
else if ( V_stricmp( name, "RandomSpawn" ) == 0 )
{
m_bRandomSpawn = subkey->GetBool();
}
else
{
m_Spawner = IPopulationSpawner::ParseSpawner( this, subkey );
if ( m_Spawner == nullptr)
{
Warning( "Unknown attribute '%s' in WaveSpawn definition.\n", name );
}
}
m_iCountNotYetSpawned = m_iTotalCount;
m_iCurrencyLeft = m_iTotalCurrency;
}
return true;
}
void CWaveSpawnPopulator::Update()
{
switch ( m_iState )
{
case InternalStateType::INITIAL:
m_ctSpawnDelay.Start( m_flWaitBeforeStarting );
SetState( InternalStateType::PRE_SPAWN_DELAY );
break;
case InternalStateType::PRE_SPAWN_DELAY:
if ( m_ctSpawnDelay.IsElapsed() )
{
m_iCountSpawned = 0;
m_iCountToSpawn = 0;
SetState( InternalStateType::SPAWNING );
}
break;
case InternalStateType::SPAWNING:
{
if ( !m_ctSpawnDelay.IsElapsed() || g_LFEPopManager->m_bIsPaused )
break;
if ( m_Spawner == nullptr )
{
Warning( "Invalid spawner\n" );
SetState( InternalStateType::DONE );
break;
}
int num_active = 0;
FOR_EACH_VEC( m_ActiveBots, i )
{
CBaseEntity *ent = m_ActiveBots[i];
if ( ent != nullptr && ent->IsAlive() )
{
++num_active;
}
}
if ( m_bWaitBetweenSpawnsAfterDeath )
{
if ( num_active != 0)
break;
if ( m_iSpawnResult != SPAWN_FAIL )
{
m_iSpawnResult = SPAWN_FAIL;
float wait_between_spawns = m_flWaitBetweenSpawns;
if ( wait_between_spawns != 0.0f )
m_ctSpawnDelay.Start( wait_between_spawns );
break;
}
}
int max_active = m_iMaxActive;
if ( num_active >= max_active )
break;
if ( m_iCountToSpawn <= 0 )
{
if ( num_active + m_iSpawnCount > max_active )
break;
m_iCountToSpawn = m_iSpawnCount;
}
Vector vec_spawn = vec3_origin;
CBaseEntity *pTeamSpawn = gEntList.FindEntityByClassname( NULL, "info_player_teamspawn" );
if ( pTeamSpawn )
vec_spawn = pTeamSpawn->GetAbsOrigin();
/*if ( m_Spawner->IsWhereRequired() )
{
if ( m_iSpawnResult != SPAWN_NORMAL )
{
m_iSpawnResult = m_Where.FindSpawnLocation( m_vecSpawn );
if (m_iSpawnResult == SPAWN_FAIL)
{
break;
}
}
vec_spawn = m_vecSpawn;
if ( m_bRandomSpawn )
{
m_iSpawnResult = SPAWN_FAIL;
}
}*/
CUtlVector<CHandle<CBaseEntity>> spawned;
if ( m_Spawner->Spawn( vec_spawn, &spawned ) == 0 )
{
m_ctSpawnDelay.Start( 1.0f );
break;
}
FOR_EACH_VEC( spawned, i )
{
CBaseEntity *ent = spawned[i];
CAI_BaseNPC *bot = dynamic_cast<CAI_BaseNPC*>(ent);
if ( bot == nullptr )
continue;
//bot->m_nCurrency = 0;
}
int num_spawned = spawned.Count();
m_iCountSpawned += num_spawned;
int count_to_spawn = m_iCountToSpawn;
if ( num_spawned > count_to_spawn )
num_spawned = count_to_spawn;
m_iCountToSpawn -= num_spawned;
FOR_EACH_VEC( spawned, i )
{
CBaseEntity *ent1 = spawned[i];
FOR_EACH_VEC( m_ActiveBots, j )
{
CBaseEntity *ent2 = m_ActiveBots[j];
if ( ent2 == nullptr )
continue;
if ( ent1->entindex() == ent2->entindex() )
{
Warning( "WaveSpawn duplicate entry in active vector\n" );
}
}
m_ActiveBots.AddToTail( ent1 );
}
if ( IsFinishedSpawning() )
{
SetState( InternalStateType::WAIT_FOR_ALL_DEAD );
}
else if ( m_iCountToSpawn <= 0 && !m_bWaitBetweenSpawnsAfterDeath )
{
m_iSpawnResult = SPAWN_FAIL;
float wait_between_spawns = m_flWaitBetweenSpawns;
if ( wait_between_spawns != 0.0f )
m_ctSpawnDelay.Start( wait_between_spawns );
}
break;
}
case InternalStateType::WAIT_FOR_ALL_DEAD:
FOR_EACH_VEC( m_ActiveBots, i )
{
CBaseEntity *ent = m_ActiveBots[i];
if ( ent != nullptr && ent->IsAlive() )
{
break;
}
}
SetState( InternalStateType::DONE );
break;
}
}
void CWaveSpawnPopulator::OnMemberKilled( CBaseEntity *pMember )
{
m_ActiveBots.FindAndFastRemove( pMember );
}
bool CWaveSpawnPopulator::IsFinishedSpawning()
{
if ( m_bSupport && !m_bSupportLimited )
return false;
return ( m_iCountSpawned >= m_iTotalCount );
}
void CWaveSpawnPopulator::OnNonSupportWavesDone()
{
if ( !m_bSupport )
return;
int state = m_iState;
if ( state == InternalStateType::INITIAL || state == InternalStateType::PRE_SPAWN_DELAY )
{
SetState( InternalStateType::DONE );
}
else if ( state == InternalStateType::SPAWNING || state == InternalStateType::WAIT_FOR_ALL_DEAD )
{
if ( TFGameRules() != nullptr && m_iCurrencyLeft > 0)
{
/*TFGameRules()->DistributeCurrencyAmount(m_iCurrencyLeft, nullptr, true, true, false);*/
m_iCurrencyLeft = 0;
}
SetState( InternalStateType::WAIT_FOR_ALL_DEAD );
}
}
void CWaveSpawnPopulator::ForceFinish()
{
int state = m_iState;
if ( state == InternalStateType::INITIAL || state == InternalStateType::PRE_SPAWN_DELAY || state == InternalStateType::SPAWNING )
{
SetState( InternalStateType::WAIT_FOR_ALL_DEAD );
}
else if ( state != InternalStateType::WAIT_FOR_ALL_DEAD )
{
SetState( InternalStateType::DONE );
}
FOR_EACH_VEC( m_ActiveBots, i )
{
CBaseEntity *ent = m_ActiveBots[i];
CAI_BaseNPC *bot = dynamic_cast<CAI_BaseNPC*>(ent);
if ( bot != nullptr )
{
bot->SetHealth( 0 );
}
else
{
UTIL_Remove( ent );
}
}
m_ActiveBots.RemoveAll();
}
int CWaveSpawnPopulator::GetCurrencyAmountPerDeath()
{
if ( m_bSupport && m_iState == InternalStateType::WAIT_FOR_ALL_DEAD )
m_iCountNotYetSpawned = m_ActiveBots.Count();
int currency_left = m_iCurrencyLeft;
if ( currency_left <= 0 )
return 0;
int bots_left = m_iCountNotYetSpawned;
if ( bots_left <= 0 )
bots_left = 1;
int amount = ( currency_left / bots_left );
--m_iCountNotYetSpawned;
m_iCurrencyLeft -= amount;
return amount;
}
void CWaveSpawnPopulator::SetState( CWaveSpawnPopulator::InternalStateType newstate )
{
m_iState = newstate;
if ( newstate == InternalStateType::PRE_SPAWN_DELAY )
{
if ( m_strStartWaveWarningSound.Length() > 0 )
TFGameRules()->BroadcastSound( 255,m_strStartWaveWarningSound.String() );
FireEvent( m_StartWaveOutput, "StartWaveOutput" );
if ( lfe_horde_debug.GetBool() )
DevMsg("%3.2f: WaveSpawn(%s) started PRE_SPAWN_DELAY\n", gpGlobals->curtime, m_strName.Get() );
}
else if ( newstate == InternalStateType::SPAWNING )
{
if ( m_strFirstSpawnWarningSound.Length() > 0 )
TFGameRules()->BroadcastSound( 255,m_strFirstSpawnWarningSound.String() );
FireEvent( m_FirstSpawnOutput, "FirstSpawnOutput" );
if ( lfe_horde_debug.GetBool() )
DevMsg( "%3.2f: WaveSpawn(%s) started SPAWNING\n", gpGlobals->curtime, m_strName.Get() );
}
else if ( newstate == InternalStateType::WAIT_FOR_ALL_DEAD )
{
if ( m_strLastSpawnWarningSound.Length() > 0 )
TFGameRules()->BroadcastSound( 255,m_strLastSpawnWarningSound.String() );
FireEvent( m_LastSpawnOutput, "LastSpawnOutput" );
if ( lfe_horde_debug.GetBool() )
DevMsg( "%3.2f: WaveSpawn(%s) started WAIT_FOR_ALL_DEAD\n", gpGlobals->curtime, m_strName.Get() );
}
else if ( newstate == InternalStateType::DONE )
{
if ( m_strDoneWarningSound.Length() > 0 )
TFGameRules()->BroadcastSound( 255,m_strDoneWarningSound.String() );
FireEvent( m_DoneOutput, "DoneOutput" );
if ( lfe_horde_debug.GetBool() )
DevMsg( "%3.2f: WaveSpawn(%s) DONE\n", gpGlobals->curtime, m_strName.Get() );
}
}
EventInfo *ParseEvent( KeyValues *kv )
{
EventInfo *info = new EventInfo();
FOR_EACH_SUBKEY( kv, subkey )
{
const char *name = subkey->GetName();
if ( strlen( name ) <= 0 )
continue;
if ( V_stricmp( name, "Target" ) == 0 )
{
info->target.sprintf( subkey->GetString() );
}
else if ( V_stricmp( name, "Action" ) == 0 )
{
info->action.sprintf( subkey->GetString() );
}
else
{
Warning( "Unknown field '%s' in WaveSpawn event definition.\n", subkey->GetString() );
delete info;
return nullptr;
}
}
return info;
}
void FireEvent( EventInfo *info, const char *name )
{
if ( info == nullptr )
return;
const char *target = info->target.Get();
const char *action = info->action.Get();
CBaseEntity *ent = gEntList.FindEntityByName( nullptr, target );
if ( ent != nullptr )
{
g_EventQueue.AddEvent( ent, action, 0.0f, nullptr, nullptr );
}
else
{
Warning( "WaveSpawnPopulator: Can't find target entity '%s' for %s\n", target, name );
}
}
| 23.529231
| 131
| 0.604682
|
bluedogz162
|
9ac36668ebf224af45f6581f291782de87fa1cf3
| 907
|
cpp
|
C++
|
ABC/ABC112/D.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | 1
|
2021-06-01T17:13:44.000Z
|
2021-06-01T17:13:44.000Z
|
ABC/ABC112/D.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | null | null | null |
ABC/ABC112/D.cpp
|
rajyan/AtCoder
|
2c1187994016d4c19b95489d2f2d2c0eab43dd8e
|
[
"MIT"
] | null | null | null |
//#include <cstdio>
//#include <cmath>
//#include <iostream>
//#include <sstream>
//#include <string>
//#include <vector>
//#include <map>
//#include <queue>
//#include <algorithm>
//
//#ifdef _DEBUG
//#define DMP(x) cerr << #x << ": " << x << "\n"
//#else
//#define DMP(x) ((void)0)
//#endif
//
//const int MOD = 1000000007, INF = 1111111111;
//using namespace std;
//typedef long long lint;
//
//template<class T>
//vector<T> divisor(T n) {
// vector<T> ret;
// for (T i = 1; i * i <= n; i++) {
// if (n % i == 0) {
// ret.emplace_back(i);
// if (i * i != n) ret.emplace_back(n / i);
// }
// }
// sort(ret.begin(), ret.end(), greater<T>());
// return ret;
//}
//
//int main() {
//
// int N, M;
// cin >> N >> M;
//
// auto divs = divisor(M);
//
// int ans;
// for (auto& ele : divs) {
// if (M / ele >= N) {
// ans = ele;
// break;
// }
// }
//
// cout << ans << "\n";
//
// return 0;
//
//}
| 16.796296
| 48
| 0.500551
|
rajyan
|
9ac6322841b57030d1ffefc3981f8aa763fe4557
| 604
|
hpp
|
C++
|
code/source/nodes/nodeeventreceiverproxy_we.hpp
|
crafn/clover
|
586acdbcdb34c3550858af125e9bb4a6300343fe
|
[
"MIT"
] | 12
|
2015-01-12T00:19:20.000Z
|
2021-08-05T10:47:20.000Z
|
code/source/nodes/nodeeventreceiverproxy_we.hpp
|
crafn/clover
|
586acdbcdb34c3550858af125e9bb4a6300343fe
|
[
"MIT"
] | null | null | null |
code/source/nodes/nodeeventreceiverproxy_we.hpp
|
crafn/clover
|
586acdbcdb34c3550858af125e9bb4a6300343fe
|
[
"MIT"
] | null | null | null |
#ifndef CLOVER_NODES_NODEEVENTRECEIVERPROXY_WE_HPP
#define CLOVER_NODES_NODEEVENTRECEIVERPROXY_WE_HPP
#include "build.hpp"
#include "game/worldentity_handle.hpp"
#include "nodeeventreceiverproxy.hpp"
namespace clover {
namespace nodes {
class WeNodeEventReceiverProxy : public NodeEventReceiverProxy {
public:
WeNodeEventReceiverProxy(const game::WeHandle& h);
virtual ~WeNodeEventReceiverProxy();
virtual void onEvent(const NodeEvent&);
virtual WeNodeEventReceiverProxy* clone();
private:
game::WeHandle handle;
};
} // nodes
} // clover
#endif // CLOVER_NODES_NODEEVENTRECEIVERPROXY_WE_HPP
| 24.16
| 64
| 0.812914
|
crafn
|
9ac7237ca05e7e2e4a70b7a4ef8ce99427e70b55
| 706
|
hpp
|
C++
|
src/examples/countPages/countPagesXercesHandler.hpp
|
Ace7k3/wiki_xml_dump_xerces
|
d64cc24042902668380140a7349ca06b73702dfe
|
[
"MIT"
] | null | null | null |
src/examples/countPages/countPagesXercesHandler.hpp
|
Ace7k3/wiki_xml_dump_xerces
|
d64cc24042902668380140a7349ca06b73702dfe
|
[
"MIT"
] | null | null | null |
src/examples/countPages/countPagesXercesHandler.hpp
|
Ace7k3/wiki_xml_dump_xerces
|
d64cc24042902668380140a7349ca06b73702dfe
|
[
"MIT"
] | null | null | null |
#pragma once
#include <stack>
#include <vector>
#include <functional>
#include <xercesc/sax2/DefaultHandler.hpp>
#include <xercesc/sax2/Attributes.hpp>
class CountPagesXercesHandler : public xercesc::DefaultHandler {
public:
inline CountPagesXercesHandler()
:_count(0)
{}
inline std::size_t count() const
{
return _count;
}
inline void startElement(const XMLCh* const uri, const XMLCh* const localname, const XMLCh* const qname, const xercesc::Attributes& attrs)
{
char* tmp = xercesc::XMLString::transcode(localname);
std::string elementName = tmp;
xercesc::XMLString::release(&tmp);
if(elementName == "page")
_count++;
}
private:
std::size_t _count;
};
| 19.611111
| 140
| 0.705382
|
Ace7k3
|
9acb80343745b42c4bb07dafb27a2d3583a520e1
| 1,074
|
hpp
|
C++
|
include/mizuiro/color/format/homogenous_ns/access/channel_max.hpp
|
cpreh/mizuiro
|
5ab15bde4e72e3a4978c034b8ff5700352932485
|
[
"BSL-1.0"
] | 1
|
2015-08-22T04:19:39.000Z
|
2015-08-22T04:19:39.000Z
|
include/mizuiro/color/format/homogenous_ns/access/channel_max.hpp
|
freundlich/mizuiro
|
5ab15bde4e72e3a4978c034b8ff5700352932485
|
[
"BSL-1.0"
] | null | null | null |
include/mizuiro/color/format/homogenous_ns/access/channel_max.hpp
|
freundlich/mizuiro
|
5ab15bde4e72e3a4978c034b8ff5700352932485
|
[
"BSL-1.0"
] | null | null | null |
// Copyright Carl Philipp Reh 2009 - 2016.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef MIZUIRO_COLOR_FORMAT_HOMOGENOUS_NS_ACCESS_CHANNEL_MAX_HPP_INCLUDED
#define MIZUIRO_COLOR_FORMAT_HOMOGENOUS_NS_ACCESS_CHANNEL_MAX_HPP_INCLUDED
#include <mizuiro/color/access/channel_max_ns/tag.hpp>
#include <mizuiro/color/detail/full_channel_max.hpp>
#include <mizuiro/color/format/store_fwd.hpp>
#include <mizuiro/color/format/homogenous_ns/tag.hpp>
#include <mizuiro/color/types/channel_value.hpp>
namespace mizuiro::color::access::channel_max_ns
{
template <typename Format, typename Channel>
mizuiro::color::types::channel_value<Format, Channel> channel_max_adl(
mizuiro::color::access::channel_max_ns::tag,
mizuiro::color::format::homogenous_ns::tag<Format>,
mizuiro::color::format::store<Format> const &,
Channel const &)
{
return mizuiro::color::detail::full_channel_max<typename Format::channel_type>();
}
}
#endif
| 34.645161
| 83
| 0.773743
|
cpreh
|
9ad178998e9d7bddea98bf82d283cfd62859e2c3
| 434
|
hpp
|
C++
|
libs/audio/include/sge/audio/scalar.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 2
|
2016-01-27T13:18:14.000Z
|
2018-05-11T01:11:32.000Z
|
libs/audio/include/sge/audio/scalar.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | null | null | null |
libs/audio/include/sge/audio/scalar.hpp
|
cpreh/spacegameengine
|
313a1c34160b42a5135f8223ffaa3a31bc075a01
|
[
"BSL-1.0"
] | 3
|
2018-05-11T01:11:34.000Z
|
2021-04-24T19:47:45.000Z
|
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_AUDIO_SCALAR_HPP_INCLUDED
#define SGE_AUDIO_SCALAR_HPP_INCLUDED
namespace sge::audio
{
/// A floating point type that's used almost everywhere (positions, gain, ...)
using scalar = float;
}
#endif
| 24.111111
| 78
| 0.721198
|
cpreh
|
9ad52b34ad0783975a3999c5c1685561b0fd81e5
| 9,656
|
cpp
|
C++
|
src/utils/MRMTransitionGroupPicker.cpp
|
mrurik/OpenMS
|
3bf48247423dc28a7df7b12b72fbc7751965c321
|
[
"Zlib",
"Apache-2.0"
] | 1
|
2018-03-06T14:12:09.000Z
|
2018-03-06T14:12:09.000Z
|
src/utils/MRMTransitionGroupPicker.cpp
|
mrurik/OpenMS
|
3bf48247423dc28a7df7b12b72fbc7751965c321
|
[
"Zlib",
"Apache-2.0"
] | null | null | null |
src/utils/MRMTransitionGroupPicker.cpp
|
mrurik/OpenMS
|
3bf48247423dc28a7df7b12b72fbc7751965c321
|
[
"Zlib",
"Apache-2.0"
] | null | null | null |
// --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2016.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Hannes Roest $
// $Authors: Hannes Roest $
// --------------------------------------------------------------------------
#include <OpenMS/APPLICATIONS/TOPPBase.h>
#include <OpenMS/CONCEPT/Exception.h>
#include <OpenMS/CONCEPT/ProgressLogger.h>
#include <OpenMS/KERNEL/MRMTransitionGroup.h>
#include <OpenMS/KERNEL/MSExperiment.h>
#include <OpenMS/KERNEL/FeatureMap.h>
#include <OpenMS/ANALYSIS/TARGETED/TargetedExperiment.h>
// files
#include <OpenMS/FORMAT/TraMLFile.h>
#include <OpenMS/FORMAT/MzMLFile.h>
#include <OpenMS/FORMAT/FeatureXMLFile.h>
// interfaces
#include <OpenMS/ANALYSIS/OPENSWATH/OPENSWATHALGO/DATAACCESS/ISpectrumAccess.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h>
// helpers
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/SimpleOpenMSSpectraAccessFactory.h>
#include <OpenMS/ANALYSIS/OPENSWATH/DATAACCESS/DataAccessHelper.h>
#include <OpenMS/ANALYSIS/OPENSWATH/MRMTransitionGroupPicker.h>
using namespace std;
using namespace OpenMS;
//-------------------------------------------------------------
//Doxygen docu
//-------------------------------------------------------------
/**
@page TOPP_MRMTransitionGroupPicker MRMTransitionGroupPicker
@brief Picks peaks in MRM chromatograms.
*/
// We do not want this class to show up in the docu:
/// @cond TOPPCLASSES
class TOPPMRMTransitionGroupPicker
: public TOPPBase
{
public:
TOPPMRMTransitionGroupPicker()
: TOPPBase("MRMTransitionGroupPicker", "", false)
{
}
protected:
typedef MSSpectrum<ChromatogramPeak> RichPeakChromatogram; // this is the type in which we store the chromatograms for this analysis
typedef ReactionMonitoringTransition TransitionType;
typedef TargetedExperiment TargetedExpType;
typedef MRMTransitionGroup<MSSpectrum <ChromatogramPeak>, TransitionType> MRMTransitionGroupType; // a transition group holds the MSSpectra with the Chromatogram peaks from above
void registerOptionsAndFlags_()
{
registerInputFile_("in", "<file>", "", "Input file");
setValidFormats_("in", ListUtils::create<String>("mzML"));
registerInputFile_("tr", "<file>", "", "transition file ('TraML' or 'csv')");
setValidFormats_("tr", ListUtils::create<String>("csv,traML"));
registerOutputFile_("out", "<file>", "", "output file");
setValidFormats_("out", ListUtils::create<String>("featureXML"));
registerSubsection_("algorithm", "Algorithm parameters section");
}
Param getSubsectionDefaults_(const String &) const
{
return MRMTransitionGroupPicker().getDefaults();
}
struct MRMGroupMapper
{
typedef std::map<String, std::vector< const TransitionType* > > AssayMapT;
// chromatogram map
std::map<String, int> chromatogram_map;
// Map peptide id
std::map<String, int> assay_peptide_map;
// Group transitions
AssayMapT assay_map;
/// Create the mapping
void doMap(OpenSwath::SpectrumAccessPtr input, TargetedExpType& transition_exp)
{
for (Size i = 0; i < input->getNrChromatograms(); i++)
{
chromatogram_map[input->getChromatogramNativeID(i)] = boost::numeric_cast<int>(i);
}
for (Size i = 0; i < transition_exp.getPeptides().size(); i++)
{
assay_peptide_map[transition_exp.getPeptides()[i].id] = boost::numeric_cast<int>(i);
}
for (Size i = 0; i < transition_exp.getTransitions().size(); i++)
{
assay_map[transition_exp.getTransitions()[i].getPeptideRef()].push_back(&transition_exp.getTransitions()[i]);
}
}
/// Check that all assays have a corresponding chromatogram
bool allAssaysHaveChromatograms()
{
for (AssayMapT::iterator assay_it = assay_map.begin(); assay_it != assay_map.end(); ++assay_it)
{
for (Size i = 0; i < assay_it->second.size(); i++)
{
if (chromatogram_map.find(assay_it->second[i]->getNativeID()) == chromatogram_map.end())
{
return false;
}
}
}
return true;
}
/// Fill up transition group with paired Transitions and Chromatograms
void getTransitionGroup(OpenSwath::SpectrumAccessPtr input, MRMTransitionGroupType& transition_group, String id)
{
transition_group.setTransitionGroupID(id);
// Go through all transitions
for (Size i = 0; i < assay_map[id].size(); i++)
{
const TransitionType* transition = assay_map[id][i];
OpenSwath::ChromatogramPtr cptr = input->getChromatogramById(chromatogram_map[transition->getNativeID()]);
MSChromatogram<ChromatogramPeak> chromatogram_old;
OpenSwathDataAccessHelper::convertToOpenMSChromatogram(chromatogram_old, cptr);
RichPeakChromatogram chromatogram;
// copy old to new chromatogram
for (MSChromatogram<ChromatogramPeak>::const_iterator it = chromatogram_old.begin(); it != chromatogram_old.end(); ++it)
{
ChromatogramPeak peak;
peak.setMZ(it->getRT());
peak.setIntensity(it->getIntensity());
chromatogram.push_back(peak);
}
chromatogram.setMetaValue("product_mz", transition->getProductMZ());
chromatogram.setMetaValue("precursor_mz", transition->getPrecursorMZ());
chromatogram.setNativeID(transition->getNativeID());
// Now add the transition and the chromatogram to the group
transition_group.addTransition(*transition, transition->getNativeID());
transition_group.addChromatogram(chromatogram, chromatogram.getNativeID());
}
}
};
void run_(OpenSwath::SpectrumAccessPtr input,
FeatureMap & output, TargetedExpType& transition_exp)
{
MRMTransitionGroupPicker trgroup_picker;
Param picker_param = getParam_().copy("algorithm:", true);
trgroup_picker.setParameters(picker_param);
MRMGroupMapper m;
m.doMap(input, transition_exp);
if (!m.allAssaysHaveChromatograms() )
{
throw Exception::IllegalArgument(__FILE__, __LINE__, __PRETTY_FUNCTION__,
"Not all assays could be mapped to chromatograms");
}
// Iterating over all the assays
for (MRMGroupMapper::AssayMapT::iterator assay_it = m.assay_map.begin(); assay_it != m.assay_map.end(); ++assay_it)
{
String id = assay_it->first;
// Create new transition group if there is none for this peptide
MRMTransitionGroupType transition_group;
m.getTransitionGroup(input, transition_group, id);
// Process the transition_group
trgroup_picker.pickTransitionGroup(transition_group);
// Add to output
for (Size i = 0; i < transition_group.getFeatures().size(); i++)
{
output.push_back(transition_group.getFeatures()[i]);
}
}
}
ExitCodes main_(int, const char **)
{
String in = getStringOption_("in");
String out = getStringOption_("out");
String tr_file = getStringOption_("tr");
boost::shared_ptr<MSExperiment<> > exp ( new MSExperiment<> );
MzMLFile mzmlfile;
mzmlfile.setLogType(log_type_);
mzmlfile.load(in, *exp);
TargetedExpType transition_exp;
TraMLFile().load(tr_file, transition_exp);
FeatureMap output;
OpenSwath::SpectrumAccessPtr input = SimpleOpenMSSpectraFactory::getSpectrumAccessOpenMSPtr(exp);
run_(input, output, transition_exp);
output.ensureUniqueId();
output.setPrimaryMSRunPath(exp->getPrimaryMSRunPath());
FeatureXMLFile().store(out, output);
return EXECUTION_OK;
}
};
int main(int argc, const char ** argv)
{
TOPPMRMTransitionGroupPicker tool;
return tool.main(argc, argv);
}
/// @endcond
| 36.996169
| 180
| 0.669635
|
mrurik
|
9ad530e8c61cd3c1e30ce8873c247cec6018247f
| 224
|
cpp
|
C++
|
Simple++/Math/BasicComparable.cpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
Simple++/Math/BasicComparable.cpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
Simple++/Math/BasicComparable.cpp
|
Oriode/Simpleplusplus
|
2ba44eeab5078d6dab66bdefdf73617696b8cb2e
|
[
"Apache-2.0"
] | null | null | null |
#include "BasicComparable.h"
namespace Math {
namespace Compare {
Math::Compare::Value BasicComparable::compare( const BasicComparable & x, const BasicComparable & y ) {
return Math::Compare::Value::Equal;
}
}
}
| 18.666667
| 105
| 0.709821
|
Oriode
|
9ad5afe335bc55d7b951a5583a233c23e0705871
| 1,918
|
hpp
|
C++
|
source/Dream/Core/Dictionary.hpp
|
kurocha/dream
|
b2c7d94903e1e8c6bfb043d3b62234508687f435
|
[
"MIT",
"Unlicense"
] | 1
|
2017-04-30T18:59:26.000Z
|
2017-04-30T18:59:26.000Z
|
source/Dream/Core/Dictionary.hpp
|
kurocha/dream
|
b2c7d94903e1e8c6bfb043d3b62234508687f435
|
[
"MIT",
"Unlicense"
] | null | null | null |
source/Dream/Core/Dictionary.hpp
|
kurocha/dream
|
b2c7d94903e1e8c6bfb043d3b62234508687f435
|
[
"MIT",
"Unlicense"
] | null | null | null |
//
// Core/Dictionary.h
// This file is part of the "Dream" project, and is released under the MIT license.
//
// Created by Samuel Williams on 22/12/08.
// Copyright (c) 2008 Samuel Williams. All rights reserved.
//
//
#ifndef _DREAM_CORE_DICTIONARY_H
#define _DREAM_CORE_DICTIONARY_H
#include "../Class.hpp"
#include "Value.hpp"
#include "Data.hpp"
#include <map>
namespace Dream
{
namespace Core
{
class Dictionary : public Object {
public:
typedef std::string KeyT;
protected:
typedef std::map<KeyT, Value> ValuesT;
ValuesT _values;
public:
/// Returns whether the key has a value in the dictionary.
bool key (const KeyT & key);
void set_value (const KeyT & key, const Value & value);
const Value get_value (const KeyT & key) const;
template <typename t>
void set (const KeyT & key, const t & value)
{
set_value(key, Value(value));
}
template <typename ValueT>
const ValueT get (const KeyT & key)
{
Value v = get_value(key);
return v.extract<ValueT>();
}
template <typename ValueT>
bool get (const KeyT & key, ValueT & value)
{
Value v = get_value(key);
if (v.defined()) {
value = v.extract<ValueT>();
return true;
} else {
return false;
}
}
/// Updates a value if the key exists in the dictionary.
template <typename t>
bool update (const KeyT & key, t & value) const
{
ValuesT::const_iterator i = _values.find(key);
if (i != _values.end()) {
value = i->second.extract<t>();
return true;
}
return false;
}
// Overwrites values present in the other dictionary.
void update (const Ptr<Dictionary> other);
// Only inserts key-values that don't already exist.
void insert (const Ptr<Dictionary> other);
Ref<IData> serialize() const;
void deserialize(Ref<IData> data);
void debug (std::ostream &) const;
};
}
}
#endif
| 20.189474
| 84
| 0.642336
|
kurocha
|
9ad990306a63baa4bd49cea67cea1fb856ce4358
| 3,821
|
cpp
|
C++
|
TopCoder/SRM/RollingDiceDivTwo.cpp
|
vios-fish/CompetitiveProgramming
|
6953f024e4769791225c57ed852cb5efc03eb94b
|
[
"MIT"
] | null | null | null |
TopCoder/SRM/RollingDiceDivTwo.cpp
|
vios-fish/CompetitiveProgramming
|
6953f024e4769791225c57ed852cb5efc03eb94b
|
[
"MIT"
] | null | null | null |
TopCoder/SRM/RollingDiceDivTwo.cpp
|
vios-fish/CompetitiveProgramming
|
6953f024e4769791225c57ed852cb5efc03eb94b
|
[
"MIT"
] | null | null | null |
// BEGIN CUT HERE
// END CUT HERE
#line 5 "RollingDiceDivTwo.cpp"
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <list>
#include <queue>
#include <stack>
#include <bitset>
#include <deque>
#include <set>
#include <sstream>
using namespace std;
const double EPS = 1e-10;
const double PI = acos(-1.0);
#define dump(x) cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << "(L" << __LINE__ << ")" << __FILE__ << endl;
#define FOR(i,a,b) for( int i = (a); i < (b); ++i)
#define rep(i,n) FOR(i,0,n)
typedef vector<int> VI;
typedef vector<VI> VII;
typedef vector<string> VS;
typedef pair<int, int> PII;
inline int toInt( string s ){int v; istringstream sin(s);sin >> v;return v;}
template<class T> inline string toString( T x ){ostringstream sout;sout<<x;return sout.str();}
class RollingDiceDivTwo {
public:
int minimumFaces(vector <string> rolls) {
int result = 0;
rep(i,rolls.size()){
sort(rolls[i].begin(),rolls[i].end());
}
rep(i,rolls[0].size()){
int m = 0;
rep(j,rolls.size()){
int a = rolls[j][i] - '0';
m = max( a, m);
}
result += m;
}
return result;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { string Arr0[] = {"137", "364", "115", "724"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 14; verify_case(0, Arg1, minimumFaces(Arg0)); }
void test_case_1() { string Arr0[] = {"1112", "1111", "1211", "1111"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 5; verify_case(1, Arg1, minimumFaces(Arg0)); }
void test_case_2() { string Arr0[] = {"24412", "56316", "66666", "45625"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 30; verify_case(2, Arg1, minimumFaces(Arg0)); }
void test_case_3() { string Arr0[] = {"931", "821", "156", "512", "129", "358", "555"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 19; verify_case(3, Arg1, minimumFaces(Arg0)); }
void test_case_4() { string Arr0[] = {"3", "7", "4", "2", "4"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 7; verify_case(4, Arg1, minimumFaces(Arg0)); }
void test_case_5() { string Arr0[] = {"281868247265686571829977999522", "611464285871136563343229916655", "716739845311113736768779647392", "779122814312329463718383927626",
"571573431548647653632439431183", "547362375338962625957869719518", "539263489892486347713288936885", "417131347396232733384379841536"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 176; verify_case(5, Arg1, minimumFaces(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main(){
RollingDiceDivTwo __test;
__test.run_test(-1);
}
// END CUT HERE
| 43.420455
| 316
| 0.601413
|
vios-fish
|
9add92b66c69ce97d207a2ef75fb688e284cf1cd
| 336
|
cpp
|
C++
|
Medium/984_String_Without_AAA_OR_BBB.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | 1
|
2021-03-15T10:02:10.000Z
|
2021-03-15T10:02:10.000Z
|
Medium/984_String_Without_AAA_OR_BBB.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | null | null | null |
Medium/984_String_Without_AAA_OR_BBB.cpp
|
ShehabMMohamed/LeetCodeCPP
|
684340f29ac15c5e8fa9f6ef5c3f99d4c95ce780
|
[
"MIT"
] | null | null | null |
class Solution {
public:
string strWithout3a3b(int A, int B) {
if(A == 0) return string(B, 'b');
if(B == 0) return string(A, 'a');
if(A == B) return "ab" + strWithout3a3b(A-1, B-1);
if(A > B) return "aab" + strWithout3a3b(A-2, B-1);
else return strWithout3a3b(A-1, B-2) + "abb";
}
};
| 33.6
| 60
| 0.520833
|
ShehabMMohamed
|
9ae2d2a93d3009f6349963a53676a439d288f7a1
| 966
|
cpp
|
C++
|
master/core/third/libtorrent/bindings/python/src/utility.cpp
|
importlib/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | 32
|
2016-05-22T23:09:19.000Z
|
2022-03-13T03:32:27.000Z
|
master/core/third/libtorrent/bindings/python/src/utility.cpp
|
isuhao/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | 2
|
2016-05-30T19:45:58.000Z
|
2018-01-24T22:29:51.000Z
|
master/core/third/libtorrent/bindings/python/src/utility.cpp
|
isuhao/klib
|
a59837857689d0e60d3df6d2ebd12c3160efa794
|
[
"MIT"
] | 17
|
2016-05-27T11:01:42.000Z
|
2022-03-13T03:32:30.000Z
|
// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <libtorrent/identify_client.hpp>
#include <libtorrent/bencode.hpp>
#include <boost/python.hpp>
using namespace boost::python;
using namespace libtorrent;
object client_fingerprint_(peer_id const& id)
{
boost::optional<fingerprint> result = client_fingerprint(id);
return result ? object(*result) : object();
}
entry bdecode_(std::string const& data)
{
return bdecode(data.begin(), data.end());
}
std::string bencode_(entry const& e)
{
std::string result;
bencode(std::back_inserter(result), e);
return result;
}
void bind_utility()
{
def("identify_client", &libtorrent::identify_client);
def("client_fingerprint", &client_fingerprint_);
def("bdecode", &bdecode_);
def("bencode", &bencode_);
}
| 25.421053
| 72
| 0.723602
|
importlib
|
9af179cef0a5044d31324b068da1750c1dfc675b
| 11,071
|
cpp
|
C++
|
xeon_version/src/shared_functions.cpp
|
Draxent/GameOfLife
|
bd7dacf1c2d8a591218f17348479318626101dfa
|
[
"Apache-2.0"
] | 2
|
2015-11-27T01:14:02.000Z
|
2015-12-01T13:23:53.000Z
|
xeon_version/src/shared_functions.cpp
|
Draxent/GameOfLife
|
bd7dacf1c2d8a591218f17348479318626101dfa
|
[
"Apache-2.0"
] | null | null | null |
xeon_version/src/shared_functions.cpp
|
Draxent/GameOfLife
|
bd7dacf1c2d8a591218f17348479318626101dfa
|
[
"Apache-2.0"
] | null | null | null |
/**
* @file shared_functions.cpp
* @brief Implementation of some functions that are shared by all different development methodologies used in this application.
* @author Federico Conte (draxent)
*
* Copyright 2015 Federico Conte
* https://github.com/Draxent/GameOfLife
*
* 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 "../include/shared_functions.h"
void compute_generation( Grid* g, size_t start, size_t end )
{
size_t pos_top = start - g->width(), pos_bottom = start + g->width();
for ( size_t pos = start; pos < end; pos++, pos_top++, pos_bottom++ )
{
// Calculate #Neighbours.
int numNeighbor = g->countNeighbours( pos, pos_top, pos_bottom );
// Box ← (( #Neighbours == 3 ) OR ( Cell is alive AND #Neighbours == 2 )).
g->Write[pos] = ( numNeighbor == 3 || ( g->Read[pos] && numNeighbor == 2 ) );
}
}
#if VECTORIZATION
void compute_generation_vect( Grid* g, int* numNeighbours, size_t start, size_t end )
{
size_t index = start, index_top = start - g->width(), index_bottom = start + g->width();
for ( ; index + VLEN < end; index += VLEN, index_top += VLEN, index_bottom += VLEN )
{
// Save the computation of the neighbours counting into the numNeighbours array.
numNeighbours[0:VLEN] = g->countNeighbours( index, index_top, index_bottom, __sec_implicit_index(0) );
// Box ← (( #Neighbours == 3 ) OR ( Cell is alive AND #Neighbours == 2 )) in vector notations.
g->Write[index:VLEN] = ( numNeighbours[0:VLEN] == 3 || ( g->Read[index:VLEN] && numNeighbours[0:VLEN] == 2 ) );
}
// Compute normally the last piece that does not fill the numNeighbours array.
for ( ; index < end; index++, index_top++, index_bottom++ )
{
// Calculate #Neighbours.
int numNeighbor = g->countNeighbours( index, index_top, index_bottom );
// Box ← (( #Neighbours == 3 ) OR ( Cell is alive AND #Neighbours == 2 )).
g->Write[index] = ( numNeighbor == 3 || ( g->Read[index] && numNeighbor == 2 ) );
}
}
#endif // VECTORIZATION
bool sequential_version( Grid* g, unsigned int iterations, bool vectorization )
{
std::chrono::high_resolution_clock::time_point t1, t2;
#if DEBUG
// Initialize the matrix that we will used as verifier.
Matrix* verifier = new Matrix( g );
#endif // DEBUG
// Start - Game of Life
t1 = std::chrono::high_resolution_clock::now();
long copyborder_time = 0;
size_t start = g->width() + 1, end = g->size() - g->width() - 1;
int* numNeighbours = NULL;
if ( vectorization )
numNeighbours = new int[VLEN];
for ( unsigned int k = 1; k <= iterations; k++ )
{
#if VECTORIZATION
if ( vectorization )
compute_generation_vect( g, numNeighbours, start, end );
else
compute_generation( g, start, end );
#else
compute_generation( g, start, end );
#endif // VECTORIZATION
copyborder_time = copyborder_time + end_generation( g, k );
}
if ( vectorization )
delete[] numNeighbours;
#if TAKE_ALL_TIME
// Print the total time in order to compute the end_generation functions.
printTime( copyborder_time, "copy border" );
#endif // TAKE_ALL_TIME
// End - Game of Life
t2 = std::chrono::high_resolution_clock::now();
printTime( t1, t2, "complete Game of Life" );
#if DEBUG
// Print only small Grid
if ( g->width() <= MAX_PRINTABLE_GRID && g->height() <= MAX_PRINTABLE_GRID )
{
// Print final configuration
g->print( "OUTPUT" );
}
// Check if the output is correct.
verifier->GOL( iterations );
if ( verifier->equal() ) std::cout << "TEST OK !!! " << std::endl;
else
{
std::cout << "Error: the verifier obtain this following different value for the GOL computation:" << std::endl;
verifier->print();
return false;
}
#endif // DEBUG
return true;
}
long end_generation( Grid* g, unsigned int current_iteration )
{
#if TAKE_ALL_TIME
std::chrono::high_resolution_clock::time_point t1, t2;
// Start - End Generation
t1 = std::chrono::high_resolution_clock::now();
#endif // TAKE_ALL_TIME
// Swap the reading and writing matrixes.
g->swap();
// Every step we need to configure the border to properly respect the logic of the 2D toroidal grid
g->copyBorder();
#if DEBUG
// Print only small Grid
if ( g->width() <= MAX_PRINTABLE_GRID && g->height() <= MAX_PRINTABLE_GRID )
{
// Print the result of the Game of Life iteration.
std::string title = "ITERATION " + std::to_string( (long long) current_iteration ) + " -";
g->print( title.c_str(), true );
}
#endif // DEBUG
#if TAKE_ALL_TIME
// End - End Generation
t2 = std::chrono::high_resolution_clock::now();
return std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count();
#else
return 0;
#endif // TAKE_ALL_TIME
}
bool menu( int argc, char** argv, bool& vectorization, unsigned int& num_tasks, size_t& width, size_t& height, unsigned int& seed, unsigned int& iterations, unsigned int& nw )
{
ProgramOptions po( argc, argv );
// Print help message if the "--help" option is present.
if ( po.exists( "--help" ) )
{
std::cerr << "Usage: " << argv[0] << " [options] " << std::endl;
std::cerr << "Possible options:" << std::endl;
#if VECTORIZATION
std::cerr << "\t -v,\t --vect \t activate the vectorization version ;" << std::endl;
#endif // VECTORIZATION
std::cerr << "\t -w NUM, --width NUM \t grid width ;" << std::endl;
std::cerr << "\t -h NUM, --height NUM \t grid height ;" << std::endl;
std::cerr << "\t -s NUM, --seed NUM \t seed used to initialize the grid ( zero for timestamp seed ) ;" << std::endl;
std::cerr << "\t -i NUM, --iterations NUM \t number of iterations ;" << std::endl;
std::cerr << "\t -t NUM, --thread NUM \t number of threads ( zero for the sequential version ) ;" << std::endl;
std::cerr << "\t -n NUM, --num_tasks NUM \t number of tasks generated ;" << std::endl;
std::cerr << "\t --help \t\t this help view ;" << std::endl;
return false;
}
// Retrieve all the options value
width = (size_t) po.get_number( "-w", "--width", 1000 );
height = (size_t) po.get_number( "-h", "--height", 1000 );
seed = (unsigned int) po.get_number( "-s", "--seed", 0 );
iterations = (unsigned int) po.get_number( "-i", "--iterations", 100 );
nw = (unsigned int) po.get_number( "-t", "--thread", 0 );
num_tasks = (unsigned int) po.get_number( "-n", "--num_chunks", nw );
// At least one task per Worker.
assert ( num_tasks >= 0 && nw >= 0 && width > 0 && height > 0 && iterations > 0 );
#if VECTORIZATION
vectorization = po.exists( "-v", "--vect" );
std::cout << "Vectorization: " << ( vectorization ? "true" : "false" ) << ", ";
#else
vectorization = false;
#endif // VECTORIZATION
std::cout << "Width: " << width << ", Height: " << height << ", Seed: " << seed;
std::cout << ", #Iterations: " << iterations << ", #Workers: " << nw << ", #Tasks: " << num_tasks << "." << std::endl;
return true;
}
void initialization( bool vectorization, size_t width, size_t height, unsigned int seed, Grid*& g )
{
std::chrono::high_resolution_clock::time_point t1, t2;
// Start - Initialization Phase
t1 = std::chrono::high_resolution_clock::now();
// Create and initialize the Grid object.
g = new Grid( height, width );
g->init( seed );
#if VECTORIZATION
if ( vectorization ) g->init_vect( seed );
else g->init( seed );
#else
g->init( seed );
#endif // VECTORIZATION
// Configure the border to properly respect the logic of the 2D toroidal grid
g->copyBorder();
#if DEBUG
// Print only small Grid
if ( g->width() <= MAX_PRINTABLE_GRID && g->height() <= MAX_PRINTABLE_GRID )
{
// Print initial configuration.
g->print( "INPUT" );
// Print iteration zero.
g->print( "ITERATION 0 -", true );
}
#endif // DEBUG
// End - Initialization Phase
t2 = std::chrono::high_resolution_clock::now();
printTime( t1, t2, "initialization phase" );
}
void setup_working_variable( Grid* g, unsigned int& num_tasks, unsigned int& nw, size_t& start, size_t*& chunks )
{
size_t workingSize = g->size() - 2*g->width() - 2;
start = g->width() + 1;
// The minimum percentage has to guarantee a task of at least MIN_BLOCK_SIZE size.
double min_perc = MIN_BLOCK_SIZE / (double) workingSize;
// Calculate the maximum number of tasks given the minimum percentage calculation.
unsigned long max_num_tasks = (unsigned long) ceil( 1 / min_perc );
// If the workingSize is small, we do not need so many tasks.
num_tasks = ( max_num_tasks < num_tasks ) ? ((int) max_num_tasks) : num_tasks;
// Adjust the number of Workers in order to have at least one task per Worker.
nw = ( num_tasks < nw ) ? num_tasks : nw;
// Calculate the chunk size of each task, with a decreasing cubic function which
// summation is equal to 100% of the workingSize.
chunks = new size_t[num_tasks];
// This percentage amount is fixed, since each task has at least min_perc of workingSize.
double fix_perc = min_perc * num_tasks;
// Compute the summation.
unsigned long long summation = 1;
for ( int i = 2; i <= num_tasks; i++ ) summation += pow3(i);
// Calculate the variable that define our cubic function.
double multiplier = (1 - fix_perc) / (double) summation;
// Since we are working with integer numbers, we can have a rest.
size_t rest = workingSize;
// Fill the chunks array with the calculated chunk size for each task.
for ( int i = 0; i < num_tasks; i++ )
{
double percentage = min_perc + multiplier * pow3(num_tasks - i);
chunks[i] = percentage * workingSize;
rest -= chunks[i];
}
// Assign the rest to the first task.
chunks[0] += rest;
#if DEBUG
std::cout << "Working Size: " << workingSize << ", #Workers: " << nw << ", #Tasks : " << num_tasks << std::endl;
std::cout << "CHUNKS = { " << chunks[0];
for ( int i = 1; i < num_tasks; i++ )
std::cout << ", " << chunks[i];
std::cout << " }" << std::endl;
#endif // DEBUG
}
void printTime( long duration, const char *msg )
{
#if MACHINE_TIME
std::cout << "Time to " << msg << ": " << duration << std::endl;
#else
char buffer[100];
int choice = 0;
const std::string time_strings[6] = { "microseconds", "milliseconds", "seconds", "minutes", "hours", "days" };
const int divisor[6] = { 1, 1000, 1000, 60, 60, 24 };
double time = duration;
while ( (choice < 5) && (time >= 1000 ) )
{
choice++;
time = time / divisor[choice];
}
sprintf( buffer, "%.2f", time );
// Print time on screen
std::cout << "Time to " << msg << ": " << buffer << " " << time_strings[choice] << "." << std::endl;
#endif // MACHINE_TIME
}
void printTime( std::chrono::high_resolution_clock::time_point t1, std::chrono::high_resolution_clock::time_point t2, const char *msg )
{
printTime( (long) std::chrono::duration_cast<std::chrono::microseconds>( t2 - t1 ).count(), msg );
}
| 36.65894
| 175
| 0.661639
|
Draxent
|
9af1f94e0a3ed34c776977d3e4dcb238933dec3a
| 21,751
|
cpp
|
C++
|
src/gui/Gui.cpp
|
beichendexiatian/InstanceFusion
|
cd48e3f477595a48d845ce01302f564b6b3fc6f6
|
[
"Apache-2.0"
] | null | null | null |
src/gui/Gui.cpp
|
beichendexiatian/InstanceFusion
|
cd48e3f477595a48d845ce01302f564b6b3fc6f6
|
[
"Apache-2.0"
] | null | null | null |
src/gui/Gui.cpp
|
beichendexiatian/InstanceFusion
|
cd48e3f477595a48d845ce01302f564b6b3fc6f6
|
[
"Apache-2.0"
] | null | null | null |
/*
* This file is part of SemanticFusion.
*
* Copyright (C) 2017 Imperial College London
*
* The use of the code within this file and all code within files that
* make up the software that is SemanticFusion is permitted for
* non-commercial purposes only. The full terms and conditions that
* apply to the code within this file are detailed within the LICENSE.txt
* file and at <http://www.imperial.ac.uk/dyson-robotics-lab/downloads/semantic-fusion/semantic-fusion-license/>
* unless explicitly stated. By downloading this file you agree to
* comply with these terms.
*
* If you wish to use any of this code for commercial purposes then
* please email researchcontracts.engineering@imperial.ac.uk.
*
*/
#include "Gui.h"
#include "GuiCuda.h"
#include <cuda_runtime.h>
#define gpuErrChk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool
abort=true) {
if (code != cudaSuccess) {
fprintf(stderr,"GPUassert: %s %s %d\n",
cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
struct ClassIdInput
{
ClassIdInput()
: class_id_(0) {}
ClassIdInput(int class_id)
: class_id_(class_id) {}
int class_id_;
};
std::ostream& operator<< (std::ostream& os, const ClassIdInput& o){
os << o.class_id_;
return os;
}
std::istream& operator>> (std::istream& is, ClassIdInput& o){
is >> o.class_id_;
return is;
}
Gui::Gui(bool live_capture, std::vector<ClassColour> class_colour_lookup, const int segmentation_width, const int segmentation_height)
: width_(1280)
, height_(980)
, segmentation_width_(segmentation_width)
, segmentation_height_(segmentation_height)
, class_colour_lookup_(class_colour_lookup)
, panel_(205)
{
width_ += panel_;
pangolin::Params window_params;
window_params.Set("SAMPLE_BUFFERS", 0);
window_params.Set("SAMPLES", 0);
pangolin::CreateWindowAndBind("InstanceFusion", width_, height_, window_params);
//Main Display
//original display of global map(origin semanticfusion)
//GlRenderBuffer
render_buffer_ = new pangolin::GlRenderBuffer(mainWidth, mainHeight);
//GPUTexture
color_texture_ = new GPUTexture(mainWidth, mainHeight, GL_RGBA32F, GL_LUMINANCE, GL_FLOAT, true);
//GlFramebuffer
color_frame_buffer_ = new pangolin::GlFramebuffer;
color_frame_buffer_->AttachColour(*color_texture_->texture);
color_frame_buffer_->AttachDepth(*render_buffer_);
//mapID use for display(InstanceFusion)
//GlRenderBuffer
mapIdGlobalRenderBuffer= new pangolin::GlRenderBuffer(mainWidth, mainHeight);
//GPUTexture
mapIdGlobalTexture= new GPUTexture(mainWidth, mainHeight, GL_LUMINANCE32I_EXT, GL_LUMINANCE_INTEGER_EXT, GL_INT, false, true);
//GlFramebuffer
mapIdGlobalFrameBuffer = new pangolin::GlFramebuffer;
mapIdGlobalFrameBuffer->AttachColour(*mapIdGlobalTexture->texture);
mapIdGlobalFrameBuffer->AttachDepth(*mapIdGlobalRenderBuffer);
//ClearBuffer
mapIdGlobalFrameBuffer->Bind();
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0, 0, mainWidth, mainHeight);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
mapIdGlobalFrameBuffer->Unbind();
//temp for renderMapMethod2
cudaMalloc((void **)&camPoseTrans_gpu, 3 * sizeof(float));
cudaMalloc((void **)&rgbdInfo_gpu, 4 * mainWidth * mainHeight * sizeof(float));
cudaMalloc((void **)&mapDisplay_gpu, 4 * mainWidth * mainHeight * sizeof(float));
tempMap = (float*)malloc(4 * mainWidth * mainHeight * sizeof(float));
//ProjectionMatrix(int w, int h, GLprecision fu, GLprecision fv, GLprecision u0, GLprecision v0, GLprecision zNear, GLprecision zFar )
s_cam_ = pangolin::OpenGlRenderState(pangolin::ProjectionMatrix(640, 480, 420, 420, 320, 240, 0.1, 1000),
pangolin::ModelViewLookAt(0, 0, -1, 0, 0, 1, pangolin::AxisNegY));
pangolin::Display("cam").SetBounds(0, 1.0f, 0, 1.0f, -640 / 480.0)
.SetHandler(new pangolin::Handler3D(s_cam_));
// Small views along the bottom
pangolin::Display("raw").SetAspect(640.0f/480.0f);
//lyc add
pangolin::Display("depth").SetAspect(640.0f/480.0f);
//lyc add over
pangolin::Display("pred").SetAspect(640.0f/480.0f);
pangolin::Display("segmentation").SetAspect(640.0f/480.0f);
pangolin::Display("multi").SetBounds(pangolin::Attach::Pix(0),1/4.0f,pangolin::Attach::Pix(180),1.0).SetLayout(pangolin::LayoutEqualHorizontal)
.AddDisplay(pangolin::Display("pred"))
.AddDisplay(pangolin::Display("segmentation"))
.AddDisplay(pangolin::Display("raw"))
.AddDisplay(pangolin::Display("depth"));
// Vertical view along the side
pangolin::Display("legend").SetAspect(640.0f/480.0f);
pangolin::Display("vert").SetBounds(pangolin::Attach::Pix(0),1/4.0f,pangolin::Attach::Pix(180),1.0).SetLayout(pangolin::LayoutEqualVertical)
.AddDisplay(pangolin::Display("legend"));
// The control panel
pangolin::CreatePanel("ui").SetBounds(0.0, 1.0, 0.0, pangolin::Attach::Pix(panel_));
pause_.reset(new pangolin::Var<bool>("ui.Pause", false, true));
step_.reset(new pangolin::Var<bool>("ui.Step", false, false));
reset_.reset(new pangolin::Var<bool>("ui.Reset", false, false));
//lyc add
save_.reset(new pangolin::Var<bool>("ui.Save",false,false));
frameCount.reset(new pangolin::Var<std::string>("ui.FrameCount","0/0"));
fps.reset(new pangolin::Var<int>("ui.FPS",0));
//lyc add over
tracking_.reset(new pangolin::Var<bool>("ui.Tracking Only", false, false));
instance_.reset(new pangolin::Var<bool>("ui.Instance Segmentation", true, false)); //TRUE
color_view_.reset(new pangolin::Var<bool>("ui.Draw Colors", true, false));
instance_view_.reset(new pangolin::Var<bool>("ui.Draw Instances", false, false));
time_view_.reset(new pangolin::Var<bool>("ui.Draw Time", false, false));
projectBoudingBox_.reset(new pangolin::Var<bool>("ui.Draw ProjectMap BBox", false, false));
displayMode_.reset(new pangolin::Var<bool>("ui.Display Mode", true, false));
bboxType_.reset(new pangolin::Var<bool>("ui.3D BBOX Type", true, false));
rawSave_.reset(new pangolin::Var<bool>("ui.Raw Save", false, false));
instanceSaveOnce_.reset(new pangolin::Var<bool>("ui.Instance Save(Once)", false, false));
class_choice_.reset(new pangolin::Var<ClassIdInput>("ui.Show class probs", ClassIdInput(0))); //No Use
//1600 1200
//fxBBOX.reset(new pangolin::Var<float>("ui.fxBBOX", 1440.0, -mainWidth , mainWidth));
//fyBBOX.reset(new pangolin::Var<float>("ui.fyBBOX", 1080.0, -mainHeight, mainHeight));
//cxBBOX.reset(new pangolin::Var<float>("ui.cxBBOX", 0.0, -mainWidth , mainWidth));
//cyBBOX.reset(new pangolin::Var<float>("ui.cyBBOX", 0.0, -mainHeight, mainHeight));
//PHT Delete
//probability_texture_array_.reset(new pangolin::GlTextureCudaArray(640,480,GL_LUMINANCE32F_ARB));
probability_texture_array_.reset(new pangolin::GlTextureCudaArray(segmentation_width_,segmentation_height_,GL_RGBA32F));
rendered_segmentation_texture_array_.reset(new pangolin::GlTextureCudaArray(segmentation_width_,segmentation_height_,GL_RGBA32F));
//PHT+
mainDisplay_texture_array_.reset(new pangolin::GlTextureCudaArray(render_buffer_->width,render_buffer_->height,GL_RGBA32F));
boundingBox_texture_array_.reset(new pangolin::GlTextureCudaArray(render_buffer_->width,render_buffer_->height,GL_RGBA32F));
// The gpu colour lookup
std::vector<float> class_colour_lookup_rgb;
for (unsigned int class_id = 0; class_id < class_colour_lookup_.size(); ++class_id) {
class_colour_lookup_rgb.push_back(static_cast<float>(class_colour_lookup_[class_id].r)/255.0f);
class_colour_lookup_rgb.push_back(static_cast<float>(class_colour_lookup_[class_id].g)/255.0f);
class_colour_lookup_rgb.push_back(static_cast<float>(class_colour_lookup_[class_id].b)/255.0f);
}
cudaMalloc((void **)&class_colour_lookup_gpu_, class_colour_lookup_rgb.size() * sizeof(float));
cudaMemcpy(class_colour_lookup_gpu_, class_colour_lookup_rgb.data(), class_colour_lookup_rgb.size() * sizeof(float), cudaMemcpyHostToDevice);
cudaMalloc((void **)&segmentation_rendering_gpu_, 4 * segmentation_width_ * segmentation_height_ * sizeof(float));
}
Gui::~Gui()
{
cudaFree(class_colour_lookup_gpu_);
cudaFree(segmentation_rendering_gpu_);
cudaFree(camPoseTrans_gpu);
cudaFree(rgbdInfo_gpu);
cudaFree(mapDisplay_gpu);
free(tempMap);
}
void Gui::renderMapID(const std::unique_ptr<ElasticFusionInterface>& map,std::vector<ClassColour> class_colour_lookup)
{
class_colour_lookup_ = class_colour_lookup;
mapIdGlobalFrameBuffer->Bind();
glPushAttrib(GL_VIEWPORT_BIT);
glViewport(0, 0, mainWidth, mainHeight);
glClearColor(0, 0, 0, 0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
map->RenderMapIDToGUIBuffer(s_cam_,instance_colours(),time_colours(),surfel_colorus());
mapIdGlobalFrameBuffer->Unbind();
glPopAttrib();
glPointSize(1);
glFinish();
}
void Gui::preCall()
{
glEnable(GL_DEPTH_TEST);
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
glClearColor(1.0,1.0,1.0, 0.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
width_ = pangolin::DisplayBase().v.w;
height_ = pangolin::DisplayBase().v.h;
pangolin::Display("cam").Activate(s_cam_);
}
void Gui::renderMapMethod1(const std::unique_ptr<ElasticFusionInterface>& map)
{
map->RenderMapToBoundGlBuffer(s_cam_,instance_colours(),time_colours(),surfel_colorus());
}
//Debug Pack
timeval time_1,time_2;
void TimeTick()
{
gettimeofday(&time_1,NULL);
}
void TimeTock(std::string name)
{
gettimeofday(&time_2,NULL);
float timeUse = (time_2.tv_sec-time_1.tv_sec)*1000000+(time_2.tv_usec-time_1.tv_usec);
std::cout<<name<<": "<<timeUse<<" us"<<std::endl;
}
void Gui::renderMapMethod2(const std::unique_ptr<ElasticFusionInterface>& map,const std::unique_ptr<InstanceFusion>& instanceFusion,bool drawBox,bool bboxType)
{
//map->RenderMapToBoundGlBuffer(s_cam_,instance_colours(),time_colours(),surfel_colorus());
//Step 1 get Info form MapID
const int surfel_size = instanceFusion->getSurfelSize();
cudaTextureObject_t mapGlobalsurfelsIds = mapIdGlobalTexture->texObj;
float* map_surfels = map->getMapSurfelsGpu();
int n = map->getMapSurfelCount();
//use projectionmodelview matrix to compute BBOX position in screen
pangolin::OpenGlMatrix mvp = s_cam_.GetProjectionModelViewMatrix();
Eigen::Matrix<float,4,4> matMVP;
for(int r=0; r<4; ++r ) {
for(int c=0; c<4; ++c ) {
matMVP(r,c) = (float)mvp.m[c*4+r];
}
}
//std::cout<<"Projection:"<<std::endl;
//std::cout<<s_cam_.GetProjectionMatrix()<<std::endl;
//std::cout<<"ModelView:"<<std::endl;
//std::cout<<s_cam_.GetModelViewMatrix()<<std::endl;
//std::cout<<"ModelView Inverse:"<<std::endl;
//std::cout<<s_cam_.GetModelViewMatrix().Inverse()<<std::endl;
//std::cout<<"Matrix MVP"<<std::endl;
//std::cout<<mvp<<std::endl;
//use modelview inverse matrix to get camera position -> use for depth
pangolin::OpenGlMatrix mvI = s_cam_.GetModelViewMatrix().Inverse();
Eigen::Matrix<float,4,4> matMVI;
for(int r=0; r<4; ++r ) {
for(int c=0; c<4; ++c ) {
matMVI(r,c) = (float)mvI.m[c*4+r];
}
}
Eigen::Vector3f trans = matMVI.topRightCorner(3, 1); //Eigen::Vector3f trans = map->getCurrPose().topRightCorner(3, 1);
cudaMemcpy(camPoseTrans_gpu, &trans(0), 3 * sizeof(float), cudaMemcpyHostToDevice); //input
cudaMemset(rgbdInfo_gpu,0, 4 * mainWidth * mainHeight * sizeof(float)); //output
//std::cout<<"trans: "<<trans(0)<<" "<<trans(1)<<" "<<trans(2)<<std::endl;
getRGBDformMapIDs(mapGlobalsurfelsIds,n,map_surfels,surfel_size,mainWidth,mainHeight,camPoseTrans_gpu,rgbdInfo_gpu);
//Step 2 draw 3DBBox in Info
if(drawBox&&n>0)
{
float* map3DBBox = instanceFusion->getMapBoundingBox();
int instanceNum = instanceFusion->getInstanceNum();
float* gcMatrix = instanceFusion->getGcMatrix();
float* instcMatrix = instanceFusion->getInstcMatrix();
cudaMemcpy(tempMap, rgbdInfo_gpu, 4 * mainWidth * mainHeight * sizeof(float), cudaMemcpyDeviceToHost); //input & output
int showBoxID=0;
for(int i=0;i<instanceNum;i++)
{
if(map3DBBox==0)break;
//std::cout<<"instanceID: "<<i<<std::endl;
float minX = map3DBBox[i*6+0]; float maxX = map3DBBox[i*6+1];
float minY = map3DBBox[i*6+2]; float maxY = map3DBBox[i*6+3];
float minZ = map3DBBox[i*6+4]; float maxZ = map3DBBox[i*6+5];
float v = (maxX-minX)*(maxY-minY)*(maxZ-minZ);
if(minX>=maxX||minY>=maxY||minZ>=maxZ/*||v>0.01f*/) continue;
//for scene19 scene21
//if(i!=1&&i!=11&&i<12)continue;
//show measureBBOX(bad code)
//char measureInfoBuf[30];
//std::sprintf(measureInfoBuf,"%4.2f/%4.2f/%4.2f",maxX-minX,maxY-minY,maxZ-minZ);
//if(class_colour_lookup_[i].name.c_str()[0]=='p')measureBBOX[showBoxID].reset(new pangolin::Var<std::string>("ui.item",measureInfoBuf));
//else if(class_colour_lookup_[i].name.c_str()[0]=='d')measureBBOX[showBoxID].reset(new pangolin::Var<std::string>("ui.table",measureInfoBuf));
//else if(class_colour_lookup_[i].name.c_str()[0]=='t')continue;
//else
//measureBBOX[showBoxID].reset(new pangolin::Var<std::string>("ui."+class_colour_lookup_[i].name+std::to_string(i),measureInfoBuf));
//if(showBoxID<12)showBoxID++;
//SKIP BY CROSS
/*
int flagContinue = 0;
for(int j=0;j<i;j++)
{
int count=0;
float minX2 = map3DBBox[j*6+0]; float maxX2 = map3DBBox[j*6+1];
float minY2 = map3DBBox[j*6+2]; float maxY2 = map3DBBox[j*6+3];
float minZ2 = map3DBBox[j*6+4]; float maxZ2 = map3DBBox[j*6+5];
if(minX2>minX&&minX2<maxX)count++;
if(minX2<minX&&minX<maxX2)count++;
if(minY2>minY&&minY2<maxY)count++;
if(minY2<minY&&minY<maxY2)count++;
if(minZ2>minZ&&minZ2<maxZ)count++;
if(minZ2<minZ&&minZ<maxZ2)count++;
if(count>=3)flagContinue=1;
}
if(flagContinue) continue;
*/
//Debug
//std::cout<<"instance: "<<i<<" minX:"<<minX<<" maxX:"<<maxX<<std::endl;
//std::cout<<"instance: "<<i<<" minY:"<<minY<<" maxY:"<<maxY<<std::endl;
//std::cout<<"instance: "<<i<<" minZ:"<<minZ<<" maxZ:"<<maxZ<<std::endl;
//3d point
float boxPoint3d_ground[8][3];
int p=0;
for(int a=0;a<=1;a++)
{
for(int b=0;b<=1;b++)
{
for(int c=0;c<=1;c++)
{
boxPoint3d_ground[p][0] = a==0?minX:maxX;
boxPoint3d_ground[p][1] = b==0?minY:maxY;
boxPoint3d_ground[p][2] = c==0?minZ:maxZ;
//Debug
//boxPoint3d_ground[p][0] = maxX;
//boxPoint3d_ground[p][1] = maxY;
//boxPoint3d_ground[p][2] = maxZ;
p++;
}
}
}
//ground->world
float boxPoint3d_world[8][3];
for(int j=0;j<8;j++)
{
if(bboxType) ////Ground
{
boxPoint3d_world[j][0] = gcMatrix[0]*boxPoint3d_ground[j][0] + gcMatrix[1]*boxPoint3d_ground[j][1]+ gcMatrix[ 2]*boxPoint3d_ground[j][2] + gcMatrix[ 3]*1.0f;
boxPoint3d_world[j][1] = gcMatrix[4]*boxPoint3d_ground[j][0] + gcMatrix[5]*boxPoint3d_ground[j][1]+ gcMatrix[ 6]*boxPoint3d_ground[j][2] + gcMatrix[ 7]*1.0f;
boxPoint3d_world[j][2] = gcMatrix[8]*boxPoint3d_ground[j][0] + gcMatrix[9]*boxPoint3d_ground[j][1]+ gcMatrix[10]*boxPoint3d_ground[j][2] + gcMatrix[11]*1.0f;
}
else
{
float bpgX = boxPoint3d_ground[j][0];
float bpgY = boxPoint3d_ground[j][1];
float bpgZ = boxPoint3d_ground[j][2];
boxPoint3d_world[j][0] = instcMatrix[i*16+0]*bpgX + instcMatrix[i*16+1]*bpgY+ instcMatrix[i*16+ 2]*bpgZ + instcMatrix[i*16+ 3]*1.0f;
boxPoint3d_world[j][1] = instcMatrix[i*16+4]*bpgX + instcMatrix[i*16+5]*bpgY+ instcMatrix[i*16+ 6]*bpgZ + instcMatrix[i*16+ 7]*1.0f;
boxPoint3d_world[j][2] = instcMatrix[i*16+8]*bpgX + instcMatrix[i*16+9]*bpgY+ instcMatrix[i*16+10]*bpgZ + instcMatrix[i*16+11]*1.0f;
}
//std::cout<<"x:"<<boxPoint3d_world[j][0]<<" y:"<<boxPoint3d_world[j][1]<<" z:"<<boxPoint3d_world[j][2]<<std::endl;
}
//std::cout<<std::endl;
//std::cout<<std::endl;
//2d point
float boxPoint2d[8][3];
for(int j=0;j<8;j++)
{
float vPosHome[3];
vPosHome[0] = matMVP(0,0)*boxPoint3d_world[j][0] + matMVP(0,1)*boxPoint3d_world[j][1]+ matMVP(0,2)*boxPoint3d_world[j][2] + matMVP(0,3)*1.0f;
vPosHome[1] = matMVP(1,0)*boxPoint3d_world[j][0] + matMVP(1,1)*boxPoint3d_world[j][1]+ matMVP(1,2)*boxPoint3d_world[j][2] + matMVP(1,3)*1.0f;
vPosHome[2] = matMVP(2,0)*boxPoint3d_world[j][0] + matMVP(2,1)*boxPoint3d_world[j][1]+ matMVP(2,2)*boxPoint3d_world[j][2] + matMVP(2,3)*1.0f;
//float fx = *fxBBOX.get();
//float fy = *fyBBOX.get();
//float cx = *cxBBOX.get();
//float cy = *cyBBOX.get();
float xloc = ((1440 * vPosHome[0]) / vPosHome[2]) + mainWidth *0.5;
float yloc = ((1080 * vPosHome[1]) / vPosHome[2]) + mainHeight*0.5;
float distX = trans(0)-boxPoint3d_world[j][0];
float distY = trans(1)-boxPoint3d_world[j][1];
float distZ = trans(2)-boxPoint3d_world[j][2];
float zloc = std::sqrt(distX*distX+distY*distY+distZ*distZ);
//float zloc = vPosHome[2] / 20.0f;
boxPoint2d[j][0] = xloc;
boxPoint2d[j][1] = yloc;
boxPoint2d[j][2] = zloc;
//std::cout<<"Screen_x:"<<xloc<<" Screen_y:"<<yloc<<std::endl;
}
//draw line
for(int j=0;j<8;j++)
{
for(int k=j+1;k<8;k++)
{
int flag = 0;
if(boxPoint2d[j][2]<=0||boxPoint2d[k][2]<=0) continue; //out of screen
if(boxPoint3d_ground[j][0]==boxPoint3d_ground[k][0])flag++;
if(boxPoint3d_ground[j][1]==boxPoint3d_ground[k][1])flag++;
if(boxPoint3d_ground[j][2]==boxPoint3d_ground[k][2])flag++;
if(flag==2)
{
float lineX = std::abs(boxPoint2d[j][0]-boxPoint2d[k][0]);
float lineY = std::abs(boxPoint2d[j][1]-boxPoint2d[k][1]);
float lineZ = std::abs(boxPoint2d[j][2]-boxPoint2d[k][2]);
float stepX,stepY,stepZ;
int needStep;
if(lineX>lineY)
{
stepX = 1;
stepY = (1.0f*lineY)/(1.0f*lineX);
stepZ = (1.0f*lineZ)/(1.0f*lineX);
needStep = lineX;
}
else if(lineX<lineY)
{
stepX = (1.0f*lineX)/(1.0f*lineY);
stepY = 1;
stepZ = (1.0f*lineZ)/(1.0f*lineY);
needStep = lineY;
}
//j to k
if(boxPoint2d[k][0]<boxPoint2d[j][0]) stepX = -stepX;
if(boxPoint2d[k][1]<boxPoint2d[j][1]) stepY = -stepY;
if(boxPoint2d[k][2]<boxPoint2d[j][2]) stepZ = -stepZ;
const int lineW = 7;
float nowX,nowY,nowZ;
nowX = boxPoint2d[j][0];
nowY = boxPoint2d[j][1];
nowZ = boxPoint2d[j][2];
for(int l=0;l<needStep;l++)
{
int Pixel_x = nowX;
int Pixel_y = nowY;
for(int m=0;m<lineW*lineW;m++)
{
int dy = (Pixel_y+m/lineW);
int dx = (Pixel_x+m%lineW);
if(dx>1&&dx<mainWidth-1&&dy>1&&dy<mainHeight-1)
{
if(nowZ<tempMap[dy*mainWidth*4+dx*4+3])
{
//if(j%2==0&&k%2==0)//(j<4&&k<4)
tempMap[dy*mainWidth*4+dx*4+0] = 1.0f;
//else
// tempMap[dy*mainWidth*4+dx*4+0] = 0.5f;
tempMap[dy*mainWidth*4+dx*4+1] = std::min(1.0f, class_colour_lookup_[i].g*1.5f/255.0f);
tempMap[dy*mainWidth*4+dx*4+2] = std::min(1.0f, class_colour_lookup_[i].b*1.5f/255.0f);
tempMap[dy*mainWidth*4+dx*4+3] = nowZ;
}
//else
//{
// tempMap[dy*mainWidth*4+dx*4+0] = tempMap[dy*mainWidth*4+dx*4+0]*0.95f+1.0f*0.05f;
// tempMap[dy*mainWidth*4+dx*4+1] = tempMap[dy*mainWidth*4+dx*4+1]*0.95f+std::min(1.0f, class_colour_lookup_[i].g*1.5f/255.0f)*0.05f;
// tempMap[dy*mainWidth*4+dx*4+2] = tempMap[dy*mainWidth*4+dx*4+2]*0.95f+std::min(1.0f, class_colour_lookup_[i].b*1.5f/255.0f)*0.05f;
//}
}
}
nowX+=stepX;
nowY+=stepY;
nowZ+=stepZ;
}
}
}
}
}
cudaMemcpy(rgbdInfo_gpu, tempMap, 4 * mainWidth * mainHeight * sizeof(float), cudaMemcpyHostToDevice);
}
//Step 3 render Info To Display
renderInfoToDisplay(rgbdInfo_gpu,mainWidth,mainHeight,mapDisplay_gpu);
//RenderToViewport
gpuErrChk(cudaGetLastError());
gpuErrChk(cudaGetLastError());
pangolin::CudaScopedMappedArray arr_tex(*mainDisplay_texture_array_.get());
cudaMemcpyToArray(*arr_tex, 0, 0, (void*)mapDisplay_gpu, sizeof(float) * 4 * mainWidth * mainHeight, cudaMemcpyDeviceToDevice);
gpuErrChk(cudaGetLastError());
gpuErrChk(cudaGetLastError());
glDisable(GL_DEPTH_TEST);
mainDisplay_texture_array_->RenderToViewport(true);
glEnable(GL_DEPTH_TEST);
}
void Gui::postCall()
{
pangolin::FinishFrame();
glFinish();
}
void Gui::displayProjectColor(const std::string & id, float* segmentation_rendering_gpu_)
{
gpuErrChk(cudaGetLastError());
gpuErrChk(cudaGetLastError());
pangolin::CudaScopedMappedArray arr_tex(*rendered_segmentation_texture_array_.get());
cudaMemcpyToArray(*arr_tex, 0, 0, (void*)segmentation_rendering_gpu_, sizeof(float) * 4 * segmentation_width_ * segmentation_height_, cudaMemcpyDeviceToDevice);
gpuErrChk(cudaGetLastError());
gpuErrChk(cudaGetLastError());
glDisable(GL_DEPTH_TEST);
pangolin::Display(id).Activate();
rendered_segmentation_texture_array_->RenderToViewport(true);
glEnable(GL_DEPTH_TEST);
}
void Gui::displayRawNetworkPredictions(const std::string & id, float* device_ptr)
{
pangolin::CudaScopedMappedArray arr_tex(*probability_texture_array_.get());
gpuErrChk(cudaGetLastError());
cudaMemcpyToArray(*arr_tex, 0, 0, (void*)device_ptr, sizeof(float) * 4 * segmentation_width_ * segmentation_height_, cudaMemcpyDeviceToDevice);
gpuErrChk(cudaGetLastError());
glDisable(GL_DEPTH_TEST);
pangolin::Display(id).Activate();
probability_texture_array_->RenderToViewport(true);
glEnable(GL_DEPTH_TEST);
}
void Gui::displayImg(const std::string & id, GPUTexture * img) {
glDisable(GL_DEPTH_TEST);
pangolin::Display(id).Activate();
img->texture->RenderToViewport(true);
glEnable(GL_DEPTH_TEST);
}
| 37.95986
| 162
| 0.688336
|
beichendexiatian
|
9af4379272c078c327799156deec4941a3abc3cb
| 3,486
|
hh
|
C++
|
Contract/DB/AwaitableQuery.hh
|
decouple/common
|
b1798868ab03ff349dccfd3fef09331ec0a1f4d3
|
[
"MIT"
] | null | null | null |
Contract/DB/AwaitableQuery.hh
|
decouple/common
|
b1798868ab03ff349dccfd3fef09331ec0a1f4d3
|
[
"MIT"
] | null | null | null |
Contract/DB/AwaitableQuery.hh
|
decouple/common
|
b1798868ab03ff349dccfd3fef09331ec0a1f4d3
|
[
"MIT"
] | null | null | null |
<?hh // strict
namespace Decouple\Common\Contract\DB;
/**
* This software is maintained voluntarily under the MIT license.
* For more information, see <http://www.decouple.io/>
*/
use Decouple\Common\Contract\Buildable;
/**
* An awaitable query interface implemented by classes that are queryable asynchronously
*
* @author Andrew Ewing <drew@phenocode.com>
*/
interface AwaitableQuery extends Queryable {
/**
* Execute the query
* @return Awaitable<Statement> The Statement result of Query execution
*/
public function execute(): Awaitable<Statement>;
/**
* Insert the provided data into the queryable datasource
* @param Map<string, mixed> $data The data to insert
* @return Awaitable<int> The ID of the inserted item
*/
public function insert(Map<string, mixed> $data): Awaitable<int>;
/**
* Retrieve the first result matching the current query structure
* @return Awaitable<?Map<string, mixed>> A Map of the result data or null if none found
*/
public function first(): Awaitable<?Map<string, mixed>>;
/**
* Fetch all of the results matching the current query structure
* @return Awaitable<?Map<string, mixed>> A Map of the results or null if none found
*/
public function fetchAll(): Awaitable<Vector<Map<string, mixed>>>;
/**
* Select the provided fields, or all fields if none/null provided
* @param ?Vector<string> $fields=null The fields to select
* @return AwaitableQuery The adjusted AwaitableQuery object
*/
public function select(?Vector<string> $fields = null): AwaitableQuery;
/**
* Update the queryable datasource with the given data
* @param Map<string, mixed> $data The data to update
* @return AwaitableQuery The adjusted AwaitableQuery object
*/
public function update(Map<string, mixed> $data): AwaitableQuery;
/**
* Delete all of the results matching the current query structure
* @param bool $soft=false Soft Delete
* @return AwaitableQuery The adjusted AwaitableQuery object
*/
public function delete(bool $soft = false): AwaitableQuery;
/**
* Assign the provided filter to the queryable datasource
* @param string $field The field to compare
* @param string $comp The comparator
* @param mixed $value The value to compare against
* @return AwaitableQuery The adjusted AwaitableQuery object
*/
public function where(string $field, string $comp, mixed $value): AwaitableQuery;
/**
* Assign the provided filter set to the queryable datasource
* @param KeyedTraversable<string, string> $array A traversable collection of filters
* @return Queryable The adjusted Queryable object
*/
public function whereAll(
KeyedTraversable<string, string> $array,
): Queryable;
/**
* Order the AwaitableQuery datasource by the given parameters
* @param string $field The field to order by
* @param string $direction The direction to order in
* @return AwaitableQuery The adjusted AwaitableQuery object
*/
public function orderBy(string $field, string $direction): AwaitableQuery;
/**
* Limit the AwaitableQuery datasource by the specified offsets
* @param int $min=0 The number of matching elements to bypass
* @param int $max=25 The number of matching elements to select
* @return AwaitableQuery The adjusted AwaitableQuery object
*/
public function limit(int $min = 0, int $max = 25): AwaitableQuery;
}
| 41.5
| 92
| 0.706827
|
decouple
|
9af5c007b6c7c2cc3f91e6d52c50e167dc930311
| 22,323
|
cpp
|
C++
|
rfal_st25tb.cpp
|
DiegoOst/RFAL
|
4d050bf2084f1c89746f4ad4a51542c64d555193
|
[
"Apache-2.0"
] | null | null | null |
rfal_st25tb.cpp
|
DiegoOst/RFAL
|
4d050bf2084f1c89746f4ad4a51542c64d555193
|
[
"Apache-2.0"
] | null | null | null |
rfal_st25tb.cpp
|
DiegoOst/RFAL
|
4d050bf2084f1c89746f4ad4a51542c64d555193
|
[
"Apache-2.0"
] | null | null | null |
/******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2016 STMicroelectronics</center></h2>
*
* Licensed under ST MYLIBERTY SOFTWARE LICENSE AGREEMENT (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.st.com/myliberty
*
* 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,
* AND SPECIFICALLY DISCLAIMING THE IMPLIED WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
/*
* PROJECT: ST25R391x firmware
* $Revision: $
* LANGUAGE: ISO C99
*/
/*! \file rfal_st25tb.c
*
* \author Gustavo Patricio
*
* \brief Implementation of ST25TB interface
*
*/
/*
******************************************************************************
* INCLUDES
******************************************************************************
*/
#include "rfal_st25tb.h"
#include "utils.h"
#include "platform1.h"
/*
******************************************************************************
* ENABLE SWITCH
******************************************************************************
*/
#ifndef RFAL_FEATURE_ST25TB
#error " RFAL: Module configuration missing. Please enable/disable ST25TB module by setting: RFAL_FEATURE_ST25TB "
#endif
#if RFAL_FEATURE_ST25TB
/*
******************************************************************************
* GLOBAL DEFINES
******************************************************************************
*/
#define RFAL_ST25TB_CMD_LEN 1 /*!< ST25TB length of a command */
#define RFAL_ST25TB_SLOTS 16 /*!< ST25TB number of slots */
#define RFAL_ST25TB_SLOTNUM_MASK 0x0F /*!< ST25TB Slot Number bit mask on SlotMarker */
#define RFAL_ST25TB_SLOTNUM_SHIFT 4 /*!< ST25TB Slot Number shift on SlotMarker */
#define RFAL_ST25TB_INITIATE_CMD1 0x06 /*!< ST25TB Initiate command byte1 */
#define RFAL_ST25TB_INITIATE_CMD2 0x00 /*!< ST25TB Initiate command byte2 */
#define RFAL_ST25TB_PCALL_CMD1 0x06 /*!< ST25TB Pcall16 command byte1 */
#define RFAL_ST25TB_PCALL_CMD2 0x04 /*!< ST25TB Pcall16 command byte2 */
#define RFAL_ST25TB_SELECT_CMD 0x0E /*!< ST25TB Select command */
#define RFAL_ST25TB_GET_UID_CMD 0x0B /*!< ST25TB Get UID command */
#define RFAL_ST25TB_COMPLETION_CMD 0x0F /*!< ST25TB Completion command */
#define RFAL_ST25TB_RESET_INV_CMD 0x0C /*!< ST25TB Reset to Inventory command */
#define RFAL_ST25TB_READ_BLOCK_CMD 0x08 /*!< ST25TB Read Block command */
#define RFAL_ST25TB_WRITE_BLOCK_CMD 0x09 /*!< ST25TB Write Block command */
#define RFAL_ST25TB_T0 2157 /*!< ST25TB t0 159 us ST25TB RF characteristics */
#define RFAL_ST25TB_T1 2048 /*!< ST25TB t1 151 us ST25TB RF characteristics */
#define RFAL_ST25TB_FWT (RFAL_ST25TB_T0 + RFAL_ST25TB_T1) /*!< ST25TB FWT = T0 + T1 */
#define RFAL_ST25TB_TW rfalConvMsTo1fc(7) /*!< ST25TB TW : Programming time for write max 7ms */
/*
******************************************************************************
* GLOBAL MACROS
******************************************************************************
*/
/*
******************************************************************************
* GLOBAL TYPES
******************************************************************************
*/
/*! Initiate Request */
typedef struct
{
uint8_t cmd1; /*!< Initiate Request cmd1: 0x06 */
uint8_t cmd2; /*!< Initiate Request cmd2: 0x00 */
} rfalSt25tbInitiateReq;
/*! Pcall16 Request */
typedef struct
{
uint8_t cmd1; /*!< Pcal16 Request cmd1: 0x06 */
uint8_t cmd2; /*!< Pcal16 Request cmd2: 0x04 */
} rfalSt25tbPcallReq;
/*! Select Request */
typedef struct
{
uint8_t cmd; /*!< Select Request cmd: 0x0E */
uint8_t chipId; /*!< Chip ID */
} rfalSt25tbSelectReq;
/*! Read Block Request */
typedef struct
{
uint8_t cmd; /*!< Select Request cmd: 0x08 */
uint8_t address; /*!< Block address */
} rfalSt25tbReadBlockReq;
/*! Write Block Request */
typedef struct
{
uint8_t cmd; /*!< Select Request cmd: 0x09 */
uint8_t address; /*!< Block address */
rfalSt25tbBlock data; /*!< Block Data */
} rfalSt25tbWriteBlockReq;
/*
******************************************************************************
* LOCAL FUNCTION PROTOTYPES
******************************************************************************
*/
/*
******************************************************************************
* LOCAL VARIABLES
******************************************************************************
*/
/*
******************************************************************************
* GLOBAL FUNCTIONS
******************************************************************************
*/
/*******************************************************************************/
ReturnCode rfalSt25tbPollerInitialize( SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
return rfalNfcbPollerInitialize( mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerCheckPresence( uint8_t *chipId, SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
ReturnCode ret;
uint8_t chipIdRes;
chipIdRes = 0x00;
/* Send Initiate Request */
ret = rfalSt25tbPollerInitiate( &chipIdRes, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* Check if a transmission error was detected */
if( (ret == ERR_CRC) || (ret == ERR_FRAMING) )
{
return ERR_NONE;
}
/* Copy chip ID if requested */
if( chipId != NULL )
{
*chipId = chipIdRes;
}
return ret;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerInitiate( uint8_t *chipId,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
ReturnCode ret;
uint16_t rxLen;
rfalSt25tbInitiateReq initiateReq;
uint8_t rxBuf[RFAL_ST25TB_CHIP_ID_LEN + RFAL_ST25TB_CRC_LEN]; /* In case we receive less data that CRC, RF layer will not remove the CRC from buffer */
/* Compute Initiate Request */
initiateReq.cmd1 = RFAL_ST25TB_INITIATE_CMD1;
initiateReq.cmd2 = RFAL_ST25TB_INITIATE_CMD2;
/* Send Initiate Request */
ret = rfalTransceiveBlockingTxRx( (uint8_t*)&initiateReq, sizeof(rfalSt25tbInitiateReq), (uint8_t*)rxBuf, sizeof(rxBuf), &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* Check for valid Select Response */
if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN) )
{
return ERR_PROTO;
}
/* Copy chip ID if requested */
if( chipId != NULL )
{
*chipId = *rxBuf;
}
return ret;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerPcall( uint8_t *chipId,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
ReturnCode ret;
uint16_t rxLen;
rfalSt25tbPcallReq pcallReq;
/* Compute Pcal16 Request */
pcallReq.cmd1 = RFAL_ST25TB_PCALL_CMD1;
pcallReq.cmd2 = RFAL_ST25TB_PCALL_CMD2;
/* Send Pcal16 Request */
ret = rfalTransceiveBlockingTxRx( (uint8_t*)&pcallReq, sizeof(rfalSt25tbPcallReq), (uint8_t*)chipId, RFAL_ST25TB_CHIP_ID_LEN, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* Check for valid Select Response */
if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN) )
{
return ERR_PROTO;
}
return ret;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerSlotMarker( uint8_t slotNum, uint8_t *chipIdRes,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
ReturnCode ret;
uint16_t rxLen;
uint8_t slotMarker;
if( (slotNum == 0) || (slotNum > 15) )
{
return ERR_PARAM;
}
/* Compute SlotMarker */
slotMarker = ( ((slotNum & RFAL_ST25TB_SLOTNUM_MASK) << RFAL_ST25TB_SLOTNUM_SHIFT) | RFAL_ST25TB_PCALL_CMD1 );
/* Send SlotMarker */
ret = rfalTransceiveBlockingTxRx( (uint8_t*)&slotMarker, RFAL_ST25TB_CMD_LEN, (uint8_t*)chipIdRes, RFAL_ST25TB_CHIP_ID_LEN, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* Check for valid ChipID Response */
if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_CHIP_ID_LEN) )
{
return ERR_PROTO;
}
return ret;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerSelect( uint8_t chipId,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
ReturnCode ret;
uint16_t rxLen;
rfalSt25tbSelectReq selectReq;
uint8_t chipIdRes;
/* Compute Select Request */
selectReq.cmd = RFAL_ST25TB_SELECT_CMD;
selectReq.chipId = chipId;
/* Send Select Request */
ret = rfalTransceiveBlockingTxRx( (uint8_t*)&selectReq, sizeof(rfalSt25tbSelectReq), (uint8_t*)&chipIdRes, RFAL_ST25TB_CHIP_ID_LEN, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* Check for valid Select Response */
if( (ret == ERR_NONE) && ((rxLen != RFAL_ST25TB_CHIP_ID_LEN) || (chipIdRes != chipId)) )
{
return ERR_PROTO;
}
return ret;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerGetUID( rfalSt25tbUID *UID,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
ReturnCode ret;
uint16_t rxLen;
uint8_t getUidReq;
/* Compute Get UID Request */
getUidReq = RFAL_ST25TB_GET_UID_CMD;
/* Send Select Request */
ret = rfalTransceiveBlockingTxRx( (uint8_t*)&getUidReq, RFAL_ST25TB_CMD_LEN, (uint8_t*)UID, sizeof(rfalSt25tbUID), &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* Check for valid UID Response */
if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_UID_LEN) )
{
return ERR_PROTO;
}
return ret;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerCollisionResolution( uint8_t devLimit, rfalSt25tbListenDevice *st25tbDevList, uint8_t *devCnt,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
uint8_t i;
uint8_t chipId;
ReturnCode ret;
bool detected; /* collision or device was detected */
if( (st25tbDevList == NULL) || (devCnt == NULL) || (devLimit == 0) )
{
return ERR_PARAM;
}
*devCnt = 0;
/* Step 1: Send Initiate */
ret = rfalSt25tbPollerInitiate( &chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
if( ret == ERR_NONE )
{
/* If only 1 answer is detected */
st25tbDevList[*devCnt].chipID = chipId;
st25tbDevList[*devCnt].isDeselected = false;
/* Retrieve its UID and keep it Selected*/
ret = rfalSt25tbPollerSelect( chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
if( ERR_NONE == ret )
{
ret = rfalSt25tbPollerGetUID( &st25tbDevList[*devCnt].UID, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
}
if( ERR_NONE == ret )
{
(*devCnt)++;
}
}
/* Always proceed to Pcall16 anticollision as phase differences of tags can lead to no tag recognized, even if there is one */
if( *devCnt < devLimit )
{
/* Multiple device responses */
do
{
detected = false;
for(i = 0; i < RFAL_ST25TB_SLOTS; i++)
{
platformDelay(1); /* Wait t2: Answer to new request delay */
if( i==0 )
{
/* Step 2: Send Pcall16 */
ret = rfalSt25tbPollerPcall( &chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
}
else
{
/* Step 3-17: Send Pcall16 */
ret = rfalSt25tbPollerSlotMarker( i, &chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
}
if( ret == ERR_NONE )
{
/* Found another device */
st25tbDevList[*devCnt].chipID = chipId;
st25tbDevList[*devCnt].isDeselected = false;
/* Select Device, retrieve its UID */
ret = rfalSt25tbPollerSelect( chipId, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* By Selecting this device, the previous gets Deselected */
if( (*devCnt) > 0 )
{
st25tbDevList[(*devCnt)-1].isDeselected = true;
}
if( ERR_NONE == ret )
{
rfalSt25tbPollerGetUID( &st25tbDevList[*devCnt].UID, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
}
if( ERR_NONE == ret )
{
(*devCnt)++;
}
}
else if( (ret == ERR_CRC) || (ret == ERR_FRAMING) )
{
detected = true;
}
if( *devCnt >= devLimit )
{
break;
}
}
}
while( (detected == true) && (*devCnt < devLimit) );
}
return ERR_NONE;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerReadBlock( uint8_t blockAddress, rfalSt25tbBlock *blockData,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
ReturnCode ret;
uint16_t rxLen;
rfalSt25tbReadBlockReq readBlockReq;
/* Compute Read Block Request */
readBlockReq.cmd = RFAL_ST25TB_READ_BLOCK_CMD;
readBlockReq.address = blockAddress;
/* Send Read Block Request */
ret = rfalTransceiveBlockingTxRx( (uint8_t*)&readBlockReq, sizeof(rfalSt25tbReadBlockReq), (uint8_t*)blockData, sizeof(rfalSt25tbBlock), &rxLen, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* Check for valid UID Response */
if( (ret == ERR_NONE) && (rxLen != RFAL_ST25TB_BLOCK_LEN) )
{
return ERR_PROTO;
}
return ret;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerWriteBlock( uint8_t blockAddress, rfalSt25tbBlock *blockData,SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
ReturnCode ret;
uint16_t rxLen;
rfalSt25tbWriteBlockReq writeBlockReq;
rfalSt25tbBlock tmpBlockData;
/* Compute Write Block Request */
writeBlockReq.cmd = RFAL_ST25TB_WRITE_BLOCK_CMD;
writeBlockReq.address = blockAddress;
ST_MEMCPY( writeBlockReq.data, blockData, RFAL_ST25TB_BLOCK_LEN );
/* Send Write Block Request */
ret = rfalTransceiveBlockingTxRx( (uint8_t*)&writeBlockReq, sizeof(rfalSt25tbWriteBlockReq), tmpBlockData, RFAL_ST25TB_BLOCK_LEN, &rxLen, RFAL_TXRX_FLAGS_DEFAULT, (RFAL_ST25TB_FWT + RFAL_ST25TB_TW), mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
/* Check if an unexpected answer was received */
if( ret == ERR_NONE )
{
return ERR_PROTO;
}
/* Check there was any error besides Timeout*/
else if( ret != ERR_TIMEOUT )
{
return ret;
}
ret = rfalSt25tbPollerReadBlock(blockAddress, &tmpBlockData, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
if( ret == ERR_NONE )
{
if( !ST_BYTECMP( tmpBlockData, blockData, RFAL_ST25TB_BLOCK_LEN ) )
{
return ERR_NONE;
}
return ERR_PROTO;
}
return ret;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerCompletion( SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
uint8_t completionReq;
/* Compute Completion Request */
completionReq = RFAL_ST25TB_COMPLETION_CMD;
/* Send Completion Request, no response is expected */
return rfalTransceiveBlockingTxRx( (uint8_t*)&completionReq, RFAL_ST25TB_CMD_LEN, NULL, 0, NULL, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
}
/*******************************************************************************/
ReturnCode rfalSt25tbPollerResetToInventory( SPI* mspiChannel, ST25R3911* mST25, DigitalOut* gpio_cs, InterruptIn* IRQ, DigitalOut* fieldLED_01, DigitalOut* fieldLED_02, DigitalOut* fieldLED_03, DigitalOut* fieldLED_04, DigitalOut* fieldLED_05, DigitalOut* fieldLED_06 )
{
uint8_t resetInvReq;
/* Compute Completion Request */
resetInvReq = RFAL_ST25TB_RESET_INV_CMD;
/* Send Completion Request, no response is expected */
return rfalTransceiveBlockingTxRx( (uint8_t*)&resetInvReq, RFAL_ST25TB_CMD_LEN, NULL, 0, NULL, RFAL_TXRX_FLAGS_DEFAULT, RFAL_ST25TB_FWT, mspiChannel, mST25, gpio_cs, IRQ, fieldLED_01, fieldLED_02, fieldLED_03, fieldLED_04, fieldLED_05, fieldLED_06 ) ;
}
#endif /* RFAL_FEATURE_ST25TB */
| 43.17795
| 346
| 0.560857
|
DiegoOst
|
9af98a615cfbf0ee6e792a1299bf60ecec5e0c5c
| 2,084
|
cpp
|
C++
|
LeetCode/DynamicProgramming/BestTimeToBuyAndSellStockii.cpp
|
a4org/Angorithm4
|
d2227d36608491bed270375bcea67fbde134209a
|
[
"MIT"
] | 3
|
2021-07-26T15:58:45.000Z
|
2021-09-08T14:55:11.000Z
|
LeetCode/DynamicProgramming/BestTimeToBuyAndSellStockii.cpp
|
a4org/Angorithm4
|
d2227d36608491bed270375bcea67fbde134209a
|
[
"MIT"
] | null | null | null |
LeetCode/DynamicProgramming/BestTimeToBuyAndSellStockii.cpp
|
a4org/Angorithm4
|
d2227d36608491bed270375bcea67fbde134209a
|
[
"MIT"
] | 2
|
2021-05-31T11:27:59.000Z
|
2021-10-03T13:26:00.000Z
|
/*
* LeetCode 122 Best time to Buy And Sell Stock ii
* Medium
* Shuo Feng
* 2021.11.10
*/
#include<iostream>
#include<vector>
using namespace std;
/*
* Solution 1: Dp
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int days = prices.size();
// The maximum profit we can get in day i with two situations:
vector<vector<int>> dp(days, vector<int>(2, 0));
// In days i:
// dp[i][0] : own no stock.
// dp[i][1] : own stock.
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < days; ++i) {
// Two situations in day i
// I. own no stock: (1) own no stock in day i - 1.
// (2) sell in day i - 1.
//
// II. own stock: (1) own in day i - 1.
// (2) buy a stock in day i - 1.
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
// Always earn the most after sell all stock.
return dp[days - 1][0];
}
};
/*
* Solution 1.5: Dp Optimize on the basis of solution 1.
* no: own no stock. (correspond dp[i][0] in solution 1.)
* hold: own a stock. (correspond dp[i][1] in solution 1.)
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int days = prices.size();
// Day 1:
int no = 0;
int hold = -prices[0];
for (int i = 1; i < days; ++i) {
no = max (no, hold + prices[i]);
hold = max (hold, no - prices[i]);
}
return no;
}
};
/*
* Solution 2: Greedy.
* Sell Stock whenever we can earn.
*/
class Solution {
public:
int maxProfit(vector<int>& prices) {
int days = prices.size();
int maxPro = 0;
for (int i = 1; i < days; ++i) {
if (prices[i] > prices[i - 1]) {
maxPro += prices[i] - prices[i - 1];
}
}
return maxPro;
}
};
| 22.901099
| 70
| 0.458733
|
a4org
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.