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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0184efcc3b5989736813b82f861630e2889a8d41
| 134
|
cpp
|
C++
|
first_app.cpp
|
venim1103/sdl-vulkan-demo
|
5c8f36eabf820e3bfb23da0aadb3be6b313a5629
|
[
"Apache-2.0"
] | null | null | null |
first_app.cpp
|
venim1103/sdl-vulkan-demo
|
5c8f36eabf820e3bfb23da0aadb3be6b313a5629
|
[
"Apache-2.0"
] | null | null | null |
first_app.cpp
|
venim1103/sdl-vulkan-demo
|
5c8f36eabf820e3bfb23da0aadb3be6b313a5629
|
[
"Apache-2.0"
] | null | null | null |
#include "first_app.hpp"
namespace vulkan
{
void FirstApp::run()
{
SDL_Event event;
while(!sdlwindow.shouldClose(&event));
}
}
| 10.307692
| 40
| 0.69403
|
venim1103
|
0184f99805058d61808eb95383e1f95ac4607084
| 1,013
|
cpp
|
C++
|
test/aoj/0560.test.cpp
|
atree-GitHub/competitive-library
|
606b444036530b698a6363b1a41cdaa90a7f9578
|
[
"CC0-1.0"
] | 1
|
2022-01-25T23:03:10.000Z
|
2022-01-25T23:03:10.000Z
|
test/aoj/0560.test.cpp
|
atree4728/competitive-library
|
1aaa4d2cf9283b9a1a3d4c7f114ff7b867ca2f8b
|
[
"CC0-1.0"
] | 6
|
2021-10-06T01:17:04.000Z
|
2022-01-16T14:45:47.000Z
|
test/aoj/0560.test.cpp
|
atree-GitHub/competitive-library
|
606b444036530b698a6363b1a41cdaa90a7f9578
|
[
"CC0-1.0"
] | null | null | null |
#define PROBLEM "http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=0560"
#include <cassert>
#include <iostream>
#include "lib/data_structure/partial_sum_2D.hpp"
int main() {
using namespace std;
size_t n, m, q;
cin >> n >> m >> q;
vector<string> field(n);
for (auto &&elem: field) cin >> elem;
vector<vector<int>> jcnt(n, vector(m, 0)), ocnt(n, vector(m, 0)), icnt(n, vector(m, 0));
for (size_t i = 0; i < n; i++)
for (size_t j = 0; j < m; j++) {
switch (field[i][j]) {
case 'J': jcnt[i][j]++; break;
case 'O': ocnt[i][j]++; break;
case 'I': icnt[i][j]++; break;
default: assert(false);
}
}
CumSum2D<int> jc(jcnt), oc(ocnt), ic(icnt);
while (q--) {
size_t sx, sy, gx, gy;
cin >> sx >> sy >> gx >> gy;
cout << jc(sx - 1, sy - 1, gx, gy) << " " << oc(sx - 1, sy - 1, gx, gy)
<< " " << ic(sx - 1, sy - 1, gx, gy) << "\n";
}
}
| 32.677419
| 92
| 0.467917
|
atree-GitHub
|
01854efcd74250706192739705de9ec6b2d42d42
| 3,151
|
cpp
|
C++
|
modules/task_2/kolesin_a_bubblesort/main.cpp
|
LioBuitrago/pp_2020_autumn_informatics
|
1ecc1b5dae978295778176ff11ffe42bedbc602e
|
[
"BSD-3-Clause"
] | 1
|
2020-11-20T15:05:12.000Z
|
2020-11-20T15:05:12.000Z
|
modules/task_2/kolesin_a_bubblesort/main.cpp
|
LioBuitrago/pp_2020_autumn_informatics
|
1ecc1b5dae978295778176ff11ffe42bedbc602e
|
[
"BSD-3-Clause"
] | 1
|
2021-02-13T03:00:05.000Z
|
2021-02-13T03:00:05.000Z
|
modules/task_2/kolesin_a_bubblesort/main.cpp
|
LioBuitrago/pp_2020_autumn_informatics
|
1ecc1b5dae978295778176ff11ffe42bedbc602e
|
[
"BSD-3-Clause"
] | 1
|
2020-10-11T09:11:57.000Z
|
2020-10-11T09:11:57.000Z
|
// Copyright 2020 Kolesin Andrey
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <stdio.h>
#include <random>
#include <vector>
#include <algorithm>
#include "./bubblesort.h"
TEST(Count_Words, Test_1) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> arr = {1};
parallelSort(&arr[0], arr.size());
if (rank == 0) {
EXPECT_EQ(arr, std::vector<int>({1}));
}
}
TEST(Count_Words, Test_5) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> arr = {-4, 10, 10, 10, 10};
parallelSort(&arr[0], arr.size());
if (rank == 0) {
EXPECT_EQ(arr, std::vector<int>({-4, 10, 10, 10, 10}));
}
}
TEST(Count_Words, Test_6) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> arr = {-4, 10, 10, 10, 10, -4};
parallelSort(&arr[0], arr.size());
if (rank == 0) {
EXPECT_EQ(arr, std::vector<int>({-4, -4, 10, 10, 10, 10}));
}
}
TEST(Count_Words, Test_12) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> arr = {12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
parallelSort(&arr[0], arr.size());
if (rank == 0) {
EXPECT_EQ(arr, std::vector<int>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}));
}
}
TEST(Count_Words, Test_13) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> arr = {13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
parallelSort(&arr[0], arr.size());
if (rank == 0) {
EXPECT_EQ(arr, std::vector<int>({1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}));
}
}
TEST(Count_Words, Test_Random) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
std::vector<int> arr = getRandomArray();
std::vector<int> arr2 = arr;
if (rank == 0) {
parallelSort(&arr[0], arr.size());
std::sort(arr2.begin(), arr2.end());
EXPECT_EQ(arr, arr2);
} else {
int a;
parallelSort(&a, 0);
}
}
// TEST(Count_Words, Test_CompareTime) {
// int rank;
// MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// std::vector<int> arr = getRandomArray(10000);
// std::vector<int> arr2 = arr;
// if (rank == 0) {
// double t1 = MPI_Wtime();
// parallelSort(&arr[0],arr.size());
// double t2 = MPI_Wtime();
// SortMass(&arr2[0],arr2.size());
// double t3 = MPI_Wtime();
// std::cout<<"seq: "<<t3-t2<<std::endl<<"paral: "<<t2-t1<<std::endl;
// std::cout<<"s/p: "<<(t3-t2)/(t2-t1)<<std::endl;
// EXPECT_EQ(arr, arr2);
// }
// else{
// std::vector<int> a = {};
// parallelSort(&arr[0],2);
// }
// }
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 30.592233
| 86
| 0.569026
|
LioBuitrago
|
0188369b84b64e22807211ad007ac4f33e189ef3
| 343
|
hpp
|
C++
|
src/sys/house.hpp
|
Hopobcn/EnTT-Pacman
|
5187472419f05b79fa9b92593e85fff7c0ae6ca1
|
[
"MIT"
] | null | null | null |
src/sys/house.hpp
|
Hopobcn/EnTT-Pacman
|
5187472419f05b79fa9b92593e85fff7c0ae6ca1
|
[
"MIT"
] | null | null | null |
src/sys/house.hpp
|
Hopobcn/EnTT-Pacman
|
5187472419f05b79fa9b92593e85fff7c0ae6ca1
|
[
"MIT"
] | null | null | null |
//
// house.hpp
// EnTT Pacman
//
// Created by Indi Kernick on 29/9/18.
// Copyright © 2018 Indi Kernick. All rights reserved.
//
#ifndef SYS_HOUSE_HPP
#define SYS_HOUSE_HPP
#include "util/registry.hpp"
// These systems deal with ghosts entering and leaving the house
void enterHouse(Registry &);
void leaveHouse(Registry &);
#endif
| 17.15
| 64
| 0.720117
|
Hopobcn
|
018e7beb17ff3ac7140452cde5d3b1849993d0f1
| 21,319
|
cc
|
C++
|
build/px4_sitl_default/build_gazebo/MagneticField.pb.cc
|
amilearning/PX4-Autopilot
|
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
|
[
"BSD-3-Clause"
] | null | null | null |
build/px4_sitl_default/build_gazebo/MagneticField.pb.cc
|
amilearning/PX4-Autopilot
|
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
|
[
"BSD-3-Clause"
] | null | null | null |
build/px4_sitl_default/build_gazebo/MagneticField.pb.cc
|
amilearning/PX4-Autopilot
|
c1b997fbc48492689a5f6d0a090d1ea2c7d6c272
|
[
"BSD-3-Clause"
] | null | null | null |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: MagneticField.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "MagneticField.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace sensor_msgs {
namespace msgs {
namespace {
const ::google::protobuf::Descriptor* MagneticField_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
MagneticField_reflection_ = NULL;
} // namespace
void protobuf_AssignDesc_MagneticField_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AssignDesc_MagneticField_2eproto() {
protobuf_AddDesc_MagneticField_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"MagneticField.proto");
GOOGLE_CHECK(file != NULL);
MagneticField_descriptor_ = file->message_type(0);
static const int MagneticField_offsets_[3] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, time_usec_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, magnetic_field_),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, magnetic_field_covariance_),
};
MagneticField_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
MagneticField_descriptor_,
MagneticField::default_instance_,
MagneticField_offsets_,
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, _has_bits_[0]),
-1,
-1,
sizeof(MagneticField),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(MagneticField, _internal_metadata_),
-1);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_MagneticField_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
MagneticField_descriptor_, &MagneticField::default_instance());
}
} // namespace
void protobuf_ShutdownFile_MagneticField_2eproto() {
delete MagneticField::default_instance_;
delete MagneticField_reflection_;
}
void protobuf_AddDesc_MagneticField_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AddDesc_MagneticField_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::gazebo::msgs::protobuf_AddDesc_vector3d_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\023MagneticField.proto\022\020sensor_msgs.msgs\032"
"\016vector3d.proto\"x\n\rMagneticField\022\021\n\ttime"
"_usec\030\001 \002(\003\022-\n\016magnetic_field\030\002 \002(\0132\025.ga"
"zebo.msgs.Vector3d\022%\n\031magnetic_field_cov"
"ariance\030\003 \003(\002B\002\020\001", 177);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"MagneticField.proto", &protobuf_RegisterTypes);
MagneticField::default_instance_ = new MagneticField();
MagneticField::default_instance_->InitAsDefaultInstance();
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_MagneticField_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_MagneticField_2eproto {
StaticDescriptorInitializer_MagneticField_2eproto() {
protobuf_AddDesc_MagneticField_2eproto();
}
} static_descriptor_initializer_MagneticField_2eproto_;
// ===================================================================
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int MagneticField::kTimeUsecFieldNumber;
const int MagneticField::kMagneticFieldFieldNumber;
const int MagneticField::kMagneticFieldCovarianceFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
MagneticField::MagneticField()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
SharedCtor();
// @@protoc_insertion_point(constructor:sensor_msgs.msgs.MagneticField)
}
void MagneticField::InitAsDefaultInstance() {
magnetic_field_ = const_cast< ::gazebo::msgs::Vector3d*>(&::gazebo::msgs::Vector3d::default_instance());
}
MagneticField::MagneticField(const MagneticField& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
MergeFrom(from);
// @@protoc_insertion_point(copy_constructor:sensor_msgs.msgs.MagneticField)
}
void MagneticField::SharedCtor() {
_cached_size_ = 0;
time_usec_ = GOOGLE_LONGLONG(0);
magnetic_field_ = NULL;
::memset(_has_bits_, 0, sizeof(_has_bits_));
}
MagneticField::~MagneticField() {
// @@protoc_insertion_point(destructor:sensor_msgs.msgs.MagneticField)
SharedDtor();
}
void MagneticField::SharedDtor() {
if (this != default_instance_) {
delete magnetic_field_;
}
}
void MagneticField::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* MagneticField::descriptor() {
protobuf_AssignDescriptorsOnce();
return MagneticField_descriptor_;
}
const MagneticField& MagneticField::default_instance() {
if (default_instance_ == NULL) protobuf_AddDesc_MagneticField_2eproto();
return *default_instance_;
}
MagneticField* MagneticField::default_instance_ = NULL;
MagneticField* MagneticField::New(::google::protobuf::Arena* arena) const {
MagneticField* n = new MagneticField;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void MagneticField::Clear() {
// @@protoc_insertion_point(message_clear_start:sensor_msgs.msgs.MagneticField)
if (_has_bits_[0 / 32] & 3u) {
time_usec_ = GOOGLE_LONGLONG(0);
if (has_magnetic_field()) {
if (magnetic_field_ != NULL) magnetic_field_->::gazebo::msgs::Vector3d::Clear();
}
}
magnetic_field_covariance_.Clear();
::memset(_has_bits_, 0, sizeof(_has_bits_));
if (_internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->Clear();
}
}
bool MagneticField::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:sensor_msgs.msgs.MagneticField)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// required int64 time_usec = 1;
case 1: {
if (tag == 8) {
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>(
input, &time_usec_)));
set_has_time_usec();
} else {
goto handle_unusual;
}
if (input->ExpectTag(18)) goto parse_magnetic_field;
break;
}
// required .gazebo.msgs.Vector3d magnetic_field = 2;
case 2: {
if (tag == 18) {
parse_magnetic_field:
DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual(
input, mutable_magnetic_field()));
} else {
goto handle_unusual;
}
if (input->ExpectTag(26)) goto parse_magnetic_field_covariance;
break;
}
// repeated float magnetic_field_covariance = 3 [packed = true];
case 3: {
if (tag == 26) {
parse_magnetic_field_covariance:
DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
input, this->mutable_magnetic_field_covariance())));
} else if (tag == 29) {
DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline<
float, ::google::protobuf::internal::WireFormatLite::TYPE_FLOAT>(
1, 26, input, this->mutable_magnetic_field_covariance())));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormat::SkipField(
input, tag, mutable_unknown_fields()));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:sensor_msgs.msgs.MagneticField)
return true;
failure:
// @@protoc_insertion_point(parse_failure:sensor_msgs.msgs.MagneticField)
return false;
#undef DO_
}
void MagneticField::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:sensor_msgs.msgs.MagneticField)
// required int64 time_usec = 1;
if (has_time_usec()) {
::google::protobuf::internal::WireFormatLite::WriteInt64(1, this->time_usec(), output);
}
// required .gazebo.msgs.Vector3d magnetic_field = 2;
if (has_magnetic_field()) {
::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(
2, *this->magnetic_field_, output);
}
// repeated float magnetic_field_covariance = 3 [packed = true];
if (this->magnetic_field_covariance_size() > 0) {
::google::protobuf::internal::WireFormatLite::WriteTag(3, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output);
output->WriteVarint32(_magnetic_field_covariance_cached_byte_size_);
}
for (int i = 0; i < this->magnetic_field_covariance_size(); i++) {
::google::protobuf::internal::WireFormatLite::WriteFloatNoTag(
this->magnetic_field_covariance(i), output);
}
if (_internal_metadata_.have_unknown_fields()) {
::google::protobuf::internal::WireFormat::SerializeUnknownFields(
unknown_fields(), output);
}
// @@protoc_insertion_point(serialize_end:sensor_msgs.msgs.MagneticField)
}
::google::protobuf::uint8* MagneticField::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
// @@protoc_insertion_point(serialize_to_array_start:sensor_msgs.msgs.MagneticField)
// required int64 time_usec = 1;
if (has_time_usec()) {
target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(1, this->time_usec(), target);
}
// required .gazebo.msgs.Vector3d magnetic_field = 2;
if (has_magnetic_field()) {
target = ::google::protobuf::internal::WireFormatLite::
InternalWriteMessageNoVirtualToArray(
2, *this->magnetic_field_, false, target);
}
// repeated float magnetic_field_covariance = 3 [packed = true];
if (this->magnetic_field_covariance_size() > 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray(
3,
::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED,
target);
target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray(
_magnetic_field_covariance_cached_byte_size_, target);
}
for (int i = 0; i < this->magnetic_field_covariance_size(); i++) {
target = ::google::protobuf::internal::WireFormatLite::
WriteFloatNoTagToArray(this->magnetic_field_covariance(i), target);
}
if (_internal_metadata_.have_unknown_fields()) {
target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray(
unknown_fields(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:sensor_msgs.msgs.MagneticField)
return target;
}
int MagneticField::RequiredFieldsByteSizeFallback() const {
// @@protoc_insertion_point(required_fields_byte_size_fallback_start:sensor_msgs.msgs.MagneticField)
int total_size = 0;
if (has_time_usec()) {
// required int64 time_usec = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->time_usec());
}
if (has_magnetic_field()) {
// required .gazebo.msgs.Vector3d magnetic_field = 2;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->magnetic_field_);
}
return total_size;
}
int MagneticField::ByteSize() const {
// @@protoc_insertion_point(message_byte_size_start:sensor_msgs.msgs.MagneticField)
int total_size = 0;
if (((_has_bits_[0] & 0x00000003) ^ 0x00000003) == 0) { // All required fields are present.
// required int64 time_usec = 1;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int64Size(
this->time_usec());
// required .gazebo.msgs.Vector3d magnetic_field = 2;
total_size += 1 +
::google::protobuf::internal::WireFormatLite::MessageSizeNoVirtual(
*this->magnetic_field_);
} else {
total_size += RequiredFieldsByteSizeFallback();
}
// repeated float magnetic_field_covariance = 3 [packed = true];
{
int data_size = 0;
data_size = 4 * this->magnetic_field_covariance_size();
if (data_size > 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::Int32Size(data_size);
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_magnetic_field_covariance_cached_byte_size_ = data_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
total_size += data_size;
}
if (_internal_metadata_.have_unknown_fields()) {
total_size +=
::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize(
unknown_fields());
}
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = total_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void MagneticField::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:sensor_msgs.msgs.MagneticField)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
const MagneticField* source =
::google::protobuf::internal::DynamicCastToGenerated<const MagneticField>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:sensor_msgs.msgs.MagneticField)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:sensor_msgs.msgs.MagneticField)
MergeFrom(*source);
}
}
void MagneticField::MergeFrom(const MagneticField& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:sensor_msgs.msgs.MagneticField)
if (GOOGLE_PREDICT_FALSE(&from == this)) {
::google::protobuf::internal::MergeFromFail(__FILE__, __LINE__);
}
magnetic_field_covariance_.MergeFrom(from.magnetic_field_covariance_);
if (from._has_bits_[0 / 32] & (0xffu << (0 % 32))) {
if (from.has_time_usec()) {
set_time_usec(from.time_usec());
}
if (from.has_magnetic_field()) {
mutable_magnetic_field()->::gazebo::msgs::Vector3d::MergeFrom(from.magnetic_field());
}
}
if (from._internal_metadata_.have_unknown_fields()) {
mutable_unknown_fields()->MergeFrom(from.unknown_fields());
}
}
void MagneticField::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:sensor_msgs.msgs.MagneticField)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void MagneticField::CopyFrom(const MagneticField& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:sensor_msgs.msgs.MagneticField)
if (&from == this) return;
Clear();
MergeFrom(from);
}
bool MagneticField::IsInitialized() const {
if ((_has_bits_[0] & 0x00000003) != 0x00000003) return false;
if (has_magnetic_field()) {
if (!this->magnetic_field_->IsInitialized()) return false;
}
return true;
}
void MagneticField::Swap(MagneticField* other) {
if (other == this) return;
InternalSwap(other);
}
void MagneticField::InternalSwap(MagneticField* other) {
std::swap(time_usec_, other->time_usec_);
std::swap(magnetic_field_, other->magnetic_field_);
magnetic_field_covariance_.UnsafeArenaSwap(&other->magnetic_field_covariance_);
std::swap(_has_bits_[0], other->_has_bits_[0]);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata MagneticField::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = MagneticField_descriptor_;
metadata.reflection = MagneticField_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// MagneticField
// required int64 time_usec = 1;
bool MagneticField::has_time_usec() const {
return (_has_bits_[0] & 0x00000001u) != 0;
}
void MagneticField::set_has_time_usec() {
_has_bits_[0] |= 0x00000001u;
}
void MagneticField::clear_has_time_usec() {
_has_bits_[0] &= ~0x00000001u;
}
void MagneticField::clear_time_usec() {
time_usec_ = GOOGLE_LONGLONG(0);
clear_has_time_usec();
}
::google::protobuf::int64 MagneticField::time_usec() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.MagneticField.time_usec)
return time_usec_;
}
void MagneticField::set_time_usec(::google::protobuf::int64 value) {
set_has_time_usec();
time_usec_ = value;
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.MagneticField.time_usec)
}
// required .gazebo.msgs.Vector3d magnetic_field = 2;
bool MagneticField::has_magnetic_field() const {
return (_has_bits_[0] & 0x00000002u) != 0;
}
void MagneticField::set_has_magnetic_field() {
_has_bits_[0] |= 0x00000002u;
}
void MagneticField::clear_has_magnetic_field() {
_has_bits_[0] &= ~0x00000002u;
}
void MagneticField::clear_magnetic_field() {
if (magnetic_field_ != NULL) magnetic_field_->::gazebo::msgs::Vector3d::Clear();
clear_has_magnetic_field();
}
const ::gazebo::msgs::Vector3d& MagneticField::magnetic_field() const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.MagneticField.magnetic_field)
return magnetic_field_ != NULL ? *magnetic_field_ : *default_instance_->magnetic_field_;
}
::gazebo::msgs::Vector3d* MagneticField::mutable_magnetic_field() {
set_has_magnetic_field();
if (magnetic_field_ == NULL) {
magnetic_field_ = new ::gazebo::msgs::Vector3d;
}
// @@protoc_insertion_point(field_mutable:sensor_msgs.msgs.MagneticField.magnetic_field)
return magnetic_field_;
}
::gazebo::msgs::Vector3d* MagneticField::release_magnetic_field() {
// @@protoc_insertion_point(field_release:sensor_msgs.msgs.MagneticField.magnetic_field)
clear_has_magnetic_field();
::gazebo::msgs::Vector3d* temp = magnetic_field_;
magnetic_field_ = NULL;
return temp;
}
void MagneticField::set_allocated_magnetic_field(::gazebo::msgs::Vector3d* magnetic_field) {
delete magnetic_field_;
magnetic_field_ = magnetic_field;
if (magnetic_field) {
set_has_magnetic_field();
} else {
clear_has_magnetic_field();
}
// @@protoc_insertion_point(field_set_allocated:sensor_msgs.msgs.MagneticField.magnetic_field)
}
// repeated float magnetic_field_covariance = 3 [packed = true];
int MagneticField::magnetic_field_covariance_size() const {
return magnetic_field_covariance_.size();
}
void MagneticField::clear_magnetic_field_covariance() {
magnetic_field_covariance_.Clear();
}
float MagneticField::magnetic_field_covariance(int index) const {
// @@protoc_insertion_point(field_get:sensor_msgs.msgs.MagneticField.magnetic_field_covariance)
return magnetic_field_covariance_.Get(index);
}
void MagneticField::set_magnetic_field_covariance(int index, float value) {
magnetic_field_covariance_.Set(index, value);
// @@protoc_insertion_point(field_set:sensor_msgs.msgs.MagneticField.magnetic_field_covariance)
}
void MagneticField::add_magnetic_field_covariance(float value) {
magnetic_field_covariance_.Add(value);
// @@protoc_insertion_point(field_add:sensor_msgs.msgs.MagneticField.magnetic_field_covariance)
}
const ::google::protobuf::RepeatedField< float >&
MagneticField::magnetic_field_covariance() const {
// @@protoc_insertion_point(field_list:sensor_msgs.msgs.MagneticField.magnetic_field_covariance)
return magnetic_field_covariance_;
}
::google::protobuf::RepeatedField< float >*
MagneticField::mutable_magnetic_field_covariance() {
// @@protoc_insertion_point(field_mutable_list:sensor_msgs.msgs.MagneticField.magnetic_field_covariance)
return &magnetic_field_covariance_;
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace msgs
} // namespace sensor_msgs
// @@protoc_insertion_point(global_scope)
| 36.195246
| 143
| 0.735166
|
amilearning
|
0192040515727a93065c7763efdbbe306a22e3e9
| 2,270
|
cpp
|
C++
|
OS/linux.cpp
|
partouf/GoPiGoCPP
|
b0605953cf5f810d7452b2a0d0592cd6715403d7
|
[
"MIT"
] | 1
|
2016-03-08T13:30:39.000Z
|
2016-03-08T13:30:39.000Z
|
OS/linux.cpp
|
partouf/GoPiGoCPP
|
b0605953cf5f810d7452b2a0d0592cd6715403d7
|
[
"MIT"
] | null | null | null |
OS/linux.cpp
|
partouf/GoPiGoCPP
|
b0605953cf5f810d7452b2a0d0592cd6715403d7
|
[
"MIT"
] | null | null | null |
#include "linux.h"
#include <stdio.h>
#include <stdlib.h>
#include <linux/i2c-dev.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdexcept>
#include <string>
GoPiGo::LinuxBoard::LinuxBoard(int AI2CDeviceNumber) : IBoard()
{
this->I2CDeviceNumber = AI2CDeviceNumber;
this->fd = 0;
this->busy = false;
}
GoPiGo::LinuxBoard::~LinuxBoard()
{
this->Disconnect();
}
void GoPiGo::LinuxBoard::Disconnect()
{
::close(fd);
fd = 0;
}
bool GoPiGo::LinuxBoard::Connect()
{
int i, raw;
std::string fileName = "/dev/i2c-" + std::to_string(I2CDeviceNumber);
int address = 0x08;
if ((fd = ::open(fileName.c_str(), O_RDWR)) < 0)
{
// Open port for reading and writing
LastKnownError = "Failed to open i2c port - " + fileName;
return false;
}
if (::ioctl(fd, I2C_SLAVE, address) < 0)
{
Disconnect();
// Set the port options and set the address of the device
LastKnownError = "Unable to get bus access to talk to slave";
return false;
}
this->ReloadBoardVersion();
this->ReloadFirmwareVersion();
return true;
}
bool GoPiGo::LinuxBoard::IsConnected()
{
return (fd != 0);
}
void GoPiGo::LinuxBoard::Sleep(milliseconds_t ATime)
{
::usleep(ATime * 1000);
}
bool GoPiGo::LinuxBoard::WriteBlock(char ACommand, char AValue1, char AValue2, char AValue3)
{
unsigned char w_buf[5];
w_buf[0] = 1;
w_buf[1] = ACommand;
w_buf[2] = AValue1;
w_buf[3] = AValue2;
w_buf[4] = AValue3;
if ((::write(fd, w_buf, 5)) != 5)
{
LastKnownError = "Error writing to GoPiGo";
return false;
}
this->Sleep(70);
return true;
}
char GoPiGo::LinuxBoard::ReadByte()
{
unsigned char r_buf[32];
int reg_size = 1;
if (::read(fd, r_buf, reg_size) != reg_size) {
throw new std::runtime_error("Error reading from GoPiGo");
return -1;
}
return r_buf[0];
}
bool GoPiGo::LinuxBoard::LockWhenAvailable(int ATimeout)
{
// no need to use actual mutex until we're really going to use threads
while (this->busy)
{
Sleep(1);
}
this->busy = true;
return true;
}
bool GoPiGo::LinuxBoard::Unlock()
{
this->busy = false;
return true;
}
| 17.734375
| 92
| 0.629075
|
partouf
|
0197d688542c3d7014675a027dc5e9ae40b81266
| 8,257
|
cpp
|
C++
|
converter.cpp
|
jackMilano/QT-Converter
|
8089f1b028dee223bc536788789ca7aa96d44b95
|
[
"MIT"
] | null | null | null |
converter.cpp
|
jackMilano/QT-Converter
|
8089f1b028dee223bc536788789ca7aa96d44b95
|
[
"MIT"
] | null | null | null |
converter.cpp
|
jackMilano/QT-Converter
|
8089f1b028dee223bc536788789ca7aa96d44b95
|
[
"MIT"
] | null | null | null |
#include "converter.h"
#include "ui_converter.h"
#include <QComboBox>
#include <QEventLoop>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QVector>
#include <QtWidgets>
#include <cmath>
#include <iostream>
Converter::Converter(QWidget *parent) :
QMainWindow(parent),
_ui(new Ui::Converter),
_cached(QVector<bool>(_currencyCodes.size())),
_cachedValueDatetime(QVector<QDateTime>(_currencyCodes.size())),
_currencyValues(QVector<QVector<double>>(_currencyCodes.size())),
_currentIndexComboBox1(_currencyCodes.indexOf("GBP")),
_currentIndexComboBox2(_currencyCodes.indexOf("EUR")),
_qNetworkAccessManager(new QNetworkAccessManager(this)),
_qValidator(new QDoubleValidator(INPUT_VAL_MIN, INPUT_VAL_MAX, 2, this))
{
_ui->setupUi(this);
// Initialization
for(int i = 0; i < _currencyValues.size(); i++)
{
_currencyValues[i] = QVector<double>(_currencyCodes.size());
}
for(const QString currencyCode : _currencyCodes)
{
_ui->comboBox->addItem(currencyCode);
_ui->comboBox_2->addItem(currencyCode);
}
_ui->comboBox->setCurrentIndex(_currentIndexComboBox1);
_ui->comboBox_2->setCurrentIndex(_currentIndexComboBox2);
// Setting input validation
_ui->lineEdit->setValidator(_qValidator);
// Signals to slots connections
connect(_ui->lineEdit, SIGNAL(textEdited(const QString &)), this, SLOT(HandleLineEditTextEditedSignal(const QString &)));
connect(_ui->lineEdit_2, SIGNAL(textEdited(const QString &)), this, SLOT(HandleLineEditTextEditedSignal(const QString &)));
connect(_qNetworkAccessManager, SIGNAL(finished(QNetworkReply*)), this, SLOT(ReplyFinished(QNetworkReply*)));
connect(_ui->comboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(ChangeCurrencyComboBox(const int)));
connect(_ui->comboBox_2, SIGNAL(currentIndexChanged(int)), this, SLOT(ChangeCurrencyComboBox(const int)));
// Showing default message in the status bar
statusBar()->showMessage(tr("Insert the value you want to convert"));
// The second qLineEdit start disabled
DisableLineEdit(_ui->lineEdit_2);
// First conversion starts as soon the program begins
HandleEnteredText(_ui->lineEdit->text(), _ui->lineEdit, _ui->lineEdit_2);
}
Converter::~Converter()
{
delete _ui;
}
void Converter::HandleLineEditTextEditedSignal(const QString &inputText)
{
// The empty string is not filtered by validator
if(inputText == nullptr || inputText == "")
{
return;
}
QObject * obj = sender();
QLineEdit * qLineEdit;
QLineEdit * otherQLineEdit;
if(obj == _ui->lineEdit)
{
_isFirstLineEdit = true;
qLineEdit = _ui->lineEdit;
otherQLineEdit = _ui->lineEdit_2;
}
else if(obj == _ui->lineEdit_2)
{
_isFirstLineEdit = false;
qLineEdit = _ui->lineEdit_2;
otherQLineEdit = _ui->lineEdit;
}
else
{
return;
}
HandleEnteredText(inputText, qLineEdit, otherQLineEdit);
}
void Converter::ReplyFinished(QNetworkReply * reply)
{
QLineEdit * qLineEdit = _isFirstLineEdit ? _ui->lineEdit : _ui->lineEdit_2;
QLineEdit * otherQLineEdit = _isFirstLineEdit ? _ui->lineEdit_2 : _ui->lineEdit;
if(reply->error())
{
qDebug() << "ERROR!";
qDebug() << reply->errorString();
}
else
{
const int index = _isFirstLineEdit ? _currentIndexComboBox1 : _currentIndexComboBox2;
const int otherIndex = _isFirstLineEdit ? _currentIndexComboBox2 : _currentIndexComboBox1;
const QJsonDocument qJsonDocument = QJsonDocument::fromJson(reply->readAll());
QJsonObject qJsonObject = qJsonDocument.object();
QJsonValue qJsonValue = qJsonObject.value("rates");
qJsonObject = qJsonValue.toObject();
int size = _currencyCodes.size();
for(int i = 0; i < size; i++)
{
QString currencyCode = _currencyCodes[i];
qJsonValue = qJsonObject.value(currencyCode);
double currencyRelVal = qJsonValue.toDouble();
if(i == index)
{
continue;
}
_currencyValues[index][i] = currencyRelVal;
}
_cached[index] = true;
_cachedValueDatetime[index] = QDateTime::currentDateTime();
ConvertAndShowValue(otherQLineEdit, index, otherIndex);
}
// Reenabling qLineEditInput
EnableLineEdit(qLineEdit);
EnableLineEdit(otherQLineEdit);
reply->deleteLater();
}
void Converter::ChangeCurrencyComboBox(const int newIndexComboBox)
{
QObject * obj = sender();
QComboBox * otherComboBox;
int comboBoxIndex = -1;
QLineEdit * qLineEdit;
QLineEdit * otherQLineEdit;
if(obj == _ui->comboBox)
{
otherComboBox = _ui->comboBox_2;
comboBoxIndex = _currentIndexComboBox1;
_currentIndexComboBox1 = newIndexComboBox;
_isFirstLineEdit = true;
qLineEdit = _ui->lineEdit;
otherQLineEdit = _ui->lineEdit_2;
}
else if(obj == _ui->comboBox_2)
{
otherComboBox = _ui->comboBox;
comboBoxIndex = _currentIndexComboBox2;
_currentIndexComboBox2 = newIndexComboBox;
_isFirstLineEdit = false;
qLineEdit = _ui->lineEdit_2;
otherQLineEdit = _ui->lineEdit;
}
else
{
return;
}
const int otherComboBoxIndex = otherComboBox->currentIndex();
if(newIndexComboBox == otherComboBoxIndex)
{
otherComboBox->setCurrentIndex(comboBoxIndex);
return;
}
HandleEnteredText(qLineEdit->text(), qLineEdit, otherQLineEdit);
return;
}
void Converter::HandleEnteredText(const QString &inputText, QLineEdit * const qLineEdit, QLineEdit * const otherQLineEdit)
{
const int index = _isFirstLineEdit ? _currentIndexComboBox1 : _currentIndexComboBox2;
const int otherIndex = _isFirstLineEdit ? _currentIndexComboBox2 : _currentIndexComboBox1;
// The input is converted into a number.
_inputNumber = ConvertStringToNumber(inputText);
// Disabling qLineEditInput
DisableLineEdit(qLineEdit);
DisableLineEdit(otherQLineEdit);
// Let's check if we can use a cached value or values needs updating
bool updateCurrencies = false;
if(_cached[index])
{
int secondsPassedFromLastUpdate = _cachedValueDatetime[index].secsTo(QDateTime::currentDateTime());
if(secondsPassedFromLastUpdate > UPDATE_CURRENCIES_INTERVAL)
{
updateCurrencies = true;
}
else
{
ConvertAndShowValue(otherQLineEdit, index, otherIndex);
}
}
else
{
updateCurrencies = true;
}
if(updateCurrencies)
{
QString url = QString("https://api.fixer.io/latest?base=") + _currencyCodes[index];
_qNetworkAccessManager->get(QNetworkRequest(QUrl(url)));
}
else
{
EnableLineEdit(qLineEdit);
EnableLineEdit(otherQLineEdit);
}
}
void Converter::ConvertAndShowValue(QLineEdit * const qLineEdit, const int currentIndexFrom, const int currentIndexTo)
{
const double relVal = _currencyValues[currentIndexFrom][currentIndexTo];
double result = _inputNumber * relVal;
result = roundf(result * 100.0f) / 100.0f;
qLineEdit->setText(QString::number(result));
return;
}
void Converter::DisableLineEdit(QLineEdit * const qLineEdit)
{
qLineEdit->setReadOnly(true);
// TODO: trasformare in campo della classe
QPalette *palette = new QPalette();
palette->setColor(QPalette::Base, Qt::white);
palette->setColor(QPalette::Text, Qt::darkGray);
qLineEdit->setPalette(*palette);
return;
}
void Converter::EnableLineEdit(QLineEdit * const qLineEdit)
{
qLineEdit->setReadOnly(false);
qLineEdit->setPalette(qLineEdit->style()->standardPalette());
return;
}
const double Converter::ConvertStringToNumber(const QString &inputText)
{
const QByteArray qByteArray = inputText.toLatin1();
const char *inputTextCharArray = qByteArray.data();
double num = -1.0f;
int sscanfRetVal = sscanf_s(inputTextCharArray, "%lf", &num);
if(sscanfRetVal == 0 || sscanfRetVal == EOF)
{
return 0;
}
return num;
}
| 28.870629
| 127
| 0.675669
|
jackMilano
|
019885849c6e40616f80020631204cd3811ae869
| 14,162
|
cpp
|
C++
|
graphicspiece.cpp
|
0yinf/Klotski
|
df3c3d6ea58d936e059b31c614bdafebd88e70ec
|
[
"MIT"
] | 2
|
2017-09-17T16:16:15.000Z
|
2017-09-17T16:16:18.000Z
|
graphicspiece.cpp
|
0yinf/Klotski
|
df3c3d6ea58d936e059b31c614bdafebd88e70ec
|
[
"MIT"
] | 1
|
2017-09-21T08:27:20.000Z
|
2017-09-21T08:27:20.000Z
|
graphicspiece.cpp
|
0yinf/Klotski
|
df3c3d6ea58d936e059b31c614bdafebd88e70ec
|
[
"MIT"
] | 3
|
2017-09-13T02:44:46.000Z
|
2017-09-17T05:41:11.000Z
|
//#define IGNORE_VALID_MOVES
#define MOVE_SYNC_THRESHOLD 0.6
//#define MOVE_DIRECTION_LIMIT_CANCEL_THRESHOLD 0.03
#include "common.h"
#include "graphicspiece.h"
#include "move.h"
#include <QPainter>
#include <QWidget>
#include <QGraphicsScene>
#include <QDebug>
#include <QGraphicsSceneMouseEvent>
#include <QSequentialAnimationGroup>
#include <QKeyEvent>
#include <QPropertyAnimation>
#include <QFont>
#include <cmath>
GraphicsPiece::GraphicsPiece(int index, const Piece &piece)
: piece_(piece), index_(index)
{
clearValidMoveDirection();
hovered_ = false;
pressed_ = false;
focused_ = false;
in_animation_ = false;
have_skin_ = false;
edit_mode_ = false;
virtual_initial_mouse_pos_ = QPointF(0, 0);
piece_base_pos_ = QPointF(0, 0);
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable);
setAcceptHoverEvents(true);
qDebug() << "New GraphicsPiece" << index << piece_.geometry();
}
const Piece &GraphicsPiece::piece() const {
return piece_;
}
int GraphicsPiece::index() const {
return index_;
}
void GraphicsPiece::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) {
Q_UNUSED(option)
Q_UNUSED(widget)
if (have_skin_) {
painter->setBrush(background_brush_);
painter->drawRoundedRect(rect_, scale_ * 0.05, scale_ * 0.05);
}
QPen pen;
pen.setColor(Qt::black);
pen.setJoinStyle(Qt::RoundJoin);
pen.setCapStyle(Qt::RoundCap);
pen.setColor(Qt::black);
pen.setJoinStyle(Qt::RoundJoin);
pen.setCapStyle(Qt::RoundCap);
if (focused_) {
pen.setWidth(3);
} else {
pen.setWidth(2);
}
// Background
painter->setPen(pen);
if (pressed_)
painter->setBrush(QColor(200, 200, 200, have_skin_ ? 64 : 128));
else
painter->setBrush(QColor(128, 128, 128, have_skin_ ? 64 : 128));
painter->drawRoundedRect(rect_, scale_ * 0.05, scale_ * 0.05);
// Arrows
QRectF bounding_rect = boundingRect();
if (!in_animation_) {
if (focused_ || have_skin_) {
painter->setBrush(QBrush(Qt::white));
} else {
painter->setBrush(QBrush(Qt::black));
}
pen.setWidth(0);
painter->setPen(pen);
qreal free_space = scale_ * 0.05;
if (can_move_up_) {
QPolygonF polygon;
polygon << QPointF(bounding_rect.width() / 2, free_space * 2)
<< QPointF(bounding_rect.width() / 2 - free_space * 2, free_space * 4)
<< QPointF(bounding_rect.width() / 2 + free_space * 2, free_space * 4);
painter->drawPolygon(polygon);
}
if (can_move_down_) {
QPolygonF polygon;
polygon << QPointF(bounding_rect.width() / 2, bounding_rect.height() - free_space * 2)
<< QPointF(bounding_rect.width() / 2 - free_space * 2, bounding_rect.height() - free_space * 4)
<< QPointF(bounding_rect.width() / 2 + free_space * 2, bounding_rect.height() - free_space * 4);
painter->drawPolygon(polygon);
}
if (can_move_left_) {
QPolygonF polygon;
polygon << QPointF(free_space * 2, bounding_rect.height() / 2)
<< QPointF(free_space * 4, bounding_rect.height() / 2 - free_space * 2)
<< QPointF(free_space * 4, bounding_rect.height() / 2 + free_space * 2);
painter->drawPolygon(polygon);
}
if (can_move_right_) {
QPolygonF polygon;
polygon << QPointF(bounding_rect.width() - free_space * 2, bounding_rect.height() / 2)
<< QPointF(bounding_rect.width() - free_space * 4, bounding_rect.height() / 2 - free_space * 2)
<< QPointF(bounding_rect.width() - free_space * 4, bounding_rect.height() / 2 + free_space * 2);
painter->drawPolygon(polygon);
}
}
// Text
if (have_skin_) {
pen.setColor(Qt::white);
} else {
pen.setColor(Qt::black);
}
painter->setPen(pen);
static QFont font("Microsoft YaHei", 20);
QFontMetrics font_metrics(font);
QSize text_size = font_metrics.size(Qt::TextSingleLine, tr("%1").arg(index_));
painter->setFont(font);
painter->drawText(
QPointF(bounding_rect.width() / 2 - text_size.width() / 2,
bounding_rect.height() / 2 + text_size.height() / 2),
QString("%1").arg(index_)
);
}
void GraphicsPiece::setBackgroundImage(const QImage &image) {
if (image.isNull()) {
have_skin_ = false;
} else {
have_skin_ = true;
background_image_ = image;
scaleBackgroundImageToBrush();
}
update();
}
void GraphicsPiece::scaleBackgroundImageToBrush() {
background_brush_ = background_image_.scaled(boundingRect().size().toSize(), Qt::KeepAspectRatioByExpanding);
}
void GraphicsPiece::setEditMode(bool edit_mode) {
edit_mode_ = edit_mode;
addValidMoveDirection(Move()); // force refresh valid moves
update();
}
QRectF GraphicsPiece::boundingRect() const {
return QRectF(QPointF(0, 0), piece_.size() * scale_);
// ignore free space for easy drawing
}
QRectF GraphicsPiece::calcRect(const Piece &piece) {
qreal space_height = scale_ * piece.size().height();
qreal space_width = scale_ * piece.size().width();
qreal free_space = scale_ * 0.05;
QRectF res(0, 0, 0, 0);
res.setSize(QSizeF(space_width - 2 * free_space, space_height - 2 * free_space));
res.moveTopLeft(QPointF( free_space, free_space));
// qDebug() << "calcRect" << "piece" << piece.geometry() << "calculated" << res;
return res;
}
QPointF GraphicsPiece::calcPosition(const Piece &piece) {
QPointF pos(piece.position().x() * scale_, piece.position().y() * scale_);
// qDebug() << "calcPosition" << "piece" << piece.geometry() << "calculated" << pos;
return pos;
}
QPointF GraphicsPiece::calcPosition(const QPoint &point) {
QPointF pos(point.x() * scale_, point.y() * scale_);
// qDebug() << "calcPosition" << "point" << point << "calculated" << pos;
return pos;
}
void GraphicsPiece::onSceneResize() {
if (scene() != nullptr) {
scale_ = scene()->sceneRect().width() / kHorizontalUnit;
rect_ = calcRect(piece_);
piece_base_pos_ = calcPosition(piece_);
setPos(piece_base_pos_);
if (have_skin_) {
scaleBackgroundImageToBrush();
}
qDebug() << "GraphicsPiece" << index_ << "Resize boundingRect" << boundingRect() << "pos" << pos();
update();
} else {
qDebug() << "Invalid" << "scene_";
rect_ = QRectF(0, 0, 0, 0);
}
}
void GraphicsPiece::hoverEnterEvent(QGraphicsSceneHoverEvent *event) {
QGraphicsObject::hoverEnterEvent(event);
setFocus();
hovered_ = true;
qDebug() << this << "hoverEnterEvent";
}
void GraphicsPiece::hoverLeaveEvent(QGraphicsSceneHoverEvent *event) {
QGraphicsObject::hoverLeaveEvent(event);
hovered_ = false;
qDebug() << this << "hoverLeaveEvent";
}
void GraphicsPiece::mousePressEvent(QGraphicsSceneMouseEvent *event) {
QGraphicsObject::mousePressEvent(event);
pressed_ = true;
update(); // update color
if (event->button() & Qt::LeftButton) {
// moving_direction_ = Direction::invalid;
virtual_initial_mouse_pos_ = event->scenePos();
}
if (edit_mode_ && (event->button() & Qt::RightButton)) {
rotatePiece();
}
qDebug() << this << "mousePressEvent" << event->button();
}
void GraphicsPiece::mouseMoveEvent(QGraphicsSceneMouseEvent *event) {
if (in_animation_) {
return;
}
if (event->button() & Qt::LeftButton) {
QGraphicsObject::mouseMoveEvent(event);
return;
}
QPointF current_mouse_pos = event->scenePos();
QPointF mouse_move = current_mouse_pos - virtual_initial_mouse_pos_;
QPointF piece_move = QPointF(0, 0);
if (std::abs(mouse_move.y()) > std::abs(mouse_move.x())) {
if (mouse_move.y() < 0) {
if (can_move_up_) {
piece_move = QPointF(0, mouse_move.y());
if (abs(piece_move.y()) > scale_ * MOVE_SYNC_THRESHOLD) {
applyMove(Move(index_, 0, -1), false);
virtual_initial_mouse_pos_.setY(virtual_initial_mouse_pos_.y() - scale_);
piece_move = QPointF(0, scale_ + mouse_move.y());
}
}
} else
if (can_move_down_) {
piece_move = QPointF(0, mouse_move.y());
if (abs(piece_move.y()) > scale_ * MOVE_SYNC_THRESHOLD) {
applyMove(Move(index_, 0, 1), false);
virtual_initial_mouse_pos_.setY(virtual_initial_mouse_pos_.y() + scale_);
piece_move = QPointF(0, -scale_ + mouse_move.y());
}
}
} else {
if (mouse_move.x() < 0) {
if (can_move_left_) {
piece_move = QPointF(mouse_move.x(), 0);
if (abs(piece_move.x()) > scale_ * MOVE_SYNC_THRESHOLD) {
applyMove(Move(index_, -1, 0), false);
virtual_initial_mouse_pos_.setX(virtual_initial_mouse_pos_.x() - scale_);
piece_move = QPointF(scale_ + mouse_move.x(), 0);
}
}
} else {
if (can_move_right_) {
piece_move = QPointF(mouse_move.x(), 0);
if (abs(piece_move.x()) > scale_ * MOVE_SYNC_THRESHOLD) {
applyMove(Move(index_, 1, 0), false);
virtual_initial_mouse_pos_.setX(virtual_initial_mouse_pos_.x() + scale_);
piece_move = QPointF(- scale_ + mouse_move.x(), 0);
}
}
}
// if (abs(piece_move.x()) > scale_)
// piece_move.setX(piece_move.x() > 0 ? scale_ : -scale_);
}
qDebug("%d, %d, %d, %d", can_move_up_, can_move_down_, can_move_left_, can_move_right_);
qDebug() << "virtual_initial_mouse_pos_" << virtual_initial_mouse_pos_;
qDebug() << "current_mouse_pos" << current_mouse_pos;
qDebug() << "piece_base_pos_" << piece_base_pos_;
qDebug() << "mouse_move" << mouse_move;
qDebug() << "piece_move" << piece_move;
setPos(piece_base_pos_ + piece_move);
update();
// QGraphicsObject::mouseMoveEvent(event);
qDebug() << this << "mouseMoveEvent" << event->button();
}
void GraphicsPiece::mouseReleaseEvent(QGraphicsSceneMouseEvent *event) {
QGraphicsObject::mouseReleaseEvent(event);
pressed_ = false;
update();
if (!in_animation_) {
applyMove(Move(-1, 0, 0));
}
qDebug() << this << "mouseReleaseEvent" << event->button();
}
void GraphicsPiece::keyPressEvent(QKeyEvent *event) {
QGraphicsObject::keyPressEvent(event);
int x = 0, y = 0;
switch (event->key()) {
case Qt::Key_W: case Qt::Key_Up:
y = can_move_up_ ? -1 : 0;
break;
case Qt::Key_S: case Qt::Key_Down:
y = can_move_down_ ? 1 : 0;
break;
case Qt::Key_A: case Qt::Key_Left:
x = can_move_left_ ? -1 : 0;
break;
case Qt::Key_D: case Qt::Key_Right:
x = can_move_right_ ? 1 : 0;
break;
case Qt::Key_R:
if (edit_mode_) {
rotatePiece();
}
break;
}
qDebug() << "Keypress move" << x << y;
if (x != 0 || y != 0) {
applyMove(Move(index_, x, y));
}
qDebug() << this << "keyPressEvent";
}
void GraphicsPiece::focusInEvent(QFocusEvent *event) {
qDebug() << index_ << event;
focused_ = true;
// gain focus will auto update
}
void GraphicsPiece::focusOutEvent(QFocusEvent *event) {
qDebug() << index_ << event;
focused_ = false;
update();
}
void GraphicsPiece::clearValidMoveDirection() {
if(!edit_mode_) {
can_move_up_ = can_move_down_ = can_move_right_ = can_move_left_ = false;
}
qDebug() << "Piece" << index_ << "clearValidMoveDirection";
update();
}
void GraphicsPiece::addValidMoveDirection(const Move &valid_move) {
qDebug() << "Piece" << index_ << "adding valid move direction";
if(!edit_mode_) {
if (valid_move.y() == -1)
can_move_up_ = true;
else if (valid_move.y() == 1)
can_move_down_ = true;
else if (valid_move.x() == -1)
can_move_left_ = true;
else if (valid_move.x() == 1)
can_move_right_ = true;
} else {
can_move_down_ = can_move_right_ = can_move_left_ = can_move_up_ = true;
}
update();
}
void GraphicsPiece::applyMove(const Move &move, bool animate) {
static std::size_t emitted = 0;
if (move.id() != emitted) {
piece_ << move;
QPointF last_piece_base_pos = piece_base_pos_;
piece_base_pos_ = calcPosition(piece_);
if (animate) {
QPropertyAnimation *animation = new QPropertyAnimation(this, "pos");
animation->setEndValue(piece_base_pos_);
animation->setDuration(200);
if (move.isNull()) {
animation->setStartValue(pos());
animation->start(QPropertyAnimation::DeleteWhenStopped);
} else {
animation->setStartValue(last_piece_base_pos);
addAnimation(animation);
}
}
qDebug() << "Move" << &move << "Finished on View";
if (move.index() != -1) {
emitted = move.id();
qDebug() << "[EMIT] syncMove(move)";
emit syncMove(move);
}
} else {
qDebug() << "Move" << &move << "required on View but have be down";
}
}
void GraphicsPiece::animationFinished() {
in_animation_ = false;
update();
}
void GraphicsPiece::animationStarted() {
in_animation_ = true;
// auto update by animation
}
void GraphicsPiece::rotatePiece() {
QRect old_rect = piece_.geometry();
piece_ = Piece(QRect(old_rect.x(), old_rect.y(), old_rect.height(), old_rect.width()));
onSceneResize(); // resize graphics piece
scene()->update();
emit pieceRotated(index_);
}
| 33.961631
| 116
| 0.59695
|
0yinf
|
019ded58dc8cb5bb2ae9c8f747fb644d00efffe2
| 431
|
hpp
|
C++
|
Hurrican/src/enemies/Gegner_Diamant.hpp
|
s1eve-mcdichae1/Hurrican
|
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
|
[
"MIT"
] | 21
|
2018-04-13T10:45:45.000Z
|
2022-03-29T14:53:43.000Z
|
Hurrican/src/enemies/Gegner_Diamant.hpp
|
s1eve-mcdichae1/Hurrican
|
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
|
[
"MIT"
] | 10
|
2018-07-03T02:08:44.000Z
|
2021-05-17T16:13:21.000Z
|
Hurrican/src/enemies/Gegner_Diamant.hpp
|
s1eve-mcdichae1/Hurrican
|
3ed6ff9ee94d2ea2b79e451466d28f06d58acf19
|
[
"MIT"
] | 3
|
2021-10-08T12:35:05.000Z
|
2022-03-03T06:03:49.000Z
|
#ifndef _GEGNER_DIAMANT_H
#define _GEGNER_DIAMANT_H
#include "GegnerClass.hpp"
#include "Gegner_Stuff.hpp"
class GegnerDiamant : public GegnerClass {
public:
GegnerDiamant(int Wert1,
int Wert2, // Konstruktor
bool Light);
void GegnerExplode() override; // Gegner explodiert
void DoKI() override; // Gegner individuell mit seiner eigenen kleinen KI bewegen
};
#endif
| 25.352941
| 95
| 0.672854
|
s1eve-mcdichae1
|
019e2d5982570cba05a08d57a7d44f0e0ca3a6c1
| 1,231
|
cpp
|
C++
|
playground/meta-programming/if-else.cpp
|
llHoYall/Cpp_Playground
|
3f50237c7530e31be571e67ad2a627d1f33bbf51
|
[
"MIT"
] | null | null | null |
playground/meta-programming/if-else.cpp
|
llHoYall/Cpp_Playground
|
3f50237c7530e31be571e67ad2a627d1f33bbf51
|
[
"MIT"
] | null | null | null |
playground/meta-programming/if-else.cpp
|
llHoYall/Cpp_Playground
|
3f50237c7530e31be571e67ad2a627d1f33bbf51
|
[
"MIT"
] | null | null | null |
/*******************************************************************************
* @brief Template Meta programming: If-Else
* @author llHoYall <hoya128@gmail.com>
* @version v1.0
* @history
* 2018.12.29 Created.
******************************************************************************/
/* Include Headers -----------------------------------------------------------*/
#include <iostream>
/* Private Functions ---------------------------------------------------------*/
static void TrueStatement(void) {
std::cout << " True Statement" << std::endl;
}
static void FalseStatement(void) {
std::cout << " False Statement" << std::endl;
}
/* Templates -----------------------------------------------------------------*/
template<bool predicate>
class IfElse {};
template<>
class IfElse<true> {
public:
static inline void func(void) {
TrueStatement();
}
};
template<>
class IfElse<false> {
public:
static inline void func(void) {
FalseStatement();
}
};
/* Main Routine --------------------------------------------------------------*/
auto Main_IfElse(void) -> int {
std::cout << "> Template Meta Programming: If-Else" << std::endl;
IfElse<(2 + 3 == 5)>::func();
std::cout << std::endl;
return 0;
}
| 24.62
| 80
| 0.434606
|
llHoYall
|
019ed6cc10cfeca30386e45142fbed1c86a29e88
| 3,553
|
cpp
|
C++
|
Povox/src/Povox/Renderer/RayTracing/RayTracerTesting.cpp
|
PowerOfNames/PonX
|
cac2c67168857409b40f9f76e9570868668370fd
|
[
"Apache-2.0"
] | null | null | null |
Povox/src/Povox/Renderer/RayTracing/RayTracerTesting.cpp
|
PowerOfNames/PonX
|
cac2c67168857409b40f9f76e9570868668370fd
|
[
"Apache-2.0"
] | null | null | null |
Povox/src/Povox/Renderer/RayTracing/RayTracerTesting.cpp
|
PowerOfNames/PonX
|
cac2c67168857409b40f9f76e9570868668370fd
|
[
"Apache-2.0"
] | null | null | null |
#include "pxpch.h"
#include "Povox/Renderer/RayTracing/RayTracerTesting.h"
#include "Povox/Renderer/RenderCommand.h"
#include "Povox/Renderer/VertexArray.h"
#include "Povox/Renderer/Texture.h"
namespace Povox {
struct TracerData
{
Ref<VertexArray> VertexArray;
Ref<Shader> RayMarchingShader;
Ref<Texture> MapData1, MapData2, MapData3;
};
static TracerData* s_TracerData;
void RayTracer::Init()
{
PX_PROFILE_FUNCTION();
RenderCommand::Init();
s_TracerData = new TracerData();
s_TracerData->VertexArray = VertexArray::Create();
float vertices[12] =
{
-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
1.0f, 1.0f, 0.0f,
-1.0f, 1.0f, 0.0f
};
Ref<VertexBuffer> vertexBuffer = VertexBuffer::Create(vertices, sizeof(vertices));
vertexBuffer->SetLayout({
{ShaderDataType::Float3, "a_Position"}
});
s_TracerData->VertexArray->AddVertexBuffer(vertexBuffer);
uint32_t indices[6] =
{
0, 1, 2,
2, 3, 0
};
Ref<IndexBuffer> indexBuffer = IndexBuffer::Create(indices, sizeof(indices) / sizeof(uint32_t));
s_TracerData->VertexArray->SetIndexBuffer(indexBuffer);
s_TracerData->MapData1 = Texture2D::Create("MapData", 8, 64);
uint32_t mapData1[512];
for (unsigned int i = 0; i < 512; i++)
{
mapData1[i] = 0x00000000;
}
mapData1[0] = 0xffffffff;
mapData1[511] = 0xffffffff;
s_TracerData->MapData1->SetData(&mapData1, sizeof(uint32_t) * 512);
s_TracerData->MapData2 = Texture2D::Create("MapData", 1, 2);
uint32_t mapData2[2];
for (unsigned int i = 0; i < 2; i++)
{
mapData2[i] = 0x22222222;
}
mapData2[1] = 0x77007700;
s_TracerData->MapData2->SetData(&mapData2, sizeof(uint32_t) * 2);
s_TracerData->MapData3 = Texture2D::Create("MapData", 1, 1);
uint32_t MapData3[1];
for (unsigned int i = 0; i < 1; i++)
{
MapData3[i] = 0x22222222;
}
s_TracerData->MapData3->SetData(&MapData3, sizeof(uint32_t) * 1);
s_TracerData->RayMarchingShader = Shader::Create("assets/shaders/RayMarchingShader.glsl");
s_TracerData->RayMarchingShader->Bind();
//s_TracerData->RayMarchingShader->SetInt("u_MapData", 0);
}
void RayTracer::Shutdown()
{
delete s_TracerData;
}
void RayTracer::BeginScene(PerspectiveCamera& camera, Light& lightsource)
{
PX_PROFILE_FUNCTION();
//s_TracerData->RayMarchingShader->SetMat4("u_ViewProjection", camera.GetViewProjection());
s_TracerData->RayMarchingShader->SetFloat("u_PointLightIntensity", lightsource.GetIntensity());
s_TracerData->RayMarchingShader->SetFloat3("u_PointLightPos", lightsource.GetPosition());
s_TracerData->RayMarchingShader->SetFloat3("u_PointLightColor", lightsource.GetColor());
s_TracerData->VertexArray->Bind();
}
void RayTracer::EndScene()
{
}
void RayTracer::Trace(PerspectiveCameraController& cameraController)
{
PX_PROFILE_FUNCTION();
PerspectiveCamera cam = cameraController.GetCamera();
s_TracerData->RayMarchingShader->SetFloat3("u_CameraPos", cam.GetPosition());
s_TracerData->RayMarchingShader->SetFloat3("u_CameraFront", cam.GetFront());
s_TracerData->RayMarchingShader->SetFloat3("u_CameraUp", cam.GetUp());
s_TracerData->RayMarchingShader->SetFloat("u_AspectRatio", cam.GetAspectRatio());
s_TracerData->RayMarchingShader->SetFloat2("u_WindowDims", glm::vec2(cameraController.GetWindowWidth(), cameraController.GetWindowHeight()));
s_TracerData->RayMarchingShader->SetInt("u_FOV", cameraController.GetFOV());
s_TracerData->VertexArray->Bind();
s_TracerData->MapData2->Bind();
RenderCommand::DrawIndexed(s_TracerData->VertexArray, 6);
}
}
| 28.653226
| 143
| 0.723614
|
PowerOfNames
|
019ee8efe8f3ac6ac6a1188e277b8ecde4de275b
| 7,839
|
cxx
|
C++
|
tests/test_string_algo.cxx
|
sikol/ivy
|
6365b8783353cf0c79c633bbc7110be95a55225c
|
[
"BSL-1.0"
] | null | null | null |
tests/test_string_algo.cxx
|
sikol/ivy
|
6365b8783353cf0c79c633bbc7110be95a55225c
|
[
"BSL-1.0"
] | null | null | null |
tests/test_string_algo.cxx
|
sikol/ivy
|
6365b8783353cf0c79c633bbc7110be95a55225c
|
[
"BSL-1.0"
] | null | null | null |
/*
* Copyright (c) 2019, 2020, 2021 SiKol Ltd.
* Distributed under the Boost Software License, Version 1.0.
*/
#include <string>
#include <vector>
#include <catch2/catch.hpp>
#include <ivy/charenc/utf32.hxx>
#include <ivy/regex.hxx>
#include <ivy/string/join.hxx>
#include <ivy/string/match.hxx>
#include <ivy/string/split.hxx>
#include <ivy/string/trim.hxx>
TEST_CASE("ivy:string:join 1-element vector<string> with iterators",
"[ivy][string][join]")
{
std::vector<std::string> strings{"foo"};
std::string r1 = ivy::join(strings.begin(), strings.end(), ",");
REQUIRE(r1 == "foo");
}
TEST_CASE("ivy:string:join 1-element vector<string> with range",
"[ivy][string][join]")
{
std::vector<std::string> strings{"foo"};
std::string r1 = ivy::join(strings, ",");
REQUIRE(r1 == "foo");
}
TEST_CASE("ivy:string:join 3-element vector<string> with iterators",
"[ivy][string][join]")
{
std::vector<std::string> strings{"foo", "bar", "quux"};
std::string r1 = ivy::join(strings.begin(), strings.end(), ",");
REQUIRE(r1 == "foo,bar,quux");
}
TEST_CASE("ivy:string:join 3-element vector<string> with range",
"[ivy][string][join]")
{
std::vector<std::string> strings{"foo", "bar", "quux"};
std::string r1 = ivy::join(strings, ",");
REQUIRE(r1 == "foo,bar,quux");
}
TEST_CASE("ivy:string:join 3-element vector<string_view> with range",
"[ivy][string][join]")
{
std::vector<std::string_view> strings{"foo", "bar", "quux"};
std::string r1 = ivy::join(strings, ",");
REQUIRE(r1 == "foo,bar,quux");
}
#if 0
TEST_CASE("ivy:string:match_regex: integer",
"[ivy][string][match][match_regex]")
{
ivy::string test_string = U"123foo";
ivy::u32regex re(U"^[0-9]+");
auto r = ivy::match_regex(test_string, re);
REQUIRE(r.first.has_value());
REQUIRE(r.first->size() == 1);
auto i_match = (*r.first)[0];
REQUIRE(i_match == U"123");
REQUIRE(r.second == U"foo");
}
TEST_CASE("ivy:string:match_regex: no match",
"[ivy][string][match][match_regex]")
{
ivy::string test_string = U"foo123";
ivy::regex re(U"^[0-9]+");
auto r = ivy::match_regex(test_string, re);
REQUIRE(!r.first.has_value());
REQUIRE(r.second == U"foo123");
}
#endif
TEST_CASE("ivy:string:match_string: match",
"[ivy][string][match][match_string]")
{
using namespace std::string_view_literals;
ivy::string test_string = U"foo123";
auto [p, rest] = ivy::match_string(test_string, U"fo");
REQUIRE(p);
REQUIRE(*p == U"fo");
REQUIRE(rest == U"o123");
}
TEST_CASE("ivy:string:match_string: no match",
"[ivy][string][match][match_string]")
{
using namespace std::string_view_literals;
ivy::string test_string = U"foo123";
auto [p, rest] = ivy::match_string(test_string, U"123");
REQUIRE(!p);
REQUIRE(rest == U"foo123");
}
TEST_CASE("ivy:string:match_int: positive decimal integer",
"[ivy][string][match][match_int]")
{
using namespace std::string_view_literals;
ivy::string test_string = U"123foo";
auto [i, rest] = ivy::match_int<std::int64_t>(test_string);
REQUIRE(i);
REQUIRE(*i == 123);
REQUIRE(rest == U"foo");
}
TEST_CASE("ivy:string:match_int: negative decimal integer",
"[ivy][string][match][match_int]")
{
using namespace std::string_view_literals;
ivy::string test_string = U"-123foo";
auto [i, rest] = ivy::match_int<std::int64_t>(test_string);
REQUIRE(i);
REQUIRE(*i == -123);
REQUIRE(rest == U"foo");
}
TEST_CASE("ivy:string:match_int: positive hex integer",
"[ivy][string][match][match_int]")
{
using namespace std::string_view_literals;
ivy::string test_string = U"1024quux";
auto [i, rest] = ivy::match_int<std::int64_t>(test_string, 16);
REQUIRE(i);
REQUIRE(*i == 0x1024);
REQUIRE(rest == U"quux");
}
TEST_CASE("ivy:string:match_int: negative hex integer",
"[ivy][string][match][match_int]")
{
using namespace std::string_view_literals;
ivy::string test_string = U"-1024quux";
auto [i, rest] = ivy::match_int<std::int64_t>(test_string, 16);
REQUIRE(i);
REQUIRE(*i == -0x1024);
REQUIRE(rest == U"quux");
}
TEST_CASE("ivy:string:match_whitespace: simple",
"[ivy][string][match][match_whitespace]")
{
using namespace std::string_view_literals;
ivy::string test_string = U" foo";
auto [ws, rest] = ivy::match_whitespace(test_string);
REQUIRE(ws);
REQUIRE(*ws == U" ");
REQUIRE(rest == U"foo");
}
TEST_CASE("ivy:string:match_whitespace: trailing space",
"[ivy][string][match][match_whitespace]")
{
using namespace std::string_view_literals;
ivy::string test_string = U" foo "sv;
auto [ws, rest] = ivy::match_whitespace(test_string);
REQUIRE(ws);
REQUIRE(*ws == U" ");
REQUIRE(rest == U"foo ");
}
TEST_CASE("ivy:string:match_whitespace: no match",
"[ivy][string][match][match_whitespace]")
{
using namespace std::string_view_literals;
ivy::string test_string = U"foo";
auto [ws, rest] = ivy::match_whitespace(test_string);
REQUIRE(!ws);
REQUIRE(rest == U"foo");
}
TEST_CASE("ivy:string:trim:triml: simple", "[ivy][string][trim][triml]")
{
using namespace std::string_view_literals;
ivy::string test_string = U" foo ";
auto trimmed = ivy::triml(test_string);
REQUIRE(trimmed == U"foo ");
}
TEST_CASE("ivy:string:trim:triml: no whitespace", "[ivy][string][trim][triml]")
{
using namespace std::string_view_literals;
ivy::string test_string = U"foo";
auto trimmed = ivy::triml(test_string);
REQUIRE(trimmed == U"foo");
}
TEST_CASE("ivy:string:split: simple string_view", "[ivy][string][split]")
{
using namespace std::string_view_literals;
std::vector<ivy::string> bits;
ivy::string test_1 = U"foo$bar$baz";
ivy::split(test_1, '$', std::back_inserter(bits));
REQUIRE(bits.size() == 3);
REQUIRE(bits[0] == U"foo");
REQUIRE(bits[1] == U"bar");
REQUIRE(bits[2] == U"baz");
}
TEST_CASE("ivy:string:split: single element", "[ivy][string][split]")
{
using namespace std::string_view_literals;
std::vector<ivy::string> bits;
ivy::string test_1 = U"foobar";
ivy::split(test_1, '$', std::back_inserter(bits));
REQUIRE(bits.size() == 1);
REQUIRE(bits[0] == U"foobar");
}
TEST_CASE("ivy:string:split: empty first token", "[ivy][string][split]")
{
using namespace std::string_view_literals;
std::vector<ivy::string> bits;
ivy::string test_1 = U"$foo$bar";
ivy::split(test_1, '$', std::back_inserter(bits));
REQUIRE(bits.size() == 3);
REQUIRE(bits[0] == U"");
REQUIRE(bits[1] == U"foo");
REQUIRE(bits[2] == U"bar");
}
TEST_CASE("ivy:string:split: empty last token", "[ivy][string][split]")
{
using namespace std::string_view_literals;
std::vector<ivy::string> bits;
ivy::string test_1 = U"foo$bar$";
ivy::split(test_1, '$', std::back_inserter(bits));
REQUIRE(bits.size() == 3);
REQUIRE(bits[0] == U"foo");
REQUIRE(bits[1] == U"bar");
REQUIRE(bits[2] == U"");
}
TEST_CASE("ivy:string:split: simple string", "[ivy][string][split]")
{
using namespace std::string_literals;
std::vector<ivy::string> bits;
ivy::string test_1 = U"foo$bar$baz";
ivy::split(test_1, '$', std::back_inserter(bits));
REQUIRE(bits.size() == 3);
REQUIRE(bits[0] == U"foo");
REQUIRE(bits[1] == U"bar");
REQUIRE(bits[2] == U"baz");
}
| 27.699647
| 80
| 0.60148
|
sikol
|
019f4e5b9a6bfc4569ad707f56c4bd5e2d12f115
| 5,964
|
cpp
|
C++
|
demos/gravitygizmo/src/player.cpp
|
leftidev/leng
|
9df738a9f5d8f90d2a01234d4d4b13311017d93e
|
[
"MIT"
] | null | null | null |
demos/gravitygizmo/src/player.cpp
|
leftidev/leng
|
9df738a9f5d8f90d2a01234d4d4b13311017d93e
|
[
"MIT"
] | null | null | null |
demos/gravitygizmo/src/player.cpp
|
leftidev/leng
|
9df738a9f5d8f90d2a01234d4d4b13311017d93e
|
[
"MIT"
] | null | null | null |
#include "player.h"
#include <iostream>
namespace leng {
Player::Player(float x, float y, float width, float height, const std::string& path) : Entity(x, y, width, height, path) {
upHeld = false;
downHeld = false;
rightHeld = false;
leftHeld = false;
inAir = true;
jumped = true;
canDoubleJump = false;
normalGravity = true;
respawn = false;
deathFlicker = true;
direction = Direction::RIGHT;
MAX_MOVE_VELOCITY = 1.0f;
JUMP_VELOCITY = 1.40f;
MAX_GRAVITY_VELOCITY = 2.0f;
GRAVITY = 0.10f;
ACCELERATION = 0.35;
deaths = 0;
levelCompleted = false;
startPosition.x = x;
startPosition.y = y;
}
Player::~Player() {
delete bubble;
}
void Player::update(std::vector<leng::Block*> blocks, std::vector<Enemy*> enemies, float deltaTime) {
Entity::update();
if(!deathFlicker) {
// Player is in air, apply gravity
if (inAir) {
jumped = true;
if(normalGravity) {
velocity.y -= GRAVITY;
} else {
velocity.y += GRAVITY;
}
} else {
velocity.y = 0.0f;
}
if(velocity.y < -MAX_GRAVITY_VELOCITY) {
velocity.y = -MAX_GRAVITY_VELOCITY;
}
if(velocity.y > MAX_GRAVITY_VELOCITY) {
velocity.y = MAX_GRAVITY_VELOCITY;
}
position.y += velocity.y * deltaTime;
// Assume player is in air, this makes player fall off platform ledges
inAir = true;
// Check collisions on Y-axis
applyCollisions(glm::fvec2(0.0f, velocity.y), blocks, enemies);
// Check movement on x-axis
if(rightHeld) {
direction = Direction::RIGHT;
if(normalGravity) {
sprite.originalDirection();
} else {
sprite.flipY();
}
// Apply acceleration
velocity.x += ACCELERATION;
if (velocity.x > MAX_MOVE_VELOCITY) {
velocity.x = MAX_MOVE_VELOCITY;
}
} else if(leftHeld) {
direction = Direction::LEFT;
if(normalGravity) {
sprite.flipX();
} else {
sprite.flipXY();
}
// Apply acceleration
velocity.x -= ACCELERATION;
if (velocity.x < -MAX_MOVE_VELOCITY) {
velocity.x = -MAX_MOVE_VELOCITY;
}
} else {
velocity.x = 0.0f;
}
position.x += velocity.x * deltaTime;
// Check collisions on X-axis
applyCollisions(glm::fvec2(velocity.x, 0.0f), blocks, enemies);
} else {
if(deathFlickerCounter == 3) {
deathFlickerCounter = 0;
deathFlicker = false;
}
if(alphaDown) {
sprite.color.a -= 0.10f;
if(sprite.color.a <= 0.0f) {
alphaDown = false;
alphaUp = true;
}
}
if(alphaUp) {
sprite.color.a += 0.10f;
if(sprite.color.a >= 1.0f) {
alphaUp = false;
alphaDown = true;
deathFlickerCounter++;
}
}
}
}
// Collisions
void Player::applyCollisions(glm::fvec2 Velocity, std::vector<Block*> blocks, std::vector<Enemy*> enemies) {
// Collide with level tiles
for (unsigned int i = 0; i < blocks.size(); i++) {
if (collideWithTile(position, width, height, blocks[i])) {
if(blocks[i]->type == SOLID || blocks[i]->type == DISAPPEARING) {
// Collide from left
if (Velocity.x > 0) {
position.x = blocks[i]->position.x - width;
}
// Collide from right
else if (Velocity.x < 0) {
position.x = blocks[i]->position.x + blocks[i]->width;
}
if(normalGravity) {
// Collide from below
if (Velocity.y > 0) {
velocity.y = 0;
position.y = blocks[i]->position.y - height;
inAir = true;
}
// Collide from above
else if (Velocity.y < 0) {
velocity.y = 0;
position.y = blocks[i]->position.y + blocks[i]->height;
inAir = false;
jumped = false;
canDoubleJump = false;
}
} else {
// Collide from below
if (Velocity.y > 0) {
velocity.y = 0;
position.y = blocks[i]->position.y - height;
inAir = false;
jumped = false;
canDoubleJump = false;
}
// Collide from above
else if (Velocity.y < 0) {
velocity.y = 0;
position.y = blocks[i]->position.y + blocks[i]->height;
inAir = true;
}
}
} else if(blocks[i]->type == KILL || blocks[i]->type == KILLREVERSE) {
respawn = true;
restart();
deaths++;
} else if(blocks[i]->type == EXIT) {
levelCompleted = true;
}
}
}
// Collide with enemies
for (unsigned int i = 0; i < enemies.size(); i++) {
if (collideWithTile(position, width, height, enemies[i])) {
if(enemies[i]->bubbled) {
enemies[i]->destroyed = true;
} else {
respawn = true;
restart();
deaths++;
}
}
}
}
void Player::jump() {
jumped = true;
inAir = true;
canDoubleJump = true;
if(normalGravity) {
velocity.y = JUMP_VELOCITY;
} else {
velocity.y = -JUMP_VELOCITY;
}
}
void Player::doubleJump() {
if(canDoubleJump) {
inAir = true;
canDoubleJump = false;
if(normalGravity) {
velocity.y = JUMP_VELOCITY;
} else {
velocity.y = -JUMP_VELOCITY;
}
}
}
void Player::gravityBendInvert() {
if(normalGravity && !inAir) {
normalGravity = false;
if(direction == Direction::RIGHT) {
sprite.flipY();
} else if (direction == Direction::LEFT) {
sprite.flipXY();
}
}
}
void Player::gravityBend() {
if(!normalGravity && !inAir) {
normalGravity = true;
if(direction == Direction::RIGHT) {
sprite.originalDirection();
} else if (direction == Direction::LEFT) {
sprite.flipX();
}
}
}
void Player::restart() {
deathFlicker = true;
velocity.x = 0.0f;
velocity.y = 0.0f;
normalGravity = true;
position.x = startPosition.x;
position.y = startPosition.y;
}
void Player::shootBubble() {
if(bubble == nullptr) {
if(direction == Direction::RIGHT) {
bubble = new Projectile(position.x + width + 1, position.y, 52, 52, "assets/textures/bubble_78x78.png", glm::fvec2(1.0f, 0.0f));
} else {
bubble = new Projectile(position.x - width - 1, position.y, 52, 52, "assets/textures/bubble_78x78.png", glm::fvec2(-1.0f, 0.0f));
}
}
}
} // namespace leng
| 22.088889
| 134
| 0.598592
|
leftidev
|
01a3a615852f421a860e6011a67dc0de0036e85a
| 294
|
cpp
|
C++
|
All_code/67.cpp
|
jnvshubham7/cpp-programming
|
7d00f4a3b97b9308e337c5d3547fd3edd47c5e0b
|
[
"Apache-2.0"
] | 1
|
2021-12-22T12:37:36.000Z
|
2021-12-22T12:37:36.000Z
|
All_code/67.cpp
|
jnvshubham7/CPP_Programming
|
a17c4a42209556495302ca305b7c3026df064041
|
[
"Apache-2.0"
] | null | null | null |
All_code/67.cpp
|
jnvshubham7/CPP_Programming
|
a17c4a42209556495302ca305b7c3026df064041
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
long long int a[n];
int sum=0;
for(int i=0;i<n;i++){
cin>>a[i];
sum=sum+a[i];
}
cout<<sum;
return 0;
}
| 14
| 38
| 0.482993
|
jnvshubham7
|
01ab1d194ef773e9550ad4b8bdfef6e9358c50f7
| 13,862
|
cpp
|
C++
|
src/core/Application.cpp
|
lutrarutra/trafsim
|
05e87b263b48e39d63f699dcaa456f10ca61e9a4
|
[
"Apache-2.0"
] | 12
|
2019-12-28T21:45:23.000Z
|
2022-03-28T12:40:44.000Z
|
src/core/Application.cpp
|
lutrarutra/trafsim
|
05e87b263b48e39d63f699dcaa456f10ca61e9a4
|
[
"Apache-2.0"
] | null | null | null |
src/core/Application.cpp
|
lutrarutra/trafsim
|
05e87b263b48e39d63f699dcaa456f10ca61e9a4
|
[
"Apache-2.0"
] | 1
|
2021-05-31T10:22:41.000Z
|
2021-05-31T10:22:41.000Z
|
#include "Application.hpp"
#include <memory>
#include <iostream>
#include <string>
#include <utility>
#include "imgui.h"
#include "imgui-SFML.h"
#include "imgui_internal.h"
#include "trafficsim/RoadTile.hpp"
#include "trafficsim/StraightRoad.hpp"
#include "trafficsim/RoadIntersection.hpp"
#include "trafficsim/RoadTrisection.hpp"
#include "trafficsim/RoadJunction.hpp"
#include "trafficsim/HomeRoad.hpp"
#include "trafficsim/HomeBuilding.hpp"
namespace ts
{
Application *Application::AppInstance = nullptr;
Application::Application()
: builder_(map_, window_), statistics_(map_, window_, logs_), time_line_(map_), data_(logs_)
{
AppInstance = this;
data_.loadTexturesFromFile("texture_list.txt");
StraightRoad::SetTexture(data_.getTexture("straight_road"));
HomeRoad::SetTexture(data_.getTexture("home_road"));
RoadTurn::SetTextures(data_.getTexture("right_turn"), data_.getTexture("left_turn"));
RoadIntersection::SetTextures(data_.getTexture("right_intersection"), data_.getTexture("left_intersection"));
RoadTrisection::SetTextures(data_.getTexture("right_trisection"), data_.getTexture("left_trisection"));
RoadJunction::SetTextures(data_.getTexture("right_junction"), data_.getTexture("left_junction"));
Car::AddTexture(data_.getTexture("blue_car"));
Car::AddTexture(data_.getTexture("brown_car"));
Car::AddTexture(data_.getTexture("green_car"));
Car::AddTexture(data_.getTexture("grey_car"));
Car::AddTexture(data_.getTexture("white_car"));
Car::AddTexture(data_.getTexture("red_car"));
Car::AddTexture(data_.getTexture("teal_car"));
HomeBuilding::SetTexture(data_.getTexture("home_building"));
OfficeBuilding::SetTexture(data_.getTexture("office_building"));
window_.setViewPos({map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount() / 2, map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount() / 2});
window_.setZoom(3.f);
}
void Application::run()
{
float last_time = time_line_.getRealTime();
sf::Vector2i delta_mouse_pos = sf::Mouse::getPosition();
//Main loop
while (window_.isOpen())
{
window_.pollEvent();
map_.update(time_line_.getGameTime(), time_line_.getFrameTime() * time_line_.getMultiplier());
time_line_.update(app_state_ == State::Simulating);
handleInputBuffers(delta_mouse_pos - sf::Mouse::getPosition());
delta_mouse_pos = sf::Mouse::getPosition();
window_.clear();
//Drawing happens between window.clear() and window.draw()
window_.draw(map_);
drawGUI();
window_.display();
}
}
void Application::changeState(State new_state)
{
app_state_ = new_state;
switch (app_state_)
{
case Editing:
builder_.setBuildingMode(true);
map_.setSimulating(false);
break;
case Simulating:
builder_.setBuildingMode(false);
map_.setSimulating(true);
break;
default:
break;
}
}
const char *state_mode(State state)
{
return (const char *[]){
"Editing",
"Simulating"}[state];
}
void Application::drawGUI()
{
ImGui::Begin("Log");
ImGui::BeginChild("");
for (unsigned int i = logs_.size(); i > 0; --i)
{
ImGui::Text("Log: %s", logs_[i - 1].c_str());
}
ImGui::EndChild();
ImGui::End();
if (app_state_ == Simulating)
{
time_line_.drawGUI();
statistics_.drawGUI();
drawHeatMap();
}
if (app_state_ == Editing)
builder_.drawGUI();
if (ImGui::BeginMainMenuBar())
{
if (ImGui::BeginMenu("File"))
{
static char buf[32];
const char *c;
std::string file_name;
ImGui::InputText("Filename", buf, IM_ARRAYSIZE(buf));
if (ImGui::IsKeyPressed(ImGui::GetKeyIndex(ImGuiKey_Enter)))
{
file_name = buf + std::string(".csv");
c = file_name.c_str();
data_.loadMap(c, builder_, map_.grid_);
}
if (ImGui::MenuItem("Load", "Enter"))
{
file_name = buf + std::string(".csv");
c = file_name.c_str();
data_.loadMap(c, builder_, map_.grid_);
}
if (ImGui::MenuItem("Save", "Ctrl+S"))
{
// ".ts" for traffic sim :)
file_name = buf + std::string(".csv");
c = file_name.c_str();
data_.saveMap(c, map_.grid_);
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Mode"))
{
for (int i = 0; i < State::StateCount; i++)
{
State new_state = static_cast<State>(i);
if (ImGui::MenuItem(state_mode(new_state), "", app_state_ == new_state))
changeState(new_state);
}
ImGui::EndMenu();
}
if (ImGui::BeginMenu("Scale"))
{
if (ImGui::MenuItem("Scale: 100%", "Ctrl+1", ImGui::GetFont()->Scale == 1.f))
ImGui::GetFont()->Scale = 1.f;
if (ImGui::MenuItem("Scale: 125%", "Ctrl+2", ImGui::GetFont()->Scale == 1.25f))
ImGui::GetFont()->Scale = 1.25f;
if (ImGui::MenuItem("Scale: 150%", "Ctrl+3", ImGui::GetFont()->Scale == 1.5f))
ImGui::GetFont()->Scale = 1.5f;
if (ImGui::MenuItem("Scale: 200%", "Ctrl+4", ImGui::GetFont()->Scale == 2.f))
ImGui::GetFont()->Scale = 2.f;
if (ImGui::MenuItem("Scale: 250%", "Ctrl+5", ImGui::GetFont()->Scale == 2.5f))
ImGui::GetFont()->Scale = 2.5f;
if (ImGui::MenuItem("Scale: 300%", "Ctrl+6", ImGui::GetFont()->Scale == 3.f))
ImGui::GetFont()->Scale = 3.f;
ImGui::EndMenu();
}
ImGui::EndMainMenuBar();
}
}
void Application::drawHeatMap()
{
ImGui::Begin("Heat map");
ImDrawList *draw_list = ImGui::GetWindowDrawList();
ImVec2 canvas_pos = ImGui::GetCursorScreenPos(); // ImDrawList API uses screen coordinates!
ImVec2 canvas_size = ImGui::GetContentRegionAvail(); // Resize canvas to what's available
if (canvas_size.x < 50.0f)
canvas_size.x = 50.0f;
if (canvas_size.y < 50.0f)
canvas_size.y = 50.0f;
draw_list->AddRectFilled(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.x), IM_COL32(119, 160, 93, 180));
draw_list->AddRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.x), IM_COL32(255, 255, 255, 255));
// Map view
// at the end canvas_size.x on purpose to get square
float canvas_view_w = window_.getView().getSize().x / (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()) * canvas_size.x;
float canvas_view_h = window_.getView().getSize().y / (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()) * canvas_size.x;
float canvas_view_x = {window_.getView().getCenter().x / (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()) * canvas_size.x};
float canvas_view_y = {window_.getView().getCenter().y / (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount()) * canvas_size.x};
sf::Vector2f view_pos_min = {canvas_view_x - canvas_view_w / 2 + canvas_pos.x, canvas_view_y - canvas_view_h / 2 + canvas_pos.y};
sf::Vector2f view_pos_max = {canvas_view_x + canvas_view_w / 2 + canvas_pos.x, canvas_view_y + canvas_view_h / 2 + canvas_pos.y};
draw_list->AddRect(view_pos_min, view_pos_max, IM_COL32(255, 255, 255, 255), 0, 15.f, 5.0f);
float canvas_tile_size = canvas_size.x / map_.grid_.getSideCount();
const unsigned int time_window = 24 * 60 * 60 / 96;
float g_time = time_line_.getGameTime().asSeconds();
unsigned int time_index = g_time / time_window;
float time_passed = (g_time / time_window - (int)(g_time / time_window)) * time_window;
const int max_cars_per_sample = 500;
// No std::tuple
struct TileSample
{
TileSample(const ImVec2 &p1, const ImVec2 &p2, const sf::Color &c)
: p1(p1), p2(p2), c(c){};
const ImVec2 p1;
const ImVec2 p2;
const sf::Color c;
};
// Heatmap
for (unsigned int i = 0; i < map_.grid_.getTotalTileCount(); ++i)
{
if (map_.grid_.getTile(i)->getCategory() == TileCategory::RoadCategory)
{
sf::Vector2f p_min = {(i % map_.grid_.getSideCount()) * canvas_tile_size + canvas_pos.x, int(i / map_.grid_.getSideCount()) * canvas_tile_size + canvas_pos.y};
sf::Vector2f p_max = p_min + sf::Vector2f(canvas_tile_size, canvas_tile_size);
std::uint16_t car_count = map_.grid_.getTile(i)->getNode()->getCarsPassed().at(time_index);
draw_list->AddRectFilled(p_min, p_max, IM_COL32(26, 26, 26, 255));
float heat_color = 255 - (car_count * time_window / time_passed) / max_cars_per_sample * 255;
if (heat_color > 0)
draw_list->AddRectFilled(p_min, p_max, IM_COL32(255, heat_color, heat_color, heat_color));
}
if (map_.grid_.getTile(i)->getCategory() == TileCategory::BuildingCategory)
{
sf::Vector2f p_min = {(i % map_.grid_.getSideCount()) * canvas_tile_size + canvas_pos.x, int(i / map_.grid_.getSideCount()) * canvas_tile_size + canvas_pos.y};
sf::Vector2f p_max = p_min + sf::Vector2f(canvas_tile_size, canvas_tile_size);
draw_list->AddRectFilled(p_min, p_max, IM_COL32(47, 58, 224, 255));
map_.grid_.getTile(i)->getNode()->getCarsPassed().at(time_index);
}
}
bool adding_preview = false;
ImGui::InvisibleButton("canvas", canvas_size);
sf::Vector2f mouse_pos_in_canvas = sf::Vector2f(ImGui::GetIO().MousePos.x - canvas_pos.x, ImGui::GetIO().MousePos.y - canvas_pos.y);
if (ImGui::IsItemHovered())
{
if (ImGui::IsMouseDown(0))
{
sf::Vector2f new_center = (mouse_pos_in_canvas / canvas_size.x) * (map_.grid_.getTile(0)->getSize() * map_.grid_.getSideCount());
window_.setViewPos(new_center);
}
}
draw_list->PushClipRect(canvas_pos, ImVec2(canvas_pos.x + canvas_size.x, canvas_pos.y + canvas_size.y), true); // clip lines within the canvas (if we resize it, etc.)
draw_list->PopClipRect();
ImGui::End();
}
void Application::handleEvent(const sf::Event &ev)
{
builder_.handleInput(ev);
statistics_.handleInput(ev);
switch (ev.type)
{
case sf::Event::KeyPressed:
key_buffer_[ev.key.code] = true;
break;
case sf::Event::KeyReleased:
key_buffer_[ev.key.code] = false;
break;
case sf::Event::MouseButtonPressed:
button_buffer_[ev.mouseButton.button] = true;
break;
case sf::Event::MouseButtonReleased:
button_buffer_[ev.mouseButton.button] = false;
break;
default:
break;
}
// Shortcuts
if (ev.type == sf::Event::KeyPressed)
{
if (ev.key.code == sf::Keyboard::Num1 && key_buffer_[sf::Keyboard::LControl])
ImGui::GetFont()->Scale = 1.f;
else if (ev.key.code == sf::Keyboard::Num2 && key_buffer_[sf::Keyboard::LControl])
ImGui::GetFont()->Scale = 1.25f;
else if (ev.key.code == sf::Keyboard::Num3 && key_buffer_[sf::Keyboard::LControl])
ImGui::GetFont()->Scale = 1.5f;
else if (ev.key.code == sf::Keyboard::Num4 && key_buffer_[sf::Keyboard::LControl])
ImGui::GetFont()->Scale = 2.f;
else if (ev.key.code == sf::Keyboard::Num5 && key_buffer_[sf::Keyboard::LControl])
ImGui::GetFont()->Scale = 2.5f;
else if (ev.key.code == sf::Keyboard::Num6 && key_buffer_[sf::Keyboard::LControl])
ImGui::GetFont()->Scale = 3.f;
else if (ev.key.code == sf::Keyboard::S && key_buffer_[sf::Keyboard::LControl])
data_.saveMap(data_.getCurrentFileName(), map_.grid_);
else if (ev.key.code == sf::Keyboard::O && key_buffer_[sf::Keyboard::LControl])
{
//data_.loadMap("test.csv", builder_, map_.grid_);
}
else if (ev.key.code == sf::Keyboard::Up && key_buffer_[sf::Keyboard::LShift])
{
float zoom_vals[6] = {1.f, 1.25, 1.5f, 2.f, 2.5f, 3.f};
if (window_.gui_zoom_index < 5)
{
window_.gui_zoom_index++;
ImGui::GetFont()->Scale = zoom_vals[window_.gui_zoom_index];
}
}
else if (ev.key.code == sf::Keyboard::Down && key_buffer_[sf::Keyboard::LShift])
{
float zoom_vals[6] = {1.f, 1.25, 1.5f, 2.f, 2.5f, 3.f};
if (window_.gui_zoom_index > 0)
{
window_.gui_zoom_index--;
ImGui::GetFont()->Scale = zoom_vals[window_.gui_zoom_index];
}
}
}
}
void Application::handleInputBuffers(const sf::Vector2i &delta_mp)
{
// LEFT mouse button is pressed down
if (button_buffer_[sf::Mouse::Left])
{
// store temporarily selected "radio button" option such as "Add Road"
// if left control is down add a road
if (key_buffer_[sf::Keyboard::LControl] && app_state_ == Editing)
builder_.slideAction(window_.convert(sf::Mouse::getPosition(window_.getWindow())), AddRoad);
// if left shift is down remove road or building
else if (key_buffer_[sf::Keyboard::LShift] && app_state_ == Editing)
builder_.slideAction(window_.convert(sf::Mouse::getPosition(window_.getWindow())), Remove);
// if no control or shift keys pressed move map
else
{
window_.moveView(delta_mp);
}
}
}
void Application::close()
{
ImGui::SFML::Shutdown();
}
Application *Application::GetInstance()
{
return AppInstance;
}
} // namespace ts
| 38.292818
| 171
| 0.608931
|
lutrarutra
|
01b0d628d63692a37ac776da1c881343806e3b6e
| 105,658
|
cpp
|
C++
|
Remote.cpp
|
kengonakajima/moyai
|
70077449eb2446de6c24de928050ad8affc6df3d
|
[
"Zlib"
] | 37
|
2015-07-23T04:02:51.000Z
|
2021-09-23T08:39:12.000Z
|
Remote.cpp
|
kengonakajima/moyai
|
70077449eb2446de6c24de928050ad8affc6df3d
|
[
"Zlib"
] | 1
|
2018-08-30T08:33:38.000Z
|
2018-08-30T08:33:38.000Z
|
Remote.cpp
|
kengonakajima/moyai
|
70077449eb2446de6c24de928050ad8affc6df3d
|
[
"Zlib"
] | 8
|
2015-07-23T04:02:58.000Z
|
2020-11-10T14:52:12.000Z
|
#include "common.h"
#include "client.h"
#include "Remote.h"
#include "JPEGCoder.h"
#include "crc32.h"
#ifdef USE_UNTZ
#include "threading/Threading.h" // To implement lock around send buffer inside libuv
RCriticalSection g_lock;
#endif
#include "ConvertUTF.h"
////////
void Moyai::globalInitNetwork() {
static bool g_global_init_done = false;
if( g_global_init_done ) return;
#ifdef WIN32
WSADATA data;
WSAStartup(MAKEWORD(2,0), &data);
#endif
#ifndef WIN32
signal( SIGPIPE, SIG_IGN );
#endif
}
void uv_run_times( int maxcount ) {
for(int i=0;i<maxcount;i++) {
uv_run( uv_default_loop(), UV_RUN_NOWAIT );
}
}
///////////
void setupPacketColorReplacerShaderSnapshot( PacketColorReplacerShaderSnapshot *outpkt, ColorReplacerShader *crs ) {
outpkt->shader_id = crs->id;
outpkt->epsilon = crs->epsilon;
copyColorToPacketColor( &outpkt->from_color, &crs->from_color );
copyColorToPacketColor( &outpkt->to_color, &crs->to_color );
}
//////////////
void copyPrimToPacketPrim( PacketPrim*out, Prim *src ) {
out->prim_id = src->id;
out->prim_type = src->type;
out->a.x = src->a.x;
out->a.y = src->a.y;
out->b.x = src->b.x;
out->b.y = src->b.y;
copyColorToPacketColor( &out->color, &src->color );
// print("copyColorToPacketColor: out:%d %d %d %d", out->color.r, out->color.g, out->color.b, out->color.a );
out->line_width = src->line_width;
}
void makePacketProp2DSnapshot( PacketProp2DSnapshot *out, Prop2D *tgt, Prop2D *parent ) {
out->prop_id = tgt->id;
if( parent ) {
out->layer_id = 0;
out->parent_prop_id = parent->id;
} else {
out->layer_id = tgt->getParentLayer()->id;
out->parent_prop_id = 0;
}
out->loc.x = tgt->loc.x;
out->loc.y = tgt->loc.y;
out->scl.x = tgt->scl.x;
out->scl.y = tgt->scl.y;
out->index = tgt->index;
out->tiledeck_id = tgt->deck ? tgt->deck->id : 0;
if(out->tiledeck_id==0 && tgt->grid_used_num==0 && tgt->children_num==0 && !tgt->prim_drawer) {
print("WARNING: tiledeck is 0 for prop %d ind:%d grid:%d childnum:%d", tgt->id , tgt->index, tgt->grid_used_num, tgt->children_num );
}
out->debug = tgt->debug_id;
out->fliprotbits = toFlipRotBits(tgt->xflip,tgt->yflip,tgt->uvrot);
out->rot = tgt->rot;
copyColorToPacketColor(&out->color,&tgt->color);
out->shader_id = tgt->fragment_shader ? tgt->fragment_shader->id : 0;
out->optbits = 0;
if( tgt->use_additive_blend ) out->optbits |= PROP2D_OPTBIT_ADDITIVE_BLEND;
out->priority = tgt->priority;
// print("ss prop:%d FS:%d size:%d", tgt->id, out->shader_id, sizeof(*out));
}
void Tracker2D::scanProp2D( Prop2D *parentprop ) {
PacketProp2DSnapshot *out = & pktbuf[cur_buffer_index];
makePacketProp2DSnapshot(out,target_prop2d,parentprop);
}
void Tracker2D::flipCurrentBuffer() {
cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 );
}
static const int CHANGED_LOC = 0x1;
static const int CHANGED_INDEX = 0x2;
static const int CHANGED_SCL = 0x4;
static const int CHANGED_ROT = 0x8;
static const int CHANGED_FLIPROTBITS = 0x10;
static const int CHANGED_COLOR = 0x20;
static const int CHANGED_SHADER = 0x40;
static const int CHANGED_OPTBITS = 0x80;
static const int CHANGED_PRIORITY = 0x100;
int getPacketProp2DSnapshotDiff( PacketProp2DSnapshot *s0, PacketProp2DSnapshot *s1 ) {
int changes = 0;
if(s0->loc.x != s1->loc.x) changes |= CHANGED_LOC;
if(s0->loc.y != s1->loc.y) changes |= CHANGED_LOC;
if(s0->index != s1->index ) changes |= CHANGED_INDEX;
if(s0->scl.x != s1->scl.x) changes |= CHANGED_SCL;
if(s0->scl.y != s1->scl.y) changes |= CHANGED_SCL;
if(s0->rot != s1->rot ) changes |= CHANGED_ROT;
if( s0->fliprotbits != s1->fliprotbits ) changes |= CHANGED_FLIPROTBITS;
if(s0->color.r != s1->color.r ) changes |= CHANGED_COLOR;
if(s0->color.g != s1->color.g ) changes |= CHANGED_COLOR;
if(s0->color.b != s1->color.b ) changes |= CHANGED_COLOR;
if(s0->color.a != s1->color.a ) changes |= CHANGED_COLOR;
if(s0->shader_id != s1->shader_id ) changes |= CHANGED_SHADER;
if(s0->optbits != s1->optbits ) changes |= CHANGED_OPTBITS;
if(s0->priority != s1->priority ) changes |= CHANGED_PRIORITY;
return changes;
}
// send packet if necessary
int Tracker2D::checkDiff() {
PacketProp2DSnapshot *curpkt, *prevpkt;
if(cur_buffer_index==0) {
curpkt = & pktbuf[0];
prevpkt = & pktbuf[1];
} else {
curpkt = & pktbuf[1];
prevpkt = & pktbuf[0];
}
return getPacketProp2DSnapshotDiff( curpkt, prevpkt );
}
void Tracker2D::broadcastDiff( bool force ) {
int diff = checkDiff();
if( diff || force ) {
if( diff == CHANGED_LOC && (!force) ) {
int prev_buffer_index = cur_buffer_index==0?1:0;
Vec2 v0(pktbuf[prev_buffer_index].loc.x,pktbuf[prev_buffer_index].loc.y);
Vec2 v1(pktbuf[cur_buffer_index].loc.x,pktbuf[cur_buffer_index].loc.y);
float l = v0.len(v1);
target_prop2d->loc_sync_score+= l;
if(v0.x!=v1.x||v0.y!=v1.y) target_prop2d->loc_changed=true;
// only location changed!
if( target_prop2d->locsync_mode == LOCSYNCMODE_LINEAR ) {
bool to_send = true;
if(target_prop2d->loc_sync_score > parent_rh->linear_sync_score_thres ) {
target_prop2d->loc_sync_score=0;
target_prop2d->loc_changed=false;
} else if( target_prop2d->poll_count>2 ){
to_send = false;
}
if(to_send) {
Vec2 vel = (v1 - v0) / target_prop2d->getParentLayer()->last_dt;
parent_rh->nearcastUS1UI3F2( target_prop2d,
PACKETTYPE_S2C_PROP2D_LOC_VEL,
pktbuf[cur_buffer_index].prop_id,
(int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y,
vel.x, vel.y );
}
// print("l:%f lss:%f id:%d", l, target_prop2d->loc_sync_score, target_prop2d->id);
} else {
target_prop2d->loc_sync_score+=1; // avoid missing syncing stopped props
if( target_prop2d->loc_sync_score < parent_rh->nonlinear_sync_score_thres ) {
if( !parent_rh->appendNonlinearChangelist( target_prop2d, &pktbuf[cur_buffer_index] ) ) {
// must send if changelist is full
// prt("FL %d", target_prop2d->id);
parent_rh->nearcastUS1UI3( target_prop2d, PACKETTYPE_S2C_PROP2D_LOC,
pktbuf[cur_buffer_index].prop_id,
(int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y );
}
} else {
// prt("NL LOC SCORE:%d prop:%d",target_prop2d->loc_sync_score, target_prop2d->id );
target_prop2d->loc_sync_score=0;
target_prop2d->loc_changed=false;
// dont use changelist sorting for big changes
parent_rh->nearcastUS1UI3( target_prop2d, PACKETTYPE_S2C_PROP2D_LOC,
pktbuf[cur_buffer_index].prop_id,
(int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y );
}
}
} else if( diff == CHANGED_SCL && (!force) ) {
parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_PROP2D_SCALE,
pktbuf[cur_buffer_index].prop_id,
pktbuf[cur_buffer_index].scl.x, pktbuf[cur_buffer_index].scl.y );
} else if( diff == CHANGED_ROT && (!force) ) {
parent_rh->broadcastUS1UI1F1( PACKETTYPE_S2C_PROP2D_ROT,
pktbuf[cur_buffer_index].prop_id,
pktbuf[cur_buffer_index].rot );
} else if( diff == CHANGED_COLOR && (!force) ) {
parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_PROP2D_COLOR,
pktbuf[cur_buffer_index].prop_id,
(const char*)&pktbuf[cur_buffer_index].color, sizeof(PacketColor));
} else if( diff == CHANGED_INDEX && (!force) ) {
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_PROP2D_INDEX, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].index );
} else if( diff == (CHANGED_INDEX | CHANGED_LOC) && (!force) ) {
parent_rh->broadcastUS1UI4( PACKETTYPE_S2C_PROP2D_INDEX_LOC, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].index, (int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y );
} else if( diff == (CHANGED_LOC | CHANGED_SCL ) && (!force) ) {
parent_rh->nearcastUS1UI3F2( target_prop2d,
PACKETTYPE_S2C_PROP2D_LOC_SCL, pktbuf[cur_buffer_index].prop_id,
(int)pktbuf[cur_buffer_index].loc.x, (int)pktbuf[cur_buffer_index].loc.y,
pktbuf[cur_buffer_index].scl.x, pktbuf[cur_buffer_index].scl.y );
} else if( diff == CHANGED_FLIPROTBITS && (!force) ) {
parent_rh->broadcastUS1UI1UC1( PACKETTYPE_S2C_PROP2D_FLIPROTBITS, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].fliprotbits );
} else if( diff == CHANGED_OPTBITS && (!force) ) {
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_PROP2D_OPTBITS, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].optbits );
} else if( diff == CHANGED_PRIORITY && (!force) ) {
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_PROP2D_PRIORITY, pktbuf[cur_buffer_index].prop_id, pktbuf[cur_buffer_index].priority );
} else {
// prt("SS%d ",diff);
parent_rh->broadcastUS1Bytes( PACKETTYPE_S2C_PROP2D_SNAPSHOT, (const char*)&pktbuf[cur_buffer_index], sizeof(PacketProp2DSnapshot) );
if( target_prop2d->target_client_id > 0 ) {
parent_rh->broadcastUS1UI2( PACKETTYPE_S2R_PROP2D_TARGET_CLIENT,target_prop2d->id, target_prop2d->target_client_id, true);
}
}
}
}
Tracker2D::~Tracker2D() {
parent_rh->notifyProp2DDeleted(target_prop2d);
}
void RemoteHead::notifyProp2DDeleted( Prop2D *deleted ) {
broadcastUS1UI1( PACKETTYPE_S2C_PROP2D_DELETE, deleted->id );
}
void RemoteHead::notifyChildCleared( Prop2D *owner_prop, Prop2D *child_prop ) {
broadcastUS1UI2( PACKETTYPE_S2C_PROP2D_CLEAR_CHILD, owner_prop->id, child_prop->id );
}
void RemoteHead::notifyGridDeleted( Grid *deleted ) {
broadcastUS1UI1( PACKETTYPE_S2C_GRID_DELETE, deleted->id );
}
void RemoteHead::addClient( Client *cl ) {
Client *stored = cl_pool.get(cl->id);
if(!stored) {
cl->parent_rh = this;
cl_pool.set(cl->id,cl);
}
}
void RemoteHead::delClient( Client *cl ) {
cl_pool.del(cl->id);
}
Client *RemoteHead::getFirstClient() {
// normal clients first and then reprecated clients
if(cl_pool.size()==0) {
if(reprecator) {
Client *cl = reprecator->logical_cl_pool.getFirst();
return cl;
} else {
return NULL;
}
}
return cl_pool.getFirst();
}
int RemoteHead::getClientCount() {
return cl_pool.size();
}
// Assume all props in all layers are Prop2Ds.
void RemoteHead::track2D() {
if(enable_timestamp) broadcastTimestamp();
clearChangelist();
for(int i=0;i<Moyai::MAXGROUPS;i++) {
Layer *layer = (Layer*) target_moyai->getGroupByIndex(i);
if(!layer)continue;
if(layer->hasDynamicCameras()) {
layer->onTrackDynamicCameras();
} else if(layer->camera) layer->camera->onTrack(this);
if(layer->hasDynamicViewports()) {
layer->onTrackDynamicViewports();
} else if(layer->viewport) layer->viewport->onTrack(this);
Prop *cur = layer->prop_top;
while(cur) {
Prop2D *p = (Prop2D*) cur;
p->onTrack(this, NULL);
cur = cur->next;
}
}
broadcastSortedChangelist();
}
uint32_t getFileCRC32(const char *path) {
const size_t MAXBUFSIZE = 1024*1024*16;
char *buf = (char*) MALLOC(MAXBUFSIZE);
assert(buf);
size_t sz = MAXBUFSIZE;
bool res = readFile( path, buf, &sz );
assertmsg(res, "getFileCRC32: file '%s' read error", path );
uint32_t crc32val = crc32_4bytes(buf,sz,0);
FREE(buf);
print("getFileCRC32: path:%s len:%d crc32:%x", path, sz, crc32val );
return crc32val;
}
void RemoteHead::appendFileEntry(const char *path) {
assert(file_ents_used<elementof(file_ents) );
FileEntry *fe=&file_ents[file_ents_used];
fe->crc32 = getFileCRC32(path);
fe->size=getFileSize(path);
strncpy(fe->path,path,sizeof(fe->path));
file_ents_used++;
print("appendFileEntry: path:%s", path);
}
bool RemoteHead::isPathAllowed(const char *path ) {
for(int i=0;i<file_ents_used;i++) {
FileEntry *fe=&file_ents[i];
if(fe->size>0 && strcmp(fe->path,path)==0) {
return true;
}
}
return false;
}
void RemoteHead::scanFiles() {
if( window_width==0 || window_height==0) {
assertmsg( false, "remotehead: window size not set?");
}
// Image, Texture, tiledeck
std::unordered_map<int,Image*> imgmap;
std::unordered_map<int,Texture*> texmap;
std::unordered_map<int,Deck*> dkmap;
std::unordered_map<int,Font*> fontmap;
std::unordered_map<int,ColorReplacerShader*> crsmap;
for(int i=0;i<Moyai::MAXGROUPS;i++) {
Group *grp = target_moyai->getGroupByIndex(i);
if(!grp)continue;
Prop *cur = grp->prop_top;
while(cur) {
Prop2D *p = (Prop2D*) cur;
if(p->deck) {
dkmap[p->deck->id] = p->deck;
if( p->deck->tex) {
texmap[p->deck->tex->id] = p->deck->tex;
if( p->deck->tex->image ) {
imgmap[p->deck->tex->image->id] = p->deck->tex->image;
}
}
}
if(p->fragment_shader) {
ColorReplacerShader *crs = dynamic_cast<ColorReplacerShader*>(p->fragment_shader); // TODO: avoid using dyncast..
if(crs) {
crsmap[crs->id] = crs;
}
}
for(int i=0;i<p->grid_used_num;i++) {
Grid *g = p->grids[i];
if(g->deck) {
dkmap[g->deck->id] = g->deck;
if( g->deck->tex) {
texmap[g->deck->tex->id] = g->deck->tex;
if( g->deck->tex->image ) {
imgmap[g->deck->tex->image->id] = g->deck->tex->image;
}
}
}
}
TextBox *tb = dynamic_cast<TextBox*>(cur); // TODO: refactor this!
if(tb) {
if(tb->font) {
fontmap[tb->font->id] = tb->font;
}
}
cur = cur->next;
}
}
// Files
for( std::unordered_map<int,Image*>::iterator it = imgmap.begin(); it != imgmap.end(); ++it ) {
Image *img = it->second;
if( img->last_load_file_path[0] ) {
print("sending file path:'%s' in image %d", img->last_load_file_path, img->id );
appendFileEntry(img->last_load_file_path);
}
}
for( std::unordered_map<int,Font*>::iterator it = fontmap.begin(); it != fontmap.end(); ++it ) {
Font *f = it->second;
appendFileEntry(f->last_load_file_path);
}
// TODO: send shader source and status
// sounds
for(int i=0;i<elementof(target_soundsystem->sounds);i++){
if(!target_soundsystem)break;
Sound *snd = target_soundsystem->sounds[i];
if(!snd)continue;
if(snd->last_load_file_path[0]) appendFileEntry(snd->last_load_file_path);
}
}
void RemoteHead::sendScannedFileList(Stream *outstream) {
for(int i=0;i<file_ents_used;i++) {
FileEntry *fe=&file_ents[i];
sendUS1UI2Str( outstream, PACKETTYPE_S2C_FILE_INFO, fe->size, fe->crc32, fe->path );
}
sendUS1(outstream,PACKETTYPE_S2C_FILE_INFO_END);
}
// Send all IDs of tiledecks, layers, textures, fonts, viwports by scanning all props and grids.
// This occurs only when new player is comming in.
void RemoteHead::scanSendAllPrerequisites( Stream *outstream ) {
if( window_width==0 || window_height==0) {
assertmsg( false, "remotehead: window size not set?");
}
std::unordered_map<int,Viewport*> vpmap;
std::unordered_map<int,Camera*> cammap;
// Viewport , Camera
for(int i=0;i<Moyai::MAXGROUPS;i++) {
Group *grp = target_moyai->getGroupByIndex(i);
if(!grp)continue;
Layer *l = (Layer*) grp; // assume all groups are layers
if(l->viewport) {
vpmap[l->viewport->id] = l->viewport;
}
if(l->camera) {
cammap[l->camera->id] = l->camera;
}
}
for( std::unordered_map<int,Viewport*>::iterator it = vpmap.begin(); it != vpmap.end(); ++it ) {
Viewport *vp = it->second;
print("sending viewport_create id:%d sz:%d,%d scl:%f,%f", vp->id, vp->screen_width, vp->screen_height, vp->scl.x, vp->scl.y );
sendViewportCreateScale(outstream,vp);
}
for( std::unordered_map<int,Camera*>::iterator it = cammap.begin(); it != cammap.end(); ++it ) {
Camera *cam = it->second;
print("sending camera_create id:%d", cam->id );
sendCameraCreateLoc(outstream,cam);
}
// Layers(Groups) don't need scanning props
for(int i=0;i<Moyai::MAXGROUPS;i++) {
Layer *l = (Layer*) target_moyai->getGroupByIndex(i);
if(!l)continue;
print("sending layer_create id:%d",l->id);
sendLayerSetup(outstream,l);
}
// Image, Texture, tiledeck
std::unordered_map<int,Image*> imgmap;
std::unordered_map<int,Texture*> texmap;
std::unordered_map<int,Deck*> dkmap;
std::unordered_map<int,Font*> fontmap;
std::unordered_map<int,ColorReplacerShader*> crsmap;
for(int i=0;i<Moyai::MAXGROUPS;i++) {
Group *grp = target_moyai->getGroupByIndex(i);
if(!grp)continue;
Prop *cur = grp->prop_top;
while(cur) {
Prop2D *p = (Prop2D*) cur;
if(p->deck) {
dkmap[p->deck->id] = p->deck;
if( p->deck->tex) {
texmap[p->deck->tex->id] = p->deck->tex;
if( p->deck->tex->image ) {
imgmap[p->deck->tex->image->id] = p->deck->tex->image;
}
}
}
if(p->fragment_shader) {
ColorReplacerShader *crs = dynamic_cast<ColorReplacerShader*>(p->fragment_shader); // TODO: avoid using dyncast..
if(crs) {
crsmap[crs->id] = crs;
}
}
for(int i=0;i<p->grid_used_num;i++) {
Grid *g = p->grids[i];
if(g->deck) {
dkmap[g->deck->id] = g->deck;
if( g->deck->tex) {
texmap[g->deck->tex->id] = g->deck->tex;
if( g->deck->tex->image ) {
imgmap[g->deck->tex->image->id] = g->deck->tex->image;
}
}
}
}
TextBox *tb = dynamic_cast<TextBox*>(cur); // TODO: refactor this!
if(tb) {
if(tb->font) {
fontmap[tb->font->id] = tb->font;
}
}
cur = cur->next;
}
}
// Files
#if 0
for( std::unordered_map<int,Image*>::iterator it = imgmap.begin(); it != imgmap.end(); ++it ) {
Image *img = it->second;
if( img->last_load_file_path[0] ) {
print("sending file path:'%s' in image %d", img->last_load_file_path, img->id );
sendFile( outstream, img->last_load_file_path );
}
}
#endif
for( std::unordered_map<int,Image*>::iterator it = imgmap.begin(); it != imgmap.end(); ++it ) {
Image *img = it->second;
sendImageSetup(outstream,img);
}
for( std::unordered_map<int,Texture*>::iterator it = texmap.begin(); it != texmap.end(); ++it ) {
Texture *tex = it->second;
// print("sending texture_create id:%d", tex->id );
sendTextureCreateWithImage(outstream,tex);
}
for( std::unordered_map<int,Deck*>::iterator it = dkmap.begin(); it != dkmap.end(); ++it ) {
Deck *dk = it->second;
sendDeckSetup(outstream,dk);
}
for( std::unordered_map<int,Font*>::iterator it = fontmap.begin(); it != fontmap.end(); ++it ) {
Font *f = it->second;
sendFontSetupWithFile(outstream,f);
}
for( std::unordered_map<int,ColorReplacerShader*>::iterator it = crsmap.begin(); it != crsmap.end(); ++it ) {
ColorReplacerShader *crs = it->second;
sendColorReplacerShaderSetup(outstream,crs);
}
// sounds
for(int i=0;i<elementof(target_soundsystem->sounds);i++){
if(!target_soundsystem)break;
Sound *snd = target_soundsystem->sounds[i];
if(!snd)continue;
sendSoundSetup(outstream,snd);
}
}
// Send snapshots of all props and grids
void RemoteHead::scanSendAllProp2DSnapshots( Stream *outstream ) {
for(int i=0;i<Moyai::MAXGROUPS;i++) {
Layer *layer = (Layer*) target_moyai->getGroupByIndex(i);
if(!layer)continue;
Prop *cur = layer->prop_top;
while(cur) {
Prop2D *p = (Prop2D*) cur;
TextBox *tb = dynamic_cast<TextBox*>(p);
if(tb) {
if(!tb->tracker) {
tb->tracker = new TrackerTextBox(this,tb);
tb->tracker->scanTextBox();
}
tb->tracker->broadcastDiff(true);
} else {
// prop body
if(!p->tracker) {
p->tracker = new Tracker2D(this,p);
p->tracker->scanProp2D(NULL);
}
p->tracker->broadcastDiff(true);
// grid
for(int i=0;i<p->grid_used_num;i++) {
Grid *g = p->grids[i];
if(!g->tracker) {
g->tracker = new TrackerGrid(this,g);
g->tracker->scanGrid();
}
g->tracker->broadcastDiff(p, true );
}
// prims
if(p->prim_drawer) {
if( !p->prim_drawer->tracker) p->prim_drawer->tracker = new TrackerPrimDrawer(this,p->prim_drawer);
p->prim_drawer->tracker->scanPrimDrawer();
p->prim_drawer->tracker->broadcastDiff(p, true );
}
// children
for(int i=0;i<p->children_num;i++) {
Prop2D *chp = p->children[i];
if(!chp->tracker) {
chp->tracker = new Tracker2D(this,chp);
chp->tracker->scanProp2D(p);
}
chp->tracker->broadcastDiff(true);
}
}
cur = cur->next;
}
}
}
void RemoteHead::heartbeat(double dt) {
if(enable_spritestream) track2D();
if(enable_videostream) broadcastCapturedScreen();
if( (!enable_videostream) && (!enable_spritestream) ) {
print("RemoteHead::heartbeat: no streaming enabled, please call enableSpriteStream or enableVideoStream. ");
}
#ifdef USE_UNTZ
if(audio_buf_ary){
RScopedLock _l(&g_lock);
for(;;) {
size_t used = audio_buf_ary->getUsedNum();
if(used==0)break;
Buffer *b = audio_buf_ary->getTop();
assert(b);
// print("heartbeat: audio used:%d next buf len:%d",audio_buf_ary->getUsedNum(), b->used );
assert(b->used % (sizeof(float)*2) == 0 ); // L+R of float sample
broadcastUS1UI1Bytes( PACKETTYPE_S2C_CAPTURED_AUDIO, b->used/sizeof(float)/2, b->buf, b->used );
static int total_audio_samples_sent_bytes = 0;
total_audio_samples_sent_bytes += b->used;
// print("sent audio: %f %d", now(), total_audio_samples_sent_bytes );
audio_buf_ary->shift();
}
}
#endif
flushBufferToNetwork(dt);
if(reprecator) reprecator->heartbeat();
uv_run_times(100);
}
void RemoteHead::flushBufferToNetwork(double dt) {
POOL_SCAN(cl_pool,Client) {
Client *cl=it->second;
bool to_send = cl->updateSendTimer(dt);
if(to_send) cl->flushSendbufToNetwork();
}
}
static void remotehead_on_close_callback( uv_handle_t *s ) {
print("remotehead_on_close_callback");
Client *cli = (Client*)s->data;
cli->parent_rh->delClient(cli); // Call this before on_disconnect_cb to make it possible to delete prop in callback and it causes write to network
if( cli->parent_rh->on_disconnect_cb ) {
cli->parent_rh->on_disconnect_cb( cli->parent_rh, cli );
}
delete cli;
}
static void remotehead_on_packet_callback( Stream *stream, uint16_t funcid, char *argdata, uint32_t argdatalen ) {
Client *cli = (Client*)stream;
// print("on_packet_callback. id:%d fid:%d len:%d", funcid, argdatalen );
switch(funcid) {
case PACKETTYPE_PING:
{
uint32_t sec = get_u32(argdata+0);
uint32_t usec = get_u32(argdata+4);
sendUS1UI2( cli, PACKETTYPE_PING, sec, usec );
}
break;
case PACKETTYPE_C2S_KEYBOARD:
{
uint32_t keycode = get_u32(argdata);
uint32_t action = get_u32(argdata+4);
uint32_t modbits = get_u32(argdata+8);
bool mod_shift,mod_ctrl,mod_alt;
getModkeyBits(modbits, &mod_shift, &mod_ctrl, &mod_alt);
// print("kbd: %d %d %d %d %d", keycode, action, mod_shift, mod_ctrl, mod_alt );
if(cli->parent_rh->on_keyboard_cb) {
cli->parent_rh->on_keyboard_cb(cli,keycode,action,mod_shift,mod_ctrl,mod_alt);
}
}
break;
case PACKETTYPE_C2S_MOUSE_BUTTON:
{
uint32_t button = get_u32(argdata);
uint32_t action = get_u32(argdata+4);
uint32_t modbits = get_u32(argdata+8);
bool mod_shift,mod_ctrl,mod_alt;
getModkeyBits(modbits, &mod_shift, &mod_ctrl, &mod_alt);
print("mou: %d %d %d %d %d", button, action, mod_shift, mod_ctrl, mod_alt );
if(cli->parent_rh->on_mouse_button_cb) {
cli->parent_rh->on_mouse_button_cb(cli,button,action,mod_shift,mod_ctrl,mod_alt);
}
}
break;
case PACKETTYPE_C2S_CURSOR_POS:
{
float x = get_f32(argdata);
float y = get_f32(argdata+4);
if(cli->parent_rh->on_mouse_cursor_cb) {
cli->parent_rh->on_mouse_cursor_cb(cli,x,y);
}
}
break;
case PACKETTYPE_C2S_REQUEST_FILE_LIST:
{
if(cli->parent_rh->file_ents_used==0) {
cli->parent_rh->scanFiles();
}
cli->parent_rh->sendScannedFileList(cli);
}
break;
case PACKETTYPE_C2S_REQUEST_FILE:
{
uint8_t cstrlen=get_u8(argdata);
char *path_utf8 = (char*)(argdata+1);
char path[256];
snprintf(path,sizeof(path),"%.*s", cstrlen,path_utf8);
print("requestfile: '%s'",path);
if(!cli->parent_rh->isPathAllowed(path)) {
print("path '%s' is not allowed", path);
break;
}
print("sending file %s",path);
sendFile(cli,path);
}
break;
case PACKETTYPE_C2S_REQUEST_FIRST_SNAPSHOT:
{
print("request_first_snapshot");
cli->parent_rh->scanSendAllPrerequisites(cli);
cli->parent_rh->scanSendAllProp2DSnapshots(cli);
}
break;
default:
print("unhandled funcid: %d",funcid);
break;
}
}
static void remotehead_on_read_callback( uv_stream_t *s, ssize_t nread, const uv_buf_t *inbuf ) {
Client *cl = (Client*) s->data;
if(nread>0) {
bool res = parseRecord( cl, &cl->recvbuf, inbuf->base, nread, remotehead_on_packet_callback );
if(!res) {
print("receiveData failed");
uv_close( (uv_handle_t*)s, remotehead_on_close_callback );
return;
}
} else if( nread < 0 ) {
print("remotehead_on_read_callback EOF. clid:%d", cl->id );
uv_close( (uv_handle_t*)s, remotehead_on_close_callback );
}
}
void moyai_libuv_alloc_buffer( uv_handle_t *handle, size_t suggested_size, uv_buf_t *outbuf ) {
*outbuf = uv_buf_init( (char*) MALLOC(suggested_size), suggested_size );
}
static void remotehead_on_accept_callback( uv_stream_t *listener, int status ) {
if( status != 0 ) {
print("remotehead_on_accept_callback status:%d", status);
return;
}
uv_tcp_t *newsock = (uv_tcp_t*) MALLOC( sizeof(uv_tcp_t) );
uv_tcp_init( uv_default_loop(), newsock );
if( uv_accept( listener, (uv_stream_t*) newsock ) == 0 ) {
uv_tcp_nodelay(newsock,1);
RemoteHead *rh = (RemoteHead*)listener->data;
Client *cl = new Client(newsock, rh, rh->enable_compression );
newsock->data = cl;
cl->tcp = newsock;
cl->parent_rh->addClient(cl);
cl->send_wait=rh->send_wait_sec;
print("remotehead_on_accept_callback. ok status:%d client-id:%d", status, cl->id );
int r = uv_read_start( (uv_stream_t*) newsock, moyai_libuv_alloc_buffer, remotehead_on_read_callback );
if(r) {
print("uv_read_start: fail ret:%d",r);
return;
}
sendWindowSize(cl, cl->parent_rh->window_width, cl->parent_rh->window_height);
if(rh->enable_videostream) {
JPEGCoder *jc = cl->parent_rh->jc;
assert(jc);
sendUS1UI3(cl, PACKETTYPE_S2C_JPEG_DECODER_CREATE, jc->capture_pixel_skip, jc->orig_w, jc->orig_h );
}
if( cl->parent_rh->on_connect_cb ) {
cl->parent_rh->on_connect_cb( cl->parent_rh, cl );
}
}
}
bool init_tcp_listener( uv_tcp_t *l, void *data, int portnum, void (*cb)(uv_stream_t*l,int status) ) {
int r = uv_tcp_init( uv_default_loop(), l );
if(r) {
print("uv_tcp_init failed");
return false;
}
l->data = data;
struct sockaddr_in addr;
uv_ip4_addr("0.0.0.0", portnum, &addr );
r = uv_tcp_bind( l, (const struct sockaddr*) &addr, SO_REUSEADDR );
if(r) {
print("uv_tcp_bind failed");
return false;
}
r = uv_listen( (uv_stream_t*)l, 10, cb );
if(r) {
print("uv_listen failed");
return false;
}
return true;
}
// return false if can't
// TODO: implement error handling
bool RemoteHead::startServer( int portnum ) {
return init_tcp_listener( &listener, (void*)this, portnum, remotehead_on_accept_callback );
}
void RemoteHead::notifySoundPlay( Sound *snd, float vol ) {
if(enable_spritestream) broadcastUS1UI1F1( PACKETTYPE_S2C_SOUND_PLAY, snd->id, vol );
}
void RemoteHead::notifySoundStop( Sound *snd ) {
if(enable_spritestream) broadcastUS1UI1( PACKETTYPE_S2C_SOUND_STOP, snd->id );
}
// [numframes of float values for ch1][numframes of float values for ch2]
void RemoteHead::appendAudioSamples( uint32_t numChannels, float *interleavedSamples, uint32_t numSamples ) {
#ifdef USE_UNTZ
if(!audio_buf_ary)return;
RScopedLock _l(&g_lock);
// print("pushing samples. numSamples:%d numChannels:%d", numSamples, numChannels );
bool ret = audio_buf_ary->push( (const char*)interleavedSamples, numSamples * numChannels * sizeof(float) );
if(!ret) print("appendAudioSamples: audio_buffer full?");
// print("appendAudioSamples pushed %d bytes. ret:%d used:%d", numSamples*sizeof(float), ret, audio_buffer->used );
#else
print("appendAudioSamples is't implemented");
#endif
}
////////////////
TrackerGrid::TrackerGrid( RemoteHead *rh, Grid *target ) : target_grid(target), cur_buffer_index(0), parent_rh(rh) {
for(int i=0;i<2;i++) {
index_table[i] = NULL;
flip_table[i] = NULL;
texofs_table[i] = NULL;
color_table[i] = NULL;
}
}
TrackerGrid::~TrackerGrid() {
parent_rh->notifyGridDeleted(target_grid);
for(int i=0;i<2;i++) {
if(index_table[i]) FREE( index_table[i] );
if(flip_table[i]) FREE( flip_table[i] );
if(texofs_table[i]) FREE( texofs_table[i] );
if(color_table[i]) FREE( color_table[i] );
}
}
void TrackerGrid::scanGrid() {
if( target_grid->index_table) {
if(!index_table[cur_buffer_index]) index_table[cur_buffer_index] = (int32_t*) MALLOC(target_grid->getCellNum() * sizeof(int32_t));
}
if( target_grid->xflip_table || target_grid->yflip_table || target_grid->rot_table ) {
if(!flip_table[cur_buffer_index]) flip_table[cur_buffer_index] = (uint8_t*) MALLOC(target_grid->getCellNum() * sizeof(uint8_t) );
}
if( target_grid->texofs_table ) {
if(!texofs_table[cur_buffer_index]) texofs_table[cur_buffer_index] = (PacketVec2*) MALLOC(target_grid->getCellNum() * sizeof(PacketVec2));
}
if( target_grid->color_table ) {
if(!color_table[cur_buffer_index]) color_table[cur_buffer_index] = (PacketColor*) MALLOC(target_grid->getCellNum() * sizeof(PacketColor));
}
for(int y=0;y<target_grid->height;y++){
for(int x=0;x<target_grid->width;x++){
int ind = target_grid->index(x,y);
if(index_table[cur_buffer_index]) {
index_table[cur_buffer_index][ind] = target_grid->get(x,y);
}
if(flip_table[cur_buffer_index] ) {
uint8_t bits = 0;
if( target_grid->getXFlip(x,y) ) bits |= GTT_FLIP_BIT_X;
if( target_grid->getYFlip(x,y) ) bits |= GTT_FLIP_BIT_Y;
if( target_grid->getUVRot(x,y) ) bits |= GTT_FLIP_BIT_UVROT;
flip_table[cur_buffer_index][ind] = bits;
}
if(texofs_table[cur_buffer_index]) {
Vec2 texofs;
target_grid->getTexOffset(x,y,&texofs);
texofs_table[cur_buffer_index][ind].x = texofs.x;
texofs_table[cur_buffer_index][ind].y = texofs.y;
}
if(color_table[cur_buffer_index]) {
Color col = target_grid->getColor(x,y);
copyColorToPacketColor(&color_table[cur_buffer_index][ind],&col);
}
}
}
}
void TrackerGrid::flipCurrentBuffer() {
cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 );
}
// TODO: add a new packet type of sending changes in each cells.
bool TrackerGrid::checkDiff( GRIDTABLETYPE gtt ) {
char *curtbl, *prevtbl;
int curind, prevind;
if(cur_buffer_index==0) {
curind = 0;
prevind = 1;
} else {
curind = 1;
prevind = 0;
}
switch(gtt) {
case GTT_INDEX:
curtbl = (char*) index_table[curind];
prevtbl = (char*) index_table[prevind];
break;
case GTT_FLIP:
curtbl = (char*) flip_table[curind];
prevtbl = (char*) flip_table[prevind];
break;
case GTT_TEXOFS:
curtbl = (char*) texofs_table[curind];
prevtbl = (char*) texofs_table[prevind];
break;
case GTT_COLOR:
curtbl = (char*) color_table[curind];
prevtbl = (char*) color_table[prevind];
break;
}
size_t compsz;
switch(gtt){
case GTT_INDEX:
compsz = target_grid->getCellNum() * sizeof(int32_t);
break;
case GTT_FLIP:
compsz = target_grid->getCellNum() * sizeof(uint8_t);
break;
case GTT_TEXOFS:
compsz = target_grid->getCellNum() * sizeof(Vec2);
break;
case GTT_COLOR:
compsz = target_grid->getCellNum() * sizeof(PacketColor);
#if 0
if(prevtbl&&curtbl){
int prevsum = bytesum(prevtbl,compsz);
int cursum = bytesum(curtbl,compsz);
if(prevsum!=cursum) {
dump(prevtbl,compsz);
print("----------------");
dump(curtbl,compsz);
}
}
#endif
break;
}
int cmp=0;
if(curtbl && prevtbl) cmp = memcmp( curtbl, prevtbl, compsz );
return cmp;
}
void TrackerGrid::broadcastDiff( Prop2D *owner, bool force ) {
bool have_index_diff = checkDiff( GTT_INDEX );
bool have_flip_diff = checkDiff( GTT_FLIP );
bool have_texofs_diff = checkDiff( GTT_TEXOFS );
bool have_color_diff = checkDiff( GTT_COLOR );
bool have_any_diff = ( have_index_diff || have_flip_diff || have_texofs_diff || have_color_diff );
if( force || have_any_diff ) {
broadcastGridConfs(owner);
}
if( (have_index_diff || force ) && index_table[cur_buffer_index] ) {
parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_GRID_TABLE_INDEX_SNAPSHOT, target_grid->id,
(const char*) index_table[cur_buffer_index],
target_grid->getCellNum() * sizeof(int32_t) );
}
if( ( have_flip_diff || force ) && flip_table[cur_buffer_index] ) {
parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_GRID_TABLE_FLIP_SNAPSHOT, target_grid->id,
(const char*) flip_table[cur_buffer_index],
target_grid->getCellNum() * sizeof(uint8_t) );
}
if( ( have_texofs_diff || force ) && texofs_table[cur_buffer_index] ) {
parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_GRID_TABLE_TEXOFS_SNAPSHOT, target_grid->id,
(const char*) texofs_table[cur_buffer_index],
target_grid->getCellNum() * sizeof(Vec2) );
}
if( ( have_color_diff || force ) && color_table[cur_buffer_index] ) {
parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_GRID_TABLE_COLOR_SNAPSHOT, target_grid->id,
(const char*) color_table[cur_buffer_index],
target_grid->getCellNum() * sizeof(PacketColor) );
}
}
void TrackerGrid::broadcastGridConfs( Prop2D *owner ) {
parent_rh->broadcastUS1UI3( PACKETTYPE_S2C_GRID_CREATE, target_grid->id, target_grid->width, target_grid->height );
int dk_id = 0;
if(target_grid->deck) dk_id = target_grid->deck->id; else if(owner->deck) dk_id = owner->deck->id;
if(dk_id) parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_GRID_DECK, target_grid->id, dk_id );
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_GRID_PROP2D, target_grid->id, owner->id );
}
/////////////
TrackerTextBox::TrackerTextBox(RemoteHead *rh, TextBox *target) : target_tb(target), cur_buffer_index(0), parent_rh(rh) {
memset( pktbuf, 0, sizeof(pktbuf) );
memset( strbuf, 0, sizeof(strbuf) );
}
TrackerTextBox::~TrackerTextBox() {
parent_rh->notifyProp2DDeleted(target_tb);
}
void TrackerTextBox::scanTextBox() {
PacketProp2DSnapshot *out = & pktbuf[cur_buffer_index];
out->prop_id = target_tb->id;
out->layer_id = target_tb->getParentLayer()->id;
out->loc.x = target_tb->loc.x;
out->loc.y = target_tb->loc.y;
out->scl.x = target_tb->scl.x;
out->scl.y = target_tb->scl.y;
out->index = 0; // fixed
out->tiledeck_id = 0; // fixed
out->debug = target_tb->debug_id;
out->rot = 0; // fixed
out->fliprotbits = 0; // fixed
copyColorToPacketColor(&out->color,&target_tb->color);
out->priority = target_tb->priority;
size_t copy_sz = (target_tb->len_str + 1) * sizeof(wchar_t);
assertmsg( copy_sz <= MAX_STR_LEN, "textbox string too long" );
memcpy( strbuf[cur_buffer_index], target_tb->str, copy_sz );
str_bytes[cur_buffer_index] = copy_sz;
// print("scantb: cpsz:%d id:%d s:%s l:%d cbi:%d",copy_sz, target_tb->id, target_tb->str, target_tb->len_str, cur_buffer_index );
}
bool TrackerTextBox::checkDiff() {
PacketProp2DSnapshot *curpkt, *prevpkt;
size_t cur_str_bytes, prev_str_bytes;
uint8_t *cur_str, *prev_str;
if(cur_buffer_index==0) {
curpkt = & pktbuf[0];
prevpkt = & pktbuf[1];
cur_str_bytes = str_bytes[0];
prev_str_bytes = str_bytes[1];
cur_str = strbuf[0];
prev_str = strbuf[1];
} else {
curpkt = & pktbuf[1];
prevpkt = & pktbuf[0];
cur_str_bytes = str_bytes[1];
prev_str_bytes = str_bytes[0];
cur_str = strbuf[1];
prev_str = strbuf[0];
}
int pktchanges = getPacketProp2DSnapshotDiff( curpkt, prevpkt );
bool str_changed = false;
if( cur_str_bytes != prev_str_bytes ) {
str_changed = true;
} else if( memcmp( cur_str, prev_str, cur_str_bytes ) ){
str_changed = true;
}
if( str_changed ) {
// print("string changed! id:%d l:%d", target_tb->id, cur_str_bytes );
}
return pktchanges || str_changed;
}
void TrackerTextBox::flipCurrentBuffer() {
cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 );
}
void TrackerTextBox::broadcastDiff( bool force ) {
if( checkDiff() || force ) {
parent_rh->broadcastUS1UI1( PACKETTYPE_S2C_TEXTBOX_CREATE, target_tb->id );
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TEXTBOX_LAYER, target_tb->id, target_tb->getParentLayer()->id );
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TEXTBOX_FONT, target_tb->id, target_tb->font->id );
parent_rh->broadcastUS1UI1Wstr( PACKETTYPE_S2C_TEXTBOX_STRING, target_tb->id, target_tb->str, target_tb->len_str );
parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_TEXTBOX_LOC, target_tb->id, target_tb->loc.x, target_tb->loc.y );
parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_TEXTBOX_SCL, target_tb->id, target_tb->scl.x, target_tb->scl.y );
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TEXTBOX_PRIORITY, target_tb->id, target_tb->priority );
PacketColor pc;
copyColorToPacketColor(&pc,&target_tb->color);
parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_TEXTBOX_COLOR, target_tb->id, (const char*)&pc, sizeof(pc) );
}
}
//////////////
TrackerColorReplacerShader::~TrackerColorReplacerShader() {
}
void TrackerColorReplacerShader::scanShader() {
PacketColorReplacerShaderSnapshot *out = &pktbuf[cur_buffer_index];
out->epsilon = target_shader->epsilon;
copyColorToPacketColor( &out->from_color, &target_shader->from_color );
copyColorToPacketColor( &out->to_color, &target_shader->to_color );
}
void TrackerColorReplacerShader::flipCurrentBuffer() {
cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 );
}
bool TrackerColorReplacerShader::checkDiff() {
PacketColorReplacerShaderSnapshot *curpkt, *prevpkt;
if(cur_buffer_index==0) {
curpkt = &pktbuf[0];
prevpkt = &pktbuf[1];
} else {
curpkt = &pktbuf[1];
prevpkt = &pktbuf[0];
}
if( ( curpkt->epsilon != prevpkt->epsilon ) ||
( curpkt->from_color.r != prevpkt->from_color.r ) ||
( curpkt->from_color.g != prevpkt->from_color.g ) ||
( curpkt->from_color.b != prevpkt->from_color.b ) ||
( curpkt->from_color.a != prevpkt->from_color.a ) ||
( curpkt->to_color.r != prevpkt->to_color.r ) ||
( curpkt->to_color.g != prevpkt->to_color.g ) ||
( curpkt->to_color.b != prevpkt->to_color.b ) ||
( curpkt->to_color.a != prevpkt->to_color.a ) ) {
return true;
} else {
return false;
}
}
void TrackerColorReplacerShader::broadcastDiff( bool force ) {
if( checkDiff() || force ) {
PacketColorReplacerShaderSnapshot pkt;
setupPacketColorReplacerShaderSnapshot( &pkt, target_shader );
parent_rh->broadcastUS1Bytes( PACKETTYPE_S2C_COLOR_REPLACER_SHADER_SNAPSHOT, (const char*)&pkt, sizeof(pkt) );
}
}
//////////////////
TrackerPrimDrawer::~TrackerPrimDrawer() {
if( pktbuf[0] ) FREE(pktbuf[0]);
if( pktbuf[1] ) FREE(pktbuf[1]);
}
void TrackerPrimDrawer::flipCurrentBuffer() {
cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 );
}
void TrackerPrimDrawer::scanPrimDrawer() {
// ensure buffer
if( pktmax[cur_buffer_index] < target_pd->prim_num ) {
if( pktbuf[cur_buffer_index] ) {
FREE( pktbuf[cur_buffer_index] );
}
size_t sz = target_pd->prim_num * sizeof(PacketPrim);
pktbuf[cur_buffer_index] = (PacketPrim*) MALLOC(sz);
pktmax[cur_buffer_index] = target_pd->prim_num;
}
//
// scan
pktnum[cur_buffer_index] = target_pd->prim_num;
for(int i=0;i<pktnum[cur_buffer_index];i++){
copyPrimToPacketPrim( &pktbuf[cur_buffer_index][i], target_pd->prims[i] );
}
}
bool TrackerPrimDrawer::checkDiff() {
PacketPrim *curary, *prevary;
int curnum, prevnum;
if(cur_buffer_index==0) {
curary = pktbuf[0];
curnum = pktnum[0];
prevary = pktbuf[1];
prevnum = pktnum[1];
} else {
curary = pktbuf[1];
curnum = pktnum[1];
prevary = pktbuf[0];
prevnum = pktnum[0];
}
if( prevnum != curnum ) return true;
for(int i=0;i<curnum;i++ ) {
PacketPrim *curpkt = &curary[i];
PacketPrim *prevpkt = &prevary[i];
if( ( curpkt->prim_id != prevpkt->prim_id ) ||
( curpkt->prim_type != prevpkt->prim_type ) ||
( curpkt->a.x != prevpkt->a.x ) ||
( curpkt->a.y != prevpkt->a.y ) ||
( curpkt->b.x != prevpkt->b.x ) ||
( curpkt->b.y != prevpkt->b.y ) ||
( curpkt->color.r != prevpkt->color.r ) ||
( curpkt->color.g != prevpkt->color.g ) ||
( curpkt->color.b != prevpkt->color.b ) ||
( curpkt->color.a != prevpkt->color.a ) ||
( curpkt->line_width != prevpkt->line_width ) ) {
return true;
}
}
return false;
}
void TrackerPrimDrawer::broadcastDiff( Prop2D *owner, bool force ) {
if( checkDiff() || force ) {
if( pktnum[cur_buffer_index] > 0 ) {
// print("sending %d prims for prop %d", pktnum[cur_buffer_index], owner->id );
// for(int i=0;i<pktnum[cur_buffer_index];i++) print("#### primid:%d", pktbuf[cur_buffer_index][i].prim_id );
parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_PRIM_BULK_SNAPSHOT,
owner->id,
(const char*) pktbuf[cur_buffer_index],
pktnum[cur_buffer_index] * sizeof(PacketPrim) );
}
}
}
//////////////////
TrackerImage::TrackerImage( RemoteHead *rh, Image *target ) : target_image(target), cur_buffer_index(0), parent_rh(rh) {
size_t sz = target->getBufferSize();
for(int i=0;i<2;i++) {
imgbuf[i] = (uint8_t*) MALLOC(sz);
assert(imgbuf[i]);
}
}
TrackerImage::~TrackerImage() {
for(int i=0;i<2;i++) if( imgbuf[i] ) FREE(imgbuf[i]);
}
void TrackerImage::scanImage() {
uint8_t *dest = imgbuf[cur_buffer_index];
memcpy( dest, target_image->buffer, target_image->getBufferSize() );
}
void TrackerImage::flipCurrentBuffer() {
cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 );
}
bool TrackerImage::checkDiff() {
uint8_t *curimg, *previmg;
if( cur_buffer_index==0) {
curimg = imgbuf[0];
previmg = imgbuf[1];
} else {
curimg = imgbuf[1];
previmg = imgbuf[0];
}
if( memcmp( curimg, previmg, target_image->getBufferSize() ) != 0 ) {
return true;
} else {
return false;
}
}
void TrackerImage::broadcastDiff( Deck *owner_dk, bool force ) {
if( checkDiff() || force ) {
assertmsg( owner_dk->getUperCell()>0, "only tiledeck is supported now" );
// print("TrackerImage::broadcastDiff bufsz:%d", target_image->getBufferSize() );
parent_rh->broadcastUS1UI3( PACKETTYPE_S2C_IMAGE_ENSURE_SIZE,
target_image->id, target_image->width, target_image->height );
parent_rh->broadcastUS1UI1Bytes( PACKETTYPE_S2C_IMAGE_RAW,
target_image->id, (const char*) imgbuf[cur_buffer_index], target_image->getBufferSize() );
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TEXTURE_IMAGE, owner_dk->tex->id, target_image->id );
parent_rh->broadcastUS1UI2( PACKETTYPE_S2C_TILEDECK_TEXTURE, owner_dk->id, owner_dk->tex->id ); // to update tileeck's image_width/height
}
}
////////////////////
TrackerCamera::TrackerCamera( RemoteHead *rh, Camera *target ) : target_camera(target), cur_buffer_index(0), parent_rh(rh) {
}
TrackerCamera::~TrackerCamera() {
}
void TrackerCamera::scanCamera() {
locbuf[cur_buffer_index] = Vec2( target_camera->loc.x, target_camera->loc.y );
}
void TrackerCamera::flipCurrentBuffer() {
cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 );
}
bool TrackerCamera::checkDiff() {
Vec2 curloc, prevloc;
if( cur_buffer_index == 0 ) {
curloc = locbuf[0];
prevloc = locbuf[1];
} else {
curloc = locbuf[1];
prevloc = locbuf[0];
}
return curloc != prevloc;
}
void TrackerCamera::broadcastDiff( bool force ) {
if( checkDiff() || force ) {
parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_CAMERA_LOC, target_camera->id, locbuf[cur_buffer_index].x, locbuf[cur_buffer_index].y );
}
}
void TrackerCamera::unicastDiff( Client *dest, bool force ) {
if( checkDiff() || force ) {
if( dest->isLogical()) {
sendUS1UI2F2( dest->getStream(), PACKETTYPE_S2R_CAMERA_LOC, dest->id, target_camera->id, locbuf[cur_buffer_index].x, locbuf[cur_buffer_index].y );
} else {
sendUS1UI1F2( dest, PACKETTYPE_S2C_CAMERA_LOC, target_camera->id, locbuf[cur_buffer_index].x, locbuf[cur_buffer_index].y );
}
}
}
void TrackerCamera::unicastCreate( Client *dest ) {
print("TrackerCamera: unicastCreate. id:%d repr:%d",dest->id, dest->isLogical() );
if( dest->isLogical() ) {
print("sending s2r_cam_creat clid:%d camid:%d",dest->id, target_camera->id);
sendUS1UI2( dest->getStream(), PACKETTYPE_S2R_CAMERA_CREATE, dest->id, target_camera->id );
} else {
print("sending s2c_cam_creat camid:%d",target_camera->id);
sendUS1UI1( dest, PACKETTYPE_S2C_CAMERA_CREATE, target_camera->id );
}
POOL_SCAN(target_camera->target_layers,Layer) {
Layer *l = it->second;
if(dest->isLogical()) {
print("sending s2r_cam_dyn_lay cl:%d cam:%d lay:%d", dest->id, target_camera->id, l->id);
sendUS1UI3( dest->getStream(), PACKETTYPE_S2R_CAMERA_DYNAMIC_LAYER, dest->id, target_camera->id, l->id );
} else {
print("sending s2c_cam_dyN_lay cam:%d lay:%d ", target_camera->id, l->id);
sendUS1UI2( dest, PACKETTYPE_S2C_CAMERA_DYNAMIC_LAYER, target_camera->id, l->id );
}
}
}
//////////////////////
TrackerViewport::TrackerViewport( RemoteHead *rh, Viewport *target ) : target_viewport(target), cur_buffer_index(0), parent_rh(rh) {
}
TrackerViewport::~TrackerViewport() {
}
void TrackerViewport::scanViewport() {
sclbuf[cur_buffer_index] = Vec2( target_viewport->scl.x, target_viewport->scl.y );
}
void TrackerViewport::flipCurrentBuffer() {
cur_buffer_index = ( cur_buffer_index == 0 ? 1 : 0 );
}
bool TrackerViewport::checkDiff() {
Vec2 curscl, prevscl;
if( cur_buffer_index == 0 ) {
curscl = sclbuf[0];
prevscl = sclbuf[1];
} else {
curscl = sclbuf[1];
prevscl = sclbuf[0];
}
return curscl != prevscl;
}
void TrackerViewport::broadcastDiff( bool force ) {
if( checkDiff() | force ) {
parent_rh->broadcastUS1UI1F2( PACKETTYPE_S2C_VIEWPORT_SCALE, target_viewport->id, sclbuf[cur_buffer_index].x, sclbuf[cur_buffer_index].y );
}
}
void TrackerViewport::unicastDiff( Client *dest, bool force ) {
if( checkDiff() || force ) {
if(dest->isLogical()) {
sendUS1UI2F2( dest->getStream(), PACKETTYPE_S2R_VIEWPORT_SCALE, dest->id, target_viewport->id, sclbuf[cur_buffer_index].x, sclbuf[cur_buffer_index].y );
} else {
sendUS1UI1F2( dest, PACKETTYPE_S2C_VIEWPORT_SCALE, target_viewport->id, sclbuf[cur_buffer_index].x, sclbuf[cur_buffer_index].y );
}
}
}
void TrackerViewport::unicastCreate( Client *dest ) {
print("TrackerViewport::unicastCreate. id:%d",dest->id);
if(dest->isLogical()) {
sendUS1UI2( dest->getStream(), PACKETTYPE_S2R_VIEWPORT_CREATE, dest->id, target_viewport->id );
} else {
sendUS1UI1( dest, PACKETTYPE_S2C_VIEWPORT_CREATE, target_viewport->id );
}
for(std::unordered_map<unsigned int,Layer*>::iterator it = target_viewport->target_layers.idmap.begin();
it != target_viewport->target_layers.idmap.end(); ++it ) {
Layer *l = it->second;
print(" TrackerViewport::unicastCreate: camera_dynamic_layer:%d", l->id );
if(dest->isLogical()) {
sendUS1UI3( dest->getStream(), PACKETTYPE_S2R_VIEWPORT_DYNAMIC_LAYER, dest->id, target_viewport->id, l->id );
} else {
sendUS1UI2( dest, PACKETTYPE_S2C_VIEWPORT_DYNAMIC_LAYER, target_viewport->id, l->id );
}
}
}
/////////////////////
static void reprecator_on_packet_cb( Stream *s, uint16_t funcid, char *argdata, uint32_t argdatalen ) {
// print("reprecator_on_packet_cb. funcid:%d",funcid);
Client *realcl = (Client*)s;
Reprecator *rep = realcl->parent_reprecator;
assert(rep);
RemoteHead *rh = rep->parent_rh;
assert(rh);
switch(funcid) {
case PACKETTYPE_R2S_CLIENT_LOGIN:
{
int reproxy_cl_id = get_u32(argdata+0);
Client *newcl = Client::createLogicalClient(s,rh);
rep->addLogicalClient(newcl);
print("received r2s_login. giving a new newclid:%d, reproxy_cl_id:%d",newcl->id, reproxy_cl_id);
sendUS1UI2(realcl,PACKETTYPE_S2R_NEW_CLIENT_ID, newcl->id, reproxy_cl_id );
if(rh->on_connect_cb) {
rh->on_connect_cb(rh,newcl);
}
}
break;
case PACKETTYPE_R2S_CLIENT_LOGOUT:
{
int gclid = get_u32(argdata+0);
print("received r2s_client_logout gclid:%d",gclid);
Client *logcl = rep->logical_cl_pool.get(gclid);
if(logcl) {
assert(logcl->id==gclid);
print("found client, deleting");
if(logcl->parent_rh->on_disconnect_cb) {
logcl->parent_rh->on_disconnect_cb( logcl->parent_rh,logcl);
}
rep->logical_cl_pool.del(logcl->id);
delete logcl;
} else {
print("can't find logical client id:%d",gclid);
}
}
break;
case PACKETTYPE_R2S_KEYBOARD:
{
uint32_t logclid = get_u32(argdata+0);
uint32_t kc = get_u32(argdata+4);
uint32_t act = get_u32(argdata+8);
uint32_t modbits = get_u32(argdata+12);
// print("received r2s_kbd. logclid:%d kc:%d act:%d modbits:%d", logclid, kc, act, modbits );
bool mod_shift,mod_ctrl,mod_alt;
getModkeyBits(modbits, &mod_shift, &mod_ctrl, &mod_alt);
Client *logcl = rep->getLogicalClient(logclid);
if(logcl && rh->on_keyboard_cb) rh->on_keyboard_cb(logcl,kc,act,mod_shift,mod_ctrl,mod_alt);
}
break;
case PACKETTYPE_R2S_MOUSE_BUTTON:
{
uint32_t logclid = get_u32(argdata+0);
uint32_t btn = get_u32(argdata+4);
uint32_t act = get_u32(argdata+8);
uint32_t modbits = get_u32(argdata+12);
// print("received r2s_mousebtn. logclid:%d b:%d a:%d mod:%d", logclid, btn,act,modbits);
bool mod_shift,mod_ctrl,mod_alt;
getModkeyBits(modbits, &mod_shift, &mod_ctrl, &mod_alt);
Client *logcl = rep->getLogicalClient(logclid);
if(logcl && rh->on_mouse_button_cb )rh->on_mouse_button_cb(logcl,btn,act,mod_shift,mod_ctrl,mod_alt);
}
break;
case PACKETTYPE_R2S_CURSOR_POS:
{
uint32_t logclid = get_u32(argdata+0);
float x = get_f32(argdata+4);
float y = get_f32(argdata+8);
// print("received r2s_cursorpos. logclid:%d %f,%f",logclid,x,y);
Client *logcl = rep->getLogicalClient(logclid);
if(logcl && rh->on_mouse_cursor_cb ) rh->on_mouse_cursor_cb(logcl,x,y);
}
break;
default:
break;
}
}
static void reprecator_on_close_callback( uv_handle_t *s ) {
print("reprecator_on_close_callback");
Client *cl = (Client*)s->data;
assert(cl->parent_reprecator);
int ids_toclean[1024];
int ids_toclean_num=0;
POOL_SCAN(cl->parent_reprecator->logical_cl_pool,Client) {
Client *logcl = it->second;
if(logcl->reprecator_stream == cl) {
print("freeing logical client id:%d", logcl->id);
if( logcl->parent_rh->on_disconnect_cb ) {
logcl->parent_rh->on_disconnect_cb( logcl->parent_rh, logcl );
}
if( ids_toclean_num==elementof(ids_toclean))break;
ids_toclean[ids_toclean_num] = logcl->id;
ids_toclean_num++;
delete logcl;
// yes we can use it=pool.erase(xx) but i dont like it..
}
}
for(int i=0;i<ids_toclean_num;i++) {
print("deleting from pool:%d",ids_toclean[i]);
cl->parent_reprecator->logical_cl_pool.del(ids_toclean[i]);
}
cl->parent_reprecator->delRealClient(cl);
}
static void reprecator_on_read_callback( uv_stream_t *s, ssize_t nread, const uv_buf_t *inbuf ) {
// print("reprecator_on_read_callback nread:%d",nread);
if(nread>0) {
Client *cl = (Client*)s->data;
bool res = parseRecord( cl, &cl->recvbuf, inbuf->base, nread, reprecator_on_packet_cb );
if(!res) {
uv_close( (uv_handle_t*)s, reprecator_on_close_callback );
return;
}
} else if( nread<0) {
print("reprecator_on_read_callback eof or error" );
uv_close( (uv_handle_t*)s, reprecator_on_close_callback );
}
}
static void reprecator_on_accept_callback( uv_stream_t *listener, int status ) {
print("reprecator_on_accept_callback status:%d",status);
if( status != 0) {
print("reprecator_on_accept_callback status:%d",status);
return;
}
uv_tcp_t *newsock = (uv_tcp_t*) MALLOC( sizeof(uv_tcp_t) );
uv_tcp_init( uv_default_loop(), newsock );
if( uv_accept( listener, (uv_stream_t*) newsock ) == 0 ) {
uv_tcp_nodelay(newsock,1);
Reprecator *rep = (Reprecator*)listener->data;
Client *cl = new Client(newsock,rep,false);
rep->addRealClient(cl);
newsock->data=(void*)cl;
int r = uv_read_start( (uv_stream_t*) newsock, moyai_libuv_alloc_buffer, reprecator_on_read_callback );
if(r) {
print("uv_read_start: fail ret:%d",r);
return;
}
print("accepted new reprecator");
sendWindowSize( cl, rep->parent_rh->window_width, rep->parent_rh->window_height);
rep->parent_rh->scanSendAllPrerequisites(cl);
rep->parent_rh->scanSendAllProp2DSnapshots(cl);
}
}
void Reprecator::addRealClient( Client *cl) {
Client *stored = cl_pool.get(cl->id);
if(!stored) {
cl->parent_reprecator = this;
cl_pool.set(cl->id,cl);
}
}
void Reprecator::delRealClient(Client*cl) {
cl_pool.del(cl->id);
}
void Reprecator::addLogicalClient( Client *cl) {
Client *stored = logical_cl_pool.get(cl->id);
if(!stored) {
logical_cl_pool.set(cl->id,cl);
}
}
void Reprecator::delLogicalClient(Client*cl) {
logical_cl_pool.del(cl->id);
}
Client *Reprecator::getLogicalClient(uint32_t logclid) {
return logical_cl_pool.get(logclid);
}
Reprecator::Reprecator(RemoteHead *rh, int portnum) : parent_rh(rh) {
if( ! init_tcp_listener( &listener, (void*)this, portnum, reprecator_on_accept_callback ) ) {
assertmsg(false, "can't initialize reprecator server");
}
print("Reprecator server started");
}
void Reprecator::heartbeat() {
POOL_SCAN(cl_pool,Client) {
it->second->flushSendbuf(256*1024);
}
}
/////////////////////
void RemoteHead::enableVideoStream( int w, int h, int pixel_skip ) {
enable_videostream = true;
assertmsg(!jc, "can't call enableVideoStream again");
jc = new JPEGCoder(w,h,pixel_skip);
audio_buf_ary = new BufferArray(256);
print("enableVideoStream done");
}
void RemoteHead::enableReprecation(int portnum) {
assertmsg(!reprecator, "can't enable reprecation twice");
reprecator = new Reprecator(this,portnum);
}
// Note: don't support dynamic cameras
void RemoteHead::broadcastCapturedScreen() {
assert(jc);
Image *img = jc->getImage();
double t0 = now();
target_moyai->capture(img);
double t1 = now();
size_t sz = jc->encode();
double t2 = now();
if((t1-t0)>0.04) print("slow screen capture. %f", t1-t0);
if((t2-t1)>0.02) print("slow encode. %f sz:%d",t2-t1, sz);
//print("broadcastCapturedScreen time:%f,%f size:%d", t1-t0,t2-t1,sz );
#if 0
writeFile("encoded.jpg", (char*)jc->compressed, jc->compressed_size);
#endif
broadcastUS1Bytes( PACKETTYPE_S2C_CAPTURED_FRAME, (const char*)jc->compressed, jc->compressed_size );
}
void RemoteHead::broadcastTimestamp() {
double t = now();
uint32_t sec = (uint32_t)t;
uint32_t usec = (t - sec)*1000000;
broadcastUS1UI2( PACKETTYPE_TIMESTAMP, sec, usec );
}
const char *RemoteHead::funcidToString(PACKETTYPE pkt) {
switch(pkt) {
case PACKETTYPE_PING: return "PACKETTYPE_PING";
case PACKETTYPE_TIMESTAMP: return "PACKETTYPE_TIMESTAMP";
case PACKETTYPE_ZIPPED_RECORDS: return "PACKETTYPE_ZIPPED_RECORDS";
// client to server
case PACKETTYPE_C2S_KEYBOARD: return "PACKETTYPE_C2S_KEYBOARD";
case PACKETTYPE_C2S_MOUSE_BUTTON: return "PACKETTYPE_C2S_MOUSE_BUTTON";
case PACKETTYPE_C2S_CURSOR_POS: return "PACKETTYPE_C2S_CURSOR_POS";
case PACKETTYPE_C2S_TOUCH_BEGIN: return "PACKETTYPE_C2S_TOUCH_BEGIN";
case PACKETTYPE_C2S_TOUCH_MOVE: return "PACKETTYPE_C2S_TOUCH_MOVE";
case PACKETTYPE_C2S_TOUCH_END: return "PACKETTYPE_C2S_TOUCH_END";
case PACKETTYPE_C2S_TOUCH_CANCEL: return "PACKETTYPE_C2S_TOUCH_CANCEL";
// reprecator to server
case PACKETTYPE_R2S_CLIENT_LOGIN: return "PACKETTYPE_R2S_CLIENT_LOGIN";
case PACKETTYPE_R2S_CLIENT_LOGOUT: return "PACKETTYPE_R2S_CLIENT_LOGOUT";
case PACKETTYPE_R2S_KEYBOARD: return "PACKETTYPE_R2S_KEYBOARD";
case PACKETTYPE_R2S_MOUSE_BUTTON: return "PACKETTYPE_R2S_MOUSE_BUTTON";
case PACKETTYPE_R2S_CURSOR_POS: return "PACKETTYPE_R2S_CURSOR_POS";
case PACKETTYPE_S2R_NEW_CLIENT_ID: return "PACKETTYPE_S2R_NEW_CLIENT_ID";
case PACKETTYPE_S2R_CAMERA_CREATE: return "PACKETTYPE_S2R_CAMERA_CREATE";
case PACKETTYPE_S2R_CAMERA_DYNAMIC_LAYER: return "PACKETTYPE_S2R_CAMERA_DYNAMIC_LAYER";
case PACKETTYPE_S2R_CAMERA_LOC: return "PACKETTYPE_S2R_CAMERA_LOC";
case PACKETTYPE_S2R_VIEWPORT_CREATE: return "PACKETTYPE_S2R_VIEWPORT_CREATE";
case PACKETTYPE_S2R_VIEWPORT_DYNAMIC_LAYER: return "PACKETTYPE_S2R_VIEWPORT_DYNAMIC_LAYER";
case PACKETTYPE_S2R_VIEWPORT_SCALE: return "PACKETTYPE_S2R_VIEWPORT_SCALE";
case PACKETTYPE_S2R_PROP2D_TARGET_CLIENT: return "PACKETTYPE_S2R_PROP2D_TARGET_CLIENT";
case PACKETTYPE_S2R_PROP2D_LOC: return "PACKETTYPE_S2R_PROP2D_LOC";
// server to client
case PACKETTYPE_S2C_PROP2D_SNAPSHOT: return "PACKETTYPE_S2C_PROP2D_SNAPSHOT";
case PACKETTYPE_S2C_PROP2D_LOC: return "PACKETTYPE_S2C_PROP2D_LOC";
case PACKETTYPE_S2C_PROP2D_INDEX: return "PACKETTYPE_S2C_PROP2D_INDEX";
case PACKETTYPE_S2C_PROP2D_SCALE: return "PACKETTYPE_S2C_PROP2D_SCALE";
case PACKETTYPE_S2C_PROP2D_ROT: return "PACKETTYPE_S2C_PROP2D_ROT";
case PACKETTYPE_S2C_PROP2D_FLIPROTBITS: return "PACKETTYPE_S2C_PROP2D_FLIPROTBITS";
case PACKETTYPE_S2C_PROP2D_COLOR: return "PACKETTYPE_S2C_PROP2D_COLOR";
case PACKETTYPE_S2C_PROP2D_OPTBITS: return "PACKETTYPE_S2C_PROP2D_OPTBITS";
case PACKETTYPE_S2C_PROP2D_PRIORITY: return "PACKETTYPE_S2C_PROP2D_PRIORITY";
case PACKETTYPE_S2C_PROP2D_DELETE: return "PACKETTYPE_S2C_PROP2D_DELETE";
case PACKETTYPE_S2C_PROP2D_CLEAR_CHILD: return "PACKETTYPE_S2C_PROP2D_CLEAR_CHILD";
case PACKETTYPE_S2C_PROP2D_LOC_VEL: return "PACKETTYPE_S2C_PROP2D_LOC_VEL";
case PACKETTYPE_S2C_PROP2D_INDEX_LOC: return "PACKETTYPE_S2C_PROP2D_INDEX_LOC";
case PACKETTYPE_S2C_PROP2D_LOC_SCL: return "PACKETTYPE_S2C_PROP2D_LOC_SCL";
case PACKETTYPE_S2C_LAYER_CREATE: return "PACKETTYPE_S2C_LAYER_CREATE";
case PACKETTYPE_S2C_LAYER_VIEWPORT: return "PACKETTYPE_S2C_LAYER_VIEWPORT";
case PACKETTYPE_S2C_LAYER_CAMERA: return "PACKETTYPE_S2C_LAYER_CAMERA";
case PACKETTYPE_S2C_VIEWPORT_CREATE: return "PACKETTYPE_S2C_VIEWPORT_CREATE";
// case PACKETTYPE_S2C_VIEWPORT_SIZE: 331, not used now
case PACKETTYPE_S2C_VIEWPORT_SCALE: return "PACKETTYPE_S2C_VIEWPORT_SCALE";
case PACKETTYPE_S2C_VIEWPORT_DYNAMIC_LAYER: return "PACKETTYPE_S2C_VIEWPORT_DYNAMIC_LAYER";
case PACKETTYPE_S2C_CAMERA_CREATE: return "PACKETTYPE_S2C_CAMERA_CREATE";
case PACKETTYPE_S2C_CAMERA_LOC: return "PACKETTYPE_S2C_CAMERA_LOC";
case PACKETTYPE_S2C_CAMERA_DYNAMIC_LAYER: return "PACKETTYPE_S2C_CAMERA_DYNAMIC_LAYER";
case PACKETTYPE_S2C_TEXTURE_CREATE: return "PACKETTYPE_S2C_TEXTURE_CREATE";
case PACKETTYPE_S2C_TEXTURE_IMAGE: return "PACKETTYPE_S2C_TEXTURE_IMAGE";
case PACKETTYPE_S2C_IMAGE_CREATE: return "PACKETTYPE_S2C_IMAGE_CREATE";
case PACKETTYPE_S2C_IMAGE_LOAD_PNG: return "PACKETTYPE_S2C_IMAGE_LOAD_PNG";
case PACKETTYPE_S2C_IMAGE_ENSURE_SIZE: return "PACKETTYPE_S2C_IMAGE_ENSURE_SIZE";
case PACKETTYPE_S2C_IMAGE_RAW: return "PACKETTYPE_S2C_IMAGE_RAW";
case PACKETTYPE_S2C_TILEDECK_CREATE: return "PACKETTYPE_S2C_TILEDECK_CREATE";
case PACKETTYPE_S2C_TILEDECK_TEXTURE: return "PACKETTYPE_S2C_TILEDECK_TEXTURE";
case PACKETTYPE_S2C_TILEDECK_SIZE: return "PACKETTYPE_S2C_TILEDECK_SIZE";
case PACKETTYPE_S2C_GRID_CREATE: return "PACKETTYPE_S2C_GRID_CREATE";
case PACKETTYPE_S2C_GRID_DECK: return "PACKETTYPE_S2C_GRID_DECK";
case PACKETTYPE_S2C_GRID_PROP2D: return "PACKETTYPE_S2C_GRID_PROP2D";
case PACKETTYPE_S2C_GRID_TABLE_INDEX_SNAPSHOT: return "PACKETTYPE_S2C_GRID_TABLE_INDEX_SNAPSHOT";
case PACKETTYPE_S2C_GRID_TABLE_FLIP_SNAPSHOT: return "PACKETTYPE_S2C_GRID_TABLE_FLIP_SNAPSHOT";
case PACKETTYPE_S2C_GRID_TABLE_TEXOFS_SNAPSHOT: return "PACKETTYPE_S2C_GRID_TABLE_TEXOFS_SNAPSHOT";
case PACKETTYPE_S2C_GRID_TABLE_COLOR_SNAPSHOT: return "PACKETTYPE_S2C_GRID_TABLE_COLOR_SNAPSHOT";
case PACKETTYPE_S2C_GRID_DELETE: return "PACKETTYPE_S2C_GRID_DELETE";
case PACKETTYPE_S2C_TEXTBOX_CREATE: return "PACKETTYPE_S2C_TEXTBOX_CREATE";
case PACKETTYPE_S2C_TEXTBOX_FONT: return "PACKETTYPE_S2C_TEXTBOX_FONT";
case PACKETTYPE_S2C_TEXTBOX_STRING: return "PACKETTYPE_S2C_TEXTBOX_STRING";
case PACKETTYPE_S2C_TEXTBOX_LOC: return "PACKETTYPE_S2C_TEXTBOX_LOC";
case PACKETTYPE_S2C_TEXTBOX_SCL: return "PACKETTYPE_S2C_TEXTBOX_SCL";
case PACKETTYPE_S2C_TEXTBOX_COLOR: return "PACKETTYPE_S2C_TEXTBOX_COLOR";
case PACKETTYPE_S2C_TEXTBOX_PRIORITY: return "PACKETTYPE_S2C_TEXTBOX_PRIORITY";
case PACKETTYPE_S2C_TEXTBOX_LAYER: return "PACKETTYPE_S2C_TEXTBOX_LAYER";
case PACKETTYPE_S2C_FONT_CREATE: return "PACKETTYPE_S2C_FONT_CREATE";
case PACKETTYPE_S2C_FONT_CHARCODES: return "PACKETTYPE_S2C_FONT_CHARCODES";
case PACKETTYPE_S2C_FONT_LOADTTF: return "PACKETTYPE_S2C_FONT_LOADTTF";
case PACKETTYPE_S2C_COLOR_REPLACER_SHADER_SNAPSHOT: return "PACKETTYPE_S2C_COLOR_REPLACER_SHADER_SNAPSHOT";
case PACKETTYPE_S2C_PRIM_BULK_SNAPSHOT: return "PACKETTYPE_S2C_PRIM_BULK_SNAPSHOT";
case PACKETTYPE_S2C_SOUND_CREATE_FROM_FILE: return "PACKETTYPE_S2C_SOUND_CREATE_FROM_FILE";
case PACKETTYPE_S2C_SOUND_CREATE_FROM_SAMPLES: return "PACKETTYPE_S2C_SOUND_CREATE_FROM_SAMPLES";
case PACKETTYPE_S2C_SOUND_DEFAULT_VOLUME: return "PACKETTYPE_S2C_SOUND_DEFAULT_VOLUME";
case PACKETTYPE_S2C_SOUND_PLAY: return "PACKETTYPE_S2C_SOUND_PLAY";
case PACKETTYPE_S2C_SOUND_STOP: return "PACKETTYPE_S2C_SOUND_STOP";
case PACKETTYPE_S2C_SOUND_POSITION: return "PACKETTYPE_S2C_SOUND_POSITION";
case PACKETTYPE_S2C_JPEG_DECODER_CREATE: return "PACKETTYPE_S2C_JPEG_DECODER_CREATE";
case PACKETTYPE_S2C_CAPTURED_FRAME: return "PACKETTYPE_S2C_CAPTURED_FRAME";
case PACKETTYPE_S2C_CAPTURED_AUDIO: return "PACKETTYPE_S2C_CAPTURED_AUDIO";
case PACKETTYPE_S2C_FILE: return "PACKETTYPE_S2C_FILE";
case PACKETTYPE_S2C_WINDOW_SIZE: return "PACKETTYPE_S2C_WINDOW_SIZE";
case PACKETTYPE_C2S_REQUEST_FILE: return "PACKETTYPE_C2S_REQUEST_FILE";
case PACKETTYPE_C2S_REQUEST_FILE_LIST: return "PACKETTYPE_C2S_REQUEST_FILE_LIST";
case PACKETTYPE_C2S_REQUEST_FIRST_SNAPSHOT: return "PACKETTYPE_C2S_REQUEST_FIRST_SNAPSHOT";
case PACKETTYPE_S2C_FILE_INFO: return "PACKETTYPE_S2C_FILE_INFO";
case PACKETTYPE_S2C_FILE_INFO_END: return "PACKETTYPE_S2C_FILE_INFO_END";
case PACKETTYPE_ERROR: return "PACKETTYPE_ERROR";
case PACKETTYPE_MAX: return "PACKETTYPE_MAX";
}
assertmsg(false,"invalid packet type:%d", pkt);
return "invalid packet type";
}
#if 1
#define FUNCID_LOG(id,sendfuncname) print( "%s %s", funcidToString(id),sendfuncname)
#else
#define FUNCID_LOG(id,sendfuncname) ;
#endif
#define REPRECATOR_ITER_SEND if(reprecator) POOL_SCAN(reprecator->cl_pool,Client)
#define CLIENT_ITER_SEND for( ClientIteratorType it = cl_pool.idmap.begin(); it != cl_pool.idmap.end(); ++it )
void RemoteHead::broadcastUS1Bytes( uint16_t usval, const char *data, size_t datalen ) {
CLIENT_ITER_SEND sendUS1Bytes( it->second, usval, data, datalen );
REPRECATOR_ITER_SEND sendUS1Bytes( it->second, usval, data, datalen );
}
void RemoteHead::broadcastUS1UI1Bytes( uint16_t usval, uint32_t uival, const char *data, size_t datalen ) {
CLIENT_ITER_SEND sendUS1UI1Bytes( it->second, usval, uival, data, datalen );
REPRECATOR_ITER_SEND sendUS1UI1Bytes( it->second, usval, uival, data, datalen );
}
void RemoteHead::broadcastUS1UI1( uint16_t usval, uint32_t uival ) {
CLIENT_ITER_SEND sendUS1UI1( it->second, usval, uival );
REPRECATOR_ITER_SEND sendUS1UI1( it->second, usval, uival );
}
void RemoteHead::broadcastUS1UI2( uint16_t usval, uint32_t ui0, uint32_t ui1, bool reprecator_only ) {
if(!reprecator_only) CLIENT_ITER_SEND sendUS1UI2( it->second, usval, ui0, ui1 );
REPRECATOR_ITER_SEND sendUS1UI2( it->second, usval, ui0, ui1 );
}
void RemoteHead::broadcastUS1UI3( uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2 ) {
CLIENT_ITER_SEND sendUS1UI3( it->second, usval, ui0, ui1, ui2 );
REPRECATOR_ITER_SEND sendUS1UI3( it->second, usval, ui0, ui1, ui2 );
}
void RemoteHead::broadcastUS1UI4( uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, uint32_t ui3 ) {
CLIENT_ITER_SEND sendUS1UI4( it->second, usval, ui0, ui1, ui2, ui3 );
REPRECATOR_ITER_SEND sendUS1UI4( it->second, usval, ui0, ui1, ui2, ui3 );
}
void RemoteHead::broadcastUS1UI1Wstr( uint16_t usval, uint32_t uival, wchar_t *wstr, int wstr_num_letters ) {
CLIENT_ITER_SEND sendUS1UI1Wstr( it->second, usval, uival, wstr, wstr_num_letters );
REPRECATOR_ITER_SEND sendUS1UI1Wstr( it->second, usval, uival, wstr, wstr_num_letters );
}
void RemoteHead::broadcastUS1UI1F4( uint16_t usval, uint32_t uival, float f0, float f1, float f2, float f3 ) {
CLIENT_ITER_SEND sendUS1UI1F4( it->second, usval, uival, f0, f1, f2, f3 );
REPRECATOR_ITER_SEND sendUS1UI1F4( it->second, usval, uival, f0, f1, f2, f3 );
}
void RemoteHead::broadcastUS1UI1F2( uint16_t usval, uint32_t uival, float f0, float f1 ) {
CLIENT_ITER_SEND sendUS1UI1F2( it->second, usval, uival, f0, f1 );
REPRECATOR_ITER_SEND sendUS1UI1F2( it->second, usval, uival, f0, f1 );
}
void RemoteHead::broadcastUS1UI2F2( uint16_t usval, uint32_t ui0, uint32_t ui1, float f0, float f1 ) {
CLIENT_ITER_SEND sendUS1UI2F2( it->second, usval, ui0, ui1, f0, f1 );
REPRECATOR_ITER_SEND sendUS1UI2F2( it->second, usval, ui0, ui1, f0, f1 );
}
void RemoteHead::broadcastUS1UI1UC1( uint16_t usval, uint32_t uival, uint8_t ucval ) {
CLIENT_ITER_SEND sendUS1UI1UC1( it->second, usval, uival, ucval );
REPRECATOR_ITER_SEND sendUS1UI1UC1( it->second, usval, uival, ucval );
}
void RemoteHead::nearcastUS1UI1F2( Prop2D *p, uint16_t usval, uint32_t uival, float f0, float f1 ) {
POOL_SCAN(cl_pool,Client) {
Client *cl = it->second;
if(cl->canSee(p)==false) continue;
sendUS1UI1F2( cl, usval, uival, f0, f1 );
}
REPRECATOR_ITER_SEND sendUS1UI1F2( it->second, usval, uival, f0, f1 );
}
void RemoteHead::nearcastUS1UI3( Prop2D *p, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, bool reprecator_only ) {
if(!reprecator_only) {
POOL_SCAN(cl_pool,Client) {
Client *cl = it->second;
if(cl->canSee(p)==false) continue;
sendUS1UI3( cl, usval, ui0, ui1, ui2 );
}
}
REPRECATOR_ITER_SEND sendUS1UI3( it->second, usval, ui0, ui1, ui2 );
}
void RemoteHead::nearcastUS1UI3F2( Prop2D *p, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, float f0, float f1 ) {
POOL_SCAN(cl_pool,Client) {
Client *cl = it->second;
if(cl->canSee(p)==false) continue;
sendUS1UI3F2( cl, usval, ui0, ui1, ui2, f0,f1 );
}
REPRECATOR_ITER_SEND sendUS1UI3F2( it->second, usval, ui0, ui1, ui2, f0, f1 );
}
void RemoteHead::broadcastUS1UI1F1( uint16_t usval, uint32_t uival, float f0 ) {
CLIENT_ITER_SEND sendUS1UI1F1( it->second, usval, uival, f0 );
REPRECATOR_ITER_SEND sendUS1UI1F1( it->second, usval, uival, f0 );
}
bool RemoteHead::appendNonlinearChangelist(Prop2D *p, PacketProp2DSnapshot *pkt) {
if( changelist_used == elementof(changelist) )return false;
changelist[changelist_used] = ChangeEntry(p,pkt);
changelist_used++;
return true;
}
void RemoteHead::broadcastSortedChangelist() {
static SorterEntry tosort[elementof(changelist)];
for(int i=0;i<changelist_used;i++) {
tosort[i].val = changelist[i].p->loc_sync_score;
tosort[i].ptr = &changelist[i];
}
quickSortF( tosort, 0, changelist_used-1);
// print("sortChangelist:%d",changelist_used);
int max_send_num = sorted_changelist_max_send_num;
if( sorted_changelist_max_send_num > changelist_used ) max_send_num = changelist_used;
int sent_n=0;
for(int i=changelist_used-1;i>=0;i--) { // reverse order: biggest first
ChangeEntry *e = (ChangeEntry*)tosort[i].ptr;
if( e->p->loc_sync_score > sort_sync_thres ) {
nearcastUS1UI3( e->p, PACKETTYPE_S2C_PROP2D_LOC, e->pkt->prop_id, (int)e->pkt->loc.x, (int)e->pkt->loc.y );
e->p->loc_sync_score=0;
e->p->loc_changed=false;
sent_n++;
if( sent_n >= max_send_num)break;
} else if( e->p->target_client_id > 0 ) {
Client *cl = cl_pool.get(e->p->target_client_id);
if(cl) {
sendUS1UI3( cl, PACKETTYPE_S2C_PROP2D_LOC, e->pkt->prop_id, (int)e->pkt->loc.x, (int)e->pkt->loc.y );
}
nearcastUS1UI3( e->p, PACKETTYPE_S2R_PROP2D_LOC, e->pkt->prop_id, (int)e->pkt->loc.x, (int)e->pkt->loc.y, true );
}
}
// print("broadcastChangelist: tot:%d sent:%d max:%d", changelist_used, sent_n, max_send_num);
}
///////////////////
int calcModkeyBits(bool shift, bool ctrl, bool alt ) {
int out=0;
if(shift) out |= MODKEY_BIT_SHIFT;
if(ctrl) out |= MODKEY_BIT_CONTROL;
if(alt) out |= MODKEY_BIT_ALT;
return out;
}
void getModkeyBits(int val, bool *shift, bool *ctrl, bool *alt ) {
*shift = val & MODKEY_BIT_SHIFT;
*ctrl = val & MODKEY_BIT_CONTROL;
*alt = val & MODKEY_BIT_ALT;
}
///////////////////
char sendbuf_work[1024*1024*16];
#define SET_RECORD_LEN_AND_US1 \
assert(totalsize<=sizeof(sendbuf_work));\
set_u32( sendbuf_work+0, totalsize - 4 ); \
set_u16( sendbuf_work+4, usval );
int pushDataToStream( Stream *s, char *buf, size_t sz ) {
#if 0 // for debugging
if(sz>=6){
uint16_t funcid = get_u16((const char*)buf+4);
print("[%.4f] SEND %s ARGLEN:%d", now(), RemoteHead::funcidToString( (PACKETTYPE)funcid), sz-4-2 );
}
#endif
int ret = s->sendbuf.push(buf,sz);
if(ret) return sz; else return 0;
}
int sendUS1RawArgs( Stream *s, uint16_t usval, const char *data, uint32_t datalen ) {
size_t totalsize = 4 + 2 + datalen;
SET_RECORD_LEN_AND_US1;
memcpy( sendbuf_work+4+2,data, datalen);
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1( Stream *s, uint16_t usval ) {
size_t totalsize = 4 + 2;
SET_RECORD_LEN_AND_US1;
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1Bytes( Stream *s, uint16_t usval, const char *bytes, uint16_t byteslen ) {
size_t totalsize = 4 + 2 + (4+byteslen);
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, byteslen );
memcpy( sendbuf_work+4+2+4, bytes, byteslen );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI1Bytes( Stream *s, uint16_t usval, uint32_t uival, const char *bytes, uint32_t byteslen ) {
size_t totalsize = 4 + 2 + 4 + (4+byteslen);
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival );
set_u32( sendbuf_work+4+2+4, byteslen );
memcpy( sendbuf_work+4+2+4+4, bytes, byteslen );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI2Bytes( Stream *s, uint16_t usval, uint32_t uival0, uint32_t uival1, const char *bytes, uint32_t byteslen ) {
size_t totalsize = 4 + 2 + 4 + 4+ (4+byteslen);
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival0 );
set_u32( sendbuf_work+4+2+4, uival1 );
set_u32( sendbuf_work+4+2+4+4, byteslen );
memcpy( sendbuf_work+4+2+4+4+4, bytes, byteslen );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI1( Stream *s, uint16_t usval, uint32_t uival ) {
size_t totalsize = 4 + 2 + 4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI2( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1 ) {
size_t totalsize = 4 + 2 + 4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, ui0 );
set_u32( sendbuf_work+4+2+4, ui1 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI3( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2 ) {
size_t totalsize = 4 + 2 + 4+4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, ui0 );
set_u32( sendbuf_work+4+2+4, ui1 );
set_u32( sendbuf_work+4+2+4+4, ui2 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI4( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, uint32_t ui3 ) {
size_t totalsize = 4 + 2 + 4+4+4+4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, ui0 );
set_u32( sendbuf_work+4+2+4, ui1 );
set_u32( sendbuf_work+4+2+4+4, ui2 );
set_u32( sendbuf_work+4+2+4+4+4, ui3 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI5( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1, uint32_t ui2, uint32_t ui3, uint32_t ui4 ) {
size_t totalsize = 4 + 2 + 4+4+4+4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, ui0 );
set_u32( sendbuf_work+4+2+4, ui1 );
set_u32( sendbuf_work+4+2+4+4, ui2 );
set_u32( sendbuf_work+4+2+4+4+4, ui3 );
set_u32( sendbuf_work+4+2+4+4+4+4, ui4 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
// not an array
int sendUS1UIn( Stream *s, uint16_t usval, uint32_t *ui, size_t ui_n ) {
size_t totalsize = 4 + 2 + 4*ui_n;
SET_RECORD_LEN_AND_US1;
for(int i=0;i<ui_n;i++) set_u32( sendbuf_work+4+2+i*4, ui[i]);
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1USn( Stream *s, uint16_t usval, uint16_t *us, size_t us_n ) {
size_t totalsize = 4 + 2 + 2*us_n;
SET_RECORD_LEN_AND_US1;
for(int i=0;i<us_n;i++) set_u16( sendbuf_work+4+2+i*2, us[i]);
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI1F1( Stream *s, uint16_t usval, uint32_t uival, float f0 ) {
size_t totalsize = 4 + 2 + 4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival );
memcpy( sendbuf_work+4+2+4, &f0, 4 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI1F2( Stream *s, uint16_t usval, uint32_t uival, float f0, float f1 ) {
size_t totalsize = 4 + 2 + 4+4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival );
memcpy( sendbuf_work+4+2+4, &f0, 4 );
memcpy( sendbuf_work+4+2+4+4, &f1, 4 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI2F2( Stream *s, uint16_t usval, uint32_t uival0, uint32_t uival1, float f0, float f1 ) {
size_t totalsize = 4 + 2 + 4+4+4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival0 );
set_u32( sendbuf_work+4+2+4, uival1 );
memcpy( sendbuf_work+4+2+4+4, &f0, 4 );
memcpy( sendbuf_work+4+2+4+4+4, &f1, 4 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI3F2( Stream *s, uint16_t usval, uint32_t uival0, uint32_t uival1, uint32_t uival2, float f0, float f1 ) {
size_t totalsize = 4 + 2 + 4+4+4+4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival0 );
set_u32( sendbuf_work+4+2+4, uival1 );
set_u32( sendbuf_work+4+2+4+4, uival2 );
memcpy( sendbuf_work+4+2+4+4+4, &f0, 4 );
memcpy( sendbuf_work+4+2+4+4+4+4, &f1, 4 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI1F4( Stream *s, uint16_t usval, uint32_t uival, float f0, float f1, float f2, float f3 ) {
size_t totalsize = 4 + 2 + 4+4+4+4+4;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival );
memcpy( sendbuf_work+4+2+4, &f0, 4 );
memcpy( sendbuf_work+4+2+4+4, &f1, 4 );
memcpy( sendbuf_work+4+2+4+4+4, &f2, 4 );
memcpy( sendbuf_work+4+2+4+4+4+4, &f3, 4 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI1UC1( Stream *s, uint16_t usval, uint32_t uival, uint8_t ucval ) {
size_t totalsize = 4 + 2 + 4+1;
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival );
sendbuf_work[4+2+4] = ucval;
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1F2( Stream *s, uint16_t usval, float f0, float f1 ) {
size_t totalsize = 4 + 2 + 4+4;
SET_RECORD_LEN_AND_US1;
memcpy( sendbuf_work+4+2, &f0, 4 );
memcpy( sendbuf_work+4+2+4, &f1, 4 );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI1Str( Stream *s, uint16_t usval, uint32_t uival, const char *cstr ) {
int cstrlen = strlen(cstr);
assert( cstrlen <= 255 );
size_t totalsize = 4 + 2 + 4 + (1+cstrlen);
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, uival );
set_u8( sendbuf_work+4+2+4, (unsigned char) cstrlen );
memcpy( sendbuf_work+4+2+4+1, cstr, cstrlen );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1UI2Str( Stream *s, uint16_t usval, uint32_t ui0, uint32_t ui1, const char *cstr ) {
int cstrlen = strlen(cstr);
assert( cstrlen <= 255 );
size_t totalsize = 4 + 2 + 4+4 + (1+cstrlen);
SET_RECORD_LEN_AND_US1;
set_u32( sendbuf_work+4+2, ui0 );
set_u32( sendbuf_work+4+2+4, ui1 );
set_u8( sendbuf_work+4+2+4+4, (unsigned char) cstrlen );
memcpy( sendbuf_work+4+2+4+4+1, cstr, cstrlen );
return pushDataToStream(s,sendbuf_work,totalsize);
}
int sendUS1Str( Stream *s, uint16_t usval, const char *cstr ) {
int cstrlen = strlen(cstr);
assert( cstrlen <= 255 );
size_t totalsize = 4 + 2 + (1+cstrlen);
SET_RECORD_LEN_AND_US1;
set_u8( sendbuf_work+4+2, (unsigned char) cstrlen );
memcpy( sendbuf_work+4+2+1, cstr, cstrlen );
return pushDataToStream(s,sendbuf_work,totalsize);
}
// [record-len:16][usval:16][cstr-len:8][cstr-body][data-len:32][data-body]
int sendUS1StrBytes( Stream *s, uint16_t usval, const char *cstr, const char *data, uint32_t datalen ) {
int cstrlen = strlen(cstr);
assert( cstrlen <= 255 );
size_t totalsize = 4 + 2 + (1+cstrlen) + (4+datalen);
SET_RECORD_LEN_AND_US1;
set_u8( sendbuf_work+4+2, (unsigned char) cstrlen );
memcpy( sendbuf_work+4+2+1, cstr, cstrlen );
set_u32( sendbuf_work+4+2+1+cstrlen, datalen );
memcpy( sendbuf_work+4+2+1+cstrlen+4, data, datalen );
// print("send_packet_str_bytes: cstrlen:%d datalen:%d totallen:%d", cstrlen, datalen, totalsize );
return pushDataToStream(s,sendbuf_work,totalsize);
}
void parsePacketStrBytes( char *inptr, char *outcstr, char **outptr, size_t *outsize ) {
uint8_t slen = get_u8(inptr);
char *s = inptr + 1;
uint32_t datalen = get_u32(inptr+1+slen);
*outptr = inptr + 1 + slen + 4;
memcpy( outcstr, s, slen );
outcstr[slen]='\0';
*outsize = (size_t) datalen;
}
// convert wchar_t to
int sendUS1UI1Wstr( Stream *s, uint16_t usval, uint32_t uival, wchar_t *wstr, int wstr_num_letters ) {
// lock is correctly handled by sendUS1UI1Bytes later in this func
#if defined(__APPLE__) || defined(__linux__)
assert( sizeof(wchar_t) == sizeof(int32_t) );
size_t bufsz = wstr_num_letters * sizeof(int32_t);
UTF8 *outbuf = (UTF8*) MALLOC( bufsz + 1);
assert(outbuf);
UTF8 *orig_outbuf = outbuf;
const UTF32 *inbuf = (UTF32*) wstr;
ConversionResult r = ConvertUTF32toUTF8( &inbuf, inbuf+wstr_num_letters, &outbuf, outbuf+bufsz, strictConversion );
assertmsg(r==conversionOK, "ConvertUTF32toUTF8 failed:%d bufsz:%d", r, bufsz );
#else
assert( sizeof(wchar_t) == sizeof(int16_t) );
size_t bufsz = wstr_num_letters * sizeof(int16_t) * 2; // utf8 gets bigger than utf16
UTF8 *outbuf = (UTF8*) MALLOC( bufsz + 1);
assert(outbuf);
UTF8 *orig_outbuf = outbuf;
const UTF16 *inbuf = (UTF16*) wstr;
ConversionResult r = ConvertUTF16toUTF8( &inbuf, inbuf+wstr_num_letters, &outbuf, outbuf+bufsz, strictConversion );
assertmsg(r==conversionOK, "ConvertUTF16toUTF8 failed:%d bufsz:%d", r, bufsz );
#endif
size_t outlen = outbuf - orig_outbuf;
// print("ConvertUTF32toUTF8 result utf8 len:%d out:'%s'", outlen, orig_outbuf );
int ret = sendUS1UI1Bytes( s, usval, uival, (const char*) orig_outbuf, outlen );
FREE(orig_outbuf);
return ret;
}
void sendFile( Stream *s, const char *filename ) {
const size_t MAXBUFSIZE = 1024*1024*16;
char *buf = (char*) MALLOC(MAXBUFSIZE);
assert(buf);
size_t sz = MAXBUFSIZE;
bool res = readFile( filename, buf, &sz );
assertmsg(res, "sendFile: file '%s' read error", filename );
int r = sendUS1StrBytes( s, PACKETTYPE_S2C_FILE, filename, buf, sz );
assert(r>0);
print("sendFile: path:%s len:%d data:%x %x %x %x sendres:%d", filename, sz, buf[0], buf[1], buf[2], buf[3], r );
FREE(buf);
}
void sendPing( Stream *s ) {
double t = now();
uint32_t sec = (uint32_t)t;
uint32_t usec = (t - sec)*1000000;
sendUS1UI2( s, PACKETTYPE_PING, sec, usec );
}
void sendWindowSize( Stream *outstream, int w, int h ) {
sendUS1UI2( outstream, PACKETTYPE_S2C_WINDOW_SIZE, w,h );
}
void sendViewportCreateScale( Stream *outstream, Viewport *vp ) {
sendUS1UI1( outstream, PACKETTYPE_S2C_VIEWPORT_CREATE, vp->id );
sendUS1UI1F2( outstream, PACKETTYPE_S2C_VIEWPORT_SCALE, vp->id, vp->scl.x, vp->scl.y );
}
void sendCameraCreateLoc( Stream *outstream, Camera *cam ) {
sendUS1UI1( outstream, PACKETTYPE_S2C_CAMERA_CREATE, cam->id );
sendUS1UI1F2( outstream, PACKETTYPE_S2C_CAMERA_LOC, cam->id, cam->loc.x, cam->loc.y );
}
void sendLayerSetup( Stream *outstream, Layer *l ) {
sendUS1UI2( outstream, PACKETTYPE_S2C_LAYER_CREATE, l->id, l->priority );
if( l->viewport ) sendUS1UI2( outstream, PACKETTYPE_S2C_LAYER_VIEWPORT, l->id, l->viewport->id);
if( l->camera ) sendUS1UI2( outstream, PACKETTYPE_S2C_LAYER_CAMERA, l->id, l->camera->id );
}
void sendImageSetup( Stream *outstream, Image *img ) {
print("sending image_create id:%d", img->id );
sendUS1UI1( outstream, PACKETTYPE_S2C_IMAGE_CREATE, img->id );
if( img->last_load_file_path[0] ) {
print("sending image_load_png: '%s'", img->last_load_file_path );
sendUS1UI1Str( outstream, PACKETTYPE_S2C_IMAGE_LOAD_PNG, img->id, img->last_load_file_path );
}
if( img->width>0 && img->buffer) {
// this image is not from file, maybe generated.
sendUS1UI3( outstream, PACKETTYPE_S2C_IMAGE_ENSURE_SIZE, img->id, img->width, img->height );
}
if( img->modified_pixel_num > 0 ) {
// modified image (includes loadPNG case)
sendUS1UI3( outstream, PACKETTYPE_S2C_IMAGE_ENSURE_SIZE, img->id, img->width, img->height );
sendUS1UI1Bytes( outstream, PACKETTYPE_S2C_IMAGE_RAW, img->id, (const char*) img->buffer, img->getBufferSize() );
}
}
void sendTextureCreateWithImage( Stream *outstream, Texture *tex ) {
sendUS1UI1( outstream, PACKETTYPE_S2C_TEXTURE_CREATE, tex->id );
sendUS1UI2( outstream, PACKETTYPE_S2C_TEXTURE_IMAGE, tex->id, tex->image->id );
}
void sendDeckSetup( Stream *outstream, Deck *dk ) {
assertmsg(dk->getUperCell()>0, "only tiledeck is supported" ); // TODO: Support PackDeck
TileDeck *td = (TileDeck*) dk;
// print("sending tiledeck_create id:%d", td->id );
sendUS1UI1( outstream, PACKETTYPE_S2C_TILEDECK_CREATE, dk->id );
sendUS1UI2( outstream, PACKETTYPE_S2C_TILEDECK_TEXTURE, dk->id, td->tex->id );
// print("sendS2RTileDeckSize: id:%d %d,%d,%d,%d", td->id, sprw, sprh, cellw, cellh );
sendUS1UI5( outstream, PACKETTYPE_S2C_TILEDECK_SIZE, td->id, td->tile_width, td->tile_height, td->cell_width, td->cell_height );
}
void sendFontSetupWithFile( Stream *outstream, Font *f ) {
print("sending font id:%d path:%s", f->id, f->last_load_file_path );
sendUS1UI1( outstream, PACKETTYPE_S2C_FONT_CREATE, f->id );
// utf32toutf8
sendUS1UI1Wstr( outstream, PACKETTYPE_S2C_FONT_CHARCODES, f->id, f->charcode_table, f->charcode_table_used_num );
// sendFile( outstream, f->last_load_file_path );
sendUS1UI2Str( outstream, PACKETTYPE_S2C_FONT_LOADTTF, f->id, f->pixel_size, f->last_load_file_path );
}
void sendColorReplacerShaderSetup( Stream *outstream, ColorReplacerShader *crs ) {
print("sending col repl shader id:%d", crs->id );
PacketColorReplacerShaderSnapshot ss;
setupPacketColorReplacerShaderSnapshot(&ss,crs);
sendUS1Bytes( outstream, PACKETTYPE_S2C_COLOR_REPLACER_SHADER_SNAPSHOT, (const char*)&ss, sizeof(ss) );
}
void sendSoundSetup( Stream *outstream, Sound *snd ) {
if( snd->last_load_file_path[0] ) {
// sendFile( outstream, snd->last_load_file_path );
print("sending sound load file: %d, '%s'", snd->id, snd->last_load_file_path );
sendUS1UI1Str( outstream, PACKETTYPE_S2C_SOUND_CREATE_FROM_FILE, snd->id, snd->last_load_file_path );
} else if( snd->last_samples ){
sendUS1UI1Bytes( outstream, PACKETTYPE_S2C_SOUND_CREATE_FROM_SAMPLES, snd->id,
(const char*) snd->last_samples,
snd->last_samples_num * sizeof(snd->last_samples[0]) );
}
sendUS1UI1F1( outstream, PACKETTYPE_S2C_SOUND_DEFAULT_VOLUME, snd->id, snd->default_volume );
if(snd->isPlaying()) {
sendUS1UI1F2( outstream, PACKETTYPE_S2C_SOUND_POSITION, snd->id, snd->getTimePositionSec(), snd->last_play_volume );
}
}
////////////////////
Buffer::Buffer() : buf(0), size(0), used(0) {
}
void Buffer::ensureMemory( size_t sz ) {
if(!buf) {
buf = (char*) MALLOC(sz);
assert(buf);
size = sz;
used = 0;
}
}
Buffer::~Buffer() {
if(buf) {
FREE(buf);
}
size = used = 0;
}
bool Buffer::push( const char *data, size_t datasz ) {
if(datasz==0)return true;
size_t left = size - used;
if( left < datasz ) return false;
memcpy( buf + used, data, datasz );
used += datasz;
// fprintf(stderr, "buffer_push: pushed %d bytes, used: %d\n", (int)datasz, (int)b->used );
return true;
}
bool Buffer::pushWithNum32( const char *data, size_t datasz ) {
size_t left = size - used;
if( left < 4 + datasz ) return false;
set_u32( buf + used, datasz );
used += 4;
push( data, datasz );
return true;
}
bool Buffer::pushU32( unsigned int val ) {
size_t left = size - used;
if( left < 4 ) return false;
set_u32( buf + used, val );
used += 4;
// fprintf(stderr, "buffer_push_u32: pushed 4 bytes. val:%u\n",val );
return true;
}
bool Buffer::pushU16( unsigned short val ) {
size_t left = size - used;
if( left < 2 ) return false;
set_u16( buf + used, val );
used += 2;
return true;
}
bool Buffer::pushU8( unsigned char val ) {
size_t left = size - used;
if( left < 1 ) return false;
set_u8( buf + used, val );
used += 1;
return true;
}
// ALL or NOTHING. true when success
bool Buffer::shift( size_t toshift ) {
if( used < toshift ) return false;
if( toshift == used ) { // most cases
used = 0;
return true;
}
// 0000000000 size=10
// uuuuu used=5
// ss shift=2
// mmm move=3
memmove( buf, buf + toshift, used - toshift );
used -= toshift;
return true;
}
//////////////////
BufferArray::BufferArray( int maxnum ) {
buffers = (Buffer**) MALLOC( maxnum * sizeof(Buffer*) );
assert(buffers);
buffer_num = maxnum;
buffer_used = 0;
for(int i=0;i<maxnum;i++) buffers[i] = NULL;
}
BufferArray::~BufferArray() {
for(unsigned int i=0;i<buffer_num;i++) {
delete buffers[i];
FREE(buffers[i]);
}
}
bool BufferArray::push(const char *data, size_t len) {
if(buffer_used == buffer_num)return false;
Buffer *b = new Buffer();
b->ensureMemory(len);
b->push(data,len);
buffers[buffer_used] = b;
buffer_used++;
return true;
}
Buffer *BufferArray::getTop() {
if(buffer_used==0)return NULL;
return buffers[0];
}
void BufferArray::shift() {
if(buffer_used==0)return;
Buffer *top = buffers[0];
for(unsigned int i=0;i<buffer_used-1;i++) {
buffers[i] = buffers[i+1];
}
buffers[buffer_used]=NULL;
buffer_used--;
delete top;
}
//////////////////
int Stream::idgen = 1;
Stream::Stream( uv_tcp_t *sk, size_t sendbufsize, size_t recvbufsize, bool compress ) : tcp(sk), use_compression(compress) {
id = ++idgen;
sendbuf.ensureMemory(sendbufsize);
recvbuf.ensureMemory(recvbufsize);
unzipped_recvbuf.ensureMemory(recvbufsize);
}
static void on_write_end( uv_write_t *req, int status ) {
// print("on_write_end! st:%d",status);
if(status<0) {
print("on_write_end error: status:%d",status);
}
FREE(req->data);
FREE(req);
}
size_t Stream::flushSendbuf(size_t unitsize) {
if(uv_is_writable((uv_stream_t*)tcp) && sendbuf.used > 0 ) {
size_t partsize = sendbuf.used;
if(partsize>unitsize) partsize = unitsize;
uv_write_t *write_req = (uv_write_t*)MALLOC(sizeof(uv_write_t));
size_t allocsize = use_compression ? partsize*2+64 : partsize; // Abs max size of snappy worst case size
char *outbuf = (char*)MALLOC(allocsize); // need this because uv_write delays actual write after shifting sendbuf!
if( use_compression ) {
size_t headersize = 4+2;
// print("partsize:%d allocsize:%d", partsize,allocsize);
int compsz = memCompressSnappy( outbuf+headersize, allocsize-headersize, sendbuf.buf, partsize);
assert(allocsize>=compsz+headersize);
set_u32(outbuf+0,compsz+2); // size of funcid
set_u16(outbuf+4,PACKETTYPE_ZIPPED_RECORDS);
// print("compress: partsize:%d compd:%d", partsize, compsz);
write_req->data = outbuf;
uv_buf_t buf = uv_buf_init(outbuf,4+2+compsz);
int r = uv_write( write_req, (uv_stream_t*)tcp, &buf, 1, on_write_end );
if(r) {
print("uv_write fail. %d",r);
return 0;
} else {
// print("uv_write ok, partsz:%d used:%d", partsize, sendbuf.used );
sendbuf.shift(partsize);
return partsize;
}
} else {
// print("nocompress used:%d", sendbuf.used );
memcpy(outbuf,sendbuf.buf,partsize);
write_req->data = outbuf;
uv_buf_t buf = uv_buf_init(outbuf,partsize);
int r = uv_write( write_req, (uv_stream_t*)tcp, &buf, 1, on_write_end );
if(r) {
print("uv_write fail. %d",r);
return 0;
} else {
// print("uv_write ok, partsz:%d used:%d", partsize, sendbuf.used );
sendbuf.shift(partsize);
return partsize;
}
}
}
return 0;
}
//////////////////
// normal headless client
Client::Client( uv_tcp_t *sk, RemoteHead *rh, bool compress ) : Stream(sk,128*1024*1024,8*1024,compress){
init();
parent_rh = rh;
}
// clients connecting to reproxy
Client::Client( uv_tcp_t *sk, ReprecationProxy *reproxy, bool compress ) : Stream(sk,128*1024*1024,8*1024,compress) {
init();
parent_reproxy = reproxy;
}
// reproxies
Client::Client( uv_tcp_t *sk, Reprecator *repr, bool compress ) : Stream(sk, 128*1024*1024,32*1024,compress){
init();
parent_reprecator = repr;
}
// creating logical clients in server
Client::Client( RemoteHead *rh ) : Stream(NULL,0,0,false){
init();
parent_rh = rh;
}
Client *Client::createLogicalClient( Stream *reprecator_stream, RemoteHead *rh ) {
Client *cl = new Client(rh);
cl->reprecator_stream = reprecator_stream;
print("createLogicalClient called. newclid:%d",cl->id);
return cl;
}
void Client::init() {
parent_rh = NULL;
parent_reproxy = NULL;
parent_reprecator = NULL;
target_camera = NULL;
target_viewport = NULL;
initialized_at = now();
global_client_id = 0;
reprecator_stream=NULL;
accum_time=0;
send_wait=0;
}
Client::~Client() {
print("~Client called for %d", id );
if(target_camera) {
POOL_SCAN(target_camera->target_layers,Layer){
it->second->delDynamicCamera(target_camera);
}
}
if(target_viewport) {
POOL_SCAN(target_viewport->target_layers,Layer) {
it->second->delDynamicViewport(target_viewport);
}
}
}
size_t Client::flushSendbufToNetwork() {
return getStream()->flushSendbuf(256*1024);
}
////////////////////////////
// return false when error(to close)
bool parseRecord( Stream *s, Buffer *recvbuf, const char *data, size_t datalen, void (*funcCallback)( Stream *s, uint16_t funcid, char *data, uint32_t datalen ) ) {
bool pushed = recvbuf->push( data, datalen );
// print("parseRecord: datalen:%d bufd:%d pushed:%d", datalen, recvbuf->used, pushed );
if(!pushed) {
print("recv buf full? close.");
return false;
}
// Parse RPC
// fprintf(stderr, "recvbuf used:%zu\n", c->recvbuf->used );
while(true) { // process everything in one poll
// print("recvbuf:%d", c->recvbuf->used );
if( recvbuf->used < (4+2) ) return true; // need more data from network
// <---RECORDLEN------>
// [RECORDLEN32][FUNCID32][..DATA..]
size_t record_len = get_u32( recvbuf->buf );
unsigned int func_id = get_u16( recvbuf->buf + 4 );
if( recvbuf->used < (4+record_len) ) {
// print("need. used:%d reclen:%d", recvbuf->used, record_len );
return true; // need more data from network
}
if( record_len < 2 ) {
fprintf(stderr, "invalid packet format" );
return false;
}
// fprintf(stderr, "dispatching func_id:%d record_len:%lu\n", func_id, record_len );
// dump( recvbuf->buf, record_len-4);
funcCallback( s, func_id, (char*) recvbuf->buf +4+2, record_len - 2 );
recvbuf->shift( 4 + record_len );
// fprintf(stderr, "after dispatch recv func: buffer used: %zu\n", c->recvbuf->used );
// if( c->recvbuf->used > 0 ) dump( c->recvbuf->buf, c->recvbuf->used );
}
}
bool Client::canSee(Prop2D*p) {
if(!target_viewport) { return true; }
Vec2 minv, maxv;
target_viewport->getMinMax(&minv,&maxv);
return p->isInView(&minv,&maxv,target_camera);
}
//////////////////////
static void reproxy_on_close_callback( uv_handle_t *s ) {
print("reproxy_on_close_callback");
Client *cli = (Client*)s->data;
if(cli->parent_reproxy->close_callback) cli->parent_reproxy->close_callback(cli);
cli->parent_reproxy->delClient(cli);
delete cli;
}
static void reproxy_on_read_callback( uv_stream_t *s, ssize_t nread, const uv_buf_t *inbuf ) {
// print("reproxy_on_read_callback: nread:%d",nread);
Client *cl = (Client*)s->data;
if(nread>0) {
ReprecationProxy *rp = cl->parent_reproxy;
assert(rp);
assert(rp->func_callback);
bool res = parseRecord(cl, &cl->recvbuf, inbuf->base, nread, rp->func_callback );
if(!res) {
uv_close( (uv_handle_t*)s, reproxy_on_close_callback );
return;
}
} else if( nread<0 ) {
print("reproxy_on_read_callback EOF. clid:%d", cl->id );
uv_close( (uv_handle_t*)s, reproxy_on_close_callback );
}
}
void reproxy_on_accept_callback(uv_stream_t *listener, int status) {
print("reproxy_on_accept_callback: status:%d",status);
if(status!=0) {
print("reproxy_on_accept_callback error status:%d",status);
return;
}
uv_tcp_t *newsock = (uv_tcp_t*)MALLOC( sizeof(uv_tcp_t));
uv_tcp_init( uv_default_loop(), newsock );
if( uv_accept( listener, (uv_stream_t*)newsock) == 0 ) {
uv_tcp_nodelay(newsock,1);
ReprecationProxy *rp = (ReprecationProxy*)listener->data;
Client *cl = new Client(newsock,rp,true);
newsock->data = cl;
cl->parent_reproxy->addClient(cl);
print("reproxy_on_accept_callback. accepted");
int r = uv_read_start( (uv_stream_t*)newsock, moyai_libuv_alloc_buffer, reproxy_on_read_callback );
if(r) {
print("uv_read_start: failed. ret:%d",r);
return;
}
assert(rp->accept_callback);
rp->accept_callback(cl);
}
}
ReprecationProxy::ReprecationProxy(int portnum) : func_callback(NULL) {
bool res = init_tcp_listener( &listener, (void*)this, portnum, reproxy_on_accept_callback );
assertmsg(res, "Reproxy: listen error");
print("Reproxy: listening on %d", portnum);
}
void ReprecationProxy::addClient( Client *cl) {
Client *stored = cl_pool.get(cl->id);
if(!stored) {
cl->parent_reproxy = this;
cl_pool.set(cl->id,cl);
}
}
void ReprecationProxy::delClient(Client*cl) {
cl_pool.del(cl->id);
}
void ReprecationProxy::broadcastUS1RawArgs(uint16_t funcid, const char*data, size_t datalen ) {
POOL_SCAN(cl_pool,Client) {
sendUS1RawArgs( it->second, funcid, data, datalen );
}
}
Client *ReprecationProxy::getClientByGlobalId(unsigned int gclid) {
POOL_SCAN(cl_pool,Client) {
if( it->second->global_client_id==gclid) {
return it->second;
}
}
return NULL;
}
void ReprecationProxy::heartbeat() {
POOL_SCAN(cl_pool,Client) {
it->second->flushSendbuf(256*1024);
}
}
| 41.548565
| 214
| 0.627326
|
kengonakajima
|
01b3e55d56db4c26698eff448438f681cbfc80e6
| 1,473
|
cc
|
C++
|
chapter-acceleration/openmp/offload-case-studies/case5.cc
|
Mark1626/road-to-plus-plus
|
500db757051e32e6ccd144b70171c826527610d4
|
[
"CC0-1.0"
] | 1
|
2021-07-04T12:41:16.000Z
|
2021-07-04T12:41:16.000Z
|
chapter-acceleration/openmp/offload-case-studies/case5.cc
|
Mark1626/road-to-plus-plus
|
500db757051e32e6ccd144b70171c826527610d4
|
[
"CC0-1.0"
] | null | null | null |
chapter-acceleration/openmp/offload-case-studies/case5.cc
|
Mark1626/road-to-plus-plus
|
500db757051e32e6ccd144b70171c826527610d4
|
[
"CC0-1.0"
] | null | null | null |
#include <cmath>
#include <cstdio>
// static const int waveletsize = 3;
// static const int size = 6;
class HaarWavelet {
public:
static const int waveletsize = 3;
static const int size = 6;
double wavelet[waveletsize] = {0.0, 1.0 / 2.0, 1.0 / 2.0};
double sigmafactors[size + 1] = {1.00000000000, 7.07167810e-1, 5.00000000e-1,
3.53553391e-1, 2.50000000e-1, 1.76776695e-1,
1.25000000e-1};
int* arr;
HaarWavelet() {
int *a = new int[10];
arr = a;
#pragma omp target enter data map(alloc:a)
}
~HaarWavelet() {
int *a = arr;
#pragma omp target exit data map(delete:a)
delete [] arr;
}
#pragma omp declare target
int getNumScales(int length) {
return 1 + int(log(double(length - 1) / double(size - 1)) / M_LN2);
}
#pragma omp end declare target
#pragma omp declare target
int getMaxSize(int scale) { return int(pow(2, scale - 1)) * (size - 1) + 1; }
#pragma omp end declare target
};
#pragma omp declare target
void offload_driver(HaarWavelet *haar) {
printf("Max Size: %d\n", haar->getMaxSize(1));
printf("Num Scales: %d\n", haar->getNumScales(400));
}
#pragma omp end declare target
void test_offload_class() {
HaarWavelet haar;
#pragma omp target map(to: haar.wavelet[:haar.waveletsize]) \
map(to:haar.sigmafactors[:haar.size + 1])
{
printf("Scales %d\n", haar.getNumScales(10));
offload_driver(&haar);
}
}
| 26.781818
| 79
| 0.619823
|
Mark1626
|
01bdd4f02548e24a34c2e63f51fc3ff6bfc8f172
| 29,130
|
cpp
|
C++
|
boolean_network/cudd_bnet.cpp
|
tonyfloatersu/simulator
|
78dc09c6a704a7e9e0ffd3ad7f33f7b71971a773
|
[
"MIT"
] | 1
|
2020-10-28T15:15:03.000Z
|
2020-10-28T15:15:03.000Z
|
boolean_network/cudd_bnet.cpp
|
SJTU-ECTL/simulator
|
78dc09c6a704a7e9e0ffd3ad7f33f7b71971a773
|
[
"MIT"
] | null | null | null |
boolean_network/cudd_bnet.cpp
|
SJTU-ECTL/simulator
|
78dc09c6a704a7e9e0ffd3ad7f33f7b71971a773
|
[
"MIT"
] | null | null | null |
/**
@file
@ingroup nanotrav
@brief Functions to read in a boolean network.
@author Fabio Somenzi
@copyright@parblock
Copyright (c) 1995-2015, Regents of the University of Colorado
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 University of Colorado nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
@endparblock
*/
#include "cudd_bnet.h"
/*---------------------------------------------------------------------------*/
/* Implementation of BnetNode->outputs */
#include <map>
#include <vector>
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Constant declarations */
/*---------------------------------------------------------------------------*/
#define MAXLENGTH 131072
/*---------------------------------------------------------------------------*/
/* Stucture declarations */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Type declarations */
/*---------------------------------------------------------------------------*/
/* Type of comparison function for qsort. */
typedef int (*DD_QSFP)(const void *, const void *);
/*---------------------------------------------------------------------------*/
/* Variable declarations */
/*---------------------------------------------------------------------------*/
static char BuffLine[MAXLENGTH];
static char *CurPos;
static int newNameNumber = 0;
/*---------------------------------------------------------------------------*/
/* Macro declarations */
/*---------------------------------------------------------------------------*/
/** \cond */
/*---------------------------------------------------------------------------*/
/* Static function prototypes */
/*---------------------------------------------------------------------------*/
static char * readString (FILE *fp);
static char ** readList (FILE *fp, int *n);
static void printList (char **list, int n);
static char ** bnetGenerateNewNames (st_table *hash, int n);
static int bnetSetLevel (_BnetNetwork *net);
static int bnetLevelDFS (_BnetNetwork *net, _BnetNode *node);
static _BnetNode ** bnetOrderRoots (_BnetNetwork *net, int *nroots);
static int bnetLevelCompare (_BnetNode **x, _BnetNode **y);
/** \endcond */
/*---------------------------------------------------------------------------*/
/* Definition of exported functions */
/*---------------------------------------------------------------------------*/
/**
@brief Reads boolean network from blif file.
@details A very restricted subset of blif is supported. Specifically:
<ul>
<li> The only directives recognized are:
<ul>
<li> .model
<li> .inputs
<li> .outputs
<li> .latch
<li> .names
<li> .exdc
<li> .wire_load_slope
<li> .end
</ul>
<li> Latches must have an initial values and no other parameters
specified.
<li> Lines must not exceed MAXLENGTH-1 characters, and individual names must
not exceed 1023 characters.
</ul>
Caveat emptor: There may be other limitations as well. One should
check the syntax of the blif file with some other tool before relying
on this parser.
@return a pointer to the network if successful; NULL otherwise.
@sideeffect None
@see Bnet_PrintNetwork Bnet_FreeNetwork
*/
_BnetNetwork *
Bnet_ReadNetwork(
FILE * fp /**< pointer to the blif file */,
int pr /**< verbosity level */)
{
char *savestring;
char **list;
int i, j, n;
_BnetNetwork *net;
_BnetNode *newnode;
_BnetNode *lastnode = nullptr;
BnetTabline *newline;
BnetTabline *lastline;
char ***latches = nullptr;
int maxlatches = 0;
int exdc = 0;
_BnetNode *node;
int count;
/*---------------------------------------------------------------------------*/
/* Implementation of BnetNode->outputs */
std::map<std::string, std::vector<std::string> > name_outputs;
std::map<std::string, std::vector<std::string> >::iterator it;
/*---------------------------------------------------------------------------*/
/* Allocate network object and initialize symbol table. */
net = ALLOC(_BnetNetwork,1);
if (net == nullptr) goto failure;
memset((char *) net, 0, sizeof(_BnetNetwork));
net->hash = st_init_table((st_compare_t) strcmp, st_strhash);
if (net->hash == nullptr) goto failure;
savestring = readString(fp);
if (savestring == nullptr) goto failure;
net->nlatches = 0;
while (strcmp(savestring, ".model") == 0 ||
strcmp(savestring, ".inputs") == 0 ||
strcmp(savestring, ".outputs") == 0 ||
strcmp(savestring, ".latch") == 0 ||
strcmp(savestring, ".wire_load_slope") == 0 ||
strcmp(savestring, ".exdc") == 0 ||
strcmp(savestring, ".names") == 0 || strcmp(savestring,".end") == 0) {
if (strcmp(savestring, ".model") == 0) {
/* Read .model directive. */
FREE(savestring);
/* Read network name. */
savestring = readString(fp);
if (savestring == nullptr) goto failure;
if (savestring[0] == '.') {
net->name = ALLOC(char, 1);
if (net->name == nullptr) goto failure;
net->name[0] = '\0';
} else {
net->name = savestring;
}
} else if (strcmp(savestring, ".inputs") == 0) {
/* Read .inputs directive. */
FREE(savestring);
/* Read input names. */
list = readList(fp,&n);
if (list == nullptr) goto failure;
if (pr > 2) printList(list,n);
/* Expect at least one input. */
if (n < 1) {
(void) fprintf(stdout,"Empty input list.\n");
goto failure;
}
if (exdc) {
for (i = 0; i < n; i++)
FREE(list[i]);
FREE(list);
savestring = readString(fp);
if (savestring == nullptr) goto failure;
continue;
}
if (net->ninputs) {
net->inputs = REALLOC(char *, net->inputs,
(net->ninputs + n) * sizeof(char *));
for (i = 0; i < n; i++)
net->inputs[net->ninputs + i] = list[i];
}
else
net->inputs = list;
/* Create a node for each primary input. */
for (i = 0; i < n; i++) {
newnode = ALLOC(_BnetNode,1);
memset((char *) newnode, 0, sizeof(_BnetNode));
if (newnode == nullptr) goto failure;
newnode->name = list[i];
newnode->inputs = nullptr;
/*---------------------------------------------------------------------------*/
/* Implementation of BnetNode->outputs */
newnode->outputs = nullptr;
/*---------------------------------------------------------------------------*/
newnode->type = BNET_INPUT_NODE;
newnode->active = FALSE;
newnode->nfo = 0;
newnode->ninp = 0;
newnode->f = nullptr;
newnode->polarity = 0;
newnode->next = nullptr;
if (lastnode == nullptr) {
net->nodes = newnode;
} else {
lastnode->next = newnode;
}
lastnode = newnode;
}
net->npis += n;
net->ninputs += n;
} else if (strcmp(savestring, ".outputs") == 0) {
/* Read .outputs directive. We do not create nodes for the primary
** outputs, because the nodes will be created when the same names
** appear as outputs of some gates.
*/
FREE(savestring);
/* Read output names. */
list = readList(fp,&n);
if (list == nullptr) goto failure;
if (pr > 2) printList(list,n);
if (n < 1) {
(void) fprintf(stdout,"Empty .outputs list.\n");
goto failure;
}
if (exdc) {
for (i = 0; i < n; i++)
FREE(list[i]);
FREE(list);
savestring = readString(fp);
if (savestring == nullptr) goto failure;
continue;
}
if (net->noutputs) {
net->outputs = REALLOC(char *, net->outputs,
(net->noutputs + n) * sizeof(char *));
for (i = 0; i < n; i++)
net->outputs[net->noutputs + i] = list[i];
} else {
net->outputs = list;
}
net->npos += n;
net->noutputs += n;
} else if (strcmp(savestring,".wire_load_slope") == 0) {
FREE(savestring);
savestring = readString(fp);
net->slope = savestring;
} else if (strcmp(savestring,".latch") == 0) {
FREE(savestring);
newnode = ALLOC(_BnetNode,1);
if (newnode == nullptr) goto failure;
memset((char *) newnode, 0, sizeof(_BnetNode));
newnode->type = BNET_PRESENT_STATE_NODE;
list = readList(fp,&n);
if (list == nullptr) goto failure;
if (pr > 2) printList(list,n);
/* Expect three names. */
if (n != 3) {
(void) fprintf(stdout,
".latch not followed by three tokens.\n");
goto failure;
}
newnode->name = list[1];
newnode->inputs = nullptr;
newnode->ninp = 0;
newnode->f = nullptr;
newnode->active = FALSE;
newnode->nfo = 0;
newnode->polarity = 0;
newnode->next = nullptr;
if (lastnode == nullptr) {
net->nodes = newnode;
} else {
lastnode->next = newnode;
}
lastnode = newnode;
/* Add next state variable to list. */
if (maxlatches == 0) {
maxlatches = 20;
latches = ALLOC(char **,maxlatches);
} else if (maxlatches <= net->nlatches) {
maxlatches += 20;
latches = REALLOC(char **,latches,maxlatches);
}
latches[net->nlatches] = list;
net->nlatches++;
savestring = readString(fp);
if (savestring == nullptr) goto failure;
} else if (strcmp(savestring,".names") == 0) {
FREE(savestring);
newnode = ALLOC(_BnetNode,1);
memset((char *) newnode, 0, sizeof(_BnetNode));
if (newnode == nullptr) goto failure;
list = readList(fp,&n);
if (list == nullptr) goto failure;
if (pr > 2) printList(list,n);
/* Expect at least one name (the node output). */
if (n < 1) {
(void) fprintf(stdout,"Missing output name.\n");
goto failure;
}
newnode->name = list[n-1];
newnode->inputs = list;
/*---------------------------------------------------------------------------*/
/* Implementation of BnetNode->outputs */
newnode->outputs = nullptr;
for(i = 0; i < n-1; i++) {
std::string input(newnode->inputs[i]);
std::string output(newnode->name);
it = name_outputs.find(input);
if(it == name_outputs.end()) {
std::vector<std::string> outputs;
outputs.push_back(output);
name_outputs.insert(
std::pair<std::string, std::vector<std::string>>
(input, outputs));
}
else
it->second.push_back(output);
}
/*---------------------------------------------------------------------------*/
newnode->ninp = n-1;
newnode->active = FALSE;
newnode->nfo = 0;
newnode->polarity = 0;
if (newnode->ninp > 0) {
newnode->type = BNET_INTERNAL_NODE;
for (i = 0; i < net->noutputs; i++) {
if (strcmp(net->outputs[i], newnode->name) == 0) {
newnode->type = BNET_OUTPUT_NODE;
break;
}
}
} else {
newnode->type = BNET_CONSTANT_NODE;
}
newnode->next = nullptr;
if (lastnode == nullptr) {
net->nodes = newnode;
} else {
lastnode->next = newnode;
}
lastnode = newnode;
/* Read node function. */
newnode->f = nullptr;
if (exdc) {
newnode->exdc_flag = 1;
node = net->nodes;
while (node) {
if (node->type == BNET_OUTPUT_NODE &&
strcmp(node->name, newnode->name) == 0) {
node->exdc = newnode;
break;
}
node = node->next;
}
}
savestring = readString(fp);
if (savestring == nullptr) goto failure;
lastline = nullptr;
while (savestring[0] != '.') {
/* Reading a table line. */
newline = ALLOC(BnetTabline,1);
if (newline == nullptr) goto failure;
newline->next = nullptr;
if (lastline == nullptr) {
newnode->f = newline;
} else {
lastline->next = newline;
}
lastline = newline;
if (newnode->type == BNET_INTERNAL_NODE ||
newnode->type == BNET_OUTPUT_NODE) {
newline->values = savestring;
/* Read output 1 or 0. */
savestring = readString(fp);
if (savestring == nullptr) goto failure;
} else {
newline->values = nullptr;
}
if (savestring[0] == '0') newnode->polarity = 1;
FREE(savestring);
savestring = readString(fp);
if (savestring == nullptr) goto failure;
}
} else if (strcmp(savestring,".exdc") == 0) {
FREE(savestring);
exdc = 1;
} else if (strcmp(savestring,".end") == 0) {
FREE(savestring);
break;
}
if ((!savestring) || savestring[0] != '.')
savestring = readString(fp);
if (savestring == nullptr) goto failure;
}
/* Put nodes in symbol table. */
newnode = net->nodes;
while (newnode != nullptr) {
int retval = st_insert(net->hash,newnode->name,(char *) newnode);
if (retval == ST_OUT_OF_MEM) {
goto failure;
} else if (retval == 1) {
printf("Error: Multiple drivers for node %s\n", newnode->name);
goto failure;
} else {
if (pr > 2) printf("Inserted %s\n",newnode->name);
}
newnode = newnode->next;
}
if (latches) {
net->latches = latches;
count = 0;
net->outputs = REALLOC(char *, net->outputs,
(net->noutputs + net->nlatches) * sizeof(char *));
for (i = 0; i < net->nlatches; i++) {
for (j = 0; j < net->noutputs; j++) {
if (strcmp(latches[i][0], net->outputs[j]) == 0)
break;
}
if (j < net->noutputs)
continue;
savestring = ALLOC(char, strlen(latches[i][0]) + 1);
strcpy(savestring, latches[i][0]);
net->outputs[net->noutputs + count] = savestring;
count++;
if (st_lookup(net->hash, savestring, (void **) &node)) {
if (node->type == BNET_INTERNAL_NODE) {
node->type = BNET_OUTPUT_NODE;
}
}
}
net->noutputs += count;
net->inputs = REALLOC(char *, net->inputs,
(net->ninputs + net->nlatches) * sizeof(char *));
for (i = 0; i < net->nlatches; i++) {
savestring = ALLOC(char, strlen(latches[i][1]) + 1);
strcpy(savestring, latches[i][1]);
net->inputs[net->ninputs + i] = savestring;
}
net->ninputs += net->nlatches;
}
/* Compute fanout counts. For each node in the linked list, fetch
** all its fanins using the symbol table, and increment the fanout of
** each fanin.
*/
newnode = net->nodes;
while (newnode != nullptr) {
_BnetNode *auxnd;
for (i = 0; i < newnode->ninp; i++) {
if (!st_lookup(net->hash,newnode->inputs[i],(void **)&auxnd)) {
(void) fprintf(stdout,"%s not driven\n", newnode->inputs[i]);
goto failure;
}
auxnd->nfo++;
}
newnode = newnode->next;
}
/*---------------------------------------------------------------------------*/
/* Implementation of BnetNode->outputs */
for (newnode = net->nodes; newnode != nullptr; newnode = newnode->next) {
std::string name_str(newnode->name);
it = name_outputs.find(name_str);
if(it != name_outputs.end() && newnode->nfo > 0) {
std::vector<std::string> outputs = it->second;
newnode->outputs = ALLOC(char *, outputs.size());
for(i = 0; i < outputs.size(); i++)
{
std::string str = outputs[i];
auto *cc = (char*)malloc(str.size()+1);
int j;
for(j = 0; j < str.size(); j++) cc[j] = str[j];
cc[str.size()] = '\0';
newnode->outputs[i] = cc;
}
}
}
/*---------------------------------------------------------------------------*/
if (!bnetSetLevel(net)) goto failure;
return(net);
failure:
/* Here we should clean up the mess. */
(void) fprintf(stdout,"Error in reading network from file.\n");
return(nullptr);
} /* end of Bnet_ReadNetwork */
/**
@brief Prints to stdout a boolean network created by Bnet_ReadNetwork.
@details Uses the blif format; this way, one can verify the
equivalence of the input and the output with, say, sis.
@sideeffect None
@see Bnet_ReadNetwork
*/
void
Bnet_PrintNetwork(
_BnetNetwork * net /**< boolean network */)
{
_BnetNode *nd;
BnetTabline *tl;
int i;
if (net == nullptr) return;
(void) fprintf(stdout,".model %s\n", net->name);
(void) fprintf(stdout,".inputs");
printList(net->inputs,net->npis);
(void) fprintf(stdout,".outputs");
printList(net->outputs,net->npos);
for (i = 0; i < net->nlatches; i++) {
(void) fprintf(stdout,".latch");
printList(net->latches[i],3);
}
nd = net->nodes;
while (nd != nullptr) {
if (nd->type != BNET_INPUT_NODE && nd->type != BNET_PRESENT_STATE_NODE) {
(void) fprintf(stdout,".names");
for (i = 0; i < nd->ninp; i++) {
(void) fprintf(stdout," %s",nd->inputs[i]);
}
(void) fprintf(stdout," %s\n",nd->name);
tl = nd->f;
while (tl != nullptr) {
if (tl->values != nullptr) {
(void) fprintf(stdout,"%s %d\n",tl->values,
1 - nd->polarity);
} else {
(void) fprintf(stdout,"%d\n", 1 - nd->polarity);
}
tl = tl->next;
}
}
nd = nd->next;
}
(void) fprintf(stdout,".end\n");
} /* end of Bnet_PrintNetwork */
/**
@brief Frees a boolean network created by Bnet_ReadNetwork.
@sideeffect None
@see Bnet_ReadNetwork
*/
void
Bnet_FreeNetwork(
_BnetNetwork * net)
{
_BnetNode *node, *nextnode;
BnetTabline *line, *nextline;
int i;
FREE(net->name);
/* The input name strings are already pointed by the input nodes.
** Here we only need to free the latch names and the array that
** points to them.
*/
for (i = 0; i < net->nlatches; i++) {
FREE(net->inputs[net->npis + i]);
}
FREE(net->inputs);
/* Free the output name strings and then the array pointing to them. */
for (i = 0; i < net->noutputs; i++) {
FREE(net->outputs[i]);
}
FREE(net->outputs);
for (i = 0; i < net->nlatches; i++) {
FREE(net->latches[i][0]);
FREE(net->latches[i][1]);
FREE(net->latches[i][2]);
FREE(net->latches[i]);
}
if (net->nlatches) FREE(net->latches);
node = net->nodes;
while (node != nullptr) {
nextnode = node->next;
if (node->type != BNET_PRESENT_STATE_NODE)
FREE(node->name);
for (i = 0; i < node->ninp; i++) {
FREE(node->inputs[i]);
}
if (node->inputs != nullptr) {
FREE(node->inputs);
}
/*---------------------------------------------------------------------------*/
/* Implementation of BnetNode->outputs */
for (i = 0; i < node->nfo; i++) {
FREE(node->outputs[i]);
}
if (node->outputs != nullptr) {
FREE(node->outputs);
}
/*---------------------------------------------------------------------------*/
/* Free the function table. */
line = node->f;
while (line != nullptr) {
nextline = line->next;
FREE(line->values);
FREE(line);
line = nextline;
}
FREE(node);
node = nextnode;
}
st_free_table(net->hash);
if (net->slope != nullptr) FREE(net->slope);
FREE(net);
} /* end of Bnet_FreeNetwork */
/*---------------------------------------------------------------------------*/
/* Definition of internal functions */
/*---------------------------------------------------------------------------*/
/*---------------------------------------------------------------------------*/
/* Definition of static functions */
/*---------------------------------------------------------------------------*/
/**
@brief Reads a string from a file.
@details The string can be MAXLENGTH-1 characters at
most. readString allocates memory to hold the string.
@return a pointer to the result string if successful. It returns
NULL otherwise.
@sideeffect None
@see readList
*/
static char *
readString(
FILE * fp /**< pointer to the file from which the string is read */)
{
char *savestring;
int length;
while (!CurPos) {
if (!fgets(BuffLine, MAXLENGTH, fp))
return(nullptr);
BuffLine[strlen(BuffLine) - 1] = '\0';
CurPos = strtok(BuffLine, " \t");
if (CurPos && CurPos[0] == '#') CurPos = (char *) nullptr;
}
length = strlen(CurPos);
savestring = ALLOC(char,length+1);
if (savestring == nullptr)
return(nullptr);
strcpy(savestring,CurPos);
CurPos = strtok(nullptr, " \t");
return(savestring);
} /* end of readString */
/**
@brief Reads a list of strings from a line of a file.
@details The strings are sequences of characters separated by spaces
or tabs. The total length of the list, white space included, must
not exceed MAXLENGTH-1 characters. readList allocates memory for
the strings and creates an array of pointers to the individual
lists. Only two pieces of memory are allocated by readList: One to
hold all the strings, and one to hold the pointers to
them. Therefore, when freeing the memory allocated by readList, only
the pointer to the list of pointers, and the pointer to the
beginning of the first string should be freed.
@return the pointer to the list of pointers if successful; NULL
otherwise.
@sideeffect n is set to the number of strings in the list.
@see readString printList
*/
static char **
readList(
FILE * fp /**< pointer to the file from which the list is read */,
int * n /**< on return, number of strings in the list */)
{
char *savestring;
int length;
char *stack[8192];
char **list;
int i, count = 0;
while (CurPos) {
if (strcmp(CurPos, "\\") == 0) {
CurPos = (char *) nullptr;
while (!CurPos) {
if (!fgets(BuffLine, MAXLENGTH, fp)) return(nullptr);
BuffLine[strlen(BuffLine) - 1] = '\0';
CurPos = strtok(BuffLine, " \t");
}
}
length = strlen(CurPos);
savestring = ALLOC(char,length+1);
if (savestring == nullptr) return(nullptr);
strcpy(savestring,CurPos);
stack[count] = savestring;
count++;
CurPos = strtok(nullptr, " \t");
}
list = ALLOC(char *, count);
for (i = 0; i < count; i++)
list[i] = stack[i];
*n = count;
return(list);
} /* end of readList */
/**
@brief Prints a list of strings to the standard output.
@details The list is in the format created by readList.
@sideeffect None
@see readList Bnet_PrintNetwork
*/
static void
printList(
char ** list /**< list of pointers to strings */,
int n /**< length of the list */)
{
int i;
for (i = 0; i < n; i++) {
(void) fprintf(stdout," %s",list[i]);
}
(void) fprintf(stdout,"\n");
} /* end of printList */
/**
@brief Generates n names not currently in a symbol table.
@details The pointer to the symbol table may be NULL, in which case
no test is made. The names generated by the procedure are
unique. So, if there is no possibility of conflict with pre-existing
names, NULL can be passed for the hash table.
@return an array of names if succesful; NULL otherwise.
@sideeffect None
@see
*/
static char **
bnetGenerateNewNames(
st_table * hash /* table of existing names (or NULL) */,
int n /* number of names to be generated */)
{
char **list;
char name[256];
int i;
if (n < 1) return(nullptr);
list = ALLOC(char *,n);
if (list == nullptr) return(nullptr);
for (i = 0; i < n; i++) {
do {
sprintf(name, "var%d", newNameNumber);
newNameNumber++;
} while (hash != nullptr && st_is_member(hash,name));
list[i] = util_strsav(name);
}
return(list);
} /* bnetGenerateNewNames */
/**
@brief Writes blif for the truth table of an n-input xnor.
@return 1 if successful; 0 otherwise.
@sideeffect None
*/
#if 0
static int
bnetBlifXnorTable(
FILE * fp /**< file pointer */,
int n /**< number of inputs */)
{
int power; /* 2 to the power n */
int i,j,k;
int nzeroes;
int retval;
char *line;
line = ALLOC(char,n+1);
if (line == NULL) return(0);
line[n] = '\0';
for (i = 0, power = 1; i < n; i++) {
power *= 2;
}
for (i = 0; i < power; i++) {
k = i;
nzeroes = 0;
for (j = 0; j < n; j++) {
if (k & 1) {
line[j] = '1';
} else {
line[j] = '0';
nzeroes++;
}
k >>= 1;
}
if ((nzeroes & 1) == 0) {
retval = fprintf(fp,"%s 1\n",line);
if (retval == 0) return(0);
}
}
return(1);
} /* end of bnetBlifXnorTable */
#endif
/**
@brief Sets the level of each node.
@return 1 if successful; 0 otherwise.
@sideeffect Changes the level and visited fields of the nodes it
visits.
@see bnetLevelDFS
*/
static int
bnetSetLevel(
_BnetNetwork * net)
{
_BnetNode *node;
/* Recursively visit nodes. This is pretty inefficient, because we
** visit all nodes in this loop, and most of them in the recursive
** calls to bnetLevelDFS. However, this approach guarantees that
** all nodes will be reached ven if there are dangling outputs. */
node = net->nodes;
while (node != nullptr) {
if (!bnetLevelDFS(net,node)) return(0);
node = node->next;
}
/* Clear visited flags. */
node = net->nodes;
while (node != nullptr) {
node->visited = 0;
node = node->next;
}
return(1);
} /* end of bnetSetLevel */
/**
@brief Does a DFS from a node setting the level field.
@return 1 if successful; 0 otherwise.
@sideeffect Changes the level and visited fields of the nodes it
visits.
@see bnetSetLevel
*/
static int
bnetLevelDFS(
_BnetNetwork * net,
_BnetNode * node)
{
int i;
_BnetNode *auxnd;
if (node->visited == 1) {
return(1);
}
node->visited = 1;
/* Graphical sources have level 0. This is the final value if the
** node has no fan-ins. Otherwise the successive loop will
** increase the level. */
node->level = 0;
for (i = 0; i < node->ninp; i++) {
if (!st_lookup(net->hash, node->inputs[i], (void **) &auxnd)) {
return(0);
}
if (!bnetLevelDFS(net,auxnd)) {
return(0);
}
if (auxnd->level >= node->level) node->level = 1 + auxnd->level;
}
return(1);
} /* end of bnetLevelDFS */
/**
@brief Orders network roots for variable ordering.
@return an array with the ordered outputs and next state variables
if successful; NULL otherwise.
@sideeffect None
*/
static _BnetNode **
bnetOrderRoots(
_BnetNetwork * net,
int * nroots)
{
int i, noutputs;
_BnetNode *node;
_BnetNode **nodes = nullptr;
/* Initialize data structures. */
noutputs = net->noutputs;
nodes = ALLOC(_BnetNode *, noutputs);
if (nodes == nullptr) goto endgame;
/* Find output names and levels. */
for (i = 0; i < net->noutputs; i++) {
if (!st_lookup(net->hash,net->outputs[i],(void **)&node)) {
goto endgame;
}
nodes[i] = node;
}
util_qsort(nodes, noutputs, sizeof(_BnetNode *),
(DD_QSFP)bnetLevelCompare);
*nroots = noutputs;
return(nodes);
endgame:
if (nodes != nullptr) FREE(nodes);
return(nullptr);
} /* end of bnetOrderRoots */
/**
@brief Comparison function used by qsort.
@details Used to order the variables according to the number of keys
in the subtables.
@return the difference in number of keys between the two variables
being compared.
@sideeffect None
*/
static int
bnetLevelCompare(
_BnetNode ** x,
_BnetNode ** y)
{
return((*y)->level - (*x)->level);
} /* end of bnetLevelCompare */
| 28.199419
| 79
| 0.545383
|
tonyfloatersu
|
01c21c7a16d17914f565eb5eccb68e4788672333
| 9,864
|
cpp
|
C++
|
src/utils/BCSimConvenience.cpp
|
sigurdstorve/OpenBCSim
|
500025c1b63bc6ff083cbd649771d1b98e3f7314
|
[
"BSD-3-Clause"
] | 17
|
2016-05-27T13:09:19.000Z
|
2022-03-21T07:08:47.000Z
|
src/utils/BCSimConvenience.cpp
|
rojsc/OpenBCSim
|
53773172974ad42fc3faceb7b36611573abf1c4c
|
[
"BSD-3-Clause"
] | 63
|
2015-09-10T11:22:56.000Z
|
2021-05-21T14:52:39.000Z
|
src/utils/BCSimConvenience.cpp
|
rojsc/OpenBCSim
|
53773172974ad42fc3faceb7b36611573abf1c4c
|
[
"BSD-3-Clause"
] | 15
|
2016-07-26T14:52:18.000Z
|
2022-01-02T15:52:28.000Z
|
/*
Copyright (c) 2015, Sigurd Storve
All rights reserved.
Licensed under the BSD license.
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 <organization> 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 <COPYRIGHT HOLDER> 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 <algorithm>
#include <stdexcept>
#include <cmath>
#include <stdexcept>
#include "BCSimConvenience.hpp"
#include "../core/bspline.hpp"
#include "rotation3d.hpp"
namespace bcsim {
std::vector<std::vector<float> > decimate_frame(const std::vector<std::vector<float> >& frame, int rad_decimation) {
if (rad_decimation < 1) throw std::runtime_error("Invalid decimation value");
auto num_beams = frame.size();
auto num_samples = frame[0].size();
auto num_samples_dec = num_samples / rad_decimation;
std::vector<std::vector<float> > decimated_frame(num_beams);
for (size_t beam_no = 0; beam_no < num_beams; beam_no++) {
decimated_frame[beam_no].resize(num_samples_dec);
for (size_t sample_no = 0; sample_no < num_samples_dec; sample_no++) {
decimated_frame[beam_no][sample_no] = frame[beam_no][sample_no*rad_decimation];
}
}
return decimated_frame;
}
float get_max_value(const std::vector<std::vector<float> >& image_lines) {
std::vector<float> max_values;
for (const auto& image_line : image_lines) {
max_values.push_back(*std::max_element(image_line.begin(), image_line.end()));
}
return *std::max_element(max_values.begin(), max_values.end());
}
void log_compress_frame(std::vector<std::vector<float> >& image_lines, float dyn_range, float normalize_factor, float gain_factor) {
auto num_beams = image_lines.size();
auto num_samples = image_lines[0].size();
for (auto& beam : image_lines) {
std::transform(beam.begin(), beam.end(), beam.begin(), [=](float pixel) {
// log-compression
pixel = static_cast<float>(20.0*std::log10(gain_factor*pixel/normalize_factor));
pixel = (255.0/dyn_range)*(pixel + dyn_range);
// clamp to [0, 255]
if (pixel < 0.0f) pixel = 0.0f;
if (pixel >= 255.0f) pixel = 255.0f;
return pixel;
});
}
}
Scatterers::s_ptr render_fixed_scatterers(SplineScatterers::s_ptr spline_scatterers, float timestamp) {
// TODO: can parts of this code be put in a separate function and used both
// here and in the CPU spline algoritm to reduce code duplication?
auto res = FixedScatterers::s_ptr(new FixedScatterers);
const auto num_scatterers = spline_scatterers->num_scatterers();
if (num_scatterers == 0) {
throw std::runtime_error("No spline scatterers");
}
// precompute basis functions
const auto num_cs = spline_scatterers->get_num_control_points();
std::vector<float> basis_fn(num_cs);
for (size_t i = 0; i < num_cs; i++) {
basis_fn[i] = bspline_storve::bsplineBasis(i, spline_scatterers->spline_degree, timestamp, spline_scatterers->knot_vector);
}
// evaluate using cached basis functions
res->scatterers.resize(num_scatterers);
for (size_t spline_no = 0; spline_no < num_scatterers; spline_no++) {
PointScatterer scatterer;
scatterer.pos = vector3(0.0f, 0.0f, 0.0f);
scatterer.amplitude = spline_scatterers->amplitudes[spline_no];
for (size_t i = 0; i < num_cs; i++) {
scatterer.pos += spline_scatterers->control_points[spline_no][i]*basis_fn[i];
}
res->scatterers[spline_no] = scatterer;
}
return res;
}
ScanSequence CreateScanSequence(std::shared_ptr<SectorScanGeometry> geometry, size_t num_lines, float timestamp) {
const auto line_length = geometry->depth;
ScanSequence res(line_length);
// Will be transformed by a rotation into lateral and radial unit vectors.
// NOTE: Need to use double to avoid "not orthonormal" error (maybe the test is to strict for floats?)
const auto unit_vector_x = unit_x<double>();
const auto unit_vector_z = unit_z<double>();
const vector3 origin(0.0f, 0.0f, 0.0f);
for (int line_no = 0; line_no < static_cast<int>(num_lines); line_no++) {
const float angle = -0.5f*geometry->width + geometry->tilt + line_no*geometry->width/(num_lines-1);
const auto ROT_MATRIX = rotation_matrix_y<double>(angle);
const auto temp_radial_direction = boost::numeric::ublas::prod(ROT_MATRIX, unit_vector_z);
const auto temp_lateral_direction = boost::numeric::ublas::prod(ROT_MATRIX, unit_vector_x);
// Copy to vector3 vectors. TODO: deduplicate
const vector3 direction ((float)temp_radial_direction(0), (float)temp_radial_direction(1), (float)temp_radial_direction(2));
const vector3 lateral_dir((float)temp_lateral_direction(0), (float)temp_lateral_direction(1), (float)temp_lateral_direction(2));
try {
auto sl = Scanline(origin, direction, lateral_dir, timestamp);
res.add_scanline(sl);
} catch (std::runtime_error& e) {
throw std::runtime_error(std::string("failed creating scan line: ") + e.what());
}
}
return res;
}
ScanSequence CreateScanSequence(std::shared_ptr<LinearScanGeometry> geometry, size_t num_lines, float timestamp) {
const auto line_length = geometry->range_max;
ScanSequence res(line_length);
const auto unit_vector_x = unit_x<double>();
const auto unit_vector_z = unit_z<double>();
// Copy to vector3 vectors. TODO: deduplicate
const vector3 direction (unit_vector_z(0), unit_vector_z(1), unit_vector_z(2));
const vector3 lateral_dir(unit_vector_x(0), unit_vector_x(1), unit_vector_x(2));
for (int line_no = 0; line_no < static_cast<int>(num_lines); line_no++) {
try {
const vector3 scanline_origin(-0.5f*geometry->width + line_no*geometry->width/(static_cast<int>(num_lines)-1), 0.0f, 0.0f);
auto sl = Scanline(scanline_origin, direction, lateral_dir, timestamp);
res.add_scanline(sl);
} catch (std::runtime_error& e) {
throw std::runtime_error(std::string("failed creating scan line: ") + e.what());
}
}
return res;
}
// probe_origin is position of probe's origin in world coordinate system.
ScanSequence CreateScanSequence(ScanGeometry::ptr geometry, size_t num_lines, float timestamp) {
auto sector_geo = std::dynamic_pointer_cast<SectorScanGeometry>(geometry);
auto linear_geo = std::dynamic_pointer_cast<LinearScanGeometry>(geometry);
if (sector_geo) {
return CreateScanSequence(sector_geo, num_lines, timestamp);
} else if (linear_geo) {
return CreateScanSequence(linear_geo, num_lines, timestamp);
} else {
throw std::runtime_error("unable to cast scan geometry");
}
}
namespace detail {
// Apply a 3x3 rotation matrix to a vector3;
template <typename T>
vector3 TransformVector(const vector3& v, const boost::numeric::ublas::matrix<T>& matrix33) {
boost::numeric::ublas::vector<T> temp_v(3);
temp_v(0) = static_cast<T>(v.x); temp_v(1) = static_cast<T>(v.y); temp_v(2) = static_cast<T>(v.z);
const auto transformed = boost::numeric::ublas::prod(matrix33, temp_v);
return vector3(static_cast<float>(transformed(0)),
static_cast<float>(transformed(1)),
static_cast<float>(transformed(2)));
}
}
ScanSequence::s_ptr OrientScanSequence(const ScanSequence& scan_seq, const vector3& rot_angles, const vector3& probe_origin) {
const auto rot_matrix = rotation_matrix_xyz(rot_angles.x, rot_angles.y, rot_angles.z);
const auto line_length = scan_seq.line_length;
auto num_lines = scan_seq.get_num_lines();
auto res = new ScanSequence(line_length);
for (int i = 0; i < num_lines; i++) {
const auto old_line = scan_seq.get_scanline(i);
const auto rotated_origin = detail::TransformVector(old_line.get_origin(), rot_matrix);
const auto rotated_direction = detail::TransformVector(old_line.get_direction(), rot_matrix);
const auto rotated_lateral_dir = detail::TransformVector(old_line.get_lateral_dir(), rot_matrix);
res->add_scanline(Scanline(rotated_origin + probe_origin,
rotated_direction,
rotated_lateral_dir,
old_line.get_timestamp()));
}
return ScanSequence::s_ptr(res);
}
} // end namespace
| 44.233184
| 136
| 0.686942
|
sigurdstorve
|
01c4bb3f0706119a5b8d4925a18a5d136aad9c19
| 160
|
cpp
|
C++
|
11Libraries/HelloLibrary.cpp
|
rianders/2016IntroToProgramming
|
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
|
[
"Apache-2.0"
] | 3
|
2016-01-27T18:12:40.000Z
|
2016-02-03T20:27:19.000Z
|
11Libraries/HelloLibrary.cpp
|
rianders/2016IntroToProgramming
|
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
|
[
"Apache-2.0"
] | 3
|
2016-03-21T02:18:52.000Z
|
2016-03-21T03:02:51.000Z
|
11Libraries/HelloLibrary.cpp
|
rianders/2016IntroToProgramming
|
0e24b2b58c5be2e4d40d3b31b83518c48df5804e
|
[
"Apache-2.0"
] | 16
|
2016-01-27T18:12:41.000Z
|
2019-09-15T01:42:28.000Z
|
#include "HelloLibrary.h"
#include <iostream>
#include <string>
using namespace std;
void HelloWorld() {
cout << "Hello My Library" << endl;
}
| 12.307692
| 39
| 0.63125
|
rianders
|
01c7a3a7f5792c81fd3eb2eb886f2c784d0d78bd
| 1,170
|
hpp
|
C++
|
include/cutee/macros.hpp
|
IanHG/cutee
|
b3b3eba5d78b4871847a5251d311b588e7ba97c0
|
[
"MIT"
] | null | null | null |
include/cutee/macros.hpp
|
IanHG/cutee
|
b3b3eba5d78b4871847a5251d311b588e7ba97c0
|
[
"MIT"
] | 12
|
2018-06-18T12:56:33.000Z
|
2020-09-08T10:29:29.000Z
|
include/cutee/macros.hpp
|
IanHG/cutee
|
b3b3eba5d78b4871847a5251d311b588e7ba97c0
|
[
"MIT"
] | null | null | null |
#pragma once
#ifndef CUTEE_MACROS_HPP_INCLUDED
#define CUTEE_MACROS_HPP_INCLUDED
#include "suite.hpp"
#include "float_eq.hpp"
/**
* Assertion Macros
**/
#define UNIT_ASSERT(a, b) \
cutee::asserter::assertt(a, cutee::info{b, __FILE__, __LINE__});
#define UNIT_ASSERT_NOT(a, b) \
cutee::asserter::assert_not(a, cutee::info{b, __FILE__, __LINE__});
#define UNIT_ASSERT_EQUAL(a, b, c) \
cutee::asserter::assert_equal(a, b, cutee::info{c, __FILE__, __LINE__});
#define UNIT_ASSERT_NOT_EQUAL(a, b, c) \
cutee::asserter::assert_not_equal(a, b, cutee::info{c, __FILE__, __LINE__});
#define UNIT_ASSERT_FEQUAL(a, b, c) \
cutee::asserter::assert_float_equal_prec(a, b, 2u, cutee::info{c, __FILE__, __LINE__});
#define UNIT_ASSERT_FEQUAL_PREC(a, b, c, d) \
cutee::asserter::assert_float_equal_prec(a, b, c, cutee::info{d, __FILE__, __LINE__});
#define UNIT_ASSERT_FZERO(a,b,c) \
cutee::asserter::assert_float_numeq_zero_prec(a, b, 2u, cutee::info{c, __FILE__, __LINE__});
#define UNIT_ASSERT_FZERO_PREC(a,b,c,d) \
cutee::asserter::assert_float_numeq_zero_prec(a, b, c, cutee::info{d, __FILE__, __LINE__});
#endif /* CUTEE_MACROS_HPP_INCLUDED */
| 32.5
| 95
| 0.722222
|
IanHG
|
01c817ed00701072add5f6d11fe4fc2d0ae003cf
| 592
|
cpp
|
C++
|
cpp/triangle/triangle.cpp
|
homembaixinho/exercism
|
fe145381365c101f8e0c5998180ef4973cd9f4ee
|
[
"MIT"
] | null | null | null |
cpp/triangle/triangle.cpp
|
homembaixinho/exercism
|
fe145381365c101f8e0c5998180ef4973cd9f4ee
|
[
"MIT"
] | null | null | null |
cpp/triangle/triangle.cpp
|
homembaixinho/exercism
|
fe145381365c101f8e0c5998180ef4973cd9f4ee
|
[
"MIT"
] | null | null | null |
#include "triangle.h"
#include <algorithm>
#include <stdexcept>
#include <vector>
using namespace std;
namespace triangle {
flavor kind(double a, double b, double c) {
// checks for invalid triangles
double smallest = min(min(a,b), c);
double largest = max(max(a,b), c);
if (a + b + c - 2*largest <= 0 || smallest < 0)
throw domain_error("invalid triangle");
if (a == b) {
if (a == c)
return flavor::equilateral;
return flavor::isosceles;
}
if (b == c || a == c)
return flavor::isosceles;
return flavor::scalene;
}
}
| 19.733333
| 51
| 0.589527
|
homembaixinho
|
01ca1ad888864e8ce50fb68689971ab6ad88eb15
| 115,748
|
cpp
|
C++
|
AStyleTest/src/AStyleTest_Format.cpp
|
a-w/astyle
|
8225c7fc9b65162bdd958cabb87eedd9749f1ecd
|
[
"MIT"
] | null | null | null |
AStyleTest/src/AStyleTest_Format.cpp
|
a-w/astyle
|
8225c7fc9b65162bdd958cabb87eedd9749f1ecd
|
[
"MIT"
] | null | null | null |
AStyleTest/src/AStyleTest_Format.cpp
|
a-w/astyle
|
8225c7fc9b65162bdd958cabb87eedd9749f1ecd
|
[
"MIT"
] | null | null | null |
// AStyleTest_Format.cpp
// Copyright (c) 2016 by Jim Pattee <jimp03@email.com>.
// Licensed under the MIT license.
// License.txt describes the conditions under which this software may be distributed.
//----------------------------------------------------------------------------
// headers
//----------------------------------------------------------------------------
#include "AStyleTest.h"
//----------------------------------------------------------------------------
// anonymous namespace
//----------------------------------------------------------------------------
namespace {
//
//-------------------------------------------------------------------------
// AStyle Break Closing Brackets
// Additional tests are in the Brackets tests
//-------------------------------------------------------------------------
TEST(BreakClosingBrackets, LongOption)
{
// test NONE_MODE brackets with break closing headers
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" } else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char options[] = "break-closing-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, ShortOption)
{
// test NONE_MODE brackets with break closing headers
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" } else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char options[] = "-y";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, Break)
{
// test BREAK_MODE brackets with break closing headers
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" } else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo)\n"
"{\n"
" if (isFoo)\n"
" {\n"
" bar();\n"
" }\n"
" else\n"
" {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char options[] = "style=allman, break-closing-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, Attach)
{
// test ATTACH_MODE brackets with break closing headers
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" } else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char options[] = "style=java, break-closing-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, Linux)
{
// test LINUX_MODE brackets with break closing headers
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" } else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo)\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char options[] = "style=kr, break-closing-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, Stroustrup)
{
// test STROUSTRUP_MODE brackets with break closing headers
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" } else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo)\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char options[] = "style=stroustrup, break-closing-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, KeepBlocks)
{
// test break closing headers with keep one line blocks
// it shouldn't make any difference
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" } else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char options[] = "style=java, break-closing-brackets, keep-one-line-blocks";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, ElseSans)
{
// test if/else without break closing brackets
// else statement should be attached to the closing bracket
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" }\n"
" else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" if (isFoo) {\n"
" bar();\n"
" } else {\n"
" anotherBar();\n"
" }\n"
"}\n"
"\n";
char options[] = "style=java";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, Catch)
{
// test try/catch with break closing brackets
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" try {\n"
" bar();\n"
" } catch (int i) {\n"
" cout << i << endl;\n"
" }\n"
"}\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" try {\n"
" bar();\n"
" }\n"
" catch (int i) {\n"
" cout << i << endl;\n"
" }\n"
"}\n";
char options[] = "style=java, break-closing-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, CatchSans)
{
// test try/catch without break closing brackets
// catch statement should be attached to the closing bracket
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" try {\n"
" bar();\n"
" }\n"
" catch (int i) {\n"
" cout << i << endl;\n"
" }\n"
"}\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" try {\n"
" bar();\n"
" } catch (int i) {\n"
" cout << i << endl;\n"
" }\n"
"}\n";
char options[] = "style=java";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, While)
{
// test do/while with break closing brackets
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" do {\n"
" bar();\n"
" } while (int x < 9);\n"
"}\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" do {\n"
" bar();\n"
" }\n"
" while (int x < 9);\n"
"}\n";
char options[] = "style=java, break-closing-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakClosingBrackets, WhileSans)
{
// test do/while without break closing brackets
// while statement should be attached to the closing bracket
char textIn[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" do {\n"
" bar();\n"
" }\n"
" while (int x < 9);\n"
"}\n";
char text[] =
"\nvoid FooClass::Foo(bool isFoo) {\n"
" do {\n"
" bar();\n"
" } while (int x < 9);\n"
"}\n";
char options[] = "style=java";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Break Else If
//-------------------------------------------------------------------------
TEST(BreakElseIfs, LongOption)
{
// test break else/if
// else/if statements should be broken
char textIn[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" } else\n"
" if (isBar) {\n"
" anotherBar();\n"
" } else if (isBar) {\n"
" anotherBar();\n"
" } else {\n"
" if (isBar) {\n"
" anotherBar();\n"
" }\n"
" }\n"
"\n"
" if (isFoo) {\n"
" bar();\n"
" } else anotherBar();\n"
" if (isFoo)\n"
" bar();\n"
"\n"
"#if 0\n"
" foo();\n"
"#else\n"
" if (bar)\n"
" fooBar();\n"
"#endif\n"
"}\n";
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" } else\n"
" if (isBar) {\n"
" anotherBar();\n"
" } else\n"
" if (isBar) {\n"
" anotherBar();\n"
" } else {\n"
" if (isBar) {\n"
" anotherBar();\n"
" }\n"
" }\n"
"\n"
" if (isFoo) {\n"
" bar();\n"
" } else anotherBar();\n"
" if (isFoo)\n"
" bar();\n"
"\n"
"#if 0\n"
" foo();\n"
"#else\n"
" if (bar)\n"
" fooBar();\n"
"#endif\n"
"}\n";
char options[] = "break-elseifs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, ShortOption)
{
// test break else/if short options
// else/if statements should be broken
char textIn[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" } else\n"
" if (isBar) {\n"
" anotherBar();\n"
" } else if (isBar) {\n"
" anotherBar();\n"
" } else {\n"
" if (isBar) {\n"
" anotherBar();\n"
" }\n"
" }\n"
"\n"
" if (isFoo) {\n"
" bar();\n"
" } else anotherBar();\n"
" if (isFoo)\n"
" bar();\n"
"\n"
"#if 0\n"
" foo();\n"
"#else\n"
" if (bar)\n"
" fooBar();\n"
"#endif\n"
"}\n";
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" } else\n"
" if (isBar) {\n"
" anotherBar();\n"
" } else\n"
" if (isBar) {\n"
" anotherBar();\n"
" } else {\n"
" if (isBar) {\n"
" anotherBar();\n"
" }\n"
" }\n"
"\n"
" if (isFoo) {\n"
" bar();\n"
" } else anotherBar();\n"
" if (isFoo)\n"
" bar();\n"
"\n"
"#if 0\n"
" foo();\n"
"#else\n"
" if (bar)\n"
" fooBar();\n"
"#endif\n"
"}\n";
char options[] = "-e";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, Sans1)
{
// test without break else/if
// else/if statements should be joined
// but do NOT join #else
char textIn[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" } else\n"
" if (isBar) {\n"
" anotherBar();\n"
" } else if (isBar) {\n"
" anotherBar();\n"
" } else {\n"
" if (isBar) {\n"
" anotherBar();\n"
" }\n"
" }\n"
"\n"
" if (isFoo) {\n"
" bar();\n"
" } else anotherBar();\n"
" if (isFoo)\n"
" bar();\n"
"\n"
"#if fooDef1\n"
" foo();\n"
"#else\n"
" if (bar)\n"
" fooBar();\n"
"#endif\n"
"# if fooDef2\n"
" foo();\n"
"# else\n"
" fooBar();\n"
"# endif\n"
"}\n";
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" if (isFoo) {\n"
" bar();\n"
" } else if (isBar) {\n"
" anotherBar();\n"
" } else if (isBar) {\n"
" anotherBar();\n"
" } else {\n"
" if (isBar) {\n"
" anotherBar();\n"
" }\n"
" }\n"
"\n"
" if (isFoo) {\n"
" bar();\n"
" } else anotherBar();\n"
" if (isFoo)\n"
" bar();\n"
"\n"
"#if fooDef1\n"
" foo();\n"
"#else\n"
" if (bar)\n"
" fooBar();\n"
"#endif\n"
"# if fooDef2\n"
" foo();\n"
"# else\n"
" fooBar();\n"
"# endif\n"
"}\n";
char options[] = "";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, Sans2)
{
// test without break else/if
// but do NOT join to #else following an else
char text[] =
"\nvoid Foo()\n"
"{\n"
"#ifdef sun\n"
" if (isUDP(mSettings)) {\n"
" UDPSingleServer();\n"
" }\n"
" else\n"
"#else\n"
" if (isSingleUDP(mSettings)) {\n"
" UDPSingleServer();\n"
" }\n"
" else\n"
"#endif\n"
" {\n"
" thread_Settings *tempSettings = NULL;\n"
" }\n"
"}\n";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(BreakElseIfs, KeepOneLineBlocks)
{
// test break else/if with keep one line blocks
// else/if statements remain the same with breaking/attaching
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" { bar(); if (isBar1) anotherBar1(); else if (isBar2) anotherBar2(); }\n"
" { if (isBar1) anotherBar1(); else if (isBar2) anotherBar2(); }\n"
"}\n";
char options[] = "break-elseifs, keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, KeepOneLineStatements)
{
// test break else/if with keep one line statements
// else/if statements remain the same with breaking/attaching
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" bar(); if (isBar1) anotherBar1(); else if (isBar2) anotherBar2();\n"
" if (isBar1) anotherBar1(); else if (isBar2) anotherBar2();\n"
"}\n";
char options[] = "break-elseifs, keep-one-line-statements";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, Comments1)
{
// Test break else/if with comments preceding the 'else'.
// The should be indented the same as the following 'else'.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" // comment 2\n"
" else if (isFoo2)\n"
" bar2();\n"
" // comment 3\n"
" else if (isFoo3)\n"
" bar3();\n"
" // comment 4\n"
" else bar4();\n"
" // not else-if comment\n"
" endBar();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" // comment 2\n"
" else\n"
" if (isFoo2)\n"
" bar2();\n"
" // comment 3\n"
" else\n"
" if (isFoo3)\n"
" bar3();\n"
" // comment 4\n"
" else bar4();\n"
" // not else-if comment\n"
" endBar();\n"
"}";
char options[] = "break-elseifs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, Comments2)
{
// Test break else/if with comments preceding the 'else'.
// The should be indented the same as the following 'else'.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1(); /* comment 1A */\n"
" /* comment 2 */\n"
" else if (isFoo2) /* comment 2A */\n"
" { bar2(); }\n"
" /* comment 3 */\n"
" else if (isFoo3)\n"
" { bar3(); }\n"
" /* comment 4 */\n"
" else bar4();\n"
" /* not else-if comment */\n"
" endBar();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1(); /* comment 1A */\n"
" /* comment 2 */\n"
" else\n"
" if (isFoo2) /* comment 2A */\n"
" { bar2(); }\n"
" /* comment 3 */\n"
" else\n"
" if (isFoo3)\n"
" { bar3(); }\n"
" /* comment 4 */\n"
" else bar4();\n"
" /* not else-if comment */\n"
" endBar();\n"
"}";
char options[] = "break-elseifs, keep-one-line-blocks";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, Comments3)
{
// Test break else/if with comments IFs with no ELSE.
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" // comment 2\n"
" if (isFoo2)\n"
" // comment 3\n"
" if (isFoo3)\n"
" bar3();\n"
" // not IF comment\n"
" endBar();\n"
"}";
char options[] = "break-elseifs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, Comments4)
{
// Test break else/if with multiple-line comments preceding the 'else'.
// The should be indented the same as the following 'else'.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" else if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
" // comment 4A\n"
" // comment 4B\n"
" // comment 4C\n"
" else bar4();\n"
" // not else-if commentA\n"
" // not else-if commentB\n"
" // not else-if commentC\n"
" endBar();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" else\n"
" if (isFoo2)\n"
" bar2();\n"
" else\n"
" if (isFoo3)\n"
" bar3();\n"
" // comment 4A\n"
" // comment 4B\n"
" // comment 4C\n"
" else bar4();\n"
" // not else-if commentA\n"
" // not else-if commentB\n"
" // not else-if commentC\n"
" endBar();\n"
"}";
char options[] = "break-elseifs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, Comments5)
{
// Test break else/if with multiple-line comments preceding the 'else'.
// The should be indented the same as the following 'else'.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" else if (isFoo2)\n"
" bar2();\n"
" /** comment 3A\n"
" * comment 3B\n"
" * comment 3C */\n"
" else if (isFoo3)\n"
" bar3();\n"
" /** comment 4A\n"
" * comment 4B\n"
" * comment 4C\n"
" */\n"
" else bar4();\n"
" /* not else-if commentA\n"
" * not else-if commentB\n"
" * not else-if commentC\n"
" */\n"
" endBar();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" else\n"
" if (isFoo2)\n"
" bar2();\n"
" /** comment 3A\n"
" * comment 3B\n"
" * comment 3C */\n"
" else\n"
" if (isFoo3)\n"
" bar3();\n"
" /** comment 4A\n"
" * comment 4B\n"
" * comment 4C\n"
" */\n"
" else bar4();\n"
" /* not else-if commentA\n"
" * not else-if commentB\n"
" * not else-if commentC\n"
" */\n"
" endBar();\n"
"}";
char options[] = "break-elseifs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, CommentsInPreprocessor)
{
// Test break else/if with comment in a preprocessor directive.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" else if (isFoo4)\n"
" bar4();\n"
"#ifdef IS_GUI\n"
" // Beg of options used by GUI\n"
" else if (isFoo4A)\n"
" bar4A();\n"
"#else\n"
" // Options used by only console\n"
" else if (isFoo5)\n"
" bar5();\n"
"#endif\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" else\n"
" if (isFoo4)\n"
" bar4();\n"
"#ifdef IS_GUI\n"
" // Beg of options used by GUI\n"
" else\n"
" if (isFoo4A)\n"
" bar4A();\n"
"#else\n"
" // Options used by only console\n"
" else\n"
" if (isFoo5)\n"
" bar5();\n"
"#endif\n"
"}";
char options[] = "break-elseifs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, AddBrackets)
{
// Test break else/if with add-brackets.
// The resulting closing brackets should align
// with the 'if' instead of the 'else'.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" bar1();\n"
" else if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
" else bar4();\n"
" endBar();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1) {\n"
" bar1();\n"
" }\n"
" else\n"
" if (isFoo2) {\n"
" bar2();\n"
" }\n"
" else\n"
" if (isFoo3) {\n"
" bar3();\n"
" }\n"
" else {\n"
" bar4();\n"
" }\n"
" endBar();\n"
"}";
char options[] = "break-elseifs, add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, EndOfFileComments1)
{
// Test comments at the end of file.
// Was causing an exception in call to PeekNextText().
char text[] =
"\nvoid Foo()\n"
"{\n"
" endBar();\n"
"}"
"// end of line comment";
char options[] = "break-elseifs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, EndOfFileComments2)
{
// Test comments at the end of file.
// Was causing an exception in call to PeekNextText().
char text[] =
"\nvoid Foo()\n"
"{\n"
" endBar();\n"
"}"
"/* end of line comment */";
char options[] = "break-elseifs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, WithSwitch)
{
// test break else/if with a switch statement
// should not separate the colon from the header
char text[] =
"\nvoid foo()\n"
"{\n"
" switch (Current_Led_Toggle)\n"
" {\n"
" case LED_TOGGLE_NORMAL:\n"
" break;\n"
" default:\n"
" break;\n"
" }\n"
"}\n";
char options[] = "break-elseifs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(BreakElseIfs, WithMaxCodeLength)
{
// test break else/if with a max code length
// should not have an empty line between the IF and the statement
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (config.chkAnnSource) param << _T(\" -A\") << config.txtAnnSource;\n"
" if (config.chkMinCount) param << _T(\" -m\") << config.spnMinCount;\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (config.chkAnnSource)\n"
" param << _T(\" -A\") << config.txtAnnSource;\n"
" if (config.chkMinCount)\n"
" param << _T(\" -m\") << config.spnMinCount;\n"
"}\n";
char options[] = "break-elseifs, max-code-length=50";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Keep One Line Statements
//-------------------------------------------------------------------------
TEST(KeepOneLineStatements, LongOption)
{
// test keep one line statements
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo)\n"
" {\n"
" isFoo=false; isBar=true;\n"
" }\n"
"}\n";
char options[] = "keep-one-line-statements";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, ShortOption)
{
// // test keep one line statements short option
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo)\n"
" {\n"
" isFoo=false; isBar=true;\n"
" }\n"
"}\n";
char options[] = "-o";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, WithHeader)
{
// test keep one line statements with a header in one of the statements
char text[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n"
" CalculatePositions();\n"
"}";
char options[] = "keep-one-line-statements";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, SansWithHeader1)
{
// test without keep-one-line statements
// one-line statements with a header in one of the statements
// should break the statements
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n"
" CalculatePositions();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te);\n"
" if (!te.IsAllowed()) return;\n"
" CalculatePositions();\n"
"}";
char options[] = "";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, SansWithHeader2)
{
// test without keep-one-line statements but with break blocks
// one-line statements with a header in one of the statements
// should break the statements and the header block
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n"
" CalculatePositions();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te);\n"
"\n"
" if (!te.IsAllowed()) return;\n"
"\n"
" CalculatePositions();\n"
"}";
char options[] = "break-blocks=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, BreakBlocks1)
{
// test with break-blocks=all and a header as the SECOND statement
// should not change the lines
char text[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n"
" CalculatePositions();\n"
"}";
char options[] = "keep-one-line-statements, break-blocks=all";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, BreakBlocks2)
{
// Test with break-blocks=all and a header as the FIRST statement.
// Should keep the one-line statements and break the block.
// Adding keep-one-line-blocks would not break the block.
// See the following test.
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te);\n"
" CalculatePositions();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te);\n"
"\n"
" CalculatePositions();\n"
"}";
char options[] = "keep-one-line-statements, break-blocks";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, BreakBlocks3)
{
// Test with break-blocks and keep-one-line-statements.
// Should not break the Block.
// Without keep-one-line-statements it will break the block.
// See the previous test.
char text[] =
"\nvoid Foo()\n"
"{\n"
" if ( getter ) mv.Get = _T ( \"Get\" ) + method;\n"
" else mv.Get = wxEmptyString;\n"
"}";
char options[] = "keep-one-line-statements, break-blocks, keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, BreakBlocksMaxCodeLength1)
{
// test with break-blocks=all and max code length
// should break the IF statement and break the block
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n"
" CalculatePositions();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te);\n"
"\n"
" if (!te.IsAllowed()) return;\n"
"\n"
" CalculatePositions();\n"
"}";
char options[] = "keep-one-line-statements, break-blocks=all, max-code-length=60";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineStatements, BreakBlocksMaxCodeLength2)
{
// test with break-blocks=all and without max code length
// should NOT break the one line statement
char text[] =
"\nvoid Foo()\n"
"{\n"
" SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return;\n"
" CalculatePositions();\n"
"}";
char options[] = "keep-one-line-statements, break-blocks=all";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Keep One Line Blocks
//-------------------------------------------------------------------------
TEST(KeepOneLineBlocks, LongOption)
{
// test keep one line blocks
char text[] =
"\nvoid foo()\n"
"{\n"
" if (!j) { j=1; i=i-10; }\n"
"}\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, ShortOption)
{
// test keep one line blocks short option
char text[] =
"\nvoid foo()\n"
"{\n"
" if (!j) { j=1; i=i-10; }\n"
"}\n";
char options[] = "-O";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, StartOfLine)
{
// line beginning with one-line blocks do NOT get a extra indent
char text[] =
"\nclass Foo\n"
"{\n"
"public:\n"
" int getFoo() const\n"
" { return isFoo; }\n"
"};\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, NoneBrackets)
{
// test keep one line blocks
char text[] =
"\nvoid foo()\n"
"{\n"
" if (comment&&code) { ++codecomments_lines; }\n"
" else if (comment) { ++comment_lines; }\n"
" else if (code) { ++code_lines; }\n"
"}\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, BreakBrackets)
{
// test keep one line blocks
char text[] =
"\nvoid foo()\n"
"{\n"
" if (comment&&code) { ++codecomments_lines; }\n"
" else if (comment) { ++comment_lines; }\n"
" else if (code) { ++code_lines; }\n"
"}\n";
char options[] = "keep-one-line-blocks, style=allman";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, AttachBrackets)
{
// test keep one line blocks
char text[] =
"\nvoid foo() {\n"
" if (comment&&code) { ++codecomments_lines; }\n"
" else if (comment) { ++comment_lines; }\n"
" else if (code) { ++code_lines; }\n"
"}\n";
char options[] = "keep-one-line-blocks, style=java";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, LinuxBrackets)
{
// test keep one line blocks
char text[] =
"\nvoid foo()\n"
"{\n"
" if (comment&&code) { ++codecomments_lines; }\n"
" else if (comment) { ++comment_lines; }\n"
" else if (code) { ++code_lines; }\n"
"}\n";
char options[] = "keep-one-line-blocks, style=kr";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, RunInBrackets)
{
// test keep one line blocks
char text[] =
"\nvoid foo()\n"
"{ if (comment&&code) { ++codecomments_lines; }\n"
" else if (comment) { ++comment_lines; }\n"
" else if (code) { ++code_lines; }\n"
"}\n";
char options[] = "keep-one-line-blocks, style=horstmann";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, BreakElseIf)
{
// test keep one line blocks and break elseifs
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (!j) { j=1; if (i) i=i-10; }\n"
" if (!j) { j=1; if (i) i=i-10; else i=i-20; }\n"
" if (!j) { j=1; if (i) i=i-10; else if (j) j=j-10; }\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (!j) { j=1; if (i) i=i-10; }\n"
" if (!j) { j=1; if (i) i=i-10; else i=i-20; }\n"
" if (!j) { j=1; if (i) i=i-10; else if (j) j=j-10; }\n"
"}\n";
char options[] = "keep-one-line-blocks, break-elseifs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, KeepOneLineStatementsAndBreakElseIf)
{
// test keep one line blocks and keep one line statements
// with if statement and break elseifs
char text[] =
"\nvoid foo()\n"
"{\n"
" if (!j) { j=1; if (i) i=i-10; }\n"
" if (!j) { j=1; if (i) i=i-10; else i=i-20; }\n"
" if (!j) { j=1; if (i) i=i-10; else if (j) j=j-10; }\n"
"}\n";
char options[] = "keep-one-line-blocks, keep-one-line-statements, break-elseifs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, BreakBlocks1)
{
// test keep one line blocks and break blocks
// should NOT break the block
char text[] =
"\nvoid foo()\n"
"{\n"
" { SendEvent(0, m_editItem, &te); if (!te.IsAllowed()) return; }\n"
" CalculatePositions();\n"
"}";
char options[] = "keep-one-line-blocks, break-blocks=all";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, BreakBlocks2)
{
// test keep one line blocks and break blocks
// should NOT break the block
char text[] =
"\nvoid foo()\n"
"{\n"
" { if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te); }\n"
" CalculatePositions();\n"
"}";
char options[] = "keep-one-line-blocks, break-blocks=all";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, BreakBlocks3)
{
// test keep one line blocks and break blocks
// should NOT break the one-line block
// should break the other IF block
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo)\n"
" { if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te); }\n"
" CalculatePositions();\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo)\n"
" { if (!te.IsAllowed()) return; SendEvent(0, m_editItem, &te); }\n"
"\n"
" CalculatePositions();\n"
"}";
char options[] = "keep-one-line-blocks, break-blocks=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, MultipleBrackets)
{
// test keep one line blocks with multiple brackets
char text[] =
"\npublic class FooClass\n"
"{\n"
" public string FooName { get { return Foo; } set { Foo = value; } }\n"
"\n"
" public event EventHandler Cancelled { add { } remove { } }\n"
"}\n";
char options[] = "keep-one-line-blocks, mode=cs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, Sans1)
{
// test without keep one line blocks
// should not break {} when break brackets
char text[] =
"\nclass JipeConsole\n"
"{\n"
" public JipeConsole(Jipe parent)\n"
" {\n"
" jipeConsole.addKeyListener(new KeyListener()\n"
" {\n"
" public void keyReleased(KeyEvent e) {}\n"
" public void keyTyped(KeyEvent e) {}\n"
" });\n"
" }\n"
"}\n";
char options[] = "style=allman, mode=java";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, Sans2)
{
// test without keep one line blocks
// test attach bracket inside comment on single line block
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) // comment\n"
" { return false; }\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) { // comment\n"
" return false;\n"
" }\n"
"}\n";
char options[] = "style=kr";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, SansMultipleBrackets)
{
// test without keep one line blocks with multiple brackets
char textIn[] =
"\npublic class FooClass\n"
"{\n"
" public string FooName { get { return Foo; } set { Foo = value; } }\n"
"\n"
" public event EventHandler Cancelled { add { } remove { } }\n"
"}\n";
char text[] =
"\npublic class FooClass\n"
"{\n"
" public string FooName {\n"
" get {\n"
" return Foo;\n"
" }\n"
" set {\n"
" Foo = value;\n"
" }\n"
" }\n"
"\n"
" public event EventHandler Cancelled {\n"
" add { } remove { }\n"
" }\n"
"}\n";
char options[] = "mode=cs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, NoneRunIn)
{
// test none brackets with keep one line blocks and run-in
// should not indent the run-in
char text[] =
"\nvoid foo()\n"
"{ if (isFoo)\n"
" {/*ok*/;}\n"
" else {bar();}\n"
"}\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, RunInRunIn)
{
// test run-in brackets with keep one line blocks and run-in
// should not indent the run-in
char text[] =
"\nvoid foo()\n"
"{ if (isFoo)\n"
" {/*ok*/;}\n"
" else {bar();}\n"
"}\n";
char options[] = "keep-one-line-blocks, style=horstmann";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, NoneClosingHeader)
{
// test keep one line blocks followed by a closing header
// should not attach header to the one line statement
char text[] =
"\nvoid foo() {\n"
" if (isFoo)\n"
" {/*ok*/;}\n"
" else {bar();}\n"
"}\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, BreakClosingHeader)
{
// test keep one line blocks followed by a closing header
// should not attach header to the one line statement
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo)\n"
" {/*ok*/;}\n"
" else {bar();}\n"
"}\n";
char options[] = "keep-one-line-blocks, style=allman";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, AttachClosingHeader)
{
// test keep one line blocks followed by a closing header
// should not attach header to the one line statement
char text[] =
"\nvoid foo() {\n"
" if (isFoo)\n"
" {/*ok*/;}\n"
" else {bar();}\n"
"}\n";
char options[] = "keep-one-line-blocks, style=java";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, LinuxClosingHeader)
{
// test keep one line blocks followed by a closing header
// should not attach header to the one line statement
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo)\n"
" {/*ok*/;}\n"
" else {bar();}\n"
"}\n";
char options[] = "keep-one-line-blocks, style=kr";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, IndentSwitchBlock)
{
// test one-line blocks with switch blocks
char text[] =
"\nvoid Foo(int fooBar)\n"
"{\n"
" switch (fooBar)\n"
" {\n"
" case 1:\n"
" fooBar = 1;\n"
" break;\n"
" case 2:\n"
" { fooBar = 2; }\n"
" break;\n"
" default:\n"
" { break; }\n"
" }\n"
" int bar = true;\n"
"}\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, IndentSwitchBlock_IndentSwitches)
{
// test one-line blocks with indented switch blocks
char text[] =
"\nvoid Foo(int fooBar)\n"
"{\n"
" switch (fooBar)\n"
" {\n"
" case 1:\n"
" fooBar = 1;\n"
" break;\n"
" case 2:\n"
" { fooBar = 2; }\n"
" break;\n"
" default:\n"
" { break; }\n"
" }\n"
" int bar = true;\n"
"}\n";
char options[] = "keep-one-line-blocks, indent-switches";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, IndentAfterHeader)
{
// test one line blocks indentation following a header
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" if (isFoo)\n"
" { bar(); }\n"
" else\n"
" { anotherBar(); }\n"
"}\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, IndentAfterHeaderSansBrackets)
{
// Test one line blocks indentation following a header
// when the header does not contain brackets.
char text[] =
"\nvoid Foo(bool isFoo)\n"
"{\n"
" if (isBar1)\n"
" if (isBar2)\n"
" { return true; }\n"
"\n"
" if (isBar1)\n"
" if (isBar2) { return true; }\n"
"}\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, IndentSansHeader)
{
// test one line blocks indentation without a header
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" bar()\n"
" { anotherBar(); }\n"
"}\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, IndentWithConstMethod)
{
// Test one line blocks indentation following a header
// when the header does not contain brackets.
char text[] =
"\nclass FooClass\n"
"{\n"
" virtual bool foo() const\n"
" { return false; }\n"
"};\n";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, WithAccessModifier)
{
// A one line block with an access modifier should not break after the modifier.
char text[] =
"\ntemplate<typename T>\n"
"struct RunHelper<T> { public: int Run(TestCases<T>&) { return 0; } };";
char options[] = "keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(KeepOneLineBlocks, WithAccessModifierSans)
{
// A one line block with an access modifier should break if keep is NOT used.
char textIn[] =
"\ntemplate<typename T>\n"
"struct RunHelper<T> { public: int Run(TestCases<T>&) { return 0; } };";
char text[] =
"\ntemplate<typename T>\n"
"struct RunHelper<T> {\n"
"public:\n"
" int Run(TestCases<T>&) {\n"
" return 0;\n"
" }\n"
"};";
char options[] = "";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Add Brackets
//-------------------------------------------------------------------------
TEST(AddBrackets, LongOption)
{
// test add brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, ShortOption)
{
// test add brackets short option
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
"}\n";
char options[] = "-j";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, All)
{
// test add brackets for all headers
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
"\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"\n"
" for (int i = 0; i <= 12; ++i)\n"
" bar &= ::FooBar();\n"
"\n"
" while (isFoo)\n"
" bar();\n"
"\n"
" do\n"
" bar();\n"
" while (isFoo);\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
"\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
" else {\n"
" return true;\n"
" }\n"
"\n"
" for (int i = 0; i <= 12; ++i) {\n"
" bar &= ::FooBar();\n"
" }\n"
"\n"
" while (isFoo) {\n"
" bar();\n"
" }\n"
"\n"
" do {\n"
" bar();\n"
" }\n"
" while (isFoo);\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, ElseIf)
{
// test add brackets for "else if" statements
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
" else if (isFoo())\n"
" return false;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
" else if (isFoo()) {\n"
" return false;\n"
" }\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, SemiFollows)
{
// test add brackets when a semi-colon follows the statement
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (a == 0) ; func1(); i++;\n"
" while (isFoo) // comment\n"
" ;\n"
" while (isFoo); // comment\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (a == 0) ;\n"
" func1();\n"
" i++;\n"
" while (isFoo) // comment\n"
" ;\n"
" while (isFoo); // comment\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, Sharp)
{
// test add brackets to C# headers
// 'delegate' statement contains brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" foreach (int i in fibarray)\n"
" System.Console.WriteLine(i);\n"
"\n"
" if (isFoo)\n"
" bar(delegate { fooBar* = null; });\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" foreach (int i in fibarray) {\n"
" System.Console.WriteLine(i);\n"
" }\n"
"\n"
" if (isFoo)\n"
" bar(delegate {\n"
" fooBar* = null;\n"
" });\n"
"}\n";
char options[] = "add-brackets, mode=cs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, KeepOneLiners)
{
// add brackets with keep one liners
// should break the added brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
"\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"\n"
" for (int i = 0; i <= 12; ++i)\n"
" bar &= ::FooBar();\n"
"\n"
" while (isFoo)\n"
" bar();\n"
"\n"
" do\n"
" bar();\n"
" while (isFoo);\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
"\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
" else {\n"
" return true;\n"
" }\n"
"\n"
" for (int i = 0; i <= 12; ++i) {\n"
" bar &= ::FooBar();\n"
" }\n"
"\n"
" while (isFoo) {\n"
" bar();\n"
" }\n"
"\n"
" do {\n"
" bar();\n"
" }\n"
" while (isFoo);\n"
"}\n";
char options[] = "add-brackets, keep-one-line-blocks, keep-one-line-statements";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, SingleLine)
{
// add brackets to one line statements
// should break the statements
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) return false;\n"
"\n"
" if (isFoo()) return false; else return true;\n"
"\n"
" for (int i = 0; i <= 12; ++i) bar &= ::FooBar();\n"
"\n"
" while (isFoo) bar();\n"
"\n"
" do bar(); while (isFoo);\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
"\n"
" if (isFoo()) {\n"
" return false;\n"
" }\n"
" else {\n"
" return true;\n"
" }\n"
"\n"
" for (int i = 0; i <= 12; ++i) {\n"
" bar &= ::FooBar();\n"
" }\n"
"\n"
" while (isFoo) {\n"
" bar();\n"
" }\n"
"\n"
" do {\n"
" bar();\n"
" }\n"
" while (isFoo);\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, SingleLineKeepOneLiners)
{
// add brackets to one line statements with keep one liners
// should keep one line blocks with added brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) return false;\n"
"\n"
" if (isFoo()) return false; else return true;\n"
"\n"
" for (int i = 0; i <= 12; ++i) bar &= ::FooBar();\n"
"\n"
" while (isFoo) bar();\n"
"\n"
" do bar(); while (isFoo);\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) { return false; }\n"
"\n"
" if (isFoo()) { return false; } else { return true; }\n"
"\n"
" for (int i = 0; i <= 12; ++i) { bar &= ::FooBar(); }\n"
"\n"
" while (isFoo) { bar(); }\n"
"\n"
" do { bar(); } while (isFoo);\n"
"}\n";
char options[] = "add-brackets, keep-one-line-blocks, keep-one-line-statements";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, Break)
{
// test add brackets for broken brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" {\n"
" return false;\n"
" }\n"
" else\n"
" {\n"
" return true;\n"
" }\n"
"}\n";
char options[] = "add-brackets, style=allman";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, Attach)
{
// test add brackets for attached brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) {\n"
" return false;\n"
" } else {\n"
" return true;\n"
" }\n"
"}\n";
char options[] = "add-brackets, style=kr";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, RunIn)
{
// test add brackets for run-in brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{ if (isFoo())\n"
" { return false;\n"
" }\n"
" else\n"
" { return true;\n"
" }\n"
"}\n";
char options[] = "add-brackets, style=horstmann";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, ExtraSpaces)
{
// extra spaces should be removed
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if ( str ) (*str) += \"<?xml \";\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if ( str ) {\n"
" (*str) += \"<?xml \";\n"
" }\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, ElseParen)
{
// else statement with following paren
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) break;\n"
" else (numBar)--;\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) {\n"
" break;\n"
" }\n"
" else {\n"
" (numBar)--;\n"
" }\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, Quote)
{
// must bypass quote with semi-colons and escaped quote marks
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) bar = '\\'';\n"
" if (isFoo) bar = '\\\\';\n"
" if (isBar) bar = \";;version=\";\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) {\n"
" bar = '\\'';\n"
" }\n"
" if (isFoo) {\n"
" bar = '\\\\';\n"
" }\n"
" if (isBar) {\n"
" bar = \";;version=\";\n"
" }\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, QuoteSans)
{
// must bypass multi-line quote
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo)\n"
" char* bar = \"one \\\n"
" two \\\n"
" three\";\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, Comment)
{
// must bypass comment before a semi-colon
// the last statement should be bracketed
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) bar = // comment\n"
" foo2;\n"
" if (isFoo) bar = /* comment */\n"
" foo2;\n"
" if (isFoo) bar = /* comment\n"
" comment */\n"
" foo2;\n"
" if (isFoo) bar = /* comment */ foo2;\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) bar = // comment\n"
" foo2;\n"
" if (isFoo) bar = /* comment */\n"
" foo2;\n"
" if (isFoo) bar = /* comment\n"
" comment */\n"
" foo2;\n"
" if (isFoo) {\n"
" bar = /* comment */ foo2;\n"
" }\n"
"}\n";
char options[] = "add-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddBrackets, Sans)
{
// brackets should be added to specified headers only
char text[] =
"\npublic unsafe int foo()\n"
"{\n"
" int readCount;\n"
" fixed(byte* pBuffer = buffer)\n"
" readCount = ReadMemory(size);\n"
"}\n";
char options[] = "add-brackets, mode=cs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Add One Line Brackets
// Implies keep-one-line-blocks
//-------------------------------------------------------------------------
TEST(AddOneLineBrackets, LongOption)
{
// test add one line brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" { return false; }\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, ShortOption)
{
// test add one line brackets short option
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" { return false; }\n"
"}\n";
char options[] = "-J";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, All)
{
// test add one line brackets for all headers
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
"\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"\n"
" for (int i = 0; i <= 12; ++i)\n"
" bar &= ::FooBar();\n"
"\n"
" while (isFoo)\n"
" bar();\n"
"\n"
" do\n"
" bar();\n"
" while (isFoo);\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" { return false; }\n"
"\n"
" if (isFoo())\n"
" { return false; }\n"
" else\n"
" { return true; }\n"
"\n"
" for (int i = 0; i <= 12; ++i)\n"
" { bar &= ::FooBar(); }\n"
"\n"
" while (isFoo)\n"
" { bar(); }\n"
"\n"
" do\n"
" { bar(); }\n"
" while (isFoo);\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, ElseIf)
{
// test add one line brackets for "else if" statements
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
" else if (isFoo())\n"
" return false;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" { return false; }\n"
" else if (isFoo())\n"
" { return false; }\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, SemiFollows)
{
// test add brackets when a semi-colon follows the statement
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (a == 0) ; func1(); i++;\n"
" while (isFoo) // comment\n"
" ;\n"
" while (isFoo); // comment\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (a == 0) ;\n"
" func1();\n"
" i++;\n"
" while (isFoo) // comment\n"
" ;\n"
" while (isFoo); // comment\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, Sharp)
{
// test add one line brackets to C# headers
// 'delegate' statement contains brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" foreach (int i in fibarray)\n"
" System.Console.WriteLine(i);\n"
"\n"
" if (isFoo)\n"
" bar(delegate { fooBar* = null; });\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" foreach (int i in fibarray)\n"
" { System.Console.WriteLine(i); }\n"
"\n"
" if (isFoo)\n"
" bar(delegate { fooBar* = null; });\n"
"}\n";
char options[] = "add-one-line-brackets, mode=cs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, SingleLine)
{
// add one line brackets to one line statements
// should keep the one line statements
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) return false;\n"
"\n"
" if (isFoo()) return false; else return true;\n"
"\n"
" for (int i = 0; i <= 12; ++i) bar &= ::FooBar();\n"
"\n"
" while (isFoo) bar();\n"
"\n"
" do bar(); while (isFoo);\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) { return false; }\n"
"\n"
" if (isFoo()) { return false; }\n"
" else { return true; }\n"
"\n"
" for (int i = 0; i <= 12; ++i) { bar &= ::FooBar(); }\n"
"\n"
" while (isFoo) { bar(); }\n"
"\n"
" do { bar(); }\n"
" while (isFoo);\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, SingleLineKeepOneLiners)
{
// add one line brackets to one line statements with keep one liners
// should keep the one liners (keep blocks is implied)
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) return false;\n"
"\n"
" if (isFoo()) return false; else return true;\n"
"\n"
" for (int i = 0; i <= 12; ++i) bar &= ::FooBar();\n"
"\n"
" while (isFoo) bar();\n"
"\n"
" do bar(); while (isFoo);\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo()) { return false; }\n"
"\n"
" if (isFoo()) { return false; } else { return true; }\n"
"\n"
" for (int i = 0; i <= 12; ++i) { bar &= ::FooBar(); }\n"
"\n"
" while (isFoo) { bar(); }\n"
"\n"
" do { bar(); } while (isFoo);\n"
"}\n";
char options[] = "add-one-line-brackets, keep-one-line-statements";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, Break)
{
// test add one line brackets for broken brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" { return false; }\n"
" else\n"
" { return true; }\n"
"}\n";
char options[] = "add-one-line-brackets, style=allman";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, Attach)
{
// test add one line brackets for attached brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" { return false; }\n"
" else\n"
" { return true; }\n"
"}\n";
char options[] = "add-one-line-brackets, style=kr";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, RunIn)
{
// test add one line brackets for run-in brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo())\n"
" return false;\n"
" else\n"
" return true;\n"
"}\n";
char text[] =
"\nvoid Foo()\n"
"{ if (isFoo())\n"
" { return false; }\n"
" else\n"
" { return true; }\n"
"}\n";
char options[] = "add-one-line-brackets, style=horstmann";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, ExtraSpaces)
{
// extra spaces should not be removed
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if ( str ) (*str) += \"<?xml \";\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if ( str ) { (*str) += \"<?xml \"; }\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, ElseParen)
{
// else statement with following paren
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) break;\n"
" else (numBar)--;\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) { break; }\n"
" else { (numBar)--; }\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, Quote)
{
// must bypass quote with semi-colons and escaped quote marks
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) bar = '\\'';\n"
" if (isFoo) bar = '\\\\';\n"
" if (isBar) bar = \";;version=\";\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) { bar = '\\''; }\n"
" if (isFoo) { bar = '\\\\'; }\n"
" if (isBar) { bar = \";;version=\"; }\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, QuoteSans)
{
// must bypass multi-line quote
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo)\n"
" char* bar = \"one \\\n"
" two \\\n"
" three\";\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, Comment)
{
// must bypass comment before a semi-colon
// the last statement should be bracketed
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) bar = // comment\n"
" foo2;\n"
" if (isFoo) bar = /* comment */\n"
" foo2;\n"
" if (isFoo) bar = /* comment\n"
" comment */\n"
" foo2;\n"
" if (isFoo) bar = /* comment */ foo2;\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (isFoo) bar = // comment\n"
" foo2;\n"
" if (isFoo) bar = /* comment */\n"
" foo2;\n"
" if (isFoo) bar = /* comment\n"
" comment */\n"
" foo2;\n"
" if (isFoo) { bar = /* comment */ foo2; }\n"
"}\n";
char options[] = "add-one-line-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(AddOneLineBrackets, Sans)
{
// brackets should be added to specified headers only
char text[] =
"\npublic unsafe int foo()\n"
"{\n"
" int readCount;\n"
" fixed(byte* pBuffer = buffer)\n"
" readCount = ReadMemory(size);\n"
"}\n";
char options[] = "add-one-line-brackets, mode=cs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Remove Brackets
//-------------------------------------------------------------------------
TEST(RemoveBrackets, LongOption)
{
// test remove brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, ShortOption)
{
// test remove brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
"}";
char options[] = "-xj";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, WithEmptyLine1)
{
// test with a preceding empty line
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
"\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" \n"
" bar3();\n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
"\n"
" bar2();\n"
" else if (isFoo3)\n"
"\n"
" bar3();\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, WithEmptyLine2)
{
// test with a following empty line
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
"\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" \n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" bar2();\n"
"\n"
" else if (isFoo3)\n"
" bar3();\n"
"\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, WithEmptyLine3)
{
// test attached brackets with a empty lines
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (IsUsingTree()) {\n"
"\n"
" m_pTree->Delete();\n"
"\n"
" }\n"
" else {\n"
"\n"
" m_pCommands->Clear();\n"
" m_pCategories->Clear();\n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (IsUsingTree())\n"
"\n"
" m_pTree->Delete();\n"
"\n"
" else {\n"
"\n"
" m_pCommands->Clear();\n"
" m_pCategories->Clear();\n"
" }\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(RemoveBrackets, Sans)
{
// don't remove if not a single statement
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" bar2a();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" bar3a();\n"
" }\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, OneLineBlock1)
{
// test with a one line block and keep-one-line-blocks
// should NOT break the one-line block
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" { bar2(); }\n"
" else if (isFoo3) { bar3(); }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3) bar3();\n"
"}";
char options[] = "remove-brackets, keep-one-line-blocks";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, OneLineBlockSans1)
{
// test with a one line block and NOT keep-one-line-blocks
// should break the one-line block
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" { bar2(); }\n"
" else if (isFoo3) { bar3(); }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, OneLineBlockSans2)
{
// test with a one line block to NOT remove brackets
// with keep-one-line-blocks
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" { bar2(); bar4(); }\n"
" else if (isFoo3) { bar3(); bar4(); }\n"
"}";
char options[] = "remove-brackets, keep-one-line-blocks";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, OneLineBlockSans3)
{
// test with a one line block to NOT remove brackets
// without keep-one-line-blocks
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" { bar2(); bar4(); }\n"
" else if (isFoo3) { bar3(); bar4(); }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" bar4();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" bar4();\n"
" }\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, BreakBlocks1)
{
// test remove brackets with break blocks
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" bar5();\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" }\n"
" bar6();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" bar5();\n"
"\n"
" if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
"\n"
" bar6();\n"
"}";
char options[] = "remove-brackets, break-blocks";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, BreakBlocks2)
{
// test remove brackets with break all blocks
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" bar5();\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" }\n"
" bar6();\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" bar5();\n"
"\n"
" if (isFoo2)\n"
" bar2();\n"
"\n"
" else if (isFoo3)\n"
" bar3();\n"
"\n"
" bar6();\n"
"}";
char options[] = "remove-brackets, break-blocks=all";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, Comment1)
{
// remove one-line brackets with a comment
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if (keycode == WXK_RETURN)\n"
" { myidx = 0; } // Edit\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" if (keycode == WXK_RETURN)\n"
" myidx = 0; // Edit\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(RemoveBrackets, Comment2)
{
// remove one-line brackets with a comment
char textIn[] =
"\nvoid foo()\n"
"{\n"
" if ( (target = Convert()) )\n"
" {;}//ok\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" if ( (target = Convert()) )\n"
" ; //ok\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(RemoveBrackets, Comment3)
{
// remove brackets with a comment following closing bracket
char textIn[] =
"\nvoid foo()\n"
"{\n"
" for(size_t i = 0; i < Count; ++i)\n"
" {\n"
" AppendToLog(Output[i]);\n"
" } // end for : idx: i\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" for(size_t i = 0; i < Count; ++i)\n"
" AppendToLog(Output[i]);\n"
" // end for : idx: i\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(RemoveBrackets, Comment4)
{
// remove attached bracket with a comment
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo) { // comment\n"
" bar();\n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo) // comment\n"
" bar();\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete[] textOut;
}
TEST(RemoveBrackets, CommentSans1)
{
// don't remove if a preceding comment
char text[] =
"\nvoid Foo()\n"
"{\n"
" // comment"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" /* comment\n"
" comment */\n"
" bar3();\n"
" }\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, CommentSans2)
{
// don't remove if a preceding column 1 comment
char text[] =
"\nvoid Foo() {\n"
" if(result)\n"
" {\n"
"// Manager::Get()->GetLogManager();\n"
" }\n"
" else\n"
" {\n"
"// Manager::Get()->GetLogManager();\n"
" }\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, FollowingHeaderSans)
{
// don't remove if a following header
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" {\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" }\n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo1)\n"
" {\n"
" if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
" }\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, AddBracketsSans)
{
// should NOT remove brackets if add brackets is also requested
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" }\n"
"}";
char options[] = "remove-brackets, add-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, AddOneLineBracketsSans)
{
// should NOT remove brackets if add one line brackets is also requested
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" }\n"
" else if (isFoo3) {\n"
" bar3();\n"
" }\n"
"}";
char options[] = "remove-brackets, add-one-line-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, OtherHeaders)
{
// test remove brackets with other headers
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" for (i = 0; i < 10; i++)\n"
" {\n"
" bar2();\n"
" }\n"
" while (i > 0 && i < 10)\n"
" {\n"
" bar3();\n"
" }\n"
" do {\n" // NOT removed from do-while
" bar4();\n"
" } while (int x < 9);\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" for (i = 0; i < 10; i++)\n"
" bar2();\n"
" while (i > 0 && i < 10)\n"
" bar3();\n"
" do {\n" // NOT removed from do-while
" bar4();\n"
" } while (int x < 9);\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, SharpOtherHeaders)
{
// test remove brackets with other C# headers
char textIn[] =
"\nprivate void Foo()\n"
"{\n"
" foreach (T x in list)\n"
" {\n"
" foo = bar;\n"
" }\n"
"}";
char text[] =
"\nprivate void Foo()\n"
"{\n"
" foreach (T x in list)\n"
" foo = bar;\n"
"}";
char options[] = "remove-brackets, mode=cs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, OTBSSans)
{
// should NOT remove brackets if "One True Brace Style" is requested
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2) {\n"
" bar2();\n"
" } else if (isFoo3) {\n"
" bar3();\n"
" }\n"
"}";
char options[] = "remove-brackets, style=otbs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, BreakClosingBrackets)
{
// test remove brackets with break closing brackets
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" } else if (isFoo3) {\n"
" bar3();\n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
"}";
char options[] = "remove-brackets, break-closing-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, UnbrokenElse)
{
// test remove brackets with a unbroken "else if" statement
char textIn[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" {\n"
" bar2();\n"
" } else if (isFoo3) {\n"
" bar3();\n"
" }\n"
"}";
char text[] =
"\nvoid Foo()\n"
"{\n"
" if (isFoo2)\n"
" bar2();\n"
" else if (isFoo3)\n"
" bar3();\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, Preprocessor)
{
// test remove brackets with a preprocessor directive
// the brackets should NOT be removed
char text[] =
"\nvoid Foo() {\n"
"#define if(_RET_SUCCEED(exp)) { result = (exp); }\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, BracketInQuote)
{
// test remove brackets within a quote
// should not remove the bracket in the quotes
char textIn[] =
"\nprivate void Foo() {\n"
" if (closingBrackets > 0) {\n"
" wrapper.Append(new string('}', closingBrackets));\n"
" }\n"
"}";
char text[] =
"\nprivate void Foo() {\n"
" if (closingBrackets > 0)\n"
" wrapper.Append(new string('}', closingBrackets));\n"
"}";
char options[] = "remove-brackets, mode=cs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, BracketInComment1)
{
// test remove with brackets within a line comment
// should not remove the brackets
char text[] =
"\nprivate void Foo() {\n"
" if (closingBrackets > 0) {\n"
" wrapper.Append(closingBrackets); // }\n"
" }\n"
"}";
char options[] = "remove-brackets, mode=cs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, BracketInComment2)
{
// test remove with brackets within a comment
// should not remove the brackets
char text[] =
"\nprivate void Foo() {\n"
" if (closingBrackets > 0) {\n"
" wrapper.Append(closingBrackets); /* } */\n"
" }\n"
"}";
char options[] = "remove-brackets, mode=cs";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveBrackets, HorstmannBracketWithComment)
{
// test remove horstmann bracket with a comment
// should not remove the brackets
char text[] =
"\nvoid Foo()\n"
"{ if (isFoo)\n"
" { // comment\n"
" bar();\n"
" }\n"
"}";
char options[] = "remove-brackets";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Convert Tabs
//-------------------------------------------------------------------------
TEST(ConvertTabs, LongOption)
{
// test convert tabs
char textIn[] =
"\nstatic FooBar foo1[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"};\n"
"\n"
"static FooBar foo2[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"};\n"
"\n"
"static FooBar foo3[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"};\n"
"\n"
"static FooBar foo4[] =\n"
"{\n"
" { 100, 0, 9 },\n"
" { 200, 0, 9 },\n"
" { 300, 0, 9 },\n"
" { 400, 0, 9 },\n"
"};\n";
char text[] =
"\nstatic FooBar foo1[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"};\n"
"\n"
"static FooBar foo2[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"};\n"
"\n"
"static FooBar foo3[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"};\n"
"\n"
"static FooBar foo4[] =\n"
"{\n"
" { 100, 0, 9 },\n"
" { 200, 0, 9 },\n"
" { 300, 0, 9 },\n"
" { 400, 0, 9 },\n"
"};\n";
char options[] = "convert-tabs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, ShortOption)
{
// test convert tabs short option
char textIn[] =
"\nstatic FooBar foo[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"};\n"
"\n"
"static FooBar fooTab[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"}\n";
char text[] =
"\nstatic FooBar foo[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"};\n"
"\n"
"static FooBar fooTab[] =\n"
"{\n"
" { 10000, 0, 9 },\n"
" { 20000, 0, 9 },\n"
" { 30000, 0, 9 },\n"
" { 40000, 0, 9 },\n"
"}\n";
char options[] = "-c";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, CommentsPreprocessorQuotes)
{
// convert comments, line comments, preprocessor
// do NOT convert quotes
char textIn[] =
"\nvoid foo()\n"
"{\n"
" /*\n"
" * comment comment\n"
" * comment comment\n"
" * comment comment\n"
" * comment comment\n"
" */\n"
"\n"
"/*\n"
" commentedCode();\n"
"*/\n"
"\n"
" // line comment\n"
" // line comment\n"
" // line comment\n"
" // line comment\n"
"\n"
"#ifdef foo\n"
" #error is foo\n"
" #endif // end of if\n"
"\n"
" char* quote =\n"
" \"this is a quote \\\n"
" quote continuation \\\n"
" quote continuation\";\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" /*\n"
" * comment comment\n"
" * comment comment\n"
" * comment comment\n"
" * comment comment\n"
" */\n"
"\n"
" /*\n"
" commentedCode();\n"
" */\n"
"\n"
" // line comment\n"
" // line comment\n"
" // line comment\n"
" // line comment\n"
"\n"
"#ifdef foo\n"
"#error is foo\n"
"#endif // end of if\n"
"\n"
" char* quote =\n"
" \"this is a quote \\\n"
" quote continuation \\\n"
" quote continuation\";\n"
"}\n";
char options[] = "convert-tabs, indent=tab";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, Comments1)
{
// test convert-tabs with comments
char textIn[] =
"\nvoid foo()\n"
"{\n"
" /* comment1\n"
" comment2\n"
" */\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" /* comment1\n"
" comment2\n"
" */\n"
"}\n";
char options[] = "convert-tabs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, Comments2)
{
// test convert-tabs with comment continuation
char textIn[] =
"\nvoid foo()\n"
"{\n"
" int bar1; /* comment1 */\n"
" int bar2; /* comment2\n"
" comment3 */\n"
" int bar3; /* comment3 */\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" int bar1; /* comment1 */\n"
" int bar2; /* comment2\n"
" comment3 */\n"
" int bar3; /* comment3 */\n"
"}\n";
char options[] = "convert-tabs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, Comments3)
{
// test convert-tabs with line comments and tabbed output
// should NOT convert the leading tabs in a non-indent comment
char textIn[] =
"\nvoid foo()\n"
"{\n"
"// comment1 comment1a\n"
" // comment2 comment2a\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
"// comment1 comment1a\n"
"// comment2 comment2a\n"
"}\n";
char options[] = "convert-tabs, --indent=tab";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, Misc1)
{
// test convert-tabs with unpad-paren and pad-paren-in
// should replace the tab after the opening paren
char textIn[] =
"\nvoid foo( bool isFoo )\n"
"{\n"
" if( isFoo )\n"
" bar;\n"
"}\n";
char text[] =
"\nvoid foo( bool isFoo )\n"
"{\n"
" if( isFoo )\n"
" bar;\n"
"}\n";
char options[] = "convert-tabs, unpad-paren, pad-paren-in";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, Misc2)
{
// verify that tabs are still present within quotes
// should NOT have been replaced when AStyle was run
char text[] =
"\nvoid foo()\n"
"{\n"
" char* quote = \"this is a quote \";\n"
"}\n";
// just check for the tab characters
EXPECT_EQ('\t', text[37]);
EXPECT_EQ('\t', text[40]);
EXPECT_EQ('\t', text[42]);
}
TEST(ConvertTabs, ForceTabX1)
{
// test convert-tabs in indent=force-tab-x
char textIn[] =
"\nvoid foo()\n"
"{\n"
" int bar1; // comment1\n"
" int bar111; /* comment2 */\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" int bar1; // comment1\n"
" int bar111; /* comment2 */\n"
"}\n";
char options[] = "indent=force-tab-x, convert-tabs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, ForceTabX2)
{
// test convert-tabs in indent=force-tab-x with comment continuation
char textIn[] =
"\nvoid foo()\n"
"{\n"
" int bar1; /* comment1 */\n"
" int bar2; /* comment2\n"
" comment3 */\n"
" int bar3; /* comment3 */\n"
"}\n";
char text[] =
"\nvoid foo()\n"
"{\n"
" int bar1; /* comment1 */\n"
" int bar2; /* comment2\n"
" comment3 */\n"
" int bar3; /* comment3 */\n"
"}\n";
char options[] = "indent=force-tab-x, convert-tabs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(ConvertTabs, PreprocessorIndent)
{
// Test convert-tabs in a preprocessor indent.
// NOTE: The defines do NOT have a #endif closing the define.
// This will cause a memory leak if the activeBeautifierStack and
// waitingBeautifierStack are not deleted properly in ASBeautifier.
char textIn[] =
"\n#if (! defined (yyoverflow) \\\n"
" && (! defined (__cplusplus) \\\n"
"\t || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)))\n";
char text[] =
"\n#if (! defined (yyoverflow) \\\n"
" && (! defined (__cplusplus) \\\n"
" || (defined (YYSTYPE_IS_TRIVIAL) && YYSTYPE_IS_TRIVIAL)))\n";
char options[] = "indent-preproc-define, convert-tabs";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Close Templates Tabs
//-------------------------------------------------------------------------
TEST(CloseTemplates, LongOption)
{
// Test close-templates long option.
char textIn[] =
"\nvoid foo()\n"
"{\n"
" vector<string<int> > vec\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" vector<string<int>> vec\n"
"}";
char options[] = "close-templates";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(CloseTemplates, ShortOption)
{
// Test close-templates short option.
char textIn[] =
"\nvoid foo()\n"
"{\n"
" vector<string<int> > vec;\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" vector<string<int>> vec;\n"
"}";
char options[] = "-xy";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(CloseTemplates, Sans)
{
// Templates should NOT be closed without the option.
char text[] =
"\nvoid foo()\n"
"{\n"
" vector<string<int> > vec;\n"
"}";
char options[] = "";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(CloseTemplates, Padded)
{
// Test close-templates with padding inside the templates.
char textIn[] =
"\nvoid foo()\n"
"{\n"
" vector< string< int > > vec;\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" vector<string<int>> vec;\n"
"}";
char options[] = "close-templates";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//-------------------------------------------------------------------------
// AStyle Remove Comment Prefix
//-------------------------------------------------------------------------
TEST(RemoveCommentPrefix, LongOption)
{
// Test remove-comment-prefix long option.
char textIn[] =
"\n/* comment\n"
" *\n"
" */";
char text[] =
"\n/* comment\n"
"\n"
"*/";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, ShortOption)
{
// Test remove-comment-prefix short option.
char textIn[] =
"\n/* comment\n"
" *\n"
" */";
char text[] =
"\n/* comment\n"
"\n"
"*/";
char options[] = "-xp";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, SansMultiLine)
{
// Test remove-comment-prefix with single-line comments.
// They should not be changed.
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" /* comment3 */\n"
" /*xcomment4x*/\n"
"}";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(text, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, Format1)
{
// Test remove-comment-prefix indentation.
char textIn[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" /* comment1\n"
" *\n"
" */\n"
" if(isFoo) {\n"
" /* comment2\n"
" *\n"
" */\n"
" fooBar();\n"
" }\n"
"}";
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" /* comment1\n"
"\n"
" */\n"
" if(isFoo) {\n"
" /* comment2\n"
"\n"
" */\n"
" fooBar();\n"
" }\n"
"}";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, Format2)
{
// Test remove-comment-prefix option.
// Beginning and ending '*' should be removed.
// Text should be indented one indent.
// The all '*' lines should not change
char textIn[] =
"\n"
"/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"
" * This software is distributed WITHOUT ANY WARRANTY, even the implied *\n"
" * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *\n"
" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */";
char text[] =
"\n"
"/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"
" This software is distributed WITHOUT ANY WARRANTY, even the implied\n"
" warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, Format3)
{
// Test remove-comment-prefix option without '*'.
// Text should be indented one indent.
char textIn[] =
"\nvoid foo()\n"
"{\n"
" /* This file is a part of Artistic Style - an indentation and\n"
" reformatting tool for C, C++, C# and Java source files.\n"
" */\n"
"}";
char text[] =
"\nvoid foo()\n"
"{\n"
" /* This file is a part of Artistic Style - an indentation and\n"
" reformatting tool for C, C++, C# and Java source files.\n"
" */\n"
"}";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, Format4)
{
// Test remove-comment-prefix option.
// Beginning '*' should be removed.
// Text should NOT be indented - it is greater than one indent.
char textIn[] =
"\n"
"/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"
" * Copyright (C) 2006-2011 by Jim Pattee <jimp03@email.com>\n"
" * Copyright (C) 1998-2002 by Tal Davidson\n"
" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"
" */";
char text[] =
"\n"
"/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"
" Copyright (C) 2006-2011 by Jim Pattee <jimp03@email.com>\n"
" Copyright (C) 1998-2002 by Tal Davidson\n"
" * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *\n"
"*/";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, Format5)
{
// Test remove-comment-prefix option.
// Beginning '*' should be removed.
// Text with tabs should NOT be indented - it is greater than one indent.
// The '*' is ERASED and not replaced with a space.
char textIn[] =
"\n"
"/*\n"
" *\ttabbed comment\n"
" */";
char text[] =
"\n"
"/*\n"
" \ttabbed comment\n"
"*/";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, Format6)
{
// Test remove-comment-prefix option.
// Beginning '*' should be removed.
// The tabbed text should be properly indented.
// The '/*!' should not be separated.
char textIn[] =
"\n"
"/*! \\brief Update manifest.xml with the latest version string.\n"
" * \\author Gary Harris\n"
" * \\date 03/03/10\n"
" * \\return void\n"
" */";
char text[] =
"\n"
"/*! \\brief Update manifest.xml with the latest version string.\n"
" \\author Gary Harris\n"
" \\date 03/03/10\n"
" \\return void\n"
"*/";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, Format7)
{
// Test remove-comment-prefix option.
// Beginning '*' should be removed.
// The text should be properly indented.
// The '/**' should not be separated.
char textIn[] =
"\n"
"/** @brief A file editor\n"
" *\n"
" * @param use If true tooltips are allowed\n"
" */";
char text[] =
"\n"
"/** @brief A file editor\n"
"\n"
" @param use If true tooltips are allowed\n"
"*/";
char options[] = "remove-comment-prefix, indent=spaces=6";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
TEST(RemoveCommentPrefix, CommentedCode1)
{
// Test remove-comment-prefix option with commented text.
// The tabbed alignment should be maintained.
char textIn[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" /*if (client == NULL) {\n"
" //int found = -1;\n"
" for (int i=0; i < getCount(); i++)\n"
" if ((Item(i)) == event.GetEventObject())\n"
" client = m_arrAttachedWnd.Item(i);\n"
" }*/\n"
"}";
char text[] =
"\nvoid foo(bool isFoo)\n"
"{\n"
" /* if (client == NULL) {\n"
" //int found = -1;\n"
" for (int i=0; i < getCount(); i++)\n"
" if ((Item(i)) == event.GetEventObject())\n"
" client = m_arrAttachedWnd.Item(i);\n"
" }*/\n"
"}";
char options[] = "remove-comment-prefix";
char* textOut = AStyleMain(textIn, options, errorHandler, memoryAlloc);
EXPECT_STREQ(text, textOut);
delete [] textOut;
}
//----------------------------------------------------------------------------
} // namespace
| 27.170892
| 117
| 0.480276
|
a-w
|
01cce684c5c58f1a380917ec02e2f24139c17f69
| 1,274
|
cpp
|
C++
|
src/segment.cpp
|
drjod/construct
|
0199baf8b56735869b28ae526f78dcca117b2060
|
[
"BSD-3-Clause"
] | null | null | null |
src/segment.cpp
|
drjod/construct
|
0199baf8b56735869b28ae526f78dcca117b2060
|
[
"BSD-3-Clause"
] | null | null | null |
src/segment.cpp
|
drjod/construct
|
0199baf8b56735869b28ae526f78dcca117b2060
|
[
"BSD-3-Clause"
] | 2
|
2020-03-23T13:08:11.000Z
|
2020-04-15T11:27:31.000Z
|
#include "segment.h"
#include "configuration.h"
#include "utilities.h"
#include <math.h>
namespace contra
{
Resistances Segment::set_resistances(Configuration* configuration)
{
return configuration->set_resistances(casing.get_D(), casing.get_lambda_g());
}
void Segment::set_functions(Piping* piping)
{
Configuration* configuration = piping->get_configuration();
greeks = configuration->set_greeks(piping);
const double dgz = greeks.get_gamma() * casing.get_L() / casing.get_N();
double gz = dgz;
for(int i=0; i<casing.get_N(); ++i)
{
configuration->set_functions(f1[i], f2[i], f3[i], gz, greeks);
//LOG("z: " << gz/greeks.get_gamma());
//LOG(" f1: " << f1[i]);
//LOG(" f2: " << f2[i]);
//LOG(" f3: " << f3[i]);
gz += dgz;
}
}
void Segment::calculate_temperatures(Configuration* configuration)
{
const int N = casing.get_N();
for(int i=1; i<N; ++i) // last node from sceleton
{
const double dz = casing.get_L() / N;
T_in[i] = T_in[0] * f1[i-1] + T_out[0] * f2[i-1];
T_out[i] = -T_in[0] * f2[i-1] + T_out[0] * f3[i-1];
for(int j=0; j<i; ++j)
{
T_in[i] += configuration->F4(i*dz, j*dz, (j+1)*dz, greeks)*(T_s[j]+T_s[j+1])/2;
T_out[i] -= configuration->F5(i*dz, j*dz, (j+1)*dz, greeks)*(T_s[j]+T_s[j+1])/2;
}
}
}
}
| 22.75
| 83
| 0.616954
|
drjod
|
01cfe3d0f5b6974abb9d2c5adde1650821f94fe1
| 642
|
hpp
|
C++
|
src/include/guinsoodb/parser/statement/vacuum_statement.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | 1
|
2021-04-22T05:41:54.000Z
|
2021-04-22T05:41:54.000Z
|
src/include/guinsoodb/parser/statement/vacuum_statement.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | null | null | null |
src/include/guinsoodb/parser/statement/vacuum_statement.hpp
|
GuinsooLab/guinsoodb
|
f200538868738ae460f62fb89211deec946cefff
|
[
"MIT"
] | 1
|
2021-12-12T10:24:57.000Z
|
2021-12-12T10:24:57.000Z
|
//===----------------------------------------------------------------------===//
// GuinsooDB
//
// guinsoodb/parser/statement/vacuum_statement.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "guinsoodb/parser/parsed_expression.hpp"
#include "guinsoodb/parser/sql_statement.hpp"
#include "guinsoodb/parser/parsed_data/vacuum_info.hpp"
namespace guinsoodb {
class VacuumStatement : public SQLStatement {
public:
VacuumStatement();
unique_ptr<VacuumInfo> info;
public:
unique_ptr<SQLStatement> Copy() const override;
};
} // namespace guinsoodb
| 22.928571
| 80
| 0.549844
|
GuinsooLab
|
01d3ad3ae93b6588103d7dd8e00ec56f2386f769
| 159
|
hh
|
C++
|
Statement/MySQLStatement.hh
|
decouple/dbal
|
ea94dcb215d9693ab81d3be5394ff7448e254380
|
[
"MIT"
] | null | null | null |
Statement/MySQLStatement.hh
|
decouple/dbal
|
ea94dcb215d9693ab81d3be5394ff7448e254380
|
[
"MIT"
] | null | null | null |
Statement/MySQLStatement.hh
|
decouple/dbal
|
ea94dcb215d9693ab81d3be5394ff7448e254380
|
[
"MIT"
] | null | null | null |
<?hh // strict
use Decouple\Common\Contract\DB\Statement;
interface MySQLStatement extends Statement {
public function fetchColumn(int $column=0) : mixed;
}
| 26.5
| 53
| 0.773585
|
decouple
|
01d409fe2a659c8b80e8da3affb79979ccebb12c
| 5,638
|
cpp
|
C++
|
src/bridge.cpp
|
dudpray0220/C-ProxyServer
|
40038726b988b21055b17af90b9142fcad2a213c
|
[
"Apache-2.0"
] | 1
|
2021-11-29T08:11:43.000Z
|
2021-11-29T08:11:43.000Z
|
src/bridge.cpp
|
dudpray0220/C-ProxyServer
|
40038726b988b21055b17af90b9142fcad2a213c
|
[
"Apache-2.0"
] | null | null | null |
src/bridge.cpp
|
dudpray0220/C-ProxyServer
|
40038726b988b21055b17af90b9142fcad2a213c
|
[
"Apache-2.0"
] | 1
|
2021-12-01T04:45:55.000Z
|
2021-12-01T04:45:55.000Z
|
#include "../inc/bridge.hpp"
// public
namespace yhbae {
bridge::bridge(boost::asio::io_service &ios) // 생성자
: downstream_socket_(ios), upstream_socket_(ios) // 멤버변수 down, upstream_socket에 파라미터를 연결해줌.
{};
bridge::socket_type &yhbae::bridge::downstream_socket() // &를 붙이면 주소가 된다. 멤버함수(Method), socket_type은 return값의 타입이다.
{
// Client socket
return downstream_socket_;
};
bridge::socket_type &yhbae::bridge::upstream_socket() {
// Remote server socket
return upstream_socket_;
};
// start 함수
void bridge::start(const std::string &upstream_host, unsigned short upstream_port) { // void는 return이 없음. string&는 upstream_host의 메모리 주소를 참조하는 것.
// Attempt connection to remote server (upstream side)
upstream_socket_.async_connect( // async_connect는 소켓을 지정된 원격 엔드포인트로 비동기 연결하는데 사용 (비동기 연결을 시작한다.)
ip::tcp::endpoint(
boost::asio::ip::address::from_string(upstream_host), // async_connect의 첫번째 파라미터
upstream_port),
// async_connect의 두번째 파라미터
// bind는 주어진 엔드포인터로 소켓을 바인드한다.
boost::bind(&bridge::handle_upstream_connect, // boost::bind() 에게 첫번째로 들어갈 인자는 바인딩할 함수의 주소. handle_upstream_connect의 메모리 주소를 참조.
// handle_upstream_connect함수를 start에 바인딩?
shared_from_this(), // 그 다음의 인자들 바인딩될시 매핑될 매개 변수 리스트들
boost::asio::placeholders::error));
};
// handle_upstream_connect 함수
void bridge::handle_upstream_connect(const boost::system::error_code &error) {
if (!error) {
// Setup async read from remote server (upstream)
upstream_socket_.async_read_some( // 비동기 읽기를 시작한다. 스트림 소켓에서 데이터를 비동기로 읽는데 사용된다.
boost::asio::buffer(upstream_data_, max_data_length),
boost::bind(&bridge::handle_upstream_read, // 서버로부터 데이터를 읽어옴
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
// Setup async read from client (downstream)
downstream_socket_.async_read_some( // 비동기 읽기를 시작한다. 스트림 소켓에서 데이터를 비동기로 읽는데 사용된다.
boost::asio::buffer(downstream_data_, max_data_length),
boost::bind(&bridge::handle_downstream_read, // 클라이언트로부터 데이터를 읽어옴
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
} else
close(); // error시 종료
};
// private
/*
Section A: Remote Server --> Proxy --> Client (다운스트림)
Process data recieved from remote sever then send to client. (서버로부터 데이터를 받아서 클라이언트에 보낸다)
*/
// Read from remote server complete, now send data to client (서버로부터 데이터를 읽기 complete, 클라이언트로 데이터를 보낸다)
void bridge::handle_upstream_read(const boost::system::error_code &error, const size_t &bytes_transferred) {
if (!error) {
async_write(downstream_socket_, // async_write는 스트림에 제공된 모든 데이터를 쓰는 비동기 작업을 시작한다.
boost::asio::buffer(upstream_data_, bytes_transferred),
boost::bind(&bridge::handle_downstream_write,
shared_from_this(),
boost::asio::placeholders::error));
} else
close();
};
// Write to client complete, Async read from remote server (클라이언트에 데이터를 쓰기 complete, 서버데이터를 비동기로 읽는다)
void bridge::handle_downstream_write(const boost::system::error_code &error) {
if (!error) {
upstream_socket_.async_read_some(
boost::asio::buffer(upstream_data_, max_data_length),
boost::bind(&bridge::handle_upstream_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
} else
close();
};
// *** End Of Section A *** (다운스트림 완료)
/*
Section B: Client --> Proxy --> Remove Server (업스트림)
Process data recieved from client then write to remove server. (클라이언트로부터 데이터를 받아 서버에 쓴다)
*/
// Read from client complete, now send data to remote server (클라이언트로부터 데이터를 읽기 complete, 서버로 데이터를 보낸다)
void bridge::handle_downstream_read(const boost::system::error_code &error, const size_t &bytes_transferred) {
if (!error) {
async_write(upstream_socket_,
boost::asio::buffer(downstream_data_, bytes_transferred),
boost::bind(&bridge::handle_upstream_write,
shared_from_this(),
boost::asio::placeholders::error));
} else
close();
};
// Write to remote server complete, Async read from client (서버에 데이터를 쓰기 complete, 클라이언트데이터를 비동기로 읽는다)
void bridge::handle_upstream_write(const boost::system::error_code &error) {
if (!error) {
downstream_socket_.async_read_some(
boost::asio::buffer(downstream_data_, max_data_length),
boost::bind(&bridge::handle_downstream_read,
shared_from_this(),
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred));
} else
close();
};
// *** End Of Section B *** (업스트림 완료)
void bridge::close() { // 종료함수
boost::mutex::scoped_lock lock(mutex_);
if (downstream_socket_.is_open()) // 소켓이 만약 열려있으면 닫는다. downstream_socket_은 즉, client socket
{
downstream_socket_.close();
}
if (upstream_socket_.is_open()) { // upstream_socket_은 즉, Remote server socket
upstream_socket_.close();
}
}
} // namespace yhbae
| 41.455882
| 146
| 0.622206
|
dudpray0220
|
01d72abac4cfe9609df0fbda7140cbaf0a1f800f
| 2,528
|
cpp
|
C++
|
async-io-linux-filesystem/AsyncFileReader.cpp
|
daank94/async-io-linux-filesystem
|
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
|
[
"MIT"
] | 1
|
2019-12-26T21:07:22.000Z
|
2019-12-26T21:07:22.000Z
|
async-io-linux-filesystem/AsyncFileReader.cpp
|
daank94/async-io-linux-filesystem
|
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
|
[
"MIT"
] | null | null | null |
async-io-linux-filesystem/AsyncFileReader.cpp
|
daank94/async-io-linux-filesystem
|
6c5a3d2a20913bbb203c5cf2618203c7ae26a569
|
[
"MIT"
] | 1
|
2020-01-02T01:27:42.000Z
|
2020-01-02T01:27:42.000Z
|
#include "AsyncFileReader.h"
#include <sys/epoll.h>
#include <unistd.h>
#include <stdio.h>
AsyncFileReader::AsyncFileReader()
: epoll_fd_(epoll_create1(0)),
stopped_(false)
{
static_assert(EVENT_BUFFER_SIZE > 0, "EVENT_BUFFER_SIZE must be greater than 0");
static_assert(READ_BUFFER_SIZE > 0, "READ_BUFFER_SIZE must be greater than 0");
}
AsyncFileReader::~AsyncFileReader()
{
close(epoll_fd_);
}
void AsyncFileReader::addFileDescriptor(const int fd)
{
struct epoll_event epoll_event;
epoll_event.events = EPOLLIN;
epoll_event.data.fd = fd;
epoll_ctl(epoll_fd_, EPOLL_CTL_ADD, fd, &epoll_event);
}
void AsyncFileReader::removeFileDescriptor(const int fd)
{
struct epoll_event epoll_event; // For the sake of compatibility with older versions of Linux, this struct must exist (pointer to struct cannot be nullptr).
epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &epoll_event);
}
void AsyncFileReader::runAsyncLoop()
{
struct epoll_event epoll_event_buffer[EVENT_BUFFER_SIZE];
while(!stopped_)
{
// Call epoll_wait with a timeout of 1000 milliseconds.
const int fds_ready = epoll_wait(epoll_fd_, epoll_event_buffer, EVENT_BUFFER_SIZE, 1000);
// Function epoll_wait returned.
if(-1 == fds_ready)
{
// An error occured.
stopped_ = true;
continue;
}
// Handle any file descriptors with events.
for(int i = 0; i < fds_ready; i++)
{
const struct epoll_event& epoll_event = epoll_event_buffer[i];
/* To use multiple CPUs, you could execute the handlers on (multiple) worker threads. For the sake of simplicity, polling and handling is done on the same thread now. */
handleEventOnFile(epoll_event);
}
}
}
void AsyncFileReader::stopAsyncLoop()
{
stopped_ = true;
}
bool AsyncFileReader::hasStopped()
{
return stopped_;
}
void AsyncFileReader::handleEventOnFile(const struct epoll_event& epoll_event)
{
const uint32_t events = epoll_event.events;
const int fd = epoll_event.data.fd;
if(EPOLLERR & events)
{
// An error occured on the file descriptor. Try to close it.
removeFileDescriptor(fd);
close(fd);
}
else if(EPOLLIN & events)
{
// Read is available, read in from the file descriptor and print the message.
int read_result = read(fd, read_buffer_, READ_BUFFER_SIZE-1);
if(-1 == read_result)
{
// An error occured while reading.
removeFileDescriptor(fd);
close(fd);
return;
}
// Successfully read in some bytes.
read_buffer_[read_result] = '\0';
printf("Read %d bytes\n", read_result);
printf("%s", read_buffer_);
}
}
| 24.07619
| 172
| 0.730222
|
daank94
|
01dd7017a5734ed0acb9fa4079335c1f4ed723f2
| 1,504
|
cpp
|
C++
|
main_web.cpp
|
kooBH/Qt_File_IO
|
2a95289f295018ece13665e0bc3112efbe889d8a
|
[
"Unlicense"
] | null | null | null |
main_web.cpp
|
kooBH/Qt_File_IO
|
2a95289f295018ece13665e0bc3112efbe889d8a
|
[
"Unlicense"
] | 6
|
2019-03-14T11:57:03.000Z
|
2019-06-07T10:42:18.000Z
|
main_web.cpp
|
kooBH/Qt_File_IO
|
2a95289f295018ece13665e0bc3112efbe889d8a
|
[
"Unlicense"
] | null | null | null |
#include <QtWebEngineCore>
#include <QApplication>
#include <QWebEngineView>
#include <QVBoxLayout>
#include <QPushButton>
#include <QWidget>
QUrl commandLineUrlArgument()
{
const QStringList args = QCoreApplication::arguments();
for (const QString &arg : args.mid(1)) {
if (!arg.startsWith(QLatin1Char('-')))
return QUrl::fromUserInput(arg);
}
return QUrl(QStringLiteral("http://iip.sogang.ac.kr"));
}
int main(int argc, char *argv[])
{
QCoreApplication::addLibraryPath("../lib");
QCoreApplication::setOrganizationName("QtExamples");
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
QApplication app(argc, argv);
QWidget widget_main;
QVBoxLayout layout_main;
QPushButton btn_scroll("scroll to bottom");
QWebEngineView view_main;
widget_main.setLayout(&layout_main);
layout_main.addWidget(&btn_scroll);
layout_main.addWidget(&view_main);
view_main.setUrl(commandLineUrlArgument());
view_main.resize(1024, 750);
widget_main.show();
QObject::connect(&btn_scroll, &QPushButton::clicked,
[&](){
/*
view_main.page()->runJavaScript("\
var scrollingElement = (document.scrollingElement || document.body);\
scrollingElement.scrollTop = scrollingElement.scrollHeight;\
");
*/
view_main.page()->runJavaScript(" window.scrollTo(0,document.body.scrollHeight);");
// view_main.page()->runJavaScript( "window.scrollTo(500, 500);");
}
);
app.exec();
return 0;
}
| 24.258065
| 89
| 0.692154
|
kooBH
|
01e23ec8197e816ffb8957afcc85f7b9973b60ef
| 3,163
|
hpp
|
C++
|
diffsim_torch3d/arcsim/src/physics.hpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
diffsim_torch3d/arcsim/src/physics.hpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
diffsim_torch3d/arcsim/src/physics.hpp
|
priyasundaresan/kaolin
|
ddae34ba5f09bffc4368c29bc50491c5ece797d4
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
/*
Copyright ©2013 The Regents of the University of California
(Regents). All Rights Reserved. Permission to use, copy, modify, and
distribute this software and its documentation for educational,
research, and not-for-profit purposes, without fee and without a
signed licensing agreement, is hereby granted, provided that the
above copyright notice, this paragraph and the following two
paragraphs appear in all copies, modifications, and
distributions. Contact The Office of Technology Licensing, UC
Berkeley, 2150 Shattuck Avenue, Suite 510, Berkeley, CA 94720-1620,
(510) 643-7201, for commercial licensing opportunities.
IN NO EVENT SHALL REGENTS BE LIABLE TO ANY PARTY FOR DIRECT,
INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
DOCUMENTATION, EVEN IF REGENTS HAS BEEN ADVISED OF THE POSSIBILITY
OF SUCH DAMAGE.
REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING
DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS
IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*/
#ifndef PHYSICS_HPP
#define PHYSICS_HPP
#include "cloth.hpp"
#include "obstacle.hpp"
#include "geometry.hpp"
#include "simulation.hpp"
#include "taucs.hpp"
#include <vector>
using torch::Tensor;
template <Space s>
Tensor internal_energy (const Cloth &cloth);
Tensor constraint_energy (const std::vector<Constraint*> &cons);
Tensor external_energy (const Cloth &cloth, const Tensor &gravity,
const Wind &wind);
// A += dt^2 dF/dx; b += dt F + dt^2 dF/dx v
// also adds damping terms
// if dt == 0, just does A += dF/dx; b += F instead, no damping
template <Space s>
void add_internal_forces (const Cloth &cloth, SpMat &A,
Tensor &b, Tensor dt);
void add_constraint_forces (const Cloth &cloth,
const std::vector<Constraint*> &cons,
SpMat &A, Tensor &b, Tensor dt);
void add_external_forces (const Cloth &cloth, const Tensor &gravity,
const Wind &wind, Tensor &fext,
Tensor &Jext);
void obs_add_external_forces (const Obstacle &obstacle, const Tensor &gravity,
const Wind &wind, Tensor &fext,
Tensor &Jext);
void add_morph_forces (const Cloth &cloth, const Morph &morph, Tensor t,
Tensor dt,
Tensor &fext, Tensor &Jext);
void implicit_update (Cloth &cloth, const Tensor &fext,
const Tensor &Jext,
const std::vector<Constraint*> &cons, Tensor dt,
bool update_positions=true);
void obs_implicit_update (Obstacle &obstacle, const vector<Mesh*> &obs_meshes, const Tensor &fext,
const Tensor &Jext,
const vector<Constraint*> &cons, Tensor dt,
bool update_positions);
#endif
| 39.5375
| 98
| 0.669617
|
priyasundaresan
|
01e2fc1419df585b6bbda0d311ec4e0ead3faa7e
| 2,287
|
cpp
|
C++
|
benchmarks/benchmark_ref_counted_ptr.cpp
|
abu-lib/mem
|
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
|
[
"Apache-2.0"
] | null | null | null |
benchmarks/benchmark_ref_counted_ptr.cpp
|
abu-lib/mem
|
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
|
[
"Apache-2.0"
] | 1
|
2021-09-26T14:15:33.000Z
|
2021-09-26T15:40:32.000Z
|
benchmarks/benchmark_ref_counted_ptr.cpp
|
abu-lib/mem
|
9a8a92b53ff079ecae0f8211213f5ed5571d1ed8
|
[
"Apache-2.0"
] | null | null | null |
#include <benchmark/benchmark.h>
#include <cstdlib>
#include <ctime>
#include <memory>
#include "abu/mem.h"
namespace {
static void BM_shared_ptr_int_lifetime(benchmark::State& state) {
std::srand(std::time(nullptr));
int v = std::rand();
for (auto _ : state) {
(void)_;
auto tmp = std::make_shared<int>(v);
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_shared_ptr_int_lifetime);
static void BM_shared_ptr_int_access(benchmark::State& state) {
std::srand(std::time(nullptr));
int v = std::rand();
for (auto _ : state) {
(void)_;
auto tmp = std::make_shared<int>(v);
int u = *tmp;
benchmark::DoNotOptimize(u);
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_shared_ptr_int_access);
static void BM_ref_counted_int_lifetime(benchmark::State& state) {
std::srand(std::time(nullptr));
int v = std::rand();
for (auto _ : state) {
(void)_;
auto tmp = abu::mem::make_ref_counted<int>(v);
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_ref_counted_int_lifetime);
static void BM_ref_counted_int_access(benchmark::State& state) {
std::srand(std::time(nullptr));
int v = std::rand();
for (auto _ : state) {
(void)_;
auto tmp = abu::mem::make_ref_counted<int>(v);
int u = *tmp;
benchmark::DoNotOptimize(u);
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_ref_counted_int_access);
static void BM_shared_ptr_obj_lifetime(benchmark::State& state) {
struct ObjType {};
for (auto _ : state) {
auto tmp = std::make_shared<ObjType>();
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_shared_ptr_obj_lifetime);
static void BM_ref_counted_obj_lifetime(benchmark::State& state) {
struct ObjType {};
for (auto _ : state) {
auto tmp = abu::mem::make_ref_counted<ObjType>();
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_ref_counted_obj_lifetime);
static void BM_ref_counted_intrusive_obj_lifetime(benchmark::State& state) {
struct ObjType : public abu::mem::ref_counted {};
for (auto _ : state) {
auto tmp = abu::mem::make_ref_counted<ObjType>();
benchmark::DoNotOptimize(tmp);
}
}
BENCHMARK(BM_ref_counted_intrusive_obj_lifetime);
} // namespace
BENCHMARK_MAIN();
| 25.131868
| 77
| 0.663314
|
abu-lib
|
01e399aae29a026843f9751f0769d04e8ba7dc2f
| 52,394
|
cpp
|
C++
|
source/equation.cpp
|
LiquidFenrir/CalculaThreeDS
|
1f87cdafa639e8289ebf886c6dd0e341c4da6279
|
[
"MIT"
] | 10
|
2020-11-08T13:40:44.000Z
|
2021-05-19T09:40:53.000Z
|
source/equation.cpp
|
LiquidFenrir/CalculaThreeDS
|
1f87cdafa639e8289ebf886c6dd0e341c4da6279
|
[
"MIT"
] | 2
|
2021-01-18T13:56:08.000Z
|
2021-03-11T13:45:05.000Z
|
source/equation.cpp
|
LiquidFenrir/CalculaThreeDS
|
1f87cdafa639e8289ebf886c6dd0e341c4da6279
|
[
"MIT"
] | null | null | null |
#include "equation.h"
#include "sprites.h"
#include "text.h"
#include "colors.h"
#include <algorithm>
#include <cmath>
static const Number E_VAL(std::exp(1.0));
static const Number PI_VAL(M_PI);
static const Number I_VAL(0.0, 1.0);
Equation::Equation() : parts(3)
{
parts[0].meta.assoc = 2;
parts[0].meta.special = Part::Specialty::Equation;
parts[0].meta.position = Part::Position::Start;
parts[0].meta.next = 1;
parts[2].meta.assoc = 0;
parts[2].meta.special = Part::Specialty::Equation;
parts[2].meta.position = Part::Position::End;
parts[2].meta.before = 1;
parts[1].meta.before = 0;
parts[1].meta.next = 2;
}
struct RenderInfo {
int current_x;
const int min_x, max_x, center_y;
const int height;
const int editing_part;
const int editing_char;
bool can_draw(const int vertical_offset) const
{
const bool x_correct = (min_x - (13 -1)) <= current_x && current_x < max_x;
const bool y_correct = -(height/2 + 24/2) < (vertical_offset - center_y) && (vertical_offset - center_y) <= (height/2 + 24);
return x_correct && y_correct;
}
int get_x() const
{
return current_x - min_x;
}
int get_y(const int vertical_offset) const
{
return center_y - vertical_offset + height/2 - 24/2;
}
};
struct RenderPart {
int data{};
// in deviation from the previous, counted in half parts
int middle_change{};
// in number of half parts, from the middle
int y_start{}; // positive, up
int y_end{}; // negative, down
// only used for special parts
int associated{};
int content_width{};
int content_middle_high{};
int paren_y_start{};
int paren_y_end{};
};
static void find_part_sizes(const std::vector<Part>& parts, std::vector<RenderPart>& part_sizes)
{
static std::vector<int> id_stack;
const auto pop_id = []() -> int {
const int i = id_stack.back();
id_stack.pop_back();
return i;
};
enum CareAbout : int {
CA_Width = 1,
CA_HeightBelow = 2,
CA_HeightAbove = 4,
CA_All = 1 | 2 | 4,
};
const auto add_content_info = [&](const RenderPart& ps, const CareAbout care = CA_All) -> void {
if(!id_stack.empty())
{
auto& container_size = part_sizes[id_stack.back()];
if(care & CA_Width)
{
container_size.content_width += ps.content_width;
}
if(care & (CA_HeightAbove | CA_HeightBelow))
{
if(care & CA_HeightAbove)
{
container_size.y_start = std::max(container_size.y_start, ps.y_start + ps.middle_change);
container_size.paren_y_start = std::max(container_size.paren_y_start, container_size.y_start);
container_size.paren_y_start = std::max(container_size.paren_y_start, ps.paren_y_start);
}
if(care & CA_HeightBelow)
{
container_size.y_end = std::min(container_size.y_end, ps.y_end + ps.middle_change);
container_size.paren_y_end = std::min(container_size.paren_y_end, container_size.y_end);
container_size.paren_y_end = std::min(container_size.paren_y_end, ps.paren_y_end);
}
container_size.content_middle_high = std::max(container_size.content_middle_high, ps.middle_change + ps.content_middle_high);
}
}
};
const auto do_part_basic = [&](const int idx) -> void {
const auto& p = parts[idx];
auto& ps = part_sizes[idx];
ps.data = [&]() -> int {;
if(p.meta.special == Part::Specialty::TempParen)
{
return 1;
}
else if(p.value.empty())
{
const auto& prev_meta = parts[p.meta.before].meta;
const auto& next_meta = parts[p.meta.next].meta;
const bool sandwiched = (check_pos_is(prev_meta.position, Part::Position::Start) && check_pos_is(next_meta.position, Part::Position::End)) && prev_meta.special == next_meta.special;
if(
(sandwiched && (
prev_meta.special == Part::Specialty::Equation ||
prev_meta.special == Part::Specialty::Paren ||
prev_meta.special == Part::Specialty::Absolute
))
||
(!sandwiched && (prev_meta.special == Part::Specialty::TempParen
|| next_meta.special != Part::Specialty::Exponent
|| (next_meta.special == Part::Specialty::Exponent && next_meta.position != Part::Position::Start)
|| (next_meta.special == Part::Specialty::Exponent && prev_meta.special == Part::Specialty::Paren && prev_meta.position == Part::Position::End)
))
)
{
return 0;
}
return 1;
}
else
{
return p.value.size();
}
}();
ps.content_width = ps.data;
ps.y_start = 1;
ps.y_end = -1;
ps.paren_y_start = 1;
ps.paren_y_end = -1;
add_content_info(ps);
};
int current_idx = 0;
while(current_idx != -1)
{
const auto& part = parts[current_idx];
if(part.meta.special == Part::Specialty::None || part.meta.special == Part::Specialty::TempParen)
{
do_part_basic(current_idx);
}
else if(part.meta.special != Part::Specialty::Equation)
{
if(check_pos_is(part.meta.position, Part::Position::End))
{
const int associated_id = pop_id();
const auto& ap = parts[associated_id];
auto& aps = part_sizes[associated_id];
auto& ps = part_sizes[current_idx];
if(part.meta.special == Part::Specialty::Exponent)
{
const int delta = (aps.y_start - aps.content_middle_high) - aps.y_end;
aps.middle_change = delta;
ps.middle_change = -delta;
aps.associated = current_idx;
ps.associated = associated_id;
add_content_info(aps, CA_All);
}
else if(part.meta.special == Part::Specialty::Fraction)
{
if(check_pos_is(ap.meta.position, Part::Position::End)) // ending bottom part
{
ps.middle_change = aps.y_start + 1;
aps.middle_change += -ps.middle_change; // middle
aps.associated = current_idx; // middle.associated points to end
ps.associated = associated_id; // end.associated points to middle
RenderPart cp = aps;
cp.content_width = std::max(aps.content_width, aps.data);
cp.middle_change = -ps.middle_change;
add_content_info(cp, CareAbout(CA_HeightBelow | CA_Width));
}
else // ending top part
{
aps.middle_change = 2 + (-aps.y_end - 1); // start
ps.middle_change = -aps.middle_change;
aps.associated = current_idx; // start.associated points to middle
ps.data = aps.content_width; // middle.data is start.content_width
add_content_info(aps, CA_HeightAbove);
}
}
else if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::Absolute)
{
aps.associated = current_idx;
ps.associated = associated_id;
ps.paren_y_start = aps.paren_y_start;
ps.paren_y_end = aps.paren_y_end;
aps.content_width += 2;
add_content_info(aps, CA_All);
}
else if(part.meta.special == Part::Specialty::Root)
{
aps.associated = current_idx;
ps.associated = associated_id;
ps.paren_y_start = aps.paren_y_start + 1;
ps.paren_y_end = aps.paren_y_end;
aps.content_width += 2;
add_content_info(aps, CA_All);
}
else if(part.meta.special == Part::Specialty::Conjugate)
{
aps.associated = current_idx;
ps.associated = associated_id;
aps.y_start += 1;
ps.y_start = aps.y_start;
aps.paren_y_start = aps.y_start;
ps.paren_y_start = aps.paren_y_start;
ps.paren_y_end = aps.paren_y_end;
add_content_info(aps, CA_All);
}
}
if(check_pos_is(part.meta.position, Part::Position::Start))
{
id_stack.push_back(current_idx);
}
}
current_idx = part.meta.next;
}
id_stack.clear();
}
static void render_parts(const std::vector<Part>& parts, RenderInfo& info, Equation::RenderResult& out, PartPos* screen, C2D_SpriteSheet sprites)
{
static std::vector<RenderPart> part_sizes;
part_sizes.resize(parts.size());
find_part_sizes(parts, part_sizes);
int selected_multi_id = -1;
int selected_multi_assoc = -1;
if(info.editing_char == 0)
{
if(const auto& part_before = parts[parts[info.editing_part].meta.before]; part_before.meta.special == Part::Specialty::Paren || part_before.meta.special == Part::Specialty::Absolute)
{
selected_multi_id = parts[info.editing_part].meta.before;
selected_multi_assoc = part_before.meta.assoc;
}
}
int current_idx = 0;
C2D_Image empty_img = C2D_SpriteSheetGetImage(sprites, sprites_empty_but_clickable_idx);
C2D_Image lpa_sprites[] = {
C2D_SpriteSheetGetImage(sprites, sprites_lparen_begin_idx),
C2D_SpriteSheetGetImage(sprites, sprites_lparen_middle_idx),
C2D_SpriteSheetGetImage(sprites, sprites_lparen_end_idx),
};
C2D_Image rpa_sprites[] = {
C2D_SpriteSheetGetImage(sprites, sprites_rparen_begin_idx),
C2D_SpriteSheetGetImage(sprites, sprites_rparen_middle_idx),
C2D_SpriteSheetGetImage(sprites, sprites_rparen_end_idx),
};
C2D_Image abs_sprites[] = {
C2D_SpriteSheetGetImage(sprites, sprites_abs_begin_idx),
C2D_SpriteSheetGetImage(sprites, sprites_abs_middle_idx),
C2D_SpriteSheetGetImage(sprites, sprites_abs_end_idx),
};
C2D_Image sqrt_sprites[] = {
C2D_SpriteSheetGetImage(sprites, sprites_sqrt_begin_idx),
C2D_SpriteSheetGetImage(sprites, sprites_sqrt_middle_idx),
C2D_SpriteSheetGetImage(sprites, sprites_sqrt_end_idx),
};
C2D_ImageTint text_tint;
C2D_PlainImageTint(&text_tint, COLOR_BLACK, 1.0f);
C2D_ImageTint temp_tint;
C2D_PlainImageTint(&temp_tint, COLOR_GRAY, 1.0f);
C2D_ImageTint paren_selected_tint;
C2D_PlainImageTint(&paren_selected_tint, COLOR_BLUE, 1.0f);
const auto draw_paren = [&](const C2D_Image* sprites, const int vertical_offset, const int y_start, const int y_end, const C2D_ImageTint* tnt) -> void {
const int span = (y_start - y_end) - 2;
const int span_pixels = (span * 24 / 4) + 1;
const int pixel_y = info.get_y(vertical_offset) - ((y_start - 1) * 24 / 4);
const int x = info.get_x();
C2D_DrawImageAt(sprites[0], x, pixel_y, 0.0f, tnt);
const int middle_y = pixel_y + sprites[0].subtex->height;
C2D_DrawImageAt(sprites[1], x, middle_y, 0.0f, tnt, 1.0f, span_pixels);
const int bottom_y = middle_y + span_pixels;
C2D_DrawImageAt(sprites[2], x, bottom_y, 0.0f, tnt);
};
const auto set_cursor = [&](const int y) -> void {
out.cursor_x = info.get_x();
out.cursor_y = y;
if(!(out.cursor_x <= -2 || out.cursor_x >= (320 - 2) || out.cursor_y <= (-24) || out.cursor_y >= EQU_REGION_HEIGHT))
{
out.cursor_visible = true;
}
};
int vertical_offset = 0;
int min_vert = 0;
int max_vert = 0;
PartPos pos;
while(current_idx != -1)
{
const auto& part = parts[current_idx];
const auto& part_size = part_sizes[current_idx];
if(part.meta.special == Part::Specialty::None)
{
pos.part = current_idx;
if(part.value.empty())
{
if(part_size.data != 0 && info.can_draw(vertical_offset))
{
const auto& img = empty_img;
C2D_DrawImageAt(img, info.get_x(), info.get_y(vertical_offset), 0.0f, &text_tint);
if(screen)
{
pos.pos = 0;
for(int y = 0; y < 24; y++)
{
const int actual_y = info.get_y(vertical_offset) + y;
if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT)
{
const int y_part = actual_y * 320;
for(int x = 0; x < 13; x++)
{
const int actual_x = info.get_x() + x;
if(actual_x >= 0 && actual_x < 320)
{
screen[actual_x + y_part] = pos;
}
}
}
}
}
}
if(info.editing_part == current_idx && info.editing_char == 0)
{
set_cursor(info.get_y(vertical_offset));
}
if(part_size.data != 0) info.current_x += 13;
}
else
{
int char_idx = 0;
for(const char c : part.value)
{
if(info.can_draw(vertical_offset))
{
const auto img = TextMap::char_to_sprite->equ.at(std::string_view(&c, 1));
C2D_DrawImageAt(img, info.get_x(), info.get_y(vertical_offset), 0.0f, &text_tint);
if(screen)
{
pos.pos = char_idx + 1;
for(int y = 0; y < 24; y++)
{
const int actual_y = info.get_y(vertical_offset) + y;
if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT)
{
const int y_part = actual_y * 320;
for(int x = 0; x < 13; x++)
{
const int actual_x = info.get_x() + x;
if(actual_x >= 0 && actual_x < 320)
{
screen[actual_x + y_part] = pos;
}
}
}
}
}
}
if(info.editing_part == current_idx && info.editing_char == char_idx)
{
set_cursor(info.get_y(vertical_offset));
}
info.current_x += 13;;
char_idx += 1;
}
if(info.editing_part == current_idx && info.editing_char == char_idx)
{
set_cursor(info.get_y(vertical_offset));
}
}
}
else if(part.meta.special != Part::Specialty::Equation)
{
if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::TempParen || part.meta.special == Part::Specialty::Absolute)
{
pos.part = part.meta.next;
const C2D_Image* sprs = nullptr;
if(part.meta.special == Part::Specialty::Absolute)
{
sprs = abs_sprites;
}
else if(part.meta.position == Part::Position::Start)
{
sprs = lpa_sprites;
}
else if(part.meta.position == Part::Position::End)
{
sprs = rpa_sprites;
}
const C2D_ImageTint* tnt = &temp_tint;
if(part.meta.special == Part::Specialty::Paren || part.meta.special == Part::Specialty::Absolute)
{
if(current_idx == selected_multi_id || current_idx == selected_multi_assoc)
{
tnt = &paren_selected_tint;
}
else
{
tnt = &text_tint;
}
}
draw_paren(sprs, vertical_offset, part_size.paren_y_start, part_size.paren_y_end, tnt);
if(screen)
{
const int h = ((part_size.paren_y_start - part_size.paren_y_end) * 24 / 2) + 1;
for(int y = 0; y < h; y++)
{
const int actual_y = info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 2) + y;
if(actual_y >= 0 && actual_y < EQU_REGION_HEIGHT)
{
const int y_part = actual_y * 320;
for(int x = 0; x < 13; x++)
{
const int actual_x = info.get_x() + x;
if(actual_x >= 0 && actual_x < 320)
{
screen[actual_x + y_part] = pos;
}
}
}
}
}
info.current_x += 13;
}
else if(part.meta.special == Part::Specialty::Root)
{
if(part.meta.position == Part::Position::Start)
{
draw_paren(sqrt_sprites, vertical_offset, part_size.paren_y_start, part_size.paren_y_end, &text_tint);
const int pixel_y = info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 4);
const int bar_x = info.get_x() + 10;
const int bar_w = (part_size.content_width - 2) * 13 + 10;
const int notch_x = bar_x + bar_w;
C2D_DrawRectSolid(bar_x, pixel_y, 0.125f, bar_w, 2, COLOR_BLACK);
C2D_DrawRectSolid(notch_x, pixel_y, 0.125f, 2, 10, COLOR_BLACK);
}
info.current_x += 13;
}
else if(part.meta.special == Part::Specialty::Conjugate)
{
if(part.meta.position == Part::Position::Start)
{
C2D_DrawRectSolid(info.get_x(), info.get_y(vertical_offset) - ((part_size.paren_y_start - 1) * 24 / 4), 0.125f, part_size.content_width * 13, 2, COLOR_BLACK);
}
}
else if(part.meta.special == Part::Specialty::Fraction)
{
if(part.meta.position == Part::Position::Start)
{
const auto& middle_size = part_sizes[part_size.associated];
const int max_width = std::max(middle_size.content_width, part_size.content_width);
C2D_DrawRectSolid(info.get_x(), info.get_y(vertical_offset) + 24 / 2 - 1, 0.0f, max_width * 13, 2.0f, COLOR_BLACK);
info.current_x += ((max_width - part_size.content_width) * 13)/2; // top align
}
else if(part.meta.position == Part::Position::Middle)
{
const int max_width = std::max(part_size.content_width, part_size.data);
info.current_x -= (part_size.data * 13); // top size
info.current_x -= ((max_width - part_size.data) * 13)/2; // top align
info.current_x += ((max_width - part_size.content_width) * 13)/2; // bottom align
}
else if(part.meta.position == Part::Position::End)
{
const auto& middle_size = part_sizes[part_size.associated];
const int max_width = std::max(middle_size.content_width, middle_size.data);
info.current_x -= (middle_size.content_width * 13); // bottom size
info.current_x -= ((max_width - middle_size.content_width) * 13)/2; // bottom align
info.current_x += max_width * 13; // full size
}
}
vertical_offset += (part_size.middle_change * 24) / 4;
max_vert = std::max(max_vert, vertical_offset);
min_vert = std::min(min_vert, vertical_offset);
}
current_idx = part.meta.next;
}
out.w = info.current_x;
out.min_y = min_vert - 24 / 2;
out.max_y = max_vert + 24 / 2;
part_sizes.clear();
}
Equation::RenderResult Equation::render_main(const int x, const int y, const int editing_part, const int editing_char, C2D_SpriteSheet sprites, PartPos* screen)
{
RenderResult out{0,0,0,-1,-1, false};
RenderInfo info{
0,
x, x + 320, y,
EQU_REGION_HEIGHT,
editing_part,
editing_char,
};
render_parts(parts, info, out, screen, sprites);
return out;
}
Equation::RenderResult Equation::render_memory(const int x, const int y, C2D_SpriteSheet sprites)
{
RenderResult out{0,0,0,-1,-1, false};
RenderInfo info{
0,
x, x + 400, y,
EQU_REGION_HEIGHT,
-1,
-1,
};
render_parts(parts, info, out, nullptr, sprites);
return out;
}
void Equation::optimize()
{
std::vector<Part> tmp;
tmp.push_back(std::move(parts[0]));
int prev_id = 0;
int next_id_parts = tmp.back().meta.next;
while(next_id_parts != -1)
{
int next_id_tmp = tmp.size();
tmp.back().meta.next = next_id_tmp;
tmp.push_back(std::move(parts[next_id_parts]));
next_id_parts = tmp.back().meta.next;
tmp.back().meta.before = prev_id;
prev_id = next_id_tmp;
}
parts = std::move(tmp);
}
std::pair<Number, bool> Equation::calculate(std::map<std::string, Number>& variables, int& error_part, int& error_position)
{
#define ERROR_AT(part, pos) { error_part = part; error_position = pos; return {}; }
struct Token {
enum class Type {
Number,
Variable,
Function,
Operator,
ParenOpen,
ParenClose,
};
std::string_view value;
int part, position;
Type type;
};
const auto base_tokens = [&, this]() -> std::vector<Token> {
std::vector<Token> toks;
int start = 0;
int len = 0;
int tmp_is_num = -1;
int current_idx = 0;
while(current_idx != -1)
{
const auto& p = parts[current_idx];
if(p.meta.special != Part::Specialty::None)
{
if(p.meta.special == Part::Specialty::TempParen)
{
ERROR_AT(p.meta.next, 0);
}
else if(p.meta.special == Part::Specialty::Absolute)
{
if(p.meta.position == Part::Position::Start)
{
toks.push_back(Token{"abs", p.meta.next, 0, Token::Type::Function});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Root)
{
if(p.meta.position == Part::Position::Start)
{
if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number))
{
toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator});
}
toks.push_back(Token{"sqrt", p.meta.next, 0, Token::Type::Function});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Conjugate)
{
if(p.meta.position == Part::Position::Start)
{
toks.push_back(Token{"conj", p.meta.next, 0, Token::Type::Function});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Paren)
{
if(p.meta.position == Part::Position::Start)
{
if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number))
{
toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator});
}
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Exponent)
{
if(p.meta.position == Part::Position::Start)
{
if(toks.size() >= 1)
{
if(const auto b = toks.back(); b.value == "e" && b.type == Token::Type::Variable)
{
toks.pop_back();
if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number))
{
toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator});
}
toks.push_back(Token{"exp", b.part, b.position, Token::Type::Function});
}
else
toks.push_back(Token{"^", p.meta.next, 0, Token::Type::Operator});
}
else
toks.push_back(Token{"^", p.meta.next, 0, Token::Type::Operator});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
else if(p.meta.special == Part::Specialty::Fraction)
{
if(p.meta.position == Part::Position::Start)
{
if(toks.size() && (toks.back().type == Token::Type::Variable || toks.back().type == Token::Type::Number))
{
toks.push_back(Token{"*", toks.back().part, toks.back().position, Token::Type::Operator});
}
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else if(p.meta.position == Part::Position::Middle)
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
toks.push_back(Token{"/", p.meta.next, 0, Token::Type::Operator});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenOpen});
}
else
{
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
toks.push_back(Token{std::string_view{}, p.meta.next, 0, Token::Type::ParenClose});
}
}
}
else
{
int pos = 0;
const char* beg = p.value.c_str();
for(const char c : p.value)
{
if(('0' <= c && c <= '9') || c == '.')
{
if(tmp_is_num == 1)
{
++len;
}
else
{
if(len != 0)
{
if(toks.size() && toks.back().type == Token::Type::ParenClose)
{
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable});
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
start = pos;
len = 1;
tmp_is_num = 1;
}
}
else if(('a' <= c && c <= 'z') || c == 'P')
{
if(tmp_is_num == 0)
{
++len;
}
else
{
if(len != 0)
{
if(toks.size() && toks.back().type == Token::Type::ParenClose)
{
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Number});
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
start = pos;
len = 1;
tmp_is_num = 0;
}
}
else
{
if(len != 0)
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, tmp_is_num ? Token::Type::Number : Token::Type::Variable});
}
start = 0;
len = 0;
tmp_is_num = -1;
toks.push_back(Token{{beg + pos, 1}, current_idx, pos, Token::Type::Operator});
}
++pos;
}
if(tmp_is_num == 0)
{
if(const auto& pn = parts[p.meta.next].meta; pn.position == Part::Position::Start && pn.special == Part::Specialty::Paren)
{
if(len == 1 || std::string_view{beg + start, size_t(len)} == "ans") // 1 letter names can only be variables
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable});
toks.push_back(Token{"*", current_idx, start, Token::Type::Operator});
}
else
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Function});
}
}
else
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Variable});
}
}
else if(tmp_is_num == 1)
{
toks.push_back(Token{{beg + start, size_t(len)}, current_idx, start, Token::Type::Number});
}
start = 0;
len = 0;
tmp_is_num = -1;
}
current_idx = p.meta.next;
}
return toks;
}();
if(base_tokens.empty()) return std::make_pair(Number{}, true);
const auto final_rpn = [&]() -> std::vector<const Token*> {
std::vector<const Token*> postfix;
std::vector<const Token*> opstack;
const auto get_prec = [](std::string_view op) -> int {
switch(op.front())
{
case '^': return 4;
case '*': return 3;
case '/': return 3;
case '+': return 2;
case '-': return 2;
case '>': return 1;
default: return 0;
}
};
const auto get_assoc = [](std::string_view op) -> bool {
return op.front() == '^';
};
for(const Token& tok : base_tokens)
{
if(tok.type == Token::Type::Variable || tok.type == Token::Type::Number)
{
postfix.push_back(&tok);
}
else if(tok.type == Token::Type::ParenOpen)
{
opstack.push_back(&tok);
}
else if(tok.type == Token::Type::ParenClose)
{
while(opstack.size() && opstack.back()->type != Token::Type::ParenOpen)
{
postfix.push_back(opstack.back());
opstack.pop_back();
}
opstack.pop_back(); // open paren (mismatch cannot happen)
}
else if(tok.type == Token::Type::Function)
{
opstack.push_back(&tok);
}
else if(tok.type == Token::Type::Operator)
{
auto prec = get_prec(tok.value);
while(opstack.size())
{
if(const Token* op = opstack.back();
op->type != Token::Type::ParenOpen && (
op->type == Token::Type::Function ||
get_prec(op->value) >= prec ||
(get_prec(op->value) == prec && get_assoc(op->value))
)
)
{
postfix.push_back(op);
opstack.pop_back();
}
else
break;
}
opstack.push_back(&tok);
}
}
while(opstack.size())
{
postfix.push_back(opstack.back());
opstack.pop_back();
}
return postfix;
}();
if(final_rpn.empty()) std::make_pair(Number{}, true);
#undef ERROR_AT
#define ERROR_AT(part, pos) { error_part = part; error_position = pos; return std::make_pair(Number{}, true); }
struct Value {
Number val;
std::string_view assoc_variable;
Value(std::string_view v) : val(v) { }
Value(const Number& v) : val(v) { }
Value(const Number& v, std::string_view a) : val(v), assoc_variable(a) { }
};
const auto get_var = [&](std::string_view name) -> Value {
if(auto it = variables.find(std::string(name)); it != variables.end())
{
return {it->second, name};
}
return {{}, name};
};
#define MK_WRAPPER_FN(fname, fn) {#fname, [](std::vector<Value>& vals) { \
vals.back() = Value(std::fn(vals.back().val.value)); \
}}
#define MK_WRAPPER(fname) MK_WRAPPER_FN(fname, fname)
const std::map<std::string_view, void(*)(std::vector<Value>&)> function_handlers{
MK_WRAPPER(abs),
MK_WRAPPER(sqrt),
MK_WRAPPER(conj),
MK_WRAPPER(cos),
MK_WRAPPER(sin),
MK_WRAPPER(tan),
MK_WRAPPER(acos),
MK_WRAPPER(asin),
MK_WRAPPER(atan),
MK_WRAPPER(cosh),
MK_WRAPPER(sinh),
MK_WRAPPER(tanh),
MK_WRAPPER(acosh),
MK_WRAPPER(asinh),
MK_WRAPPER(atanh),
MK_WRAPPER(exp),
MK_WRAPPER_FN(ln, log),
MK_WRAPPER_FN(log, log10),
};
std::vector<Value> value_stack;
for(const Token* tok : final_rpn)
{
if(tok->type == Token::Type::Number)
{
if(tok->value.front() == '.' || tok->value.back() == '.')
{
ERROR_AT(tok->part, tok->position);
}
else
{
value_stack.emplace_back(tok->value);
}
}
else if(tok->type == Token::Type::Variable)
{
if(tok->value == "P")
{
value_stack.emplace_back(PI_VAL);
}
else if(tok->value == "e")
{
value_stack.emplace_back(E_VAL);
}
else if(tok->value == "i")
{
value_stack.emplace_back(I_VAL);
}
else
{
value_stack.push_back(get_var(tok->value));
}
}
else if(tok->type == Token::Type::Operator)
{
#define OP_CASE(op) case #op[0] : { \
const Value left = value_stack.back(); \
value_stack.pop_back(); \
const Value right = value_stack.back(); \
value_stack.pop_back(); \
value_stack.emplace_back(right.val.value op left.val.value); \
} break;
switch(tok->value.front())
{
OP_CASE(+)
OP_CASE(-)
OP_CASE(*)
OP_CASE(/)
case '^':
{
const Value left = value_stack.back();
value_stack.pop_back();
const Value right = value_stack.back();
value_stack.pop_back();
value_stack.emplace_back(std::pow(right.val.value, left.val.value));
}
break;
case '>':
{
const Value left = value_stack.back();
value_stack.pop_back();
const Value right = value_stack.back();
value_stack.pop_back();
variables.insert_or_assign(std::string(left.assoc_variable), right.val.value);
value_stack.push_back(right);
}
break;
}
}
else if(tok->type == Token::Type::Function)
{
if(auto it = function_handlers.find(tok->value); it != function_handlers.end())
{
it->second(value_stack);
}
}
}
return {value_stack.back().val, false};
#undef ERROR_AT
}
int Equation::set_special(const int current_part_id, const int at_position, const Part::Specialty special)
{
if(static_cast<size_t>(at_position) != parts[current_part_id].value.size()) return 0;
const int next_id = parts[current_part_id].meta.next;
if(next_id == -1) return 0;
auto& p = parts[next_id];
if(p.meta.special != Part::Specialty::Paren || p.meta.position != Part::Position::Start) return 0;
p.meta.special = special;
parts[p.meta.assoc].meta.special = special;
return 1;
}
void Equation::find_matching_tmp_paren(const int original_pos)
{
using HelperType = int(*)(Equation&, const int);
const auto do_find = [](Equation& e, const int original_pos, int inc_on_start, HelperType get_following) {
int current_count = 0;
int prev_pos = original_pos;
const Part::Position searching_for = !e.parts[original_pos].meta.position;
int pos = get_following(e, prev_pos);
while(current_count >= 0 /* && pos != -1 */) // second test redundant, since we have the Equation start and end chunks
{
if(current_count == 0 && e.parts[pos].meta.special == Part::Specialty::TempParen && e.parts[pos].meta.position == searching_for)
{
e.parts[pos].meta.special = Part::Specialty::Paren;
e.parts[pos].meta.assoc = original_pos;
e.parts[original_pos].meta.special = Part::Specialty::Paren;
e.parts[original_pos].meta.assoc = pos;
break;
}
if(check_pos_is(e.parts[pos].meta.position, Part::Position::End) && e.parts[pos].meta.special != Part::Specialty::TempParen)
{
current_count -= inc_on_start;
}
if(check_pos_is(e.parts[pos].meta.position, Part::Position::Start) && e.parts[pos].meta.special != Part::Specialty::TempParen)
{
current_count += inc_on_start;
}
prev_pos = pos;
pos = get_following(e, pos);
}
};
if(parts[original_pos].meta.position == Part::Position::Start)
{
// go forward
do_find(*this, original_pos, +1,
[](Equation& e, const int pos) -> int {
return e.parts[pos].meta.next;
}
);
}
else if(parts[original_pos].meta.position == Part::Position::End)
{
// go backwards
do_find(*this, original_pos, -1,
[](Equation& e, const int pos) -> int {
return e.parts[pos].meta.before;
}
);
}
}
std::pair<bool, bool> Equation::add_part_at(int& current_part_id, int& at_position, const Part::Specialty special, const Part::Position position, const int assoc)
{
std::string before_val = parts[current_part_id].value.substr(0, at_position);
std::string after_val = parts[current_part_id].value.substr(at_position);
const bool after_val_empty = after_val.empty();
const bool before_val_empty = before_val.empty();
const int new_part_id = parts.size();
if(after_val_empty)
{
parts.emplace_back();
auto& current_part = parts[current_part_id];
auto& new_part = parts[new_part_id];
new_part.meta.special = special;
new_part.meta.position = position;
new_part.meta.assoc = assoc;
new_part.meta.before = current_part_id;
new_part.meta.next = current_part.meta.next;
parts[new_part.meta.next].meta.before = new_part_id;
current_part.meta.next = new_part_id;
}
else if(before_val_empty)
{
parts.emplace_back();
auto& current_part = parts[current_part_id];
auto& new_part = parts[new_part_id];
new_part.meta.special = special;
new_part.meta.position = position;
new_part.meta.assoc = assoc;
new_part.meta.before = current_part.meta.before;
new_part.meta.next = current_part_id;
parts[new_part.meta.before].meta.next = new_part_id;
current_part.meta.before = new_part_id;
}
else
{
parts.emplace_back();
const int after_part_id = parts.size();
parts.emplace_back();
auto& current_part = parts[current_part_id];
auto& new_part = parts[new_part_id];
auto& after_part = parts[after_part_id];
new_part.meta.special = special;
new_part.meta.position = position;
new_part.meta.assoc = assoc;
new_part.meta.before = current_part_id;
new_part.meta.next = after_part_id;
after_part.meta.before = new_part_id;
after_part.meta.next = current_part.meta.next;
current_part.meta.next = new_part_id;
current_part.value = std::move(before_val);
after_part.value = std::move(after_val);
}
current_part_id = new_part_id;
at_position = 0;
const auto& new_part = parts[new_part_id];
return {parts[new_part.meta.before].meta.special == Part::Specialty::None, parts[new_part.meta.next].meta.special == Part::Specialty::None};
}
bool Equation::remove_at(int& current_part_id, int& at_position)
{
if(at_position == 0)
{
const auto merge_single_part = [this](Part::Meta single_meta) -> std::pair<int, int> {
const int before_part_start_id = single_meta.before;
const int after_part_start_id = single_meta.next;
const int part_id = before_part_start_id;
const int at_char = parts[part_id].value.size();
/*
* equ_start -> A -> single -> B -> equ_end
* append B to A
* make A's next into B's next
* make B's next's before into A
* equ_start -> AB -> equ_end
*/
Part::Meta after_start_meta = parts[after_part_start_id].meta;
parts[before_part_start_id].value.append(parts[after_part_start_id].value);
parts[before_part_start_id].meta.next = after_start_meta.next;
parts[after_start_meta.next].meta.before = before_part_start_id;
return {part_id, at_char};
};
const auto merge_parts = [this](Part::Meta start_meta, Part::Meta end_meta) -> std::pair<int, int> {
const int before_part_start_id = start_meta.before;
const int after_part_start_id = start_meta.next;
const int before_part_end_id = end_meta.before;
const int after_part_end_id = end_meta.next;
const int part_id = before_part_start_id;
const int at_char = parts[part_id].value.size();
/*
* if after_part_start_id != before_part_end_id:
* equ_start -> A -> start -> B -> ... -> C -> end -> D -> equ_end
* append D to C
* make C's next into D's next
* make C's new next's before into C
* equ_start -> A -> start -> B -> ... -> CD -> equ_end
* append B to A
* make A's next into B's next
* make CD's next's before into C
* equ_start -> A -> start -> B -> ... -> CD -> equ_end
*/
/*
* if after_part_start_id == before_part_end_id:
* equ_start -> A -> start -> B -> end -> C -> equ_end
* append C to B
* make B's next into C's next
* make B's new next's before into B
* equ_start -> A -> start -> BC -> equ_end
* append BC to A
* make A's next into BC's next
* make A's next's before into A
* equ_start -> ABC -> equ_end
*/
Part::Meta after_end_meta = parts[after_part_end_id].meta;
parts[before_part_end_id].value.append(parts[after_part_end_id].value);
parts[before_part_end_id].meta.next = after_end_meta.next;
parts[after_end_meta.next].meta.before = before_part_end_id;
Part::Meta after_start_meta = parts[after_part_start_id].meta;
parts[before_part_start_id].value.append(parts[after_part_start_id].value);
parts[before_part_start_id].meta.next = after_start_meta.next;
parts[after_start_meta.next].meta.before = before_part_start_id;
return {part_id, at_char};
};
Part::Meta start_meta = parts[parts[current_part_id].meta.before].meta; // select the special chunk before the writing area we're in
// Don't allow deleting the first chunk or chunks we're after the end of. chunks have to be deleted from the front of the inside
if((!(start_meta.special == Part::Specialty::Paren || start_meta.special == Part::Specialty::TempParen) && check_pos_is(start_meta.position, Part::Position::End)) || start_meta.special == Part::Specialty::Equation) return false;
if(start_meta.special == Part::Specialty::Fraction)
{
Part::Meta middle_meta = parts[start_meta.assoc].meta;
Part::Meta end_meta = parts[middle_meta.assoc].meta;
merge_parts(middle_meta, end_meta);
const int before_part_start_id = start_meta.before;
const int part_id = before_part_start_id;
const int at_char = parts[part_id].value.size();
Part::Meta after_start_meta = parts[start_meta.next].meta;
parts[before_part_start_id].value.append(parts[start_meta.next].value);
parts[before_part_start_id].meta.next = after_start_meta.next;
parts[after_start_meta.next].meta.before = before_part_start_id;
current_part_id = part_id;
at_position = at_char;
return true;
}
else if(start_meta.special == Part::Specialty::Paren)
{
parts[start_meta.assoc].meta.assoc = -1;
parts[start_meta.assoc].meta.special = Part::Specialty::TempParen;
std::tie(current_part_id, at_position) = merge_single_part(start_meta);
return true;
}
else if(start_meta.special == Part::Specialty::TempParen)
{
std::tie(current_part_id, at_position) = merge_single_part(start_meta);
return true;
}
else
{
std::tie(current_part_id, at_position) = merge_parts(start_meta, parts[start_meta.assoc].meta);
return true;
}
}
else
{
at_position -= 1;
parts[current_part_id].value.erase(at_position, 1);
return true;
}
}
bool Equation::left_of(int& current_part_id, int& at_position)
{
if(at_position != 0)
{
at_position--;
return true;
}
if(parts[parts[current_part_id].meta.before].meta.special != Part::Specialty::Equation)
{
do {
current_part_id = parts[current_part_id].meta.before;
} while(parts[current_part_id].meta.special != Part::Specialty::None);
at_position = parts[current_part_id].value.size();
return true;
}
return false;
}
bool Equation::right_of(int& current_part_id, int& at_position)
{
if(static_cast<size_t>(at_position) != parts[current_part_id].value.size())
{
at_position++;
return true;
}
if(parts[parts[current_part_id].meta.next].meta.special != Part::Specialty::Equation)
{
do {
current_part_id = parts[current_part_id].meta.next;
} while(parts[current_part_id].meta.special != Part::Specialty::None);
at_position = 0;
return true;
}
return false;
}
| 38.83914
| 236
| 0.492881
|
LiquidFenrir
|
01e39ce818b54c879e1b196b68ac199bd3856752
| 2,133
|
cpp
|
C++
|
Sources/AGEngine/Utils/Frustum.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 47
|
2015-03-29T09:44:25.000Z
|
2020-11-30T10:05:56.000Z
|
Sources/AGEngine/Utils/Frustum.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 313
|
2015-01-01T18:16:30.000Z
|
2015-11-30T07:54:07.000Z
|
Sources/AGEngine/Utils/Frustum.cpp
|
Another-Game-Engine/AGE
|
d5d9e98235198fe580a43007914f515437635830
|
[
"MIT"
] | 9
|
2015-06-07T13:21:54.000Z
|
2020-08-25T09:50:07.000Z
|
#pragma once
#include "Frustum.hh"
#include <glm/glm.hpp>
namespace AGE
{
void Frustum::buildPlanes()
{
_planes[PLANE_NEAR].setCoefficients(
_viewProj[0][2] + _viewProj[0][3],
_viewProj[1][2] + _viewProj[1][3],
_viewProj[2][2] + _viewProj[2][3],
_viewProj[3][2] + _viewProj[3][3]);
_planes[PLANE_FAR].setCoefficients(
-_viewProj[0][2] + _viewProj[0][3],
-_viewProj[1][2] + _viewProj[1][3],
-_viewProj[2][2] + _viewProj[2][3],
-_viewProj[3][2] + _viewProj[3][3]);
_planes[PLANE_BOTTOM].setCoefficients(
_viewProj[0][1] + _viewProj[0][3],
_viewProj[1][1] + _viewProj[1][3],
_viewProj[2][1] + _viewProj[2][3],
_viewProj[3][1] + _viewProj[3][3]);
_planes[PLANE_TOP].setCoefficients(
-_viewProj[0][1] + _viewProj[0][3],
-_viewProj[1][1] + _viewProj[1][3],
-_viewProj[2][1] + _viewProj[2][3],
-_viewProj[3][1] + _viewProj[3][3]);
_planes[PLANE_LEFT].setCoefficients(
_viewProj[0][0] + _viewProj[0][3],
_viewProj[1][0] + _viewProj[1][3],
_viewProj[2][0] + _viewProj[2][3],
_viewProj[3][0] + _viewProj[3][3]);
_planes[PLANE_RIGHT].setCoefficients(
-_viewProj[0][0] + _viewProj[0][3],
-_viewProj[1][0] + _viewProj[1][3],
-_viewProj[2][0] + _viewProj[2][3],
-_viewProj[3][0] + _viewProj[3][3]);
}
void Frustum::setMatrix(const glm::mat4 &viewProj)
{
if (_viewProj != viewProj)
{
_viewProj = viewProj;
buildPlanes();
}
}
bool Frustum::checkCollision(AABoundingBox const &aabb) const
{
for (int i = 0; i < PLANE_END; i++)
{
if (_planes[i].getPointDistance(aabb.getPositivePoint(_planes[i].getNormal())) < 0)
return (false);
}
return (true);
}
bool Frustum::checkCollision(Sphere const &sphere) const
{
assert(!"Not implemented");
return (false);
}
bool Frustum::checkCollision(glm::vec4 const &sphere) const
{
for (int i = 0; i < PLANE_END; i++)
{
float dist = _planes[i].getPointDistance(glm::vec3(sphere));
if (dist + sphere.w < 0)
return (false);
}
return (true);
}
bool Frustum::checkCollision(Frustum const &frustum) const
{
assert(!"Not implemented");
return (false);
}
}
| 23.966292
| 86
| 0.631036
|
Another-Game-Engine
|
01e7355d0093d04bd17cd74177abaa99133bd59e
| 20,259
|
cpp
|
C++
|
render_algorithms/ripgen-fbo/src/UI.cpp
|
itsermo/holovideo-algorithms
|
6b39f896a8c61d2a82a7314efc583940d685dd55
|
[
"BSD-3-Clause"
] | 3
|
2018-02-26T19:53:10.000Z
|
2020-01-16T14:30:02.000Z
|
render_algorithms/ripgen-fbo/src/UI.cpp
|
itsermo/holovideo-algorithms
|
6b39f896a8c61d2a82a7314efc583940d685dd55
|
[
"BSD-3-Clause"
] | null | null | null |
render_algorithms/ripgen-fbo/src/UI.cpp
|
itsermo/holovideo-algorithms
|
6b39f896a8c61d2a82a7314efc583940d685dd55
|
[
"BSD-3-Clause"
] | null | null | null |
#include <stdlib.h>
#include <stdio.h>
#include "setupglew.h"
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glxew.h>
//#include <GL/glx.h> //for Nvida Framelock code
#include <GL/glut.h>
#include "JSharedMemory.h"
#include "JSequencer.h"
#include "JDisplayState.h"
#include "RIP.h"
#include "UI.h"
#include "flyRender.h"
#include "holoren.h"
#include <sys/time.h>
//headers for 3d mouse
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/Xos.h>
#include <X11/Xatom.h>
#include <X11/keysym.h>
#include "xdrvlib.h"
#include <stdio.h> /* for printf and NULL */
#include <stdlib.h> /* for exit */
#include <string.h>
#include <GL/gl.h> // The GL Header File
#include <GL/glut.h> // The GL Utility Toolkit (Glut) Header
//#include <GL/glx.h>
//end 3d mouse headers
static HoloRenderParams *holoRenParams = NULL;
static HoloRenderParams *holoRenParams2 = NULL;
static RIPHologram *ripParams = NULL;
static RIPHologram *ripParams2 = NULL;
//static int attributeList[] = { GLX_RGBA, GLX_DOUBLEBUFFER, None }; //JB: The only use of this was if'd out of Tyler's old code.
static Display *dpy;
//static Window win;
//static XVisualInfo *vi; //not used
//static XSetWindowAttributes swa; //not used
static GLXContext cx;
static JDisplayState statecopy;
static JSharedMemory *sharedstate;
float MASTER_GAIN = 0.7; //this is overridden by the external UI
double MagellanSensitivity = 1.0;
Display *dsp;
Window root, drw;
XEvent report;
MagellanFloatEvent MagellanEvent;
int fringeToUse = 0;
bool freeSpin = false; // should object be sipinning for demo?
static bool ismaster = false; // is this instance the one that has keyboard/mouse? For now, pick based on screen number & make sure 0 is opened last.
static JSharedMemory* sharedFilename;
static JSharedMemory* sharedDepthA;
static JSharedMemory* sharedDepthB;
static JSequencer* sequencer = NULL;
//#define FILENAME_KEY 6624
//#define DEPTH_A_KEY 6625
//#define DEPTH_B_KEY 6626
void spaceball()
{
if(!dsp) return;
XEvent report;
report.type = 0;
if(XPending(dsp) <= 0) return;
XNextEvent( dsp, &report ); //BLOCKING. BOO. Hopefully checking for pending events above keeps this from blocking
if (!XCheckTypedEvent(dsp, ClientMessage, &report))
{
//no event
return;
}
switch( report.type )
{
case ClientMessage :
switch( MagellanTranslateEvent( dsp, &report, &MagellanEvent, 1.0, 1.0 ) )
{
case MagellanInputMotionEvent :
MagellanRemoveMotionEvents( dsp );
printf(
"x=%+5.0lf y=%+5.0lf z=%+5.0lf a=%+5.0lf b=%+5.0lf c=%+5.0lf \n",
MagellanEvent.MagellanData[ MagellanX ],
MagellanEvent.MagellanData[ MagellanY ],
MagellanEvent.MagellanData[ MagellanZ ],
MagellanEvent.MagellanData[ MagellanA ],
MagellanEvent.MagellanData[ MagellanB ],
MagellanEvent.MagellanData[ MagellanC ] );
ripParams->m_render->motion(MagellanEvent.MagellanData[ MagellanX ], -MagellanEvent.MagellanData[ MagellanZ ]);
ripParams->m_render->spin(MagellanEvent.MagellanData[ MagellanA ]/100.0, MagellanEvent.MagellanData[ MagellanB ]/100.0);
// XClearWindow( drw, drw );
// XDrawString( drw, drw, wingc, 10,40,
//MagellanBuffer, (int)strlen(MagellanBuffer) );
// XFlush( display );
//tz= MagellanEvent.MagellanData[ MagellanZ];
break;
switch( MagellanEvent.MagellanButton )
{
case 5:
MagellanSensitivity = MagellanSensitivity <= 1.0/32.0 ? 1.0/32.0 : MagellanSensitivity/2.0; break;
case 6:
MagellanSensitivity = MagellanSensitivity >= 32.0 ? 32.0 : MagellanSensitivity*2.0; break;
}
default : // another ClientMessage event
break;
};
break;
};
}
void loadModelIfChanged(char* newname)
{
if(strncmp(newname, ripParams2->m_render->loadedFile, 1024))
{
ripParams2->m_render->config(newname);
ripParams2->m_render->init();
//load the new configuration!
//TODO: verify that this doesn't blow anything up.
}
}
void display(void)
{
struct timeval tp;
struct timezone tz;
//uncomment to restore spaceball rotation (flaky?)
//spaceball();
//JB: window gets reset somehow. Let's try fixing before we draw
//if ((holoRenParams->m_framebufferNumber % 2) == 0) {
// glutPositionWindow(0,hit);
//}
//glutReshapeWindow(wid,hit);
#ifdef SCREEN_SIZE_DIAGNOSTICS
//Some JB Diagnostics:
{
int screenHeight = glutGet(GLUT_SCREEN_HEIGHT);
int screenWidth = glutGet(GLUT_SCREEN_WIDTH);
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
int windowXPos = glutGet(GLUT_WINDOW_X);
int windowYPos = glutGet(GLUT_WINDOW_Y);
printf("At top of display function,\n");
printf("The glut Current Window is %d\n", glutGetWindow());
printf("Screen is %d by %d\n", screenWidth, screenHeight);
printf("OpenGL window is %d by %d\n", windowWidth, windowHeight);
printf("Window is located at %d, %d\n",windowXPos, windowYPos);
}
#endif
#ifdef XSCREENDUMP
static int framect = 0;
system("xwd -display localhost:0.0 -root -screen -silent | xwdtopnm 2>/dev/null | pnmtopng > ~/screendump.png");
printf("dumped screen to screendump.png\n");
if (framect++ == 5) exit(0);
#endif
//**** get current state from shared memory
//get state from UI & update model
#ifndef IGNORE_GUI
sharedstate->getDataCopy(&statecopy);
MASTER_GAIN = statecopy.gain;
if(ripParams)
{
ripParams->m_render->models->orient->rotate[0] = statecopy.xrot;
ripParams->m_render->models->orient->rotate[1] = statecopy.yrot;
ripParams->m_render->models->orient->rotate[2] = statecopy.zrot;
ripParams->m_render->models->orient->translate[0] = statecopy.xpos;
ripParams->m_render->models->orient->translate[1] = statecopy.ypos;
ripParams->m_render->models->orient->translate[2] = statecopy.zpos;
if(ripParams->m_flatrender != statecopy.rendermode1)
{
ripParams->m_flatrender = statecopy.rendermode1;
if(ripParams->m_flatrender == 0) //switch to RIP Method
{
ripParams->m_projectionPlaneDist = RIP_PROJ_PLANE;
ripParams->recomputeGeometry(ripParams->m_holorenparams);
}
else //switch to planar method
{
ripParams->m_projectionPlaneDist = statecopy.flatdepth1;
ripParams->recomputeGeometry(ripParams->m_holorenparams);
}
}
if(ripParams->m_flatrender && (statecopy.flatdepth1 != ripParams->m_projectionPlaneDist))
{
ripParams->m_projectionPlaneDist = statecopy.flatdepth1;
ripParams->recomputeGeometry(ripParams->m_holorenparams);
}
}
if(ripParams2)
{
ripParams2->m_render->models->orient->rotate[0] = statecopy.xrot;
ripParams2->m_render->models->orient->rotate[1] = statecopy.yrot;
ripParams2->m_render->models->orient->rotate[2] = statecopy.zrot;
//ripParams2->m_render->models->orient->translate[0] = statecopy.xpos;
//ripParams2->m_render->models->orient->translate[1] = statecopy.ypos;
//ripParams2->m_render->models->orient->translate[2] = statecopy.zpos;
if(ripParams2->m_flatrender != statecopy.rendermode2)
{
ripParams2->m_flatrender = statecopy.rendermode2;
if(ripParams2->m_flatrender == 0) //switch to RIP Method
{
ripParams2->m_projectionPlaneDist = RIP_PROJ_PLANE;
ripParams2->recomputeGeometry(ripParams2->m_holorenparams);
}
else //switch to planar method
{
ripParams2->m_projectionPlaneDist = statecopy.flatdepth2;
ripParams2->recomputeGeometry(ripParams2->m_holorenparams);
}
}
if(ripParams2->m_flatrender && (statecopy.flatdepth2 != ripParams2->m_projectionPlaneDist))
{
ripParams2->m_projectionPlaneDist = statecopy.flatdepth2;
ripParams2->recomputeGeometry(ripParams2->m_holorenparams);
}
}
#endif
/*char newname[1024];
if(sharedFilename->getDataCopyIfUnlocked(newname))
{
loadModelIfChanged(newname);
}
float newdepthA;
float newdepthB;
sharedDepthA->getDataCopyIfUnlocked(&newdepthA);
if(newdepthA != ripParams->m_projectionPlaneDist)
{
ripParams->m_projectionPlaneDist = newdepthA;
ripParams->recomputeGeometry(ripParams->m_holorenparams);
}
sharedDepthB->getDataCopyIfUnlocked(&newdepthB);
if(newdepthB != ripParams2->m_projectionPlaneDist)
{
ripParams2->m_projectionPlaneDist = newdepthB;
ripParams2->recomputeGeometry(ripParams2->m_holorenparams);
}
*/
//**** render
//black the color buffer
glClearColor(0.0,0.0,0.0,0.0);
glClear (GL_COLOR_BUFFER_BIT);
sequencer->update();
if(ripParams2 != NULL)
{
glPushAttrib(GL_ALL_ATTRIB_BITS);
ripParams2->DisplayRIPHologramSingleFramebuffer(holoRenParams2);
glPopAttrib();
}
glPushAttrib(GL_ALL_ATTRIB_BITS);
// calls RIPHologram::DisplayRIPHologramSingleFramebuffer (in RIP.cpp)
ripParams->DisplayRIPHologramSingleFramebuffer(holoRenParams);
glPopAttrib();
glFlush();
glutSwapBuffers();
//JB: Make it move
#ifdef SPIN_OBJECT_HACK
if(freeSpin)
{
if(ripParams) ripParams->m_render->spin(2, 0);
if(ripParams2) ripParams2->m_render->spin(-1.5,0);
}
#endif
//warp pointer back to center of screen if it isn't already there.
int cx, cy;
#ifndef LOCKED_UI
cx = glutGet(GLUT_WINDOW_WIDTH)/2;
cy = glutGet(GLUT_WINDOW_HEIGHT)/2;
if(ripParams->m_render->mLX != cx || ripParams->m_render->mLY != cy)
{
glutWarpPointer(cx,cy);
ripParams->m_render->mLX = cx;
ripParams->m_render->mLY = cy;
}
#endif
glutPostRedisplay(); //JB: This causes glut to continue to repeatedly execute display()
#ifdef TIMING_DIAGNOSTICS
{
gettimeofday(&tp, &tz);
printf("time now is: %ld sec %ld usec \n", tp.tv_sec, tp.tv_usec);
printf("time now is: (tp.tv_sec*100000)/100000)\n");
}
#endif
#ifdef SCREEN_SIZE_DIAGNOSTICS
int screenHeight = glutGet(GLUT_SCREEN_HEIGHT);
int screenWidth = glutGet(GLUT_SCREEN_WIDTH);
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
int windowXPos = glutGet(GLUT_WINDOW_X);
int windowYPos = glutGet(GLUT_WINDOW_Y);
printf("After buffer swap,\n");
printf("The glut Current Window is %d\n", glutGetWindow());
printf("Screen is %d by %d\n", screenWidth, screenHeight);
printf("OpenGL window is %d by %d\n", windowWidth, windowHeight);
printf("Window is located at %d, %d\n",windowXPos, windowYPos);
#endif
#ifdef WRITE_FB_TO_FILE
unsigned char *pic;
unsigned char *bptr;
FILE *fp;
int allocfail = 0;
printf("attempting to write framebuffer to file");
if ((pic = (unsigned char*)malloc(screenWidth*screenHeight*3 * sizeof(unsigned char))) == NULL) {
printf("couldn't allocate memory for framebuffer dump.\n");
allocfail = 1;
}
if ( !allocfail) {
char fname[255];
glReadBuffer(GL_FRONT);
bptr = pic;
glReadPixels(0, 0, screenWidth, screenHeight, GL_RGB, GL_UNSIGNED_BYTE, pic);
printf("saving %dx%dx3 to file...\n", screenWidth,screenHeight);
sprintf(fname, "FBcontents%d.raw", holoRenParams->m_framebufferNumber);
if ( (fp = fopen (fname, "w")) == NULL) {
printf("failure opening file.\n");
exit(0);
}
else {
if (fwrite (pic, 1, 3*screenWidth*screenHeight, fp) != screenWidth*screenHeight*3) {
printf("failure writing file.\n");
//exit(0);
}
fclose (fp);
}
free (pic);
}
exit(1);
#endif
}
//called by GLUT on mouseup and mousedown
void mouse(int button, int state, int x, int y)
{
// calls holoConf::mouse which sets cursor state and mousebutton state
ripParams->m_render->mouse(button, state, x, y);
}
//called by GLUT on mouse move (buttons up only)
//keep mouse at middle of screen
void passiveMotion(int x, int y)
{
//TODO: check for recursive events? Dead zone?
#ifndef LOCKED_UI
glutWarpPointer(holoRenParams->m_xRes/2,holoRenParams->m_yRes);
#endif
}
//called by GLUT on drag
void motion(int x, int y)
{
// calls holoConf::motion() which appears to
// translate the scene based on mouse movement.
ripParams->m_render->motion(x, y);
}
void keyboard(unsigned char key, int x, int y) {
printf("got key \"%c\" on screen %d\n", key, holoRenParams->m_framebufferNumber);
sequencer->keypress(key);
#ifndef LOCKED_UI
switch(key) {
case 'q':
case 'Q':
exit(0);
break;
case 'a':
fringeToUse ++;
if(fringeToUse >= NUM_PRECOMPUTED_FRINGES)
fringeToUse = NUM_PRECOMPUTED_FRINGES-1;
printf("using fringe %d\n", fringeToUse);
ripParams->m_fringeToUse = fringeToUse;
glutPostRedisplay();
break;
case 'A':
fringeToUse--;
if(fringeToUse < 0)
fringeToUse = 0;
printf("using fringe %d\n", fringeToUse);
ripParams->m_fringeToUse = fringeToUse;
glutPostRedisplay();
break;
case ' ':
freeSpin = !freeSpin;
glutPostRedisplay();
break;
case 'd':
ripParams->m_projectionPlaneDist += 1.0;
printf("projection plane now at %g\n", ripParams->m_projectionPlaneDist);
ripParams->recomputeGeometry(ripParams->m_holorenparams);
break;
case 'D':
ripParams->m_projectionPlaneDist -= 1.0;
printf("projection plane now at %g\n", ripParams->m_projectionPlaneDist);
ripParams->recomputeGeometry(ripParams->m_holorenparams);
break;
case 'l' :
//if(ismaster)
{
char fname[1024] = "/models/letters/SLOAN/C.xml";
sharedFilename->write(fname);
loadModelIfChanged(fname);
}
break;
case 'k' :
//if(ismaster)
{
char fname[1024] = "/models/letters/SLOAN/K.xml";
sharedFilename->write(fname);
loadModelIfChanged(fname);
}
break;
};
// calls holoConf::keyboard() which adds other commands:
// + = +ztranlate
// - = -ztranslate
// 4 = -xtranslate
// 6 = +xtranslate
// 8 = -ytranslate
// 2 = +ytranslate
ripParams->m_render->keyboard(key, x, y);
#endif
}
//JB: for testing on desktop display:
void reshape(int w, int h) {
glViewport(0,0,(GLsizei)w, (GLsizei)h);
glutPostRedisplay();
}
// setup UI
// uses structs holoRenParams.
void InitGL(int &argc, char **&argv, HoloRenderParams *hrP, RIPHologram *ripP, HoloRenderParams *hrP2, RIPHologram *ripP2)
{
holoRenParams = hrP;
ripParams = ripP;
holoRenParams2 = hrP2;
ripParams2 = ripP2;
printf("initializing GL\n");
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_STENCIL | GLUT_ACCUM);
//instance on framebuffer 0 gets to interact with keyboard & send events to other instances.
if(holoRenParams->m_framebufferNumber == 0)
{
ismaster = true;
}
else
{
ismaster = false;
}
//state for slaving to separate UI
sharedstate = new JSharedMemory(sizeof(JDisplayState),ALL_STATE_KEY);
sharedstate->getDataCopy(&statecopy);
/*
sharedFilename = new JSharedMemory(1024,FILENAME_KEY);
sharedDepthA = new JSharedMemory(sizeof(float),DEPTH_A_KEY);
sharedDepthB = new JSharedMemory(sizeof(float),DEPTH_B_KEY);
*/
/*
char f[1024] = "/models/blankframe.xml";
sharedFilename->write(f);
//initalize z-distance to first & second hologram.
float pdA = 10;
float pdB = 128;
sharedDepthA->write(&pdA);
sharedDepthB->write(&pdB);
*/
//TODO: get subject ID!
// glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
//glutInitDisplayString("xvisual=250");//doesn't seem to work
//glutInitDisplayString("depth=>1 rgba>1");//doesn't seem to work
// set up window size to be (these are hardcoded in RIP.h) 2048x(2*1780)
//(2 vertically stacked "framebuffers" worth per window)
glutInitWindowSize(holoRenParams->m_xRes,holoRenParams->m_yRes*2);
//glutInitWindowSize(2048,holoRenParams->m_yRes*2);
// TODO: Update block comment for version 3.0.
// Bottom line: each PC has 2 framebuffers, one window.
// PCnumber = floor(framebufferNumber/2) has one window, with framebuffer
// number PCnumber*2+1 on top and PCnumber*2 on bottom half of screen.
// previously, we had one window per framebuffer, but the two windows on the
// same video card liked to fight.
// WJP's note from pre-3.0 version:
// In holocomputation, we assume that hololines are apportioned
// in logical order in FB0, FB1, FB2, FB3, FB4 and FB5, and comments
// throughout the code reflect this. FB0 gets hololines 0,1,2, 18,19,20,...
// and FB1 gets hololines 3,4,5, 21,22,23... and so on. And the
// scripts: /home/holovideox/local/framebuffer1 and framebuffer2 return
// 0 and 1 on holovideo1, 2 and 3 on holovideo2, and 4 and 5 on holovideo3
// respectively.
// Here's what we've learned about the way framebuffers on
// holovideo1, holovideo2, holovideo3 map to holoLines.
// on holovideo1, framebufferNumber 1 has the top 3 hololines.
// framebufferNumber 0 has the next 3 hololines.
// on holovideo2, framebufferNumber 3 has the next 3 hololines.
// framebufferNumber 2 has the next three lines.
// on holovideo3, framebufferNumber 5 has the next three lines, and
// framebufferNumber 4 has the bottom three lines.
// our software assumes that lines are arranged from top to bottom
// in framebufferNumber 0 - 5. So, we swap the position of the output
// windows for FBs (0and1) (2and3) (4and5) in UI.cpp,
// so that FB0's output window is at (0,m_viewYRes) and FB1's is at (0,0).
// I hope this is understandable.
//JB removed for version 3.0
//if((hrP->m_framebufferNumber % 2) == 1)
//{
glutInitWindowPosition(0, 0);
//} else {
// glutInitWindowPosition(0, hrP->m_yRes);
//}
// specifies display, keyboard, mouse, motion callacks,
// configures window and turns OFF the cursor!
int winnum = glutCreateWindow("HoloLoadExec"); //title is hint to window manager to not decorate window
GLenum glewerr = glewInit();
if(GLEW_OK != glewerr)
{
printf("Glew Init Failed! (%s) \n", glewGetErrorString(glewerr));
}
glutDisplayFunc(display);
GLuint numgroups,numbars;
int ret;
#ifdef USE_HARDWARE_GENLOCK
//Code block to turn on buffer swap syncronization using genlock hardware
ret = glXQueryMaxSwapGroupsNV(dsp,drw,&numgroups, &numbars);
if (!ret) printf("Couldn't query swap group info\n");
ret = glXJoinSwapGroupNV(dsp,drw,1);//Make our drawable part of framelock group zero
if (!ret) printf("Failed to start swap group\n");
ret = glXBindSwapBarrierNV(dsp,1,1);//make framelock group zero part of barrier zero
if (!ret) printf("Failed to start swap barrier\n");
printf("System supports %d groups and %d barriers\n", numgroups, numbars);
#endif
#ifdef WORKSTATION_DEBUG
glutReshapeFunc(reshape);
#endif
glutKeyboardFunc(keyboard);
glutMouseFunc(mouse);
glutMotionFunc(motion);
glutPassiveMotionFunc(passiveMotion);
//glutFullScreen();
glutSetCursor(GLUT_CURSOR_NONE);
//TODO: This will probably need to change with three wimultaneous windows...
glutWarpPointer(glutGet(GLUT_WINDOW_WIDTH)/2, glutGet(GLUT_WINDOW_HEIGHT)/2); // move mouse to center of display
//Set up Spaceball/SpaceNavigator support
GLXDrawable drw = glXGetCurrentDrawable();
dsp = glXGetCurrentDisplay();
if ( !MagellanInit( dsp, drw ) )
{
fprintf( stderr, "Can't find the spaceball driver. try running:\n sudo /etc/3DxWare/daemon/3dxsrv -d usb \n" );
}
//testing GLX capabilities...
int vid = glutGet(GLUT_WINDOW_FORMAT_ID);
printf("Using openGL visual #%d. See visualinfo for more information\n", vid);
XVisualInfo* newVisual = NULL;
int visattrib[] = {GLX_RGBA, GLX_RED_SIZE, 64};
newVisual = glXChooseVisual(dsp, 0, visattrib);
sequencer = new JSequencer("HoloLayerLetter", 0, holoRenParams->m_framebufferNumber, hrP, ripP, hrP2, ripP2);
//Some JB Diagnostics:
#ifdef SCREEN_SIZE_DIAGNOSTICS
{
int screenHeight = glutGet(GLUT_SCREEN_HEIGHT);
int screenWidth = glutGet(GLUT_SCREEN_WIDTH);
int windowWidth = glutGet(GLUT_WINDOW_WIDTH);
int windowHeight = glutGet(GLUT_WINDOW_HEIGHT);
int windowXPos = glutGet(GLUT_WINDOW_X);
int windowYPos = glutGet(GLUT_WINDOW_Y);
printf("Before starting main loop,\n");
printf("glutCreateWindow returned window ID %d\n", winnum);
printf("The glut Current Window is %d\n", glutGetWindow());
printf("Screen is %d by %d\n", screenWidth, screenHeight);
printf("OpenGL window is %d by %d\n", windowWidth, windowHeight);
printf("Window is located at %d, %d\n",windowXPos, windowYPos);
printf("swapped buffers: you should SEE something on the display now...\n");
}
#endif
}
//I don't think this ever gets called (JB);
void CloseGL()
{
// glXDestroyContext(dpy, cx);
// XDestroyWindow(dpy, win);
// XCloseDisplay(dpy);
}
| 27.982044
| 149
| 0.710203
|
itsermo
|
543527a510cb32554b395028916e54e8d894c42f
| 775
|
cpp
|
C++
|
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
|
BaderEddineOuaich/xtd
|
6f28634c7949a541d183879d2de18d824ec3c8b1
|
[
"MIT"
] | 1
|
2022-02-25T16:53:06.000Z
|
2022-02-25T16:53:06.000Z
|
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
|
leanid/xtd
|
2e1ea6537218788ca08901faf8915d4100990b53
|
[
"MIT"
] | null | null | null |
src/xtd.core/src/xtd/reflection/assembly_title_attribute.cpp
|
leanid/xtd
|
2e1ea6537218788ca08901faf8915d4100990b53
|
[
"MIT"
] | null | null | null |
#include "../../../include/xtd/reflection/assembly_title_attribute.h"
using namespace std;
using namespace xtd;
using namespace xtd::reflection;
assembly_title_attribute::assembly_title_attribute(const ustring& title) : title_(title) {
}
assembly_title_attribute::assembly_title_attribute(const ustring& title, const object& executing_assembly) : title_(title) {
__assembly_title_attribute__() = make_shared<xtd::reflection::assembly_title_attribute>(title);
}
shared_ptr<object> assembly_title_attribute::get_type_id() const {
return xtd::guid::new_guid().memberwise_clone<xtd::guid>();
}
shared_ptr<xtd::reflection::assembly_title_attribute>& __assembly_title_attribute__() {
static shared_ptr<xtd::reflection::assembly_title_attribute> title;
return title;
}
| 35.227273
| 124
| 0.79871
|
BaderEddineOuaich
|
543614d4379119294edb2d06606b2e4da4f4ceee
| 755
|
cpp
|
C++
|
p636/p636_2.cpp
|
suzyz/leetcode_practice
|
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
|
[
"MIT"
] | 1
|
2019-10-07T05:00:21.000Z
|
2019-10-07T05:00:21.000Z
|
p636/p636_2.cpp
|
suzyz/leetcode_practice
|
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
|
[
"MIT"
] | null | null | null |
p636/p636_2.cpp
|
suzyz/leetcode_practice
|
e22dc5a81e065dc962e5561b14ac84b9a2302e8a
|
[
"MIT"
] | null | null | null |
class Solution {
public:
vector<int> exclusiveTime(int n, vector<string>& logs) {
vector<int> res(n);
stack<int> st;
int preTime = 0;
for (int i = 0; i < logs.size(); ++i) {
int pos = logs[i].find(':');
int id = atoi(logs[i].substr(0, pos).c_str());
pos = logs[i].find(':', pos+1);
int curTime = atoi(logs[i].substr(pos+1).c_str());
if (!st.empty())
res[st.top()] += curTime - preTime;
preTime = curTime;
if (logs[i][pos-1] == 't')
st.push(id);
else {
++res[st.top()];
st.pop();
++preTime;
}
}
return res;
}
};
| 23.59375
| 62
| 0.403974
|
suzyz
|
543fa89656496c552e0840f549271c1541df4c4e
| 865
|
cpp
|
C++
|
src/state_vector/state_vector.cpp
|
libtangle/tools
|
4362e5312bcfbe93c912c3f8df9159816003b66e
|
[
"MIT"
] | 1
|
2019-10-14T05:41:58.000Z
|
2019-10-14T05:41:58.000Z
|
src/state_vector/state_vector.cpp
|
libtangle/tools
|
4362e5312bcfbe93c912c3f8df9159816003b66e
|
[
"MIT"
] | 1
|
2019-09-15T17:57:43.000Z
|
2019-09-16T06:36:19.000Z
|
src/state_vector/state_vector.cpp
|
libtangle/tools
|
4362e5312bcfbe93c912c3f8df9159816003b66e
|
[
"MIT"
] | null | null | null |
#include "state_vector.h"
#include "omp.h"
#include <iostream>
#include <stdlib.h>
StateVector::StateVector(int num_qubits)
{
this->num_qubits = num_qubits;
this->num_amps = 1L << num_qubits;
// Allocate the required memory for the state vector
std::size_t bytes = num_amps * sizeof(complex);
state = (complex *)malloc(bytes);
// Initialize the state vector
state[0] = complex(1);
#pragma omp parallel for
for (std::size_t i = 1; i < num_amps; i++)
{
state[i] = complex(0);
}
}
void StateVector::print()
{
for (std::size_t i = 0; i < num_amps; i++)
{
complex amp = state[i];
std::cout
<< i << ": "
<< std::real(amp)
<< (std::imag(amp) >= 0.0 ? " + " : " - ")
<< std::abs(std::imag(amp))
<< "i"
<< std::endl;
}
}
| 22.179487
| 56
| 0.523699
|
libtangle
|
5440b08301628ef96e197bf93542acbaa63f2f0f
| 1,490
|
hpp
|
C++
|
include/prog/sym/func_def.hpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 14
|
2020-04-14T17:00:56.000Z
|
2021-08-30T08:29:26.000Z
|
include/prog/sym/func_def.hpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 27
|
2020-12-27T16:00:44.000Z
|
2021-08-01T13:12:14.000Z
|
include/prog/sym/func_def.hpp
|
BastianBlokland/novus
|
3b984c36855aa84d6746c14ff7e294ab7d9c1575
|
[
"MIT"
] | 1
|
2020-05-29T18:33:37.000Z
|
2020-05-29T18:33:37.000Z
|
#pragma once
#include "prog/expr/node.hpp"
#include "prog/sym/const_decl_table.hpp"
#include "prog/sym/func_decl_table.hpp"
#include <vector>
namespace prog::sym {
// Function definition. Contains the body of a user-function.
class FuncDef final {
friend class FuncDefTable;
public:
enum class Flags : unsigned int {
None = 0U,
NoInline = 1U << 0U, // Hint to the optmizer that it should not inline this function.
};
FuncDef() = delete;
FuncDef(const FuncDef& rhs) = delete;
FuncDef(FuncDef&& rhs) = default;
~FuncDef() = default;
auto operator=(const FuncDef& rhs) -> FuncDef& = delete;
auto operator=(FuncDef&& rhs) noexcept -> FuncDef& = delete;
[[nodiscard]] auto getId() const noexcept -> const FuncId&;
[[nodiscard]] auto getFlags() const noexcept -> Flags;
[[nodiscard]] auto hasFlags(Flags flags) const noexcept -> bool;
[[nodiscard]] auto getConsts() const noexcept -> const sym::ConstDeclTable&;
[[nodiscard]] auto getBody() const noexcept -> const expr::Node&;
[[nodiscard]] auto getOptArgInitializer(unsigned int i) const -> expr::NodePtr;
private:
sym::FuncId m_id;
sym::ConstDeclTable m_consts;
expr::NodePtr m_body;
std::vector<expr::NodePtr> m_optArgInitializers;
Flags m_flags;
FuncDef(
sym::FuncId id,
sym::ConstDeclTable consts,
expr::NodePtr body,
std::vector<expr::NodePtr> optArgInitializers,
Flags flags);
};
} // namespace prog::sym
| 29.8
| 89
| 0.672483
|
BastianBlokland
|
5445fbb01d0b541ba8265c0941408dadaf0ef837
| 226
|
hpp
|
C++
|
source/platform/windows/defines.hpp
|
ameisen/gcgg
|
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
|
[
"Apache-2.0"
] | null | null | null |
source/platform/windows/defines.hpp
|
ameisen/gcgg
|
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
|
[
"Apache-2.0"
] | null | null | null |
source/platform/windows/defines.hpp
|
ameisen/gcgg
|
6ee9a841ddd88182c235a688e6b7d8894f7af1fe
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <cassert>
#define OS Windows
#define __likely(c) (c)
#define __unlikely(c) (c)
#define __unreachable __assume(0)
#define nodefault default: { __unreachable; }
#define xassert(c) assert(c)
| 17.384615
| 46
| 0.69469
|
ameisen
|
5446676bcffd729b260e4aba4e25c442da814dc9
| 2,705
|
cxx
|
C++
|
src/shared/init_models.cxx
|
solomonik/ctf
|
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
|
[
"BSD-2-Clause"
] | 56
|
2015-02-28T08:19:58.000Z
|
2021-11-04T16:46:17.000Z
|
src/shared/init_models.cxx
|
solomonik/ctf
|
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
|
[
"BSD-2-Clause"
] | 40
|
2015-04-08T14:58:42.000Z
|
2017-11-17T20:57:26.000Z
|
src/shared/init_models.cxx
|
solomonik/ctf
|
b79428ca8e7a5fa6ef22197ff5129d1aace3134b
|
[
"BSD-2-Clause"
] | 17
|
2015-04-03T00:57:43.000Z
|
2018-03-30T20:46:14.000Z
|
namespace CTF_int{
double seq_tsr_spctr_cst_off_k0_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_off_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_off_k2_init[] = {-2.1996E-04, 3.1883E-09, 3.8743E-11};
double seq_tsr_spctr_off_k0_init[] = {8.6970E-06, 4.5598E-11, 1.1544E-09};
double seq_tsr_spctr_off_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_off_k2_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_k0_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_cst_k2_init[] = {-8.8459E-08, 8.1207E-10, -2.8486E-12};
double seq_tsr_spctr_cst_k3_init[] = {1.8504E-08, 2.9154E-11, 2.1973E-11};
double seq_tsr_spctr_cst_k4_init[] = {2.0948E-05, 1.2294E-09, 8.0037E-10};
double seq_tsr_spctr_k0_init[] = {2.2620E-08, -5.7494E-10, 2.2146E-09};
double seq_tsr_spctr_k1_init[] = {5.3745E-06, 3.6464E-08, 2.2334E-10};
double seq_tsr_spctr_k2_init[] = {3.0917E-08, 5.2181E-11, 4.1634E-12};
double seq_tsr_spctr_k3_init[] = {7.2456E-08, 1.5128E-10, -1.5528E-12};
double seq_tsr_spctr_k4_init[] = {1.6880E-07, 4.9411E-10, 9.2847E-13};
double pin_keys_mdl_init[] = {3.1189E-09, 6.6717E-08};
double seq_tsr_ctr_mdl_cst_init[] = {5.1626E-06, -6.3215E-11, 3.9638E-09};
double seq_tsr_ctr_mdl_ref_init[] = {4.9138E-08, 5.8290E-10, 4.8575E-11};
double seq_tsr_ctr_mdl_inr_init[] = {2.0647E-08, 1.9721E-10, 2.9948E-11};
double seq_tsr_ctr_mdl_off_init[] = {6.2925E-05, 1.7449E-11, 1.7211E-12};
double seq_tsr_ctr_mdl_cst_inr_init[] = {1.3863E-04, 2.0119E-10, 9.8820E-09};
double seq_tsr_ctr_mdl_cst_off_init[] = {8.4844E-04, -5.9246E-11, 3.5247E-10};
double long_contig_transp_mdl_init[] = {2.9158E-10, 3.0501E-09};
double shrt_contig_transp_mdl_init[] = {1.3427E-08, 4.3168E-09};
double non_contig_transp_mdl_init[] = {4.0475E-08, 4.0463E-09};
double dgtog_res_mdl_init[] = {2.9786E-05, 2.4335E-04, 1.0845E-08};
double blres_mdl_init[] = {1.0598E-05, 7.2741E-08};
double alltoall_mdl_init[] = {1.0000E-06, 1.0000E-06, 5.0000E-10};
double alltoallv_mdl_init[] = {2.7437E-06, 2.2416E-05, 1.0469E-08};
double red_mdl_init[] = {6.2935E-07, 4.6276E-06, 9.2245E-10};
double red_mdl_cst_init[] = {5.7302E-07, 4.7347E-06, 6.0191E-10};
double allred_mdl_init[] = {8.4416E-07, 6.8651E-06, 3.5845E-08};
double allred_mdl_cst_init[] = {-3.3754E-04, 2.1343E-04, 3.0801E-09};
double bcast_mdl_init[] = {1.5045E-06, 1.4485E-05, 3.2876E-09};
double spredist_mdl_init[] = {1.2744E-04, 1.0278E-03, 7.6837E-08};
double csrred_mdl_init[] = {3.7005E-05, 1.1854E-04, 5.5165E-09};
double csrred_mdl_cst_init[] = {-1.8323E-04, 1.3076E-04, 2.8732E-09};
}
| 65.97561
| 79
| 0.721257
|
solomonik
|
5450373884e4d7eeae4d4c943765a34f77388329
| 650
|
cpp
|
C++
|
dlls/ADM/Physics/PhysManager.cpp
|
BlueNightHawk4906/HL-ADM-Custom
|
7cd3925de819d4f5a2a808e5c0b34bb03a51c991
|
[
"Unlicense"
] | 1
|
2020-12-11T17:52:33.000Z
|
2020-12-11T17:52:33.000Z
|
dlls/ADM/Physics/PhysManager.cpp
|
BlueNightHawk4906/HL-ADM-Custom
|
7cd3925de819d4f5a2a808e5c0b34bb03a51c991
|
[
"Unlicense"
] | 7
|
2021-07-09T09:19:14.000Z
|
2021-07-20T19:35:21.000Z
|
dlls/ADM/Physics/PhysManager.cpp
|
phoenixprojectsoftware/phoenixADM
|
5f170a34739e64111dbe161d9ab9e0baa219512b
|
[
"Unlicense"
] | null | null | null |
#include "Base/ExtDLL.h"
#include "Util.h"
#include "Base/CBase.h"
#include "PhysManager.h"
#include "../shared/ADM/Physics/PhysicsWorld.h"
LINK_ENTITY_TO_CLASS( phys_manager, CPhysManager );
void CPhysManager::Spawn()
{
pev->solid = SOLID_NOT;
pev->movetype = MOVETYPE_NONE;
// pev->flags |= FL_ALWAYSTHINK;
SetThink( &CPhysManager::PhysManagerThink );
pev->nextthink = gpGlobals->time + 1.5f;
}
void CPhysManager::PhysManagerThink()
{
g_Physics.StepSimulation( 1.f / 64.f, 16 );
pev->nextthink = gpGlobals->time + 1.f / 64.f;
//ALERT( at_console, "CPhysManager::Think() time %3.2f\n", pev->nextthink );
}
| 22.413793
| 78
| 0.673846
|
BlueNightHawk4906
|
54571cf0e13f22a286b8c650a63c535529550a82
| 35,187
|
hpp
|
C++
|
include/ext/net/http/http_server.hpp
|
dmlys/netlib
|
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
|
[
"BSL-1.0"
] | 1
|
2018-05-14T13:46:59.000Z
|
2018-05-14T13:46:59.000Z
|
include/ext/net/http/http_server.hpp
|
dmlys/netlib
|
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
|
[
"BSL-1.0"
] | null | null | null |
include/ext/net/http/http_server.hpp
|
dmlys/netlib
|
81627e5f9bea8f1225b1083efa66a8b5dcb9c514
|
[
"BSL-1.0"
] | null | null | null |
#pragma once
#include <memory>
#include <string>
#include <vector>
#include <functional>
#include <iterator>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <boost/container/flat_set.hpp>
#include <boost/container/flat_map.hpp>
#include <ext/config.hpp>
#include <ext/future.hpp>
#include <ext/thread_pool.hpp>
#include <ext/intrusive_ptr.hpp>
#include <ext/library_logger/logger.hpp>
#include <ext/stream_filtering/filter_types.hpp>
#include <ext/openssl.hpp>
#include <ext/net/socket_stream.hpp>
#include <ext/net/socket_queue.hpp>
#include <ext/net/http_parser.hpp>
#include <ext/net/http/http_types.hpp>
#include <ext/net/http/http_server_handler.hpp>
#include <ext/net/http/http_server_filter.hpp>
#include <ext/net/http/nonblocking_http_parser.hpp>
#include <ext/net/http/nonblocking_http_writer.hpp>
namespace ext::net::http
{
/// Simple embedded http server.
/// Listens for incoming connections on given listener sockets,
/// parses http requests, calls registered handler that accepts that request
///
/// supports:
/// * SSL
/// * http_handlers: sync and async(result is returned via ext::future)
/// * http_filters
/// * thread_pool executor
///
/// have 2 working modes(those should not be mixed):
/// * work on current thread(join/interrupt), useful when you want start simple http_server on main thread
/// * work on internal background thread(start/stop), useful when you do not want block main thread in http_server
///
/// NOTE: by default there no preinstalled filters or handlers
class http_server
{
using self_type = http_server;
public:
using handle_type = socket_queue::handle_type;
using duration_type = socket_queue::duration_type;
using time_point = socket_queue::time_point;
using handler_result_type = http_server_handler::result_type;
using simple_handler_result_type = simple_http_server_handler::result_type;
using simple_handler_body_function_type = simple_http_server_handler::body_function_types;
using simple_handler_request_function_type = simple_http_server_handler::request_function_type;
#ifdef EXT_ENABLE_OPENSSL
using SSL = ::SSL;
using ssl_ctx_iptr = ext::openssl::ssl_ctx_iptr;
using ssl_iptr = ext::openssl::ssl_iptr;
#else
using SSL = std::nullptr_t;
using ssl_ctx_iptr = std::nullptr_t;
using ssl_iptr = std::nullptr_t;
#endif
// Internally sockets(both regular and listeners) are handled by ext::net::socket_queue, this class is not thread safe
// (system calls select/poll used by ext::net::socket_queue do not affected by any pthread related functions).
// So we have background thread(internal or joined) running ext::net::socket_queue, whenever some action is performed via public method
// it's submitted into internal task queue -> socket_queue interrupted and all pending queued actions are executed on background thread.
// See m_sock_queue, m_tasks, m_delayed
//
// http_request/socket processing:
// When there is ready socket in socket_queue - it's taken, http_request is read, then action handler is searched and invoked,
// http_response is written back, socket is placed back into the queue or closed.
//
// This whole http processing can be done on executor or, if unset, in background thread.
// http action handlers can be async - return ext::future<http_response>, sync - return ready http_response
//
// Currently http request and response are synchronously processed in executor or background thread -
// while whole http request will not be read, action handler invoked, http response written back - socket will not be placed back into queue,
// and background thread will be busy working with current request/socket, unless processing executor is set.
//
// In case of async special continuation is attached to returned future, it submits special task when http_result future become ready.
// This task continues processing of this http request, writes back response, etc(see m_delayed)
//
// There also pre/post http filters, currently those can't be async, but maybe changed in future.
// Those can be used for some common functionality: zlib processing, authentication, CORS, other.
//
// processing_context:
// When http request is processed - processing context is allocated for it, it holds registered filters, handlers and some helper members.
// Some minimal numbers of contexts are cached and only reinitialized if needed, if there no cached contexts are available - one is allocated.
// When maximum number exceeds - server busy is returned as http answer.
//
// handle_* group:
// http request is handled by handle_* method group. All methods can be overridden, also to allow more customization, each method returns what must be done next:
// handle_request -> handle_prefilters -> .... -> handle_finish
protected:
using process_result = http_server_handler::result_type;
using async_process_result = std::variant<ext::future<http_response>, ext::future<null_response_type>>;
using hook_type = boost::intrusive::list_base_hook<
boost::intrusive::link_mode<boost::intrusive::link_mode_type::normal_link>
>;
class task_base; // inherits hook_type
template <class Functor, class ResultType>
class task_impl; // implements task_base
class delayed_async_executor_task_continuation;
class processing_executor;
template <class ExecutorPtr>
class processing_executor_impl;
class async_http_body_source_impl;
class http_body_streambuf_impl;
protected:
using list_option = boost::intrusive::base_hook<hook_type>;
using task_list = boost::intrusive::list<task_base, list_option, boost::intrusive::constant_time_size<false>>;
using delayed_async_executor_task_continuation_list = boost::intrusive::list<delayed_async_executor_task_continuation, list_option, boost::intrusive::constant_time_size<false>>;
protected:
class closable_http_body;
struct processing_context;
class http_server_control;
/// sort of union of bellow methods;
class handle_method_type;
using regular_handle_methed = auto (http_server::*)(processing_context * context) -> handle_method_type ;
using finalizer_handle_method = void (http_server::*)(processing_context * context);
protected:
using streaming_context = ext::stream_filtering::streaming_context
<
std::vector<std::unique_ptr<ext::stream_filtering::filter>>, // FilterVector
std::vector<ext::stream_filtering::data_context>, // DataContextVector
std::vector<std::vector<char>> // BuffersVector
>;
/// holds some listener context configuration
struct listener_context
{
unsigned backlog;
ssl_ctx_iptr ssl_ctx;
ext::net::listener listener; // valid until it placed into sock_queue
};
struct config_context;
struct filtering_context;
struct filtering_context
{
streaming_context request_streaming_ctx, response_streaming_ctx;
boost::container::flat_map<std::string, http::http_server_control::property> property_map;
};
/// groups some context parameters for processing http request
struct processing_context
{
socket_streambuf sock; // socket where http request came from
ssl_iptr ssl_ptr = nullptr; // ssl session, created from listener ssl context
// socket waiting
socket_queue::wait_type wait_type;
// next method after socket waiting is complete
regular_handle_methed next_method;
// current method that is executed
regular_handle_methed cur_method;
// state used by some handle_methods, value for switch
unsigned async_state = 0;
// should this connection be closed after request processed, determined by Connection header,
// but also - were there errors while processing request.
connection_action_type conn_action = connection_action_type::close;
// byte counters, used in various scenarios
std::size_t read_count; // number of bytes read from socket
std::size_t written_count; // number of bytes written socket
http_server_utils::nonblocking_http_parser parser; // http parser with state
http_server_utils::nonblocking_http_writer writer; // http writer with state
// buffers for filtered and non filtered parsing and writting
std::vector<char> request_raw_buffer, request_filtered_buffer;
std::vector<char> response_raw_buffer, response_filtered_buffer;
std::string chunk_prefix; // buffer for preparing and holding chunk prefix(chunked transfer encoding)
// contexts for filtering request/reply http_body;
std::unique_ptr<filtering_context> filter_ctx;
ext::stream_filtering::processing_parameters filter_params;
http_request request; // current http request, valid after is was parsed
process_result response = null_response; // current http response, valid after handler was called
std::shared_ptr<const config_context> config; // config snapshot
const http_server_handler * handler; // found handler for request
bool expect_extension; // request with Expect: 100-continue header, see RFC7231 section 5.1.1.
bool continue_answer; // context holds answer 100 Continue
bool first_response_written; // wrote first 100-continue
bool final_response_written; // wrote final(possibly second) response
bool response_is_final; // response was marked as final, see http_server_filter_control
std::atomic<ext::shared_state_basic *> executor_state = nullptr; // holds current pending processing execution task state, used for internal synchronization
std::atomic<ext::shared_state_basic *> async_task_state = nullptr; // holds current pending async operation(from handlers), used for internal synchronization
// async_http_body_source/http_body_streambuf closing closer
// allowed values:
// 0x00 - no body closer
// 0x01 - http_server is closing, already set body closer is taken, new should not be installed
// other - some body closer
std::atomic_uintptr_t body_closer = 0;
};
/// holds some configuration parameters sharable by processing contexts
struct config_context
{
/// http filters, handlers can added when http server already started. What if we already processing some request and handler is added?
/// When processing starts - context holds snapshot of currently registered handlers, filters and only they are used; it also handles multithreaded issues.
/// whenever filters, handlers or anything config related changes -> new context is config_context as copy of current is created with dirty set to true.
/// sort of copy on write
unsigned dirty = true;
std::vector<const http_server_handler *> handlers; // http handlers registered in server
std::vector<const http_prefilter *> prefilters; // http prefilters registered in server, sorted by order
std::vector<const http_postfilter *> postfilters; // http postfilters registered in server, sorted by order
/// Maximum bytes read from socket while parsing HTTP request headers, -1 - unlimited.
/// If request headers are not parsed yet, and server read from socket more than maximum_http_headers_size, BAD request is returned
std::size_t maximum_http_headers_size = -1;
/// Maximum bytes read from socket while parsing HTTP body, -1 - unlimited.
/// This affects only simple std::vector<char>/std::string bodies, and never affects stream/async bodies.
/// If server read from socket more than maximum_http_body_size, BAD request is returned
std::size_t maximum_http_body_size = -1;
/// Maximum bytes read from socket while parsing discarded HTTP request, -1 - unlimited.
/// If there is no handler for this request, or some other error code is answered(e.g. unauthorized),
/// this request is considered to be discarded - in this case we still might read it's body,
/// but no more than maximum_discarded_http_body_size, otherwise connection is forcibly closed.
std::size_t maximum_discarded_http_body_size = -1;
};
protected:
socket_queue m_sock_queue; // intenal socket and listener queue
boost::container::flat_map<socket_handle_type, listener_context> m_listener_contexts; // listener contexts map by listener handle
// sharable cow config context, see config_context description
std::shared_ptr<config_context> m_config_context = std::make_shared<config_context>();
ext::library_logger::logger * m_logger = nullptr;
// log level on which http request and reply headers are logged
unsigned m_request_logging_level = -1;
// log level on which http request and reply body are logger, overrides m_request_logging_level if bigger
unsigned m_request_body_logging_level = -1;
// log level on which every read from socket operation buffer is logged
unsigned m_read_buffer_logging_level = -1;
// log level on which every write to socket operation buffer is logged
unsigned m_write_buffer_logging_level = -1;
// processing_contexts
std::size_t m_minimum_contexts = 10;
std::size_t m_maximum_contexts = 128;
// set of existing contexts for which sockets are waiting for read/write state
boost::container::flat_map<socket_streambuf::handle_type, processing_context *> m_pending_contexts;
// set of existing contexts
boost::container::flat_set<processing_context *> m_processing_contexts;
// free contexts that can be reused
std::vector<processing_context *> m_free_contexts;
mutable std::mutex m_mutex;
mutable std::condition_variable m_event;
mutable std::thread m_thread;
std::thread::id m_threadid; // id of thread running tasks and socket queue
// linked list of task
task_list m_tasks;
// delayed tasks are little tricky, for every one - we create a service continuation,
// which when fired, adds task to task_list.
// Those can work and fire when we are being destructed,
// http_server lifetime should not linger on delayed_task - they should become abandoned.
// Nevertheless we have lifetime problem.
//
// So we store those active service continuations in a list:
// - When continuation is fired it checks if it's taken(future internal helper flag):
// * if yes - http_server is gone, nothing to do;
// * if not - http_server is still there - we should add task to a list;
//
// - When destructing we are checking each continuation if it's taken(future internal helper flag):
// * if successful - service continuation is sort of cancelled and it will not access http_server
// * if not - continuation is firing right now somewhere in the middle,
// so destructor must wait until it finishes and then complete destruction.
delayed_async_executor_task_continuation_list m_delayed;
// how many delayed_continuations were not "taken/cancelled" at destruction,
// and how many we must wait - it's sort of a semaphore.
std::size_t m_delayed_count = 0;
// optional http request processing executor
std::shared_ptr<processing_executor> m_processing_executor;
// http_server running state variables
bool m_running = false; // http_server is in running state
bool m_started = false; // http_server is started either by start or join
bool m_joined = false; // used only by join/interrupt pair methods
bool m_interrupted = false; // used only by join/interrupt pair methods
// listeners default backlog
int m_default_backlog = 10;
/// socket HTTP request processing operations(read/write) timeout
duration_type m_socket_timeout = std::chrono::seconds(10);
/// how long socket can be kept open awaiting new incoming HTTP requests
duration_type m_keep_alive_timeout = m_sock_queue.get_default_timeout();
/// timeout for socket operations when closing, basicly affects SSL shutdown
static constexpr duration_type m_close_socket_timeout = std::chrono::milliseconds(100);
static constexpr auto chunkprefix_size = sizeof(int) * CHAR_BIT / 4 + (CHAR_BIT % 4 ? 1 : 0); // in hex
static constexpr std::string_view crlf = "\r\n";
protected:
/// Performs actual startup of http server, blocking
virtual void do_start(std::unique_lock<std::mutex> & lk);
/// Performs actual stopping of http server, blocking
virtual void do_stop (std::unique_lock<std::mutex> & lk);
/// Resets http server to default state: closes all sockets, deletes handlers, filters.
/// Some properties are not reset
virtual void do_reset(std::unique_lock<std::mutex> & lk);
/// clears m_config_context
virtual void do_clear_config(std::unique_lock<std::mutex> & lk);
public:
/// Starts http_server: internal background thread + listeners start listen
virtual void start();
/// Stops http_server: background thread stopped, all sockets are closed, all http handlers, filters are deleted
virtual void stop();
/// Similar to start, but callers thread becomes background one and caller basicly joins it.
/// Useful for simple configurations were you start https_server from main thread
virtual void join();
/// Similar to stop, but must be called if http_server was started via join.
/// Can be called from signal handler.
virtual void interrupt();
protected:
/// Main background thread function, started_promise can be used to propagate exceptions to caller, and notify when actual startup is complete
virtual void run_proc(ext::promise<void> & started_promise);
/// Runs socket_queue until it interrupted.
virtual void run_sockqueue();
/// Reads, parses, process http request and writes http_response back, full cycle for single http request on socket.
virtual void run_socket(processing_context * context);
/// Runs handle_* circuit, updates context->cur_method for regular methods
virtual void executor_handle_runner(handle_method_type next_method, processing_context * context);
/// Submits and schedules processing of async result
virtual void submit_async_executor_task(ext::intrusive_ptr<ext::shared_state_basic> handle, handle_method_type method, processing_context * context);
/// Helper method for creating async handle_method
static auto async_method(ext::intrusive_ptr<ext::shared_state_basic> future_handle, regular_handle_methed async_method) -> handle_method_type;
static auto async_method(socket_queue::wait_type wait, regular_handle_methed async_method) -> handle_method_type;
/// non blocking recv with MSG_PEEK:
/// * if successfully reads something - returns nullptr
/// * if read would block - returns wait_connection operation,
/// * if some error occurs sets it into sock, logs it and returns handle_finish
virtual auto peek(processing_context * context, char * data, int len, int & read) const -> handle_method_type;
/// non blocking recv method:
/// * if successfully reads something - returns nullptr
/// * if read would block - returns wait_connection operation,
/// * if some error occurs sets it into sock, logs it and returns handle_finish
virtual auto recv(processing_context * context, char * data, int len, int & read) const -> handle_method_type;
/// non blocking send method:
/// * if successfully sends something - returns nullptr
/// * if send would block - returns wait_connection operation,
/// * if some error occurs sets it into sock, logs it and returns handle_finish
virtual auto send(processing_context * context, const char * data, int len, int & written) const -> handle_method_type;
/// returns socket send buffer size getsockopt(..., SOL_SOCKET, SO_SNDBUF, ...), but no more that 10 * 1024
virtual std::size_t sendbuf_size(processing_context * context) const;
/// non blocking recv method, read data is parsed with http parser,
/// result is stored in whatever parser body destination is set
/// * if successfully reads something - returns nullptr
/// * if read would block - returns wait_connection operation,
/// * if some error occurs sets it into sock, logs it and returns handle_finish.
virtual auto recv_and_parse(processing_context * context) const -> handle_method_type;
/// same as recv_and_parse, but no more than limit is ever read from socket in total,
/// otherwise bad response is created and http_server::handle_response is returned, connection is closed.
virtual auto recv_and_parse(processing_context * context, std::size_t limit) const -> handle_method_type;
protected:
// http_request processing parts
virtual auto handle_start(processing_context * context) -> handle_method_type;
virtual auto handle_close(processing_context * context) -> handle_method_type;
virtual void handle_finish(processing_context * context);
virtual auto handle_ssl_configuration(processing_context * context) -> handle_method_type;
virtual auto handle_ssl_start_handshake(processing_context * context) -> handle_method_type;
virtual auto handle_ssl_continue_handshake(processing_context * context) -> handle_method_type;
virtual auto handle_ssl_finish_handshake(processing_context * context) -> handle_method_type;
virtual auto handle_ssl_shutdown(processing_context * context) -> handle_method_type;
virtual auto handle_request_headers_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_request_normal_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_request_filtered_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_discarded_request_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_request_normal_async_source_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_request_filtered_async_source_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_parsed_headers(processing_context * context) -> handle_method_type;
virtual auto handle_prefilters(processing_context * context) -> handle_method_type;
virtual auto handle_find_handler(processing_context * context) -> handle_method_type;
virtual auto handle_request_header_processing(processing_context * context) -> handle_method_type;
virtual auto handle_request_init_body_parsing(processing_context * context) -> handle_method_type;
virtual auto handle_parsed_request(processing_context * context) -> handle_method_type;
virtual auto handle_processing(processing_context * context) -> handle_method_type;
virtual auto handle_processing_result(processing_context * context) -> handle_method_type;
virtual auto handle_postfilters(processing_context * context) -> handle_method_type;
virtual auto handle_response(processing_context * context) -> handle_method_type;
virtual auto handle_response_headers_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_headers_written(processing_context * context) -> handle_method_type;
virtual auto handle_response_normal_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_filtered_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_lstream_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_normal_stream_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_filtered_stream_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_normal_async_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_filtered_async_body_writting(processing_context * context) -> handle_method_type;
virtual auto handle_response_written(processing_context * context) -> handle_method_type;
protected: // filtering
virtual void prepare_request_http_body_filtering(processing_context * context);
virtual void filter_request_http_body(processing_context * context);
virtual void prepare_response_http_body_filtering(processing_context * context);
virtual void filter_response_http_body(processing_context * context);
protected:
/// Acquires processing context, one of cached ones, or creates one if allowed. If exhausted - returns null
virtual auto acquire_context() -> processing_context *;
/// Release processing context after http request processed, this method should place this context to cache or delete it, if cache is full
virtual void release_context(processing_context * context);
/// Prepares processing context, called each time new http request should be processed.
/// Makes http handlers and filters snapshots if needed.
virtual void prepare_context(processing_context * context, const socket_streambuf & sock, bool newconn);
/// Called when processing context is created, default implementation does nothing
virtual void construct_context(processing_context * context);
/// Called when processing context is deleted, default implementation does nothing
virtual void destruct_context(processing_context * context);
/// Checks if there is pending context for this socket and returns it, otherwise returns new context via acquire_context()
/// Can return null if maximum number of contexts are created.
virtual auto acquire_context(socket_streambuf & sock) -> processing_context *;
/// Checks if there is pending context for this socket and release it, otherwise does nothing
virtual void release_context(socket_streambuf & sock);
/// Submits socket into internal socket_queue for waiting socket event(readable/writable).
/// When socket will become ready, processing will continue from where it stopped.
/// Should be called from server background thread
virtual void wait_connection(processing_context * context);
/// Submits connection into socket_queue, also sets m_keep_alive_timeout on socket. Should be called from server background thread
virtual void submit_connection(socket_streambuf sock);
/// Closes connection, logs, does some internal cleanup. Should be called from server background thread
virtual void close_connection(socket_streambuf sock);
/// Writes http response to socket, if errors occurs, logs it and returns false
virtual bool write_response(socket_streambuf & sock, const http_response & resp) const;
/// Postprocess ready http response, can be used to do some http headers machinery,
/// called after all http filter are handled, just before writting response.
/// Also called for special answers created via create_*_response.
/// Default implementation tweaks Close and Content-Length
virtual void postprocess_response(http_response & resp) const;
virtual void postprocess_response(processing_context * context) const;
/// Does some response checking, default implementation checks if request http body was fully parsed
/// NOTE: postprocess_response is called separately
virtual void check_response(processing_context * context) const;
/// Exception wrapper for handler.process(request), on exception returns create_internal_server_error_response(sock, request, ex)
virtual auto process_request(socket_streambuf & sock, const http_server_handler & handler, http_request & request) -> process_result;
/// Exception wrapper for getting result from ext::future<http_response>, on exception returns create_internal_server_error_response(sock, request, ex).
/// Also checks if future is cancelled or abandoned.
virtual auto process_ready_response(async_process_result result, socket_streambuf & sock, http_request & request) -> process_result;
/// Searches listener context by listener handle
virtual const listener_context & get_listener_context(socket_handle_type listener_handle) const;
/// Searches acceptable http handler, nullptr if not found
virtual const http_server_handler * find_handler(processing_context & context) const;
protected:
template <class Lock>
void process_tasks(Lock & lock);
template <class Lock, class Task>
auto submit_task(Lock & lk, Task && task) -> ext::future<std::invoke_result_t<std::decay_t<Task>>>;
template <class Task>
auto submit_task(Task && task) -> ext::future<std::invoke_result_t<std::decay_t<Task>>>;
/// submits task for running handle_* circuit
void submit_handler(handle_method_type next_method, processing_context * context);
template <class Lock>
void submit_handler(Lock & lk, handle_method_type next_method, processing_context * context);
protected:
/// obtains current config context, copying one if needed
config_context & current_config();
protected:
virtual auto do_add_listener(listener listener, int backlog, ssl_ctx_iptr ssl_ctx) -> ext::future<void>;
virtual void do_add_handler(std::unique_ptr<const http_server_handler> handler);
virtual void do_add_filter(ext::intrusive_ptr<http_filter_base> filter);
//virtual void do_remove_handler(std::string uri, std::vector<std::string> methods);
protected:
/// Logs http request, checks log levels
virtual void log_request(const http_request & request) const;
/// Logs http response, checks log levels
virtual void log_response(const http_response & response) const;
/// Formats error from error codes, in case of SSL error reads and formats all SSL errors from OpenSSL error queue
virtual std::string format_error(std::error_code errc) const;
/// logs read buffer in hex dump format
virtual void log_read_buffer(handle_type sock_handle, const char * buffer, std::size_t size) const;
/// logs write buffer in hex dump format
virtual void log_write_buffer(handle_type sock_handle, const char * buffer, std::size_t size) const;
/// parses Accept header and returns text/plain and text/html weights
static std::pair<double, double> parse_accept(const http_request & request);
/// Creates HTTP 400 BAD REQUEST answer
virtual http_response create_bad_request_response(const socket_streambuf & sock, connection_action_type conn = connection_action_type::close) const;
/// Creates HTTP 503 Service Unavailable answer
virtual http_response create_server_busy_response(const socket_streambuf & sock, connection_action_type conn = connection_action_type::close) const;
/// Creates HTTP 404 Not found answer
virtual http_response create_unknown_request_response(const socket_streambuf & sock, const http_request & request) const;
/// Creates HTTP 500 Internal Server Error answer, body = Request processing abandoned
virtual http_response create_processing_abondoned_response(const socket_streambuf & sock, const http_request & request) const;
/// Creates HTTP 404 Canceled, body = Request processing cancelled
virtual http_response create_processing_cancelled_response(const socket_streambuf & sock, const http_request & request) const;
/// Creates HTTP 500 Internal Server Error answer
virtual http_response create_internal_server_error_response(const socket_streambuf & sock, const http_request & request, std::exception * ex) const;
/// Creates HTTP 417 Expectation Failed answer
virtual http_response create_expectation_failed_response(const processing_context * context) const;
/// Creates HTTP 100 Continue response
virtual http_response create_continue_response(const processing_context * context) const;
public:
/// Adds http filter(both pre and post if applicable)
virtual void add_filter(ext::intrusive_ptr<http_filter_base> filter);
/// Adds listener with optional SSL configuration
virtual void add_listener(listener listener, ssl_ctx_iptr ssl_ctx = nullptr);
/// Adds opens listener with given backlog with optional SSL configuration
virtual void add_listener(listener listener, int backlog, ssl_ctx_iptr ssl_ctx = nullptr);
/// Adds and opens listener by port number with optional SSL configuration
virtual void add_listener(unsigned short port, ssl_ctx_iptr ssl_ctx = nullptr);
/// Adds http handler
virtual void add_handler(std::unique_ptr<const http_server_handler> handler);
/// Adds simple http handler
virtual void add_handler(std::vector<std::string> methods, std::string url, simple_handler_body_function_type function);
/// Adds simple http handler
virtual void add_handler(std::string url, simple_handler_body_function_type function);
/// Adds simple http handler
virtual void add_handler(std::string method, std::string url, simple_handler_body_function_type function);
/// Adds simple http handler
virtual void add_handler(std::vector<std::string> methods, std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string);
/// Adds simple http handler
virtual void add_handler(std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string);
/// Adds simple http handler
virtual void add_handler(std::string method, std::string url, simple_handler_request_function_type function, http_body_type wanted_request_body_type = http_body_type::string);
public:
/// Configures processing context limits
virtual void set_processing_context_limits(std::size_t minimum, std::size_t maximum);
/// Sets http processing executor
virtual void set_processing_executor(std::shared_ptr<processing_executor> executor);
/// Sets http processing executor to given thread_pool
virtual void set_thread_pool(std::shared_ptr<ext::thread_pool> pool);
public:
void set_socket_timeout(duration_type timeout);
auto get_socket_timeout() const -> duration_type;
void set_keep_alive_timeout(duration_type timeout);
auto get_keep_alive_timeout() const -> duration_type;
public: // limits
void set_maximum_http_headers_size(std::size_t size);
auto get_maximum_http_headers_size() -> std::size_t;
void set_maximum_http_body_size(std::size_t size);
auto get_maximum_http_body_size() -> std::size_t;
void set_maximum_discarded_http_body_size(std::size_t size);
auto get_maximum_discarded_http_body_size() -> std::size_t;
public:
void set_logger(ext::library_logger::logger * logger) { m_logger = logger; m_sock_queue.set_logger(logger); }
auto get_logger() const noexcept { return m_logger; }
void set_request_logging_level(unsigned log_level) noexcept { m_request_logging_level = log_level; }
auto get_request_logging_level() const noexcept { return m_request_logging_level; }
void set_request_body_logging_level(unsigned log_level) noexcept { m_request_body_logging_level = log_level; }
auto get_request_body_logging_level() const noexcept { return m_request_body_logging_level; }
void set_read_buffer_logging_level(unsigned log_level) noexcept { m_read_buffer_logging_level = log_level; }
auto get_read_buffer_logging_level() const noexcept { return m_read_buffer_logging_level; }
void set_write_buffer_logging_level(unsigned log_level) noexcept { m_write_buffer_logging_level = log_level; }
auto get_write_buffer_logging_level() const noexcept { return m_write_buffer_logging_level; }
public:
http_server();
virtual ~http_server();
http_server(http_server && ) = delete;
http_server & operator =(http_server && ) = delete;
};
}
| 55.412598
| 191
| 0.772729
|
dmlys
|
5463d9bb199bab6956d3a9ba142fbd22002a67a9
| 3,707
|
hpp
|
C++
|
hydra/vulkan/pipeline_layout.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | 2
|
2016-09-15T22:29:46.000Z
|
2017-11-30T11:16:12.000Z
|
hydra/vulkan/pipeline_layout.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | null | null | null |
hydra/vulkan/pipeline_layout.hpp
|
tim42/hydra
|
dfffd50a2863695742c0c6122a505824db8be7c3
|
[
"MIT"
] | null | null | null |
//
// file : pipeline_layout.hpp
// in : file:///home/tim/projects/hydra/hydra/vulkan/pipeline_layout.hpp
//
// created by : Timothée Feuillet
// date: Sun Aug 14 2016 13:43:28 GMT+0200 (CEST)
//
//
// Copyright (c) 2016 Timothée Feuillet
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
#ifndef __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__
#define __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__
#include <vulkan/vulkan.h>
#include "../hydra_exception.hpp"
#include "device.hpp"
#include "descriptor_set_layout.hpp"
namespace neam
{
namespace hydra
{
namespace vk
{
/// \brief Wraps a VkPipelineLayout and its creation
/// \note This class is far from being complete
class pipeline_layout
{
public: // advanced
public:
/// \brief Create an empty pipeline layout
pipeline_layout(device &_dev)
: dev(_dev)
{
VkPipelineLayoutCreateInfo plci
{
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
0, nullptr,
0, nullptr
};
check::on_vulkan_error::n_throw_exception(dev._vkCreatePipelineLayout(&plci, nullptr, &vk_playout));
}
/// \brief Create a pipeline layout (without push constants)
pipeline_layout(device &_dev, const std::vector<descriptor_set_layout *> &dsl_vct, const std::vector<VkPushConstantRange> &pc_range_vct = {})
: dev(_dev)
{
std::vector<VkDescriptorSetLayout> vk_dsl_vct;
vk_dsl_vct.reserve(dsl_vct.size());
for (descriptor_set_layout *it : dsl_vct)
vk_dsl_vct.push_back(it->_get_vk_descriptor_set_layout());
VkPipelineLayoutCreateInfo plci
{
VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, nullptr, 0,
(uint32_t)vk_dsl_vct.size(), vk_dsl_vct.data(),
(uint32_t)pc_range_vct.size(), pc_range_vct.data()
};
check::on_vulkan_error::n_throw_exception(dev._vkCreatePipelineLayout(&plci, nullptr, &vk_playout));
}
~pipeline_layout()
{
if (vk_playout)
dev._vkDestroyPipelineLayout(vk_playout, nullptr);
}
public: // advanced
/// \brief Return the VkPipelineLayout
VkPipelineLayout _get_vk_pipeline_layout() const { return vk_playout; }
private:
device &dev;
VkPipelineLayout vk_playout = nullptr;
};
} // namespace vk
} // namespace hydra
} // namespace neam
#endif // __N_4443230312283431824_1717216114_PIPELINE_LAYOUT_HPP__
| 36.70297
| 151
| 0.671702
|
tim42
|
546a11c1b2fb0ea64885541a70df951ecaf43844
| 1,136
|
hpp
|
C++
|
src/common/naive.hpp
|
TNishimoto/rlbwt_iterator
|
f2a4ae0276cb756d2724570def84641449da2f87
|
[
"MIT"
] | null | null | null |
src/common/naive.hpp
|
TNishimoto/rlbwt_iterator
|
f2a4ae0276cb756d2724570def84641449da2f87
|
[
"MIT"
] | null | null | null |
src/common/naive.hpp
|
TNishimoto/rlbwt_iterator
|
f2a4ae0276cb756d2724570def84641449da2f87
|
[
"MIT"
] | null | null | null |
#pragma once
#include <vector>
#include <iostream>
#include <list>
#include <memory>
#include <random>
#include <exception>
#include <algorithm>
#include <fstream>
#include <chrono>
#include <time.h> //#include <stdio.h>
namespace stool
{
class NaiveAlgorithms
{
template <typename INDEX>
static std::vector<INDEX> naive_sa(std::string &text)
{
std::vector<INDEX> sa;
INDEX n = text.size();
sa.resize(n);
for (INDEX i = 0; i < n; i++)
{
sa[i] = i;
}
std::sort(sa.begin(), sa.end(),
[&](const INDEX &x, const INDEX &y) {
INDEX size = x < y ? text.size() - y : text.size() - x;
for (INDEX i = 0; i < size; i++)
{
if ((uint8_t)text[x + i] != (uint8_t)text[y + i])
{
return (uint8_t)text[x + i] < (uint8_t)text[y + i];
}
}
return x <= y ? false : true;
});
return sa;
}
};
} // namespace stool
| 27.047619
| 81
| 0.43662
|
TNishimoto
|
54720cd912f3adf5ecc237fbb8e1ef36829439c1
| 773
|
hpp
|
C++
|
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 10
|
2020-02-17T19:08:46.000Z
|
2021-07-31T11:07:19.000Z
|
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 9
|
2020-02-17T18:15:41.000Z
|
2021-06-06T19:17:34.000Z
|
SDK/ARKSurvivalEvolved_EngramEntry_Toilet_classes.hpp
|
2bite/ARK-SDK
|
c38ca9925309516b2093ad8c3a70ed9489e1d573
|
[
"MIT"
] | 3
|
2020-07-22T17:42:07.000Z
|
2021-06-19T17:16:13.000Z
|
#pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_EngramEntry_Toilet_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass EngramEntry_Toilet.EngramEntry_Toilet_C
// 0x0000 (0x0090 - 0x0090)
class UEngramEntry_Toilet_C : public UPrimalEngramEntry
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass EngramEntry_Toilet.EngramEntry_Toilet_C");
return ptr;
}
void ExecuteUbergraph_EngramEntry_Toilet(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 19.820513
| 106
| 0.626132
|
2bite
|
5472d4010d1eaeaf62637e439bd939e07cee465d
| 28,590
|
cpp
|
C++
|
src/Renderer.cpp
|
smithy545/engine
|
1818a1acafdbc2550b10ef74a215aa41d94edf0f
|
[
"MIT"
] | null | null | null |
src/Renderer.cpp
|
smithy545/engine
|
1818a1acafdbc2550b10ef74a215aa41d94edf0f
|
[
"MIT"
] | null | null | null |
src/Renderer.cpp
|
smithy545/engine
|
1818a1acafdbc2550b10ef74a215aa41d94edf0f
|
[
"MIT"
] | null | null | null |
//
// Created by Philip Smith on 10/17/2020.
//
#include <engine/Renderer.h>
#include <engine/OrbitCam.h>
#include <engine/InstanceList.h>
#include <engine/mesh/Mesh.h>
#include <engine/sprite/ShapeSprite.h>
#include <engine/sprite/TextSprite.h>
#include <engine/sprite/TextureSprite.h>
#include <fmt/format.h>
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <iostream>
#include <utils/file_util.h>
namespace engine {
Renderer::Renderer(entt::registry& registry) {
m_context_entity = registry.create();
registry.emplace<RenderContext>(m_context_entity);
}
bool Renderer::init(entt::registry ®istry) {
// init config
auto& context = registry.get<RenderContext>(m_context_entity);
context.screen_width = 800;
context.screen_height = 600;
context.fovy = 45.0f;
context.z_near = 0.1f;
context.z_far = 10000.0f;
json requested_textures;
json requested_fonts;
try {
// load override from config file if available
auto config_json = utils::file::read_json_file("../res/renderer.json");
if (config_json.contains("width"))
context.screen_width = config_json["width"];
if (config_json.contains("height"))
context.screen_height = config_json["height"];
if(config_json.contains("fovy"))
context.fovy = config_json["fovy"];
if(config_json.contains("z_near"))
context.z_near = config_json["z_near"];
if(config_json.contains("z_far"))
context.z_far = config_json["z_far"];
if(config_json.contains("textures"))
requested_textures = config_json["textures"];
if(config_json.contains("fonts"))
requested_fonts = config_json["fonts"];
} catch (nlohmann::detail::parse_error& e) {
std::cout << "Error reading config file: " << e.what() << std::endl;
}
//init subsystems
if(!init_glfw()) {
std::cerr << "Failed to init GLFW" << std::endl;
return false;
}
if(!init_window(context)) {
std::cerr << "Failed to init window" << std::endl;
return false;
}
if(!init_glew()) {
std::cerr << "Failed to init glew" << std::endl;
return false;
}
if(!init_shaders(context)) {
std::cerr << "Failed to init shaders" << std::endl;
return false;
}
if(!init_fonts(requested_fonts)) {
std::cerr << "Failed to init fonts" << std::endl;
return false;
}
// cull triangles facing away from camera
glEnable(GL_CULL_FACE);
// enable depth buffer
glEnable(GL_DEPTH_TEST);
// background
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
// load textures from config
for(auto info: requested_textures) {
std::string path = info["filepath"];
std::string name = info["name"];
std::cout << "Loading texture '" << name << "' at '" << path << "'" << std::endl;
m_loaded_textures.insert({name, utils::file::read_png_file_to_texture(path)});
}
registry.on_construct<Mesh>().connect<&load_mesh>();
registry.on_construct<ShapeSprite>().connect<&load_shape_sprite>();
registry.on_construct<TextureSprite>().connect<&Renderer::load_texture_sprite>(this);
registry.on_construct<TextSprite>().connect<&Renderer::load_text_sprite>();
registry.on_update<Mesh>().connect<&update_mesh>();
registry.on_update<ShapeSprite>().connect<&update_shape_sprite>();
registry.on_update<TextureSprite>().connect<&Renderer::update_texture_sprite>(this);
registry.on_update<TextSprite>().connect<&Renderer::update_text_sprite>( );
registry.on_destroy<VertexArrayObject>().connect<&destroy_vao>();
registry.on_destroy<InstanceList>().connect<&destroy_instances>();
return true;
}
bool Renderer::init_glfw() {
if (!glfwInit())
return false;
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#if __APPLE__
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
return true;
}
bool Renderer::init_glew() {
glewExperimental = true; // Needed for core profile
if (glewInit() != GLEW_OK) {
glfwTerminate();
return false;
}
return true;
}
bool Renderer::init_fonts(const nlohmann::json& fonts) {
FT_Library ft;
if(FT_Init_FreeType(&ft)) {
std::cerr << "Could not initialize FreeType library" << std::endl;
return false;
}
// enable blending for text transparency
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
for(auto font: fonts) {
auto glyphs = load_font(ft, font["path"], font["size"]);
if(glyphs.empty())
std::cerr << "Could not initialize font from '" << font["path"] << "'" << std::endl;
else
m_loaded_fonts[font["name"]] = glyphs;
}
FT_Done_FreeType(ft);
return true;
}
bool Renderer::init_window(RenderContext& context) {
// Open a window and create its OpenGL context
context.window = glfwCreateWindow(context.screen_width, context.screen_height, "Civil War", nullptr, nullptr);
if (context.window == nullptr) {
std::cerr << "Failed to open GLFW window" << std::endl;
glfwTerminate();
return false;
}
glfwMakeContextCurrent(context.window);
return true;
}
bool Renderer::init_shaders(RenderContext& context) {
auto color_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/color_vert.glsl");
auto color_vshader_src2d = utils::file::read_file_to_string("../res/shaders/vert/color_vert2d.glsl");
auto color_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/color_frag.glsl");
auto tex_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/tex_vert.glsl");
auto tex_vshader_src2d = utils::file::read_file_to_string("../res/shaders/vert/tex_vert2d.glsl");
auto tex_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/tex_frag.glsl");
auto text_vshader_src = utils::file::read_file_to_string("../res/shaders/vert/text_vert.glsl");
auto text_fshader_src = utils::file::read_file_to_string("../res/shaders/frag/text_frag.glsl");
try {
context.color_shader2d = load_shader(color_vshader_src2d.c_str(), color_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "2d color shader failed to init: " << e.what() << std::endl;
return false;
}
try {
context.color_shader3d = load_shader(color_vshader_src.c_str(), color_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "3d color shader failed to init: " << e.what() << std::endl;
return false;
}
try {
context.tex_shader2d = load_shader(tex_vshader_src2d.c_str(), tex_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "2d texture shader failed to init: " << e.what() << std::endl;
return false;
}
try {
context.tex_shader3d = load_shader(tex_vshader_src.c_str(), tex_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "3d texture shader failed to init: " << e.what() << std::endl;
return false;
}
try {
context.text_shader = load_shader(text_vshader_src.c_str(), text_fshader_src.c_str());
} catch (std::runtime_error& e) {
std::cout << "Text shader failed to init: " << e.what() << std::endl;
return false;
}
return true;
}
void Renderer::load_mesh(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec4 = sizeof(glm::vec4);
auto sizeof_vec3 = sizeof(glm::vec3);
auto& mesh = registry.get<Mesh>(entity);
// setup vertex array object
glGenVertexArrays(1, &mesh.vao);
glBindVertexArray(mesh.vao);
// verts
glGenBuffers(1, &mesh.vbo);
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.vertices.size(), &mesh.vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
// colors
glGenBuffers(1, &mesh.cbo);
glBindBuffer(GL_ARRAY_BUFFER, mesh.cbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.colors.size(), &mesh.colors[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
// indices
glGenBuffers(1, &mesh.ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh.indices.size(), &mesh.indices[0],
GL_STATIC_DRAW);
// instance buffer (initially empty)
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ARRAY_BUFFER, ibo);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4));
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
mesh.num_indices = mesh.indices.size();
registry.emplace<InstanceList>(entity, ibo);
glBindVertexArray(0);
}
void Renderer::load_shape_sprite(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec4 = sizeof(glm::vec4);
auto& sprite = registry.get<ShapeSprite>(entity);
// setup vertex array object
glGenVertexArrays(1, &sprite.vao);
glBindVertexArray(sprite.vao);
// verts
glGenBuffers(1, &sprite.vbo);
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec2) * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// colors
glGenBuffers(1, &sprite.cbo);
glBindBuffer(GL_ARRAY_BUFFER, sprite.cbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * sprite.colors.size(), &sprite.colors[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, nullptr);
// indices
glGenBuffers(1, &sprite.ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0],
GL_STATIC_DRAW);
// instance buffer (initially empty)
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ARRAY_BUFFER, ibo);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4));
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
glBindVertexArray(0);
sprite.num_indices = sprite.indices.size();
registry.emplace<InstanceList>(entity, ibo);
}
void Renderer::load_texture_sprite(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec2 = sizeof(glm::vec2);
auto sizeof_vec4 = sizeof(glm::vec4);
auto& sprite = registry.get<TextureSprite>(entity);
// setup vertex array object
glGenVertexArrays(1, &sprite.vao);
glBindVertexArray(sprite.vao);
// verts
glGenBuffers(1, &sprite.vbo);
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// uvs
glGenBuffers(1, &sprite.tex_uvs);
glBindBuffer(GL_ARRAY_BUFFER, sprite.tex_uvs);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.uvs.size(), &sprite.uvs[0], GL_STATIC_DRAW);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
// indices
glGenBuffers(1, &sprite.ebo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0],
GL_STATIC_DRAW);
// texture sampler
sprite.tex_id = m_loaded_textures[sprite.name];
// instance buffer (initially empty)
GLuint ibo;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ARRAY_BUFFER, ibo);
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) 0);
glEnableVertexAttribArray(3);
glVertexAttribPointer(3, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (1 * sizeof_vec4));
glEnableVertexAttribArray(4);
glVertexAttribPointer(4, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (2 * sizeof_vec4));
glEnableVertexAttribArray(5);
glVertexAttribPointer(5, 4, GL_FLOAT, GL_FALSE, 4 * sizeof_vec4, (void *) (3 * sizeof_vec4));
glVertexAttribDivisor(2, 1);
glVertexAttribDivisor(3, 1);
glVertexAttribDivisor(4, 1);
glVertexAttribDivisor(5, 1);
glBindVertexArray(0);
sprite.num_indices = sprite.indices.size();
registry.emplace<InstanceList>(entity, ibo);
}
void Renderer::load_text_sprite(entt::registry ®istry, entt::entity entity) {
auto& sprite = registry.get<TextSprite>(entity);
glGenVertexArrays(1, &sprite.vao);
glGenBuffers(1, &sprite.vbo);
glBindVertexArray(sprite.vao);
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, nullptr, GL_DYNAMIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 4 * sizeof(float), nullptr);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Renderer::update_mesh(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec3 = sizeof(glm::vec3);
auto& mesh = registry.get<Mesh>(entity);
glBindVertexArray(mesh.vao);
// verts
glBindBuffer(GL_ARRAY_BUFFER, mesh.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.vertices.size(), &mesh.vertices[0], GL_STATIC_DRAW);
// colors
glBindBuffer(GL_ARRAY_BUFFER, mesh.cbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * mesh.colors.size(), &mesh.colors[0], GL_STATIC_DRAW);
// indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * mesh.indices.size(), &mesh.indices[0],
GL_STATIC_DRAW);
glBindVertexArray(0);
}
void Renderer::update_shape_sprite(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec3 = sizeof(glm::vec3);
auto sizeof_vec2 = sizeof(glm::vec2);
auto& sprite = registry.get<ShapeSprite>(entity);
glBindVertexArray(sprite.vao);
// verts
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW);
// colors
glBindBuffer(GL_ARRAY_BUFFER, sprite.cbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec3 * sprite.colors.size(), &sprite.colors[0], GL_STATIC_DRAW);
// indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0],
GL_STATIC_DRAW);
glBindVertexArray(0);
}
void Renderer::update_texture_sprite(entt::registry ®istry, entt::entity entity) {
auto sizeof_vec2 = sizeof(glm::vec2);
auto& sprite = registry.get<TextureSprite>(entity);
glBindVertexArray(sprite.vao);
// verts
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.vertices.size(), &sprite.vertices[0], GL_STATIC_DRAW);
// uvs
glBindBuffer(GL_ARRAY_BUFFER, sprite.tex_uvs);
glBufferData(GL_ARRAY_BUFFER, sizeof_vec2 * sprite.uvs.size(), &sprite.uvs[0], GL_STATIC_DRAW);
// indices
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, sprite.ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(unsigned int) * sprite.indices.size(), &sprite.indices[0],
GL_STATIC_DRAW);
// texture sampler
sprite.tex_id = m_loaded_textures[sprite.name];
glBindVertexArray(0);
}
void Renderer::update_text_sprite(entt::registry ®istry, entt::entity entity) {}
void Renderer::destroy_vao(entt::registry ®istry, entt::entity entity) {
auto vao = registry.get<VertexArrayObject>(entity);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
glBindVertexArray(0);
if(vao.vao)
glDeleteVertexArrays(1, &vao.vao);
if(vao.vbo)
glDeleteBuffers(1, &vao.vbo);
if(vao.ebo)
glDeleteBuffers(1, &vao.ebo);
if(vao.cbo)
glDeleteBuffers(1, &vao.cbo);
if(vao.tex_id)
glDeleteTextures(1, &vao.tex_id);
if(vao.tex_uvs)
glDeleteBuffers(1, &vao.tex_uvs);
}
void Renderer::destroy_instances(entt::registry ®istry, entt::entity entity) {
auto instances = registry.get<InstanceList>(entity);
if(instances.id)
glDeleteBuffers(1, &instances.id);
}
void Renderer::render(entt::registry ®istry, const Camera::Ptr& camera) {
const auto& ctx = registry.get<RenderContext>(m_context_entity);
glm::mat4 vp;
// 3D rendering
if(camera != nullptr) {
vp = glm::perspective(ctx.fovy, ctx.screen_width / ctx.screen_height, ctx.z_near, ctx.z_far) * camera->get_view();
glUseProgram(ctx.color_shader3d);
glUniformMatrix4fv(glGetUniformLocation(ctx.color_shader3d, "VP"), 1, GL_FALSE, &vp[0][0]);
auto view3d = registry.view<Mesh, InstanceList>();
for (const auto &entity: view3d) {
auto[mesh, ilist] = view3d.get(entity);
if (mesh.visible) {
glBindVertexArray(mesh.vao);
glDrawElementsInstanced(ilist.render_strategy, mesh.num_indices, GL_UNSIGNED_INT, 0,
ilist.instances.size());
}
}
}
// 2D rendering (TODO: Add occlusion culling to prevent drawing 3D entities that are covered by 2D elements)
vp = glm::ortho(0.f, ctx.screen_width, ctx.screen_height, 0.f);
glUseProgram(ctx.color_shader2d);
glUniformMatrix4fv(glGetUniformLocation(ctx.color_shader2d, "VP"), 1, GL_FALSE, &vp[0][0]);
auto color_view = registry.view<ShapeSprite, InstanceList>();
for(const auto &entity: color_view) {
auto [sprite, ilist] = color_view.get(entity);
if(sprite.visible) {
glBindVertexArray(sprite.vao);
glDrawElementsInstanced(ilist.render_strategy, sprite.num_indices, GL_UNSIGNED_INT, 0,
ilist.instances.size());
}
}
// texture rendering
glUseProgram(ctx.tex_shader2d);
glUniformMatrix4fv(glGetUniformLocation(ctx.tex_shader2d, "VP"), 1, GL_FALSE, &vp[0][0]);
glUniform1i(glGetUniformLocation(ctx.tex_shader2d, "texSampler"), 0);
auto tex_view = registry.view<TextureSprite, InstanceList>();
for(const auto &entity: tex_view) {
auto [sprite, ilist] = tex_view.get(entity);
if(sprite.visible) {
glBindVertexArray(sprite.vao);
glBindTexture(GL_TEXTURE_2D, sprite.tex_id);
glDrawElementsInstanced(ilist.render_strategy, sprite.num_indices, GL_UNSIGNED_INT, 0,
ilist.instances.size());
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
}
}
// text rendering
glUseProgram(ctx.text_shader);
glUniformMatrix4fv(glGetUniformLocation(ctx.text_shader, "VP"), 1, GL_FALSE, &vp[0][0]);
glUniform1i(glGetUniformLocation(ctx.text_shader, "texSampler"), 0);
auto text_view = registry.view<TextSprite>();
for(const auto &entity: text_view) {
auto [sprite] = text_view.get(entity);
if(sprite.visible) {
if(!m_loaded_fonts.contains(sprite.font))
std::cerr << "Can't render sprite with unloaded font '" << sprite.font << "'" << std::endl;
else {
glUniform3f(glGetUniformLocation(ctx.text_shader, "textColor"),
sprite.color.x, sprite.color.y, sprite.color.z);
auto x = sprite.x;
for(std::string::const_iterator c = sprite.text.begin(); c != sprite.text.end(); c++) {
if(!m_loaded_fonts[sprite.font].contains(*c)) {
std::cerr << "Todo: add 404 texture. Error on '" << *c << "'"<< std::endl;
continue;
}
auto glyph = m_loaded_fonts[sprite.font][*c];
float xpos = x + glyph.bearing.x * sprite.scale;
float ypos = sprite.y - (glyph.size.y - glyph.bearing.y) * sprite.scale;
float w = glyph.size.x * sprite.scale;
float h = glyph.size.y * sprite.scale;
// update VBO for each character
float vertices[6][4] = {
{ xpos, ypos - h, 0.0f, 0.0f },
{ xpos, ypos, 0.0f, 1.0f },
{ xpos + w, ypos, 1.0f, 1.0f },
{ xpos, ypos - h, 0.0f, 0.0f },
{ xpos + w, ypos, 1.0f, 1.0f },
{ xpos + w, ypos - h, 1.0f, 0.0f }
};
glBindVertexArray(sprite.vao);
// render glyph texture over quad
glBindTexture(GL_TEXTURE_2D, glyph.tex_id);
// update content of VBO memory
glBindBuffer(GL_ARRAY_BUFFER, sprite.vbo);
glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(vertices), vertices);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// render quad
glDrawArrays(GL_TRIANGLES, 0, 6);
// now advance cursors for next glyph (note that advance is number of 1/64 pixels)
x += (glyph.advance >> 6) * sprite.scale; // bitshift by 6 to get value in pixels (2^6 = 64)
glBindTexture(GL_TEXTURE_2D, 0);
glBindVertexArray(0);
}
}
}
}
glUseProgram(0);
}
void Renderer::cleanup(entt::registry ®istry) {
const auto& ctx = registry.get<RenderContext>(m_context_entity);
glDeleteProgram(ctx.color_shader2d);
glDeleteProgram(ctx.color_shader3d);
glDeleteProgram(ctx.tex_shader2d);
glDeleteProgram(ctx.tex_shader3d);
glDeleteProgram(ctx.text_shader);
glfwTerminate();
}
const RenderContext& Renderer::get_context(entt::registry& registry) const {
return registry.get<RenderContext>(m_context_entity);
}
GLuint Renderer::load_shader(const char* vertex_source, const char* frag_source) {
int vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertex_shader, 1, &vertex_source, nullptr);
glCompileShader(vertex_shader);
int success;
char infoLog[512];
glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(vertex_shader, 512, nullptr, infoLog);
std::string message = fmt::format("Error on vertex compilation ", infoLog);
throw std::runtime_error(message.c_str());
}
int fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragment_shader, 1, &frag_source, nullptr);
glCompileShader(fragment_shader);
glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
if (!success) {
glGetShaderInfoLog(fragment_shader, 512, nullptr, infoLog);
std::string message = fmt::format("Error on fragment compilation ", infoLog);
throw std::runtime_error(message.c_str());
}
auto shader = glCreateProgram();
glAttachShader(shader, vertex_shader);
glAttachShader(shader, fragment_shader);
glLinkProgram(shader);
glValidateProgram(shader);
glGetProgramiv(shader, GL_LINK_STATUS, &success);
if (!success) {
glGetProgramInfoLog(shader, 512, nullptr, infoLog);
std::string message = fmt::format("Error linking program ", infoLog);
throw std::runtime_error(message.c_str());
}
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
return shader;
}
std::map<unsigned long, Renderer::Glyph> Renderer::load_font(FT_Library ft,
const std::string& fontfile,
unsigned int font_size,
const std::string& text) {
std::cout << "Loading font at '" << fontfile << "'" << std::endl;
FT_Face face;
if(FT_New_Face(ft, fontfile.c_str(), 0, &face)) {
std::cerr << "Could not initialize font from file at " << fontfile << std::endl;
FT_Done_Face(face);
return {};
}
// set size to load glyphs as
FT_Set_Pixel_Sizes(face, 0, font_size);
// disable byte-alignment restriction
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
std::map<unsigned long, Glyph> glyphs;
for (unsigned char c: text) {
if(glyphs.contains(c))
continue;
if (FT_Load_Char(face, c, FT_LOAD_RENDER)) {
std::cout << "ERROR::FREETYTPE: Failed to load Glyph '" << c << "'" << std::endl;
continue;
}
// generate texture
unsigned int texture;
glGenTextures(1, &texture);
glBindTexture(GL_TEXTURE_2D, texture);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RED,
face->glyph->bitmap.width,
face->glyph->bitmap.rows,
0,
GL_RED,
GL_UNSIGNED_BYTE,
face->glyph->bitmap.buffer);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
Glyph glyph = {
texture,
glm::ivec2(face->glyph->bitmap.width, face->glyph->bitmap.rows),
glm::ivec2(face->glyph->bitmap_left, face->glyph->bitmap_top),
static_cast<unsigned int>(face->glyph->advance.x)
};
glyphs.insert({c, glyph});
}
glBindTexture(GL_TEXTURE_2D, 0);
// destroy FreeType once we're finished
FT_Done_Face(face);
return glyphs;
}
} // namespace engine
| 42.863568
| 123
| 0.619203
|
smithy545
|
5473a402d01ac1bead5979450f8b478098257405
| 1,972
|
cpp
|
C++
|
test2.cpp
|
jhxqy/WebServerDemo
|
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
|
[
"MIT"
] | null | null | null |
test2.cpp
|
jhxqy/WebServerDemo
|
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
|
[
"MIT"
] | null | null | null |
test2.cpp
|
jhxqy/WebServerDemo
|
5fce6dcbda875f61c96e7952b063e34b8ae6cb29
|
[
"MIT"
] | null | null | null |
//
// test2.cpp
// EZasync
//
// Created by 贾皓翔 on 2019/6/5.
// Copyright © 2019 贾皓翔. All rights reserved.
//
#include <stdio.h>
#include "asynchttp/HTTP.hpp"
using namespace std;
using namespace HTTP;
int main(){
IOContext ctx;
Serv s(ctx,"8088");
HttpDispatcher *http=HttpDispatcherImpl::Create();
http->SetDefaultPath("./web");
http->Register("/hello", [](RequestBody &request,ResponseBody &response){
response.status=200;
response.otherHeaders_["Content-Type"]="text/html";
response.out("hello Nice my HTTP!");
});
http->Register("/world", [](RequestBody &request,ResponseBody &response){
response.status=200;
response.otherHeaders_["Content-Type"]="text/html;charset=utf-8";
for(auto i:request.headers_){
response.out("%s:%s<br>",i.first.c_str(),i.second.c_str());
}
for(auto i:request.cookies_){
response.out("%s=%s<br>",i.first.c_str(),i.second.c_str());
}
});
http->Register("/jump", [](RequestBody &request,ResponseBody &response){
response.sendRedirect("/world");
});
http->Register("/param", [](RequestBody &request,ResponseBody& response){
response.out("param:%s",request.parameters.c_str());
});
http->Register("/forward", [](RequestBody &req,ResponseBody &res){
res.out("这是跳转前第一个接口<br>");
res.forward(req,"/world");
});
http->RegisterFilter("/hello", [](RequestBody &request,ResponseBody &response){
cout<<"调用第一个过滤器!"<<endl;
return FILTER_NEXT;
});
http->RegisterFilter("/index.html", [](RequestBody &request,ResponseBody &response){
if (request.parameters.compare("hello")!=0) {
cout<<request.parameters<<endl;
response.forward(request, "/hello");
return FILTER_END;
}
cout<<"NICE!"<<endl;
return FILTER_NEXT;
});
ctx.run();
}
| 31.301587
| 88
| 0.591785
|
jhxqy
|
54802c98caf4d2337d84f7b53369a0cc6d201cb7
| 334
|
cpp
|
C++
|
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
|
mklabs/ue-xelu-icons
|
4aaf54ecb9533fc3689f457b280b79293b861b47
|
[
"MIT"
] | 5
|
2022-02-01T22:49:51.000Z
|
2022-03-03T10:18:36.000Z
|
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
|
mklabs/ue-xelu-icons
|
4aaf54ecb9533fc3689f457b280b79293b861b47
|
[
"MIT"
] | 1
|
2022-01-31T23:09:04.000Z
|
2022-01-31T23:09:04.000Z
|
Source/XeluIcons/Private/XeluIconsDeveloperSettings.cpp
|
mklabs/ue-xelu-icons
|
4aaf54ecb9533fc3689f457b280b79293b861b47
|
[
"MIT"
] | null | null | null |
// Copyright 2022 Mickael Daniel. All Rights Reserved.
#include "XeluIconsDeveloperSettings.h"
UXeluIconsDeveloperSettings::UXeluIconsDeveloperSettings()
{
IconsDataTable = FSoftObjectPath(TEXT("/XeluIcons/DT_Xelu_Icons.DT_Xelu_Icons"));
}
FName UXeluIconsDeveloperSettings::GetCategoryName() const
{
return FName("Plugins");
}
| 22.266667
| 82
| 0.805389
|
mklabs
|
54873d2ce7769081b8be72c41d3903efc133f45d
| 155
|
cpp
|
C++
|
src/Zadanie20.cpp
|
radzbydzi/Podstawy-Programowania
|
c97e72fd2fc0ecf3a88b0095cc409802be009013
|
[
"Unlicense"
] | null | null | null |
src/Zadanie20.cpp
|
radzbydzi/Podstawy-Programowania
|
c97e72fd2fc0ecf3a88b0095cc409802be009013
|
[
"Unlicense"
] | null | null | null |
src/Zadanie20.cpp
|
radzbydzi/Podstawy-Programowania
|
c97e72fd2fc0ecf3a88b0095cc409802be009013
|
[
"Unlicense"
] | null | null | null |
#include "Zadanie20.h"
Zadanie20::Zadanie20()
{
}
Zadanie20::~Zadanie20()
{
}
void Zadanie20::run()
{
cout<<"Zadanie20"<<endl<<endl;
pokazTresc();
}
| 9.117647
| 31
| 0.645161
|
radzbydzi
|
54888c9318b3b338b8652db0a9750d917d1eef3b
| 297
|
hpp
|
C++
|
include/RegularExpressionMatching.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 43
|
2015-10-10T12:59:52.000Z
|
2018-07-11T18:07:00.000Z
|
include/RegularExpressionMatching.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | null | null | null |
include/RegularExpressionMatching.hpp
|
yanzhe-chen/LeetCode
|
d82f0b9721ea613ab216c78e7286671d0e9e4187
|
[
"MIT"
] | 11
|
2015-10-10T14:41:11.000Z
|
2018-07-28T06:03:16.000Z
|
#ifndef REGULAR_EXPRESSION_MATCHING_HPP_
#define REGULAR_EXPRESSION_MATCHING_HPP_
#include <string>
using namespace std;
class RegularExpressionMatching {
public:
bool isMatch(string s, string p);
private:
bool isMatch(char _s, char _p);
};
#endif // REGULAR_EXPRESSION_MATCHING_HPP_
| 17.470588
| 42
| 0.787879
|
yanzhe-chen
|
5489c5139f0a48c5e723f63b2936a0cfd0342dfb
| 995
|
cpp
|
C++
|
workbench/src/event.cpp
|
MasterQ32/cg-workbench
|
3d6229b961192689e6dbd0a09ec4b61041ecb155
|
[
"MIT"
] | 5
|
2017-12-27T12:57:36.000Z
|
2021-10-02T03:21:40.000Z
|
workbench/src/event.cpp
|
MasterQ32/cg-workbench
|
3d6229b961192689e6dbd0a09ec4b61041ecb155
|
[
"MIT"
] | 9
|
2020-09-29T22:40:49.000Z
|
2020-10-17T20:05:05.000Z
|
workbench/src/event.cpp
|
MasterQ32/cg-workbench
|
3d6229b961192689e6dbd0a09ec4b61041ecb155
|
[
"MIT"
] | null | null | null |
#include "event.hpp"
#include <SDL.h>
#include "sink.hpp"
timestamp_t Event::system_time;
Event::Event() :
current(system_time - 10000), // 10 seconds ago...
counter(0)
{
}
void Event::Trigger()
{
this->triggered = true;
this->current = system_time;
this->counter += 1;
}
void Event::Reset()
{
this->counter = 0;
}
float Event::GetTimeSinceLastTrigger() const
{
return (system_time - this->current) / 1000.0;
}
void Event::NewFrame()
{
system_time = SDL_GetTicks();
}
bool Event::Any(Sink * sink)
{
if(sink == nullptr)
return false;
assert(sink->GetType() == CgDataType::Event);
for(int i = 0; i < sink->GetSourceCount(); i++)
{
if(sink->GetObject<CgDataType::Event>(i))
return true;
}
return false;
}
int Event::Count(Sink * sink)
{
if(sink == nullptr)
return false;
assert(sink->GetType() == CgDataType::Event);
int cnt = 0;
for(int i = 0; i < sink->GetSourceCount(); i++)
{
if(sink->GetObject<CgDataType::Event>(i))
++cnt;
}
return cnt;
}
| 15.307692
| 54
| 0.638191
|
MasterQ32
|
548bc5e3181dfac55df4e56c841997aa1b26ed76
| 8,428
|
hpp
|
C++
|
source/list.hpp
|
saJonMR/programmiersprachen_aufgabenblatt_3
|
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
|
[
"MIT"
] | null | null | null |
source/list.hpp
|
saJonMR/programmiersprachen_aufgabenblatt_3
|
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
|
[
"MIT"
] | null | null | null |
source/list.hpp
|
saJonMR/programmiersprachen_aufgabenblatt_3
|
2d02c2da6389cc152986aa55ffce91f86ff8b6e3
|
[
"MIT"
] | null | null | null |
#ifndef BUW_LIST_HPP
#define BUW_LIST_HPP
#include <cassert>
#include <cstddef> //ptrdiff_t
#include <iterator> //std::bidirectional_iterator_tag
#include <iostream>
#include <initializer_list>
template <typename T>
class List;
template <typename T>
struct ListNode {
T value = T{};
ListNode* prev = nullptr;
ListNode* next = nullptr;
};
//TODO: Implementierung der Methoden des Iterators
// (nach Vorlesung STL-1 am 09. Juni) (Aufgabe 3.11)
template <typename T>
struct ListIterator {
using Self = ListIterator<T>;
using value_type = T;
using pointer = T*;
using reference = T&;
using difference_type = ptrdiff_t;
using iterator_category = std::bidirectional_iterator_tag;
/* Returns Reference to Value of current Node */
T& operator*() const {
if(nullptr == node) {
throw "Iterator does not point to valid node";
}
return node->value;
} //call *it
/* Returns pointer to Reference of current node */
T* operator->() const {
if(nullptr == node) {
throw "Iterator does not point to valid node";
}
return &node->value;
} //call it->method() or it->member
/* PREINCREMENT, call: ++it, advances one element forward */
ListIterator<T>& operator++() {
if(nullptr == node) {
throw "Iterator does not point to valid node";
}
node = node->next;
return *this;
}
/* POSTINCREMENT (signature distinguishes the iterators),
call: it++, advances one element forward*/
ListIterator<T> operator++(int) {
if(nullptr == node) {
throw "Iterator does not point to valid node";
}
auto newit = *this;
++*this;
return newit;
}
/* Compares Values of Both Nodes */
bool operator==(ListIterator<T> const& x) const {
if(x.node == node) {
return true;
}
return false;
} // call it: == it
/* Compares Values of Both Nodes */
bool operator!=(ListIterator<T> const& x) const {
if(x.node != node) {
return true;
}
return false;
} // call it: != it
/* Advances Iterator */
ListIterator<T> next() const {
if (nullptr != node) {
return ListIterator{node->next};
} else {
return ListIterator{nullptr};
}
}
ListNode <T>* node = nullptr;
};
template <typename T>
class List {
public:
//friend declarations for testing the members
template <typename TEST_TYPE>
friend size_t get_size(List<TEST_TYPE> const& list_to_test);
template <typename TEST_TYPE>
friend ListNode<TEST_TYPE>* get_first_pointer(List<TEST_TYPE> const& list_to_test);
template <typename TEST_TYPE>
friend ListNode<TEST_TYPE>* get_last_pointer(List<TEST_TYPE> const& list_to_test);
using value_type = T;
using pointer = T*;
using const_pointer = T const*;
using reference = T&;
using const_reference = T const&;
using iterator = ListIterator<T>;
/* Initializes the List with size_ = 0 and both the first and the last node pointing to null */
List()=default;
//Copy Constructor (Deep Copy)
/* Initializes a new empty List and copies (deep) the elements of the input List until it reaches the last node */
List(List<T> const& l) :
size_{0},
first_{nullptr},
last_{nullptr }
{
ListNode<T> *node = l.first_;
while(node != nullptr) {
push_back(node->value);
node = node->next;
}
}
//TODO: Initializer-List Konstruktor (3.14 - Teil 1)
/* ... */
// test and implement:
List(std::initializer_list<T> ini_list) {
//not implemented yet
}
/* Unifying Assignment Operator */
/* Makes Use of Swap function to Assign Pointers and Size */
List& operator=(List rhs) {
swap(rhs);
return *this;
}
//swap function that swaps the first_ and last_ pointers as well as size_
void swap(List& rhs) {
std::swap(first_, rhs.first_);
std::swap(last_, rhs.last_);
std::swap(size_, rhs.size_);
}
/* ... */
// test and implement:
bool operator==(List const& rhs) {
bool status = false;
if(size_ == rhs.size_) {
status = true;
ListNode<T> *nodelhs = first_;
ListNode<T> *noderhs = rhs.first_;
while(nodelhs != nullptr && status) {
if(nodelhs->value == noderhs->value) {
nodelhs = nodelhs->next;
noderhs = noderhs->next;
} else {
status = false;
}
}
}
return status;
}
bool operator!=(List const& rhs)
{
if(*this == rhs) {
return false;
} else {
return true;
}
}
/* calls clear function */
~List() {
clear();
} //can not really be tested
/* Returns iterator that points to first node */
ListIterator<T> begin() {
auto begin = first_;
return {begin};
}
/* Returns iterator that points behind last node (nullptr) */
ListIterator<T> end() {
auto end = nullptr;
return {end};
}
/* Calls pop_front until first_ = last_ and then pops the last element indivdually */
void clear() {
while(size_ > 0) {
pop_back();
}
}
/* ... */
//TODO: member function insert (Aufgabe 3.12)
/* ... */
//TODO: member function insert (Aufgabe 3.13)
/* Reverses List by changing the direction of the pointers, from front to back*/
//TODO: member function reverse (Aufgabe 3.7 - Teil 1)
void reverse() {
ListNode<T> *node = last_;
last_ = first_;
first_ = node;
while(node != nullptr) {
std::swap(node->next, node->prev);
node = node->next;
}
}
/* Insert Element at the front of the List */
void push_front(T const& element) {
ListNode<T> *node = new ListNode<T>{element};
if (first_ == nullptr) {
first_ = node;
last_ = node;
node->next = nullptr;
node->prev = nullptr;
} else {
node->next = first_;
first_->prev = node;
first_ = node;
}
size_++;
}
/* Insert Element at the back of the List */
void push_back(T const& element) {
ListNode<T> *node = new ListNode<T>{element};
if (first_ == nullptr) {
first_ = node;
last_ = node;
node->next = nullptr;
node->prev = nullptr;
} else {
last_->next = node;
node->prev = last_;
last_ = node;
}
size_++;
}
/* Checks if list has one or more than one item and adjusts pointers */
void pop_front() {
if(empty()) {
throw "List is empty";
}
if(first_ == last_) {
first_ = nullptr;
last_ = nullptr;
} else {
ListNode<T> *newFirst = first_->next;
first_->next = nullptr;
delete first_;
first_ = newFirst;
first_->prev = nullptr;
}
size_--;
}
/* Checks if list has one or more than one item and adjusts pointers */
void pop_back() {
if(empty()) {
throw "List is empty";
}
if(first_ == last_) {
first_ = nullptr;
last_ = nullptr;
} else {
ListNode<T> *newLast = last_->prev;
last_->prev = nullptr;
delete last_;
last_ = newLast;
last_->next = nullptr;
}
size_--;
}
/* returns value of first node */
T& front() {
if(empty()) {
throw "List is empty";
}
return first_->value;
}
/* returns value of last node */
T& back() {
if(empty()) {
throw "List is empty";
}
return last_->value;
}
/* Returns wether List is empty or not*/
bool empty() const {
return size_ == 0;
};
/* Size */
std::size_t size() const{
return size_;
};
// list members
private:
std::size_t size_ = 0;
ListNode<T>* first_ = nullptr;
ListNode<T>* last_ = nullptr;
};
/* Makes use of member function reverse - takes a List as input and returns a new one */
//TODO: Freie Funktion reverse
//(Aufgabe 3.7 - Teil 2, benutzt Member-Funktion reverse)
template<typename T>
List<T> reverse(List<T> const& list) {
List<T> newL = list;
newL.reverse();
return newL;
}
/* ... */
//TODO: Freie Funktion operator+ (3.14 - Teil 2)
#endif // # define BUW_LIST_HPP
| 24.218391
| 118
| 0.568818
|
saJonMR
|
548d738958b13f8c71e2e4d7c9fec12a2f52df80
| 316
|
cpp
|
C++
|
Source/HippoQOR/do_wrapper.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 9
|
2016-05-27T01:00:39.000Z
|
2021-04-01T08:54:46.000Z
|
Source/HippoQOR/do_wrapper.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 1
|
2016-03-03T22:54:08.000Z
|
2016-03-03T22:54:08.000Z
|
Source/HippoQOR/do_wrapper.cpp
|
mfaithfull/QOR
|
0fa51789344da482e8c2726309265d56e7271971
|
[
"BSL-1.0"
] | 4
|
2016-05-27T01:00:43.000Z
|
2018-08-19T08:47:49.000Z
|
//do_wrapper.cpp
#include "HippoQOR/do_wrapper.h"
//--------------------------------------------------------------------------------
namespace nsUnitTesting
{
//--------------------------------------------------------------------------------
VirtualDestructable::~VirtualDestructable()
{
}
}//nsUnitTesting
| 22.571429
| 83
| 0.35443
|
mfaithfull
|
5496e5f2c2d9d4d1c0f06af597e04c1a5be7b8db
| 30,774
|
hpp
|
C++
|
include/misc.hpp
|
harith-alsafi/statistic-model-cpp
|
0883f208ff6dcdc6634b95e88b92e9097bd76475
|
[
"Condor-1.1",
"Naumen",
"Xnet",
"X11",
"MS-PL"
] | null | null | null |
include/misc.hpp
|
harith-alsafi/statistic-model-cpp
|
0883f208ff6dcdc6634b95e88b92e9097bd76475
|
[
"Condor-1.1",
"Naumen",
"Xnet",
"X11",
"MS-PL"
] | null | null | null |
include/misc.hpp
|
harith-alsafi/statistic-model-cpp
|
0883f208ff6dcdc6634b95e88b92e9097bd76475
|
[
"Condor-1.1",
"Naumen",
"Xnet",
"X11",
"MS-PL"
] | null | null | null |
#pragma once
#include <vector>
#include <string>
#include <iostream>
#include <fstream>
/**
* @file misc.hpp
* @author Harith Al-Safi
* @brief
* @version 0.1
* @date 2021-12-10
*
* @copyright Copyright (c) 2021
*
*/
#include <algorithm>
#include <numeric>
#include "graphs.hpp"
/**
* @brief Operator to multiply two vectors
*
* @tparam TYPE
* @param first
* @param second
* @return std::vector<TYPE>
*/
template<typename TYPE>
std::vector<TYPE> operator *(std::vector<TYPE> first, std::vector<TYPE> second){
if(first.size() != second.size()){
throw std::invalid_argument("Invalid size");
}
std::vector<TYPE> temp;
for(int i = 0; i < first.size(); i++){
temp.push_back(first[i]*second[i]);
}
return temp;
}
/**
* @brief Overloads the round function
*
* @tparam TYPE
* @param a the value itself
* @param dp number of decimal places
* @return TYPE
*/
template<typename TYPE>
TYPE round(TYPE a, int dp = 0){
if(a < TYPE(0)){
return TYPE((int)(a*pow(10, dp)-.5)/pow(10, dp));
}
return TYPE((int)(a*pow(10, dp)+.5)/pow(10, dp));
}
namespace misc
{
/**
* @brief Genarate vector from min, max andn number of points
*
* @tparam TYPE
* @param mn min val
* @param mx max val
* @param n number of points
* @return std::vector<TYPE>
*/
template<typename TYPE>
std::vector<TYPE> generate_vector(TYPE mn, TYPE mx, int n){
std::vector<TYPE> v;
for(TYPE i = mn; i <= mx; i+=(TYPE)(mx-mn)/n){
v.push_back(i);
}
return v;
}
/**
* @brief Table class to contain the dataframe
*/
class Table: public std::vector<std::vector<long double>>
{
public:
/**
* @brief Struct to contain the quartile range
*
*/
struct QR
{
/**
* @brief Lower quartile
*
*/
long double LQ;
/**
* @brief Q1 (25%)
*
*/
long double Q1;
/**
* @brief Q2 (50%)
*
*/
long double Q2;
/**
* @brief Q3 (75%)
*
*/
long double Q3;
/**
* @brief Upper quartile
*
*/
long double UQ;
};
private:
/**
* @brief Checks the header and returns index
*
* @param head
* @return int
*/
int check_header(std::string head){
for(int i = 0; i < headers.size(); i++){
if(headers[i] == head){
return i;
}
}
return -1;
}
/**
* @brief Get the col vector based on header name
*
* @param headname
* @return std::vector<long double>
*/
std::vector<long double> get_col_(std::string headname){
int j = check_header(headname);
std::vector<long double> a;
if(j >= 0){
for(int i = 0; i < size(); i++){
a.push_back(at(i).at(j));
}
}
return a;
}
/**
* @brief Get the return average of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<long double> get_avgs(){
std::vector<long double> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_avg(get_col_(headers[j])));
}
return a;
}
/**
* @brief Get the return std of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<long double> get_stds(){
std::vector<long double> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_std(get_col_(headers[j])));
}
return a;
}
/**
* @brief Get the return variance of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<long double> get_vars(){
std::vector<long double> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_var(get_col_(headers[j])));
}
return a;
}
/**
* @brief Get the return quartile range of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<QR> get_qrs(){
std::vector<QR> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_qr(get_col_(headers[j])));
}
return a;
}
/**
* @brief Get the return sums of all colums in vector
*
* Used in describe_all()
*
* @return std::vector<long double>
*/
std::vector<long double> get_sums(){
std::vector<long double> a;
for(int j = 0; j < headers.size(); j++){
a.push_back(get_sum(get_col_(headers[j])));
}
return a;
}
/**
* @brief Re-centers a string based on given width
*
* @param s
* @param w
* @return std::string
*/
static std::string center(const string s, const int w) {
std::stringstream ss, spaces;
int padding = w - s.size(); // count excess room to pad
for(int i=0; i<padding/2; ++i)
spaces << " ";
ss << spaces.str() << s << spaces.str(); // format with padding
if(padding>0 && padding%2!=0) // if odd #, add 1 space
ss << " ";
return ss.str();
}
/**
* @brief converts double to a string with white space
*
* @param x
* @param width
* @return std::string
*/
static std::string prd(long double x, int width) {
std::stringstream ss;
ss << std::fixed << std::left;
ss.fill(' '); // fill space around displayed #
ss.width(width); // set width around displayed #
ss.precision(2); // set # places after decimal
ss << x;
return center(ss.str(), width);
}
/**
* @brief Gives spacing to a string
*
* @param x
* @param width
* @return std::string
*/
static std::string prd(std::string x, int width) {
std::stringstream ss;
ss << std::left;
ss.fill(' '); // fill space around displayed #
ss.width(width); // set width around displayed #
ss << x;
return center(ss.str(), width);
}
/**
* @brief Generates row names
*
*/
void generate_rows(){
rows.clear();
for(int i = 0; i < size(); i++){
rows.push_back("Row-"+std::to_string(i));
}
}
/**
* @brief Checks size of current class
*
*/
void check_size(){
if(empty()){
row = 0;
col = 0;
return;
}
col = at(0).size();
row = size();
}
/**
* @brief Generates line to seperate rows
*
* @param l
* @return std::string
*/
std::string generate_line(int l){
std::string line;
for(int i = 0; i < l; i++){
line+="―";
}
return line;
}
/**
* @brief Stores the headers
*
*/
std::vector<std::string> headers;
/**
* @brief Stores the row names
*
*/
std::vector<std::string> rows;
/**
* @brief Row size
*
*/
int row;
/**
* @brief Colum size
*
*/
int col;
/**
* @brief Spacing size for print
*
*/
int sz = 10;
public:
/**
* @brief Construct a new Table object
*
*/
Table(){}
/**
* @brief Destroy the Table object
*
*/
~Table(){}
/**
* @brief Reads from csv file
*
* @param file
* @return true: if read is success
* @return false: if read did not complete
*/
bool read_csv(std::string filename){
ifstream file(filename);
if(file.is_open()){
clear();
headers.clear();
// col name
string line, colname;
getline(file, line);
stringstream ss(line);
while(getline(ss, colname, ',')){
headers.push_back(colname);
}
// data
long double val;
while(std::getline(file, line))
{
// Create a stringstream of the current line
std::stringstream ss(line);
std::vector<long double> r;
while(ss >> val){
r.push_back(val);
// If the next token is a comma, ignore it and move on
if(ss.peek() == ',') ss.ignore();
}
push_back(r);
}
check_size();
file.close();
return true;
}
file.close();
return false;
}
/**
* @brief Reads from csv file
*
* @param file
* @return true: if read is success
* @return false: if read did not complete
*/
bool save_csv(std::string filename)
{
ofstream file(filename);
if(file.is_open()){
for(int i = 0; i < headers.size(); i++){
if(i != headers.size()-1){
file << headers[i] << ",";
}
else{
file << headers[i] << "\n";
}
}
check_size();
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
if(j != col-1){
file << at(i).at(j) << ",";
}
else if (j == col-1){
file << at(i).at(j) << "\n";
}
}
}
file.close();
return true;
}
file.close();
return false;
}
/**
* @brief Get the row size object
*
* @return int
*/
int get_row_size(){
return size();
}
/**
* @brief Get the col size object
*
* @return int
*/
int get_col_size(){
return at(0).size();
}
/**
* @brief Returns colum of certain header
*
* @param headname
* @return std::vector<TYPE>&
*/
std::vector<long double> operator[](std::string headname){
return get_col_(headname);
}
/**
* @brief Sorts data ascending
*
* @param a
* @return std::vector<long double>
*/
static std::vector<long double> sort_asc(std::vector<long double> & a){
std::vector<long double> v_sorted(a.size());
std::partial_sort_copy(a.begin(), a.end(),
v_sorted.begin(), v_sorted.end());
return v_sorted;
}
/**
* @brief Get the min value of vector
*
* @param a
* @return long double
*/
static long double get_min(std::vector<long double> a){
return *std::min_element(a.begin(), a.end());
}
/**
* @brief Get the max value of vector
*
* @param a
* @return long double
*/
static long double get_max(std::vector<long double> a){
return *std::max_element(a.begin(), a.end());
}
/**
* @brief Get the sum of vector
*
* @param a
* @return long double
*/
static long double get_sum(std::vector<long double> a){
return std::accumulate(a.begin(), a.end(), 0);
}
/**
* @brief Get the avg of vector
*
* @param a
* @return long double
*/
static long double get_avg(std::vector<long double> a){
return get_sum(a)/a.size();
}
/**
* @brief Get the variance of vector
*
* @param a
* @return long double
*/
static long double get_var(std::vector<long double> a){
long double mean = get_avg(a);
int N = a.size();
long double sum = 0;
for(int i = 0; i < N; i++){
sum+=pow((a[i]-mean), 2);
}
return (long double) sum/N;
}
/**
* @brief Get the standard diviation of vector
*
* @param a
* @return long double
*/
static long double get_std(std::vector<long double> a){
return sqrt(get_var(a));
}
/**
* @brief Get the quartile range of a vector
*
* @param a
* @return QR
*/
static QR get_qr(std::vector<long double> a){
QR qr;
qr.LQ = get_min(a);
qr.UQ = get_max(a);
auto a_sorted = sort_asc(a);
qr.Q1 = a_sorted.at((int) (a_sorted.size())/4);
qr.Q2 = a_sorted.at((int) (a_sorted.size())/2);
qr.Q3 = a_sorted.at((int) (3*(a_sorted.size()))/4);
return qr;
}
/**
* @brief Get the relation coefficient of two vectors
*
* @param _x
* @param _y
* @return long double
*/
static long double get_r(
std::vector<long double> _x, std::vector<long double> _y){
if(_x.size() != _y.size()){
throw std::invalid_argument("misc::Table::get_r -> Size mismatch");
}
long double sumx = misc::Table::get_sum(_x);
long double sumy = misc::Table::get_sum(_y);
long double sumxx = misc::Table::get_sum(_x*_x);
long double sumxy = misc::Table::get_sum(_x*_y);
long double sumyy = misc::Table::get_sum(_y*_y);
return (_x.size()*sumxy-(sumx*sumy))/
(sqrt((_x.size()*sumxx-pow(sumx, 2))*(_x.size()*sumyy-pow(sumy, 2))));
}
/**
* @brief Shows a certain number of rows in table
*
* @param r
*/
void show(int r){
if(rows.empty()){
generate_rows();
}
check_size();
std::string line;
if(col == 1){
line = generate_line((std::pow(2, 1/col)+0.2)*sz*col);
}
else{
line = generate_line((std::pow(1.05, 1/col)+1.9/col)*sz*col);
}
for(int i = -1; i < r; i++){
for(int j = 0; j < col; j++){
// to print header
if(i == -1){
if (j == 0 && col > 1){
std::cout << prd(" ", sz) << "│"
<< prd(headers[j], sz) << "│";
}
else if(j == 0 && col == 1){
std::cout << prd(" ", sz) << "│"
<< prd(headers[j], sz) << "\n";
std::cout << line << "\n";
}
else if(j != col-1){
std::cout << prd(headers[j], sz) << "│";
}
else{
std::cout << prd(headers[j], sz) << "\n";
std::cout << line << "\n";
}
}
// printing values
else{
// row name + val
if(j == 0 && col > 1){
std::cout << prd(rows[i], sz) << "│"
<< prd(get_col_(headers[j]).at(i), sz) << "│";
}
else if(j == 0 && col == 1){
std::cout << prd(rows[i], sz) << "│"
<< prd(get_col_(headers[j]).at(i), sz) << "│" << "\n";
std::cout << line << "\n";
}
else if(j != col-1){
std::cout << prd(get_col_(headers[j]).at(i), sz) << "│";
}
else{
std::cout << prd(get_col_(headers[j]).at(i), sz) << "\n";
std::cout << line << "\n";
}
}
}
}
}
/**
* @brief shows all of the table
*
*/
void show(){
check_size();
show(row);
}
/**
* @brief Statistical summary of all colums in table
*
* @return Table
*/
Table describe_all(){
Table t;
auto avg = get_avgs();
auto std = get_stds();
auto var = get_vars();
auto qrs = get_qrs();
auto sms = get_sums();
check_size();
// loading row names
for(int i = 0; i < col; i++){
t.rows.push_back(headers[i]);
}
// loading col names
t.headers.push_back("Mean");
t.headers.push_back("STD");
t.headers.push_back("VAR");
t.headers.push_back("Min");
t.headers.push_back("Q1");
t.headers.push_back("Q2");
t.headers.push_back("Q3");
t.headers.push_back("Max");
t.headers.push_back("IQR");
t.headers.push_back("Sum");
// loading values
t.row = t.rows.size();
t.col = t.headers.size();
for(int i = 0; i < t.row; i++){
std::vector<long double> rr;
rr.push_back(avg[i]);
rr.push_back(std[i]);
rr.push_back(var[i]);
rr.push_back(qrs[i].LQ);
rr.push_back(qrs[i].Q1);
rr.push_back(qrs[i].Q2);
rr.push_back(qrs[i].Q3);
rr.push_back(qrs[i].UQ);
rr.push_back(qrs[i].Q3-qrs[i].Q1);
rr.push_back(sms[i]);
t.push_back(rr);
}
t.check_size();
t.sz = 11;
return t;
}
/**
* @brief Get the row as table
*
* @param r
* @return Table
*/
Table get_row(int r){
Table t;
t.push_back(at(r));
t.headers = headers;
if(rows.empty()){
generate_rows();
}
t.rows.push_back(rows[r]);
return t;
}
/**
* @brief Get the col as table
*
* @param name
* @return Table
*/
Table get_col(std::string name){
Table t;
auto a = get_col_(name);
for(int i = 0; i < a.size(); i++){
t.push_back({a[i]});
}
if(rows.empty()){
generate_rows();
}
t.headers.push_back(headers[check_header(name)]);
return t;
}
/**
* @brief Adds new colum
*
* @param col_name
* @param col_data
* @return true
* @return false
*/
bool add_col(std::string col_name, std::vector<long double> col_data){
check_size();
if((col_data.size() != row && row != 0) || col_data.empty()){
return false;
}
headers.push_back(col_name);
for(int i = 0; i < col_data.size(); i++){
if(row == 0){
push_back({col_data[i]});
}
else{
at(i).push_back(col_data[i]);
}
}
return true;
}
/**
* @brief Shows headers only
*
*/
void show_header(){
show(0);
}
};
/**
* @brief Encapsulates graph.hpp (https://github.com/tdulcet/Tables-and-Graphs)
*
*/
class Plot
{
public:
/**
* @brief Colors for plots
*
*/
enum Color
{
red = 10,
green = 11,
yellow = 12,
purple = 14,
blue = 15,
white = 16
};
private:
/**
* @brief Height of terminal plot
*
*/
size_t height;
/**
* @brief Width of terminal plot
*
*/
size_t width;
/**
* @brief Minimum x-value
*
*/
long double xmin;
/**
* @brief Maxmimum x-value
*
*/
long double xmax;
/**
* @brief Minimum y-value
*
*/
long double ymin;
/**
* @brief Maximum y-value
*
*/
long double ymax;
/**
* @brief Size for cols which is 2
*
*/
const size_t cols = 2;
/**
* @brief Used to store domain vector
*
*/
std::vector<long double> domain;
/**
* @brief Stores graphing options
*
*/
graphoptions aoptions;
/**
* @brief Stores color
*
*/
Color c;
/**
* @brief Stores title
*
*/
std::string title;
public:
/**
* @brief Construct a new Plot object
*
* @param h height
* @param w width
* @param xmn min x
* @param xmx max x
* @param ymn min y
* @param ymx max y
*/
Plot(int h = 145, int w = 145,
long double xmn = -10, long double xmx = 10,
long double ymn = -10, long double ymx = 10):
height(h), width(w),
xmin(xmn), xmax(xmx),
ymin(ymn), ymax(ymx){}
/**
* @brief Set the Domain
*
* @param xmn
* @param xmx
*/
void set_domain(long double xmn = -10, long double xmx = 10){
xmin = xmn;
xmax = xmx;
}
/**
* @brief Set the Range
*
* @param ymn
* @param ymx
*/
void set_range(long double ymn = -10, long double ymx = 10){
ymin = ymn;
ymax = ymx;
}
/**
* @brief Set the Size of figure
*
* @param h
* @param w
*/
void set_size(int h = 140, int w = 140){
height = h;
width = w;
}
/**
* @brief Set the color
*
* @param cc
*/
void set_color(Color cc = Color::blue){
c = cc;
}
/**
* @brief Set the title
*
* @param tt
*/
void set_title(std::string tt){
title = tt;
}
/**
* @brief Generates domain
*
* @param n
*/
void generate_domain(int n = 50){
generate_domain(xmin, xmax, n);
}
/**
* @brief Generates domain to plot function
*
* @param xmn
* @param xmx
* @param n number of points
*/
void generate_domain(long double xmn, long double xmx, int n){
domain = generate_vector(xmn, xmx, n);
}
/**
* @brief Plots vectors
*
* @param x vector for x
* @param y vector for y
*/
void plot_vect(std::vector<long double> &x, std::vector<long double> &y)
{
if(x.size() != y.size()){
std::cerr << x.size() << "\t" << y.size() << "\n";
std::cerr << "misc::Plot::plot_vect-> Size mismatch \n";
return;
}
long double **array;
array = new long double *[x.size()];
for (unsigned int i = 0; i < x.size(); ++i){
array[i] = new long double[cols];
}
for (unsigned int i = 0; i < x.size(); ++i){
for (unsigned int j = 0; j < cols; ++j){
// x
if (j == 0){
array[i][j] = x[i];
}
// y
else{
array[i][j] = y[i];
}
}
}
aoptions.color = c;
std::cout <<
colors[c]
<< title << "\n"
<< colors[Color::white];
graph(height, width, xmin, xmax, ymin, ymax, x.size(), array, aoptions);
if(array != NULL){
for (unsigned int i = 0; i < x.size(); ++i){
delete[] array[i];
}
delete[] array;
}
}
/**
* @brief Plots function
*
* @tparam LAMBDA
* @param fun lambda function
*/
template<typename LAMBDA>
void plot_fun(LAMBDA fun)
{
std::vector<long double> y;
for(int i = 0; i < domain.size(); i++){
y.push_back(fun(domain[i]));
}
plot_vect(domain, y);
}
};
}
| 30.052734
| 96
| 0.34136
|
harith-alsafi
|
549e0a60308d6fc7cd2622cc282f2236689aee00
| 2,950
|
cc
|
C++
|
DAPPLES.cc
|
hkktr/POLSKI-SPOJ
|
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
|
[
"Unlicense"
] | 1
|
2021-02-01T11:21:56.000Z
|
2021-02-01T11:21:56.000Z
|
DAPPLES.cc
|
hkktr/POLSKI-SPOJ
|
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
|
[
"Unlicense"
] | null | null | null |
DAPPLES.cc
|
hkktr/POLSKI-SPOJ
|
59f7e0be99fca6532681c2ca01c8a7d97c6b5eed
|
[
"Unlicense"
] | 1
|
2022-01-28T15:25:45.000Z
|
2022-01-28T15:25:45.000Z
|
// C++14 (gcc 8.3)
#include <cmath>
#include <iostream>
#include <limits>
#include <vector>
constexpr int kG{1'000};
long long CalculateTreeHeight(long long height, int max_velocity) {
return static_cast<long long>(std::pow(max_velocity, 2)) / (2 * kG) + height;
}
class Resident {
public:
Resident(int height, int age, int growth_quotient)
: height_{height}, age_{age}, growth_quotient_{growth_quotient} {}
long long GetTreeHeight(int year, int max_velocity) const {
return CalculateTreeHeight(GetHeight(year), max_velocity);
}
private:
int height_;
int age_;
int growth_quotient_;
long long GetHeight(int year) const {
if (age_ < 20) {
const int growth_years{std::min(year, 20 - age_)};
return static_cast<long long>(height_) +
growth_years * static_cast<long long>(growth_quotient_);
} else {
return height_;
}
}
};
int main() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
int t;
std::cin >> t;
while (--t >= 0) {
int max_velocity, n;
std::cin >> max_velocity >> n;
max_velocity *= 100;
std::vector<Resident> residents;
residents.reserve(n);
long long const_min_tree_height{std::numeric_limits<long long>::max()};
long long min_tree_height{std::numeric_limits<long long>::max()};
while (--n >= 0) {
int height, age, growth_quotient;
std::cin >> height >> age >> growth_quotient;
if (age >= 20) {
const long long tree_height{CalculateTreeHeight(height, max_velocity)};
if (tree_height < const_min_tree_height) {
const_min_tree_height = tree_height;
if (const_min_tree_height < min_tree_height) {
min_tree_height = const_min_tree_height;
}
}
} else {
const Resident new_resident(height, age, growth_quotient);
residents.push_back(new_resident);
const long long tree_height{
new_resident.GetTreeHeight(0, max_velocity)};
if (tree_height < min_tree_height) {
min_tree_height = tree_height;
}
}
}
std::cout << "0: " << min_tree_height << "\n";
bool const_heights{false};
for (int year{1}; year <= 20; ++year) {
if (!const_heights) {
min_tree_height = const_min_tree_height;
for (const Resident& resident : residents) {
const long long tree_height{
resident.GetTreeHeight(year, max_velocity)};
if (tree_height < min_tree_height) {
min_tree_height = tree_height;
}
}
if (min_tree_height == const_min_tree_height) {
const_heights = true;
}
std::cout << year << ": " << min_tree_height << "\n";
} else {
std::cout << year << ": " << const_min_tree_height << "\n";
}
}
}
return 0;
}
| 28.365385
| 80
| 0.591525
|
hkktr
|
54a0b6e2a9f9e376b72d0ade5bee4b71640c8e76
| 3,711
|
cpp
|
C++
|
Src/Eni/Gpio/STM32/Gpio.cpp
|
vlad230596/Eni
|
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
|
[
"MIT"
] | null | null | null |
Src/Eni/Gpio/STM32/Gpio.cpp
|
vlad230596/Eni
|
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
|
[
"MIT"
] | null | null | null |
Src/Eni/Gpio/STM32/Gpio.cpp
|
vlad230596/Eni
|
2bbd07b6e4e20b2c2a6ad6fdc9d948e6352eecb7
|
[
"MIT"
] | null | null | null |
#include "EniConfig.h"
#if defined(ENI_GPIO) && defined(ENI_STM)
#include "../Gpio.h"
#include "GpioPin.h"
#if !IS_ENI_GPIO_SUPPORTED
#if defined(ENI_HAL_INCLUDE_FILE)
#include ENI_HAL_INCLUDE_FILE
#else
#error "HAL include file missing declaration"
#endif
#endif
namespace Eni {
void Gpio::applyConfig(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
*(pin.getConfigRegister()) = static_cast<uint32_t>(pin.init.value) << ((pin.pin % (GpioPin::countPinInConfigRegister)) << 2);
#else
HAL_GPIO_Init(pin.port, &pin.init);
#endif
}
void Gpio::initInput(const GpioPin& pin, InputMode inputMode) {
#if IS_ENI_GPIO_SUPPORTED
pin.init.mode.mode = 0;
switch(inputMode) {
case InputMode::Analog:
pin.init.mode.cnf1 = 0;
pin.init.mode.cnf0 = 0;
break;
case InputMode::Floating:
pin.init.mode.cnf1 = 0;
pin.init.mode.cnf0 = 1;
break;
case InputMode::PullDown:
pin.init.mode.cnf1 = 1;
pin.init.mode.cnf0 = 0;
pin.port->ODR &= ~pin.mask;
break;
case InputMode::PullUp:
pin.init.mode.cnf1 = 1;
pin.init.mode.cnf0 = 0;
pin.port->ODR |= pin.mask;
break;
}
#else
pin.init.Mode = GPIO_MODE_INPUT;
switch(inputMode) {
case InputMode::Analog:
pin.init.Mode = GPIO_MODE_ANALOG;
pin.init.Pull = GPIO_NOPULL;
break;
case InputMode::Floating:
pin.init.Pull = GPIO_NOPULL;
break;
case InputMode::PullUp:
pin.init.Pull = GPIO_PULLUP;
break;
case InputMode::PullDown:
pin.init.Pull = GPIO_PULLDOWN;
break;
}
#endif
applyConfig(pin);
}
void Gpio::initOutput(const GpioPin& pin, OutputMode mode, bool isAlternateFunction, PinSpeed speed) {
#if IS_ENI_GPIO_SUPPORTED
pin.init.mode.mode = static_cast<uint8_t>(speed);
pin.init.mode.cnf1 = isAlternateFunction;
switch(mode) {
case OutputMode::PushPull:
pin.init.mode.cnf0 = 0;
break;
case OutputMode::OpenDrain:
pin.init.mode.cnf0 = 1;
break;
}
#else
switch(mode) {
case OutputMode::OpenDrain:
if(isAlternateFunction) {
pin.init.Mode = GPIO_MODE_AF_OD;
}
else {
pin.init.Mode = GPIO_MODE_OUTPUT_OD;
}
break;
case OutputMode::PushPull:
if(isAlternateFunction) {
pin.init.Mode = GPIO_MODE_AF_PP;
}
else {
pin.init.Mode = GPIO_MODE_OUTPUT_PP;
}
break;
}
#endif
applyConfig(pin);
}
void Gpio::disconnect(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
initInput(pin, InputMode::Floating);
#else
HAL_GPIO_DeInit(pin.port, pin.pin);
#endif
}
void Gpio::set(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
pin.port->BSRR = pin.mask;
#else
HAL_GPIO_WritePin(pin.port, pin.mask, GPIO_PIN_SET);
#endif
}
void Gpio::reset(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
pin.port->BSRR = static_cast<uint32_t>(pin.mask) << 16U;
#else
HAL_GPIO_WritePin(pin.port, pin.mask, GPIO_PIN_RESET);
#endif
}
void Gpio::toggle(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
pin.port->ODR ^= pin.mask;
#else
HAL_GPIO_TogglePin(pin.port, pin.mask);
#endif
}
bool Gpio::read(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
return (pin.port->IDR & pin.mask) != 0;
#else
return HAL_GPIO_ReadPin(pin.port, pin.mask) == GPIO_PIN_SET;
#endif
}
bool Gpio::lock(const GpioPin& pin) {
#if IS_ENI_GPIO_SUPPORTED
/*LOCK key writing sequence:
Write 1
Write 0
Write 1
Read 0
Read 1 (this read is optional but confirms that the lock is active)
Note: During the LOCK Key Writing sequence, the value of LCK[15:0] must not change
*/
pin.port->LCKR = GPIO_LCKR_LCKK | pin.mask;
pin.port->LCKR = pin.mask;
pin.port->LCKR = GPIO_LCKR_LCKK | pin.mask;
auto dummy = pin.port->LCKR;
static_cast<void>(dummy);
return (pin.port->LCKR & GPIO_LCKR_LCKK) != 0;
#else
return HAL_GPIO_LockPin(pin.port, pin.pin) == HAL_OK;
#endif
}
}
#endif
| 21.327586
| 126
| 0.70574
|
vlad230596
|
54a9ea3d1cf584a8d1505c07faf72697055e4aa0
| 26,301
|
cpp
|
C++
|
Vault/Source/Vault/Private/SLoaderWindow.cpp
|
Unreal-Vault/Vault-Dev
|
5232794276b238c700c9f4a5fc5bfc4082612f04
|
[
"MIT"
] | 11
|
2020-11-04T13:51:19.000Z
|
2022-02-24T23:11:44.000Z
|
Vault/Source/Vault/Private/SLoaderWindow.cpp
|
Unreal-Vault/Vault-Dev
|
5232794276b238c700c9f4a5fc5bfc4082612f04
|
[
"MIT"
] | null | null | null |
Vault/Source/Vault/Private/SLoaderWindow.cpp
|
Unreal-Vault/Vault-Dev
|
5232794276b238c700c9f4a5fc5bfc4082612f04
|
[
"MIT"
] | 3
|
2022-01-23T10:14:56.000Z
|
2022-03-30T13:35:10.000Z
|
// Copyright Daniel Orchard 2020
#include "SLoaderWindow.h"
#include "Vault.h"
#include "VaultSettings.h"
#include "MetadataOps.h"
#include "SAssetPackTile.h"
#include "VaultStyle.h"
#include "AssetPublisher.h"
#include "VaultTypes.h"
#include "ImageUtils.h"
#include "EditorStyleSet.h"
#include "PakFileUtilities.h"
#include "EditorFramework/AssetImportData.h"
#include "AssetImportTask.h"
#include "AssetToolsModule.h"
#define LOCTEXT_NAMESPACE "SVaultLoader"
const int32 SLoaderWindow::THUMBNAIL_BASE_HEIGHT = 415;
const int32 SLoaderWindow::THUMBNAIL_BASE_WIDTH = 415;
const int32 SLoaderWindow::TILE_BASE_HEIGHT = 465;
const int32 SLoaderWindow::TILE_BASE_WIDTH = 415;
namespace VaultColumnNames
{
static const FName TagCheckedColumnName(TEXT("Flag"));
static const FName TagNameColumnName(TEXT("Tag Name"));
static const FName TagCounterColumnName(TEXT("Used"));
};
class VAULT_API STagFilterRow : public SMultiColumnTableRow<FTagFilteringItemPtr>
{
public:
SLATE_BEGIN_ARGS(STagFilterRow) {}
SLATE_ARGUMENT(FTagFilteringItemPtr, TagData)
SLATE_ARGUMENT(TSharedPtr<SLoaderWindow>, ParentWindow)
SLATE_END_ARGS()
void Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& OwnerTableView)
{
TagData = InArgs._TagData;
ParentWindow = InArgs._ParentWindow;
SMultiColumnTableRow<FTagFilteringItemPtr>::Construct(FSuperRowType::FArguments().Padding(1.0f), OwnerTableView);
}
void OnCheckBoxStateChanged(ECheckBoxState NewCheckedState)
{
const bool Filter = NewCheckedState == ECheckBoxState::Checked;
ParentWindow->ModifyActiveTagFilters(TagData->Tag, Filter);
}
virtual TSharedRef<SWidget> GenerateWidgetForColumn(const FName& ColumnName) override
{
static const FMargin ColumnItemPadding(5, 0, 5, 0);
if (ColumnName == VaultColumnNames::TagCheckedColumnName)
{
return SNew(SCheckBox)
.IsChecked(false)
.OnCheckStateChanged(this, &STagFilterRow::OnCheckBoxStateChanged);
}
else if (ColumnName == VaultColumnNames::TagNameColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(TagData->Tag));
}
else if (ColumnName == VaultColumnNames::TagCounterColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(FString::FromInt(TagData->UseCount)));
}
else
{
return SNullWidget::NullWidget;
}
}
private:
FTagFilteringItemPtr TagData;
TSharedPtr<SLoaderWindow> ParentWindow;
};
class VAULT_API SDeveloperFilterRow : public SMultiColumnTableRow<FDeveloperFilteringItemPtr>
{
public:
SLATE_BEGIN_ARGS(SDeveloperFilterRow) {}
SLATE_ARGUMENT(FDeveloperFilteringItemPtr, Entry)
SLATE_ARGUMENT(TSharedPtr<SLoaderWindow>, ParentWindow)
SLATE_END_ARGS()
void Construct(const FArguments& InArgs, const TSharedRef<STableViewBase>& OwnerTableView)
{
Entry = InArgs._Entry;
ParentWindow = InArgs._ParentWindow;
SMultiColumnTableRow<FDeveloperFilteringItemPtr>::Construct(FSuperRowType::FArguments().Padding(1.0f), OwnerTableView);
}
void OnCheckBoxStateChanged(ECheckBoxState NewCheckedState)
{
const bool Filter = NewCheckedState == ECheckBoxState::Checked;
ParentWindow->ModifyActiveDevFilters(Entry->Developer, Filter);
}
virtual TSharedRef<SWidget> GenerateWidgetForColumn(const FName& ColumnName) override
{
static const FMargin ColumnItemPadding(5, 0, 5, 0);
if (ColumnName == VaultColumnNames::TagCheckedColumnName)
{
return SNew(SCheckBox)
.IsChecked(false)
.OnCheckStateChanged(this, &SDeveloperFilterRow::OnCheckBoxStateChanged);
}
else if (ColumnName == VaultColumnNames::TagNameColumnName)
{
return SNew(STextBlock)
.Text(FText::FromName(Entry->Developer));
}
else if (ColumnName == VaultColumnNames::TagCounterColumnName)
{
return SNew(STextBlock)
.Text(FText::FromString(FString::FromInt(Entry->UseCount)));
}
else
{
return SNullWidget::NullWidget;
}
}
private:
FDeveloperFilteringItemPtr Entry;
TSharedPtr<SLoaderWindow> ParentWindow;
};
void SLoaderWindow::Construct(const FArguments& InArgs, const TSharedRef<SDockTab>& ConstructUnderMajorTab, const TSharedPtr<SWindow>& ConstructUnderWindow)
{
RefreshAvailableFiles();
PopulateBaseAssetList();
PopulateTagArray();
PopulateDeveloperNameArray();
// Bind to our publisher so we can refresh automatically when the user publishes an asset (they wont need to import it, but its a visual feedback for the user to check it appeared in the library
UAssetPublisher::OnVaultPackagingCompletedDelegate.BindRaw(this, &SLoaderWindow::OnNewAssetPublished);
// Construct the Holder for the Metadata List
MetadataWidget = SNew(SVerticalBox);
// Set the Default Scale for Sliders.
TileUserScale = 0.5;
const float TILE_SCALED_WIDTH = TILE_BASE_WIDTH * TileUserScale;
const float TILE_SCALED_HEIGHT = TILE_BASE_HEIGHT * TileUserScale;
// Main Widget
TSharedRef<SVerticalBox> LoaderRoot = SNew(SVerticalBox)
+ SVerticalBox::Slot()
.FillHeight(1.0f)
[
// Primary 3 Boxes go in Here
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
[
SNew(SSplitter)
.Orientation(Orient_Horizontal)
+SSplitter::Slot()
.Value(0.2f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
// Left Sidebar!
SNew(SVerticalBox)
+SVerticalBox::Slot()
.Padding(0,3,0,5)
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("VaultLoaderSidebarHeaderLabel", "FILTERING"))
.TextStyle(FVaultStyle::Get(), "MetaTitleText")
]
// Asset List Amount
+ SVerticalBox::Slot()
.AutoHeight()
.HAlign(HAlign_Left)
.VAlign(VAlign_Top)
.Padding(0,0,0,5)
[
SNew(STextBlock)
.Text(this, &SLoaderWindow::DisplayTotalAssetsInLibrary)
]
// Tag filtering
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SListView<FTagFilteringItemPtr>)
.SelectionMode(ESelectionMode::Single)
.ListItemsSource(&TagCloud)
.OnGenerateRow(this, &SLoaderWindow::MakeTagFilterViewWidget)
.HeaderRow
(
SNew(SHeaderRow)
+ SHeaderRow::Column(VaultColumnNames::TagCheckedColumnName)
.DefaultLabel(LOCTEXT("FilteringBoolLabel", "Filter"))
.FixedWidth(40.0f)
+ SHeaderRow::Column(VaultColumnNames::TagNameColumnName)
.DefaultLabel(LOCTEXT("TagFilteringTagNameLabel", "Tags"))
+ SHeaderRow::Column(VaultColumnNames::TagCounterColumnName)
.DefaultLabel(LOCTEXT("TagFilteringCounterLabel", "Used"))
)
]
// Developer Filtering
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SListView<FDeveloperFilteringItemPtr>)
.SelectionMode(ESelectionMode::Single)
.ListItemsSource(&DeveloperCloud)
.OnGenerateRow(this, &SLoaderWindow::MakeDeveloperFilterViewWidget)
.HeaderRow
(
SNew(SHeaderRow)
+ SHeaderRow::Column(VaultColumnNames::TagCheckedColumnName)
.DefaultLabel(LOCTEXT("FilteringBoolLabel", "Filter"))
.FixedWidth(40.0f)
+ SHeaderRow::Column(VaultColumnNames::TagNameColumnName)
.DefaultLabel(LOCTEXT("TagFilteringTagNameLabel", "Tags"))
+ SHeaderRow::Column(VaultColumnNames::TagCounterColumnName)
.DefaultLabel(LOCTEXT("TagFilteringCounterLabel", "Used"))
)
]
// Misc Filtering
+SVerticalBox::Slot()
// Spacer
+ SVerticalBox::Slot()
[
SNew(SSpacer)
]
// Selected Asset metadata
+ SVerticalBox::Slot()
] // close SBorder
] // ~Close Left Splitter Area
// Center Area!
+SSplitter::Slot()
.Value(0.6f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.FillWidth(1)
.Padding(FMargin(0,3,0,0))
[
// Center content area
SAssignNew(SearchBox, SSearchBox)
.HintText(LOCTEXT("SearchBoxHintText", "Search..."))
.OnTextChanged(this, &SLoaderWindow::OnSearchBoxChanged)
.OnTextCommitted(this, &SLoaderWindow::OnSearchBoxCommitted)
.DelayChangeNotificationsWhileTyping(false)
.Visibility(EVisibility::Visible)
.Style(FVaultStyle::Get(), "AssetSearchBar")
.AddMetaData<FTagMetaData>(FTagMetaData(TEXT("AssetSearch")))
]
+ SHorizontalBox::Slot()
.Padding(FMargin(15.f,0.f, 5.f, 0.f))
.AutoWidth()
[
SAssignNew(StrictSearchCheckBox, SCheckBox)
.Style(FCoreStyle::Get(), "ToggleButtonCheckbox")
.Padding(FMargin( 5.f,0.f ))
.ToolTipText(LOCTEXT("StrictSearchToolTip", "Search only the Pack Names"))
[
SNew(SBox)
.VAlign(VAlign_Center)
.HAlign(HAlign_Center)
.Padding(FMargin(4.f,2.f))
[
SNew(STextBlock)
.Text(LOCTEXT("StrictSearchCheckBox", "Strict Search"))
]
]
]
]
// Tile View
+ SVerticalBox::Slot()
.FillHeight(1.0f)
[
SNew(SBox)
.Padding(FMargin(5,5,5,5))
[
SAssignNew(TileView, STileView<TSharedPtr<FVaultMetadata>>)
.ItemWidth(TILE_SCALED_WIDTH)
.ItemHeight(TILE_SCALED_HEIGHT)
.ItemAlignment(EListItemAlignment::EvenlyDistributed)
.ListItemsSource(&FilteredAssetItems)
.OnGenerateTile(this, &SLoaderWindow::MakeTileViewWidget)
.SelectionMode(ESelectionMode::Single)
.OnSelectionChanged(this, &SLoaderWindow::OnAssetTileSelectionChanged)
.OnMouseButtonDoubleClick(this, &SLoaderWindow::OnAssetTileDoubleClicked)
.OnContextMenuOpening(this, &SLoaderWindow::OnAssetTileContextMenuOpened)
]
]
// Bottom Bar
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
[
SNew(SButton)
.Text(LOCTEXT("RefreshLibraryScreenBtnLbl", "Refresh Library"))
.OnClicked(this, &SLoaderWindow::OnRefreshLibraryClicked)
]
+ SHorizontalBox::Slot()
[
SNew(SSpacer)
]
+ SHorizontalBox::Slot()
[
// Scale Slider
SNew(SHorizontalBox)
+ SHorizontalBox::Slot()
.AutoWidth()
.HAlign(HAlign_Right)
.Padding(FMargin(0, 0, 0, 0))
[
SNew(STextBlock)
.Text(LOCTEXT("ScaleSliderLabel", "Thumbnail Scale"))
.Justification(ETextJustify::Right)
]
+ SHorizontalBox::Slot()
[
SAssignNew(UserScaleSlider, SSlider)
.Value(TileUserScale)
.MinValue(0.2)
.OnValueChanged(this, &SLoaderWindow::OnThumbnailSliderValueChanged)
]
]
]
] // close border for center area
] // ~ Close Center Area Splitter
// Metadata Zone
+ SSplitter::Slot()
.Value(0.2f)
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.GroupBorder"))
.Padding(FMargin(4.0f, 4.0f))
[
// Left Sidebar!
SNew(SVerticalBox)
+ SVerticalBox::Slot()
.AutoHeight()
[
SNew(STextBlock)
.Text(LOCTEXT("VaultLoaderRightSidebarHeaderLabel", "METADATA"))
.TextStyle(FVaultStyle::Get(), "MetaTitleText")
]
+ SVerticalBox::Slot()
.FillHeight(1)
[
SNew(SBox)
[
MetadataWidget.ToSharedRef()
]
]
]
]
] // ~ hbox
]; // ~ LoaderRoot
ChildSlot
[
SNew(SBorder)
.BorderImage(FEditorStyle::GetBrush("ToolPanel.DarkGroupBorder"))
.Padding(FMargin(2.f,2.f))
[
LoaderRoot
]
];
}
void SLoaderWindow::Tick(const FGeometry& AllottedGeometry, const double InCurrentTime, const float InDeltaTime)
{
}
void SLoaderWindow::PopulateBaseAssetList()
{
FilteredAssetItems.Empty();
for (FVaultMetadata Meta : MetaFilesCache)
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Meta)));
}
}
// Only shows tags that are actually used, no empty tags will appear.
void SLoaderWindow::PopulateTagArray()
{
// Empty Tag Container
TagCloud.Empty();
// Create a map version of the array for more efficient searching.
TMap<FString, FTagFilteringItemPtr> TagCloudMap;
// For each Asset in our global list of assets...
for (auto Asset : MetaFilesCache)
{
// Get each tag belonging to that asset...
for (const FString AssetTag : Asset.Tags)
{
// If we already have a tag stored for it, increment the use counter
if (TagCloudMap.Contains(AssetTag))
{
TagCloudMap.Find(AssetTag)->Get()->UseCount++;
}
// otherwise, add a new tag to our list.
else
{
FTagFilteringItemPtr TagTemp = MakeShareable(new FTagFilteringItem);
TagTemp->Tag = AssetTag;
TagTemp->UseCount = 1;
TagCloudMap.Add(AssetTag, TagTemp);
}
}
}
// The Map version is easier to work with during generation, but since we have to use an Array, we convert our cloud map into an array now:
TagCloudMap.GenerateValueArray(TagCloud);
}
void SLoaderWindow::PopulateDeveloperNameArray()
{
// Developer Array
DeveloperCloud.Empty();
TMap<FName, int32> DevAssetCounter;
for (auto AssetItem : FilteredAssetItems)
{
if (DevAssetCounter.Contains(AssetItem->Author))
{
int Count = *DevAssetCounter.Find(AssetItem->Author);
Count++;
DevAssetCounter.Add(AssetItem->Author, Count);
}
else
{
DevAssetCounter.Add(AssetItem->Author, 1);
}
}
for (auto dev : DevAssetCounter)
{
FDeveloperFilteringItemPtr DevTemp = MakeShareable(new FDeveloperFilteringItem);
DevTemp->Developer = dev.Key;
DevTemp->UseCount = dev.Value;
DeveloperCloud.AddUnique(DevTemp);
}
}
TSharedRef<ITableRow> SLoaderWindow::MakeTileViewWidget(TSharedPtr<FVaultMetadata> AssetItem, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(STableRow<TSharedPtr<FVaultMetadata>>, OwnerTable)
.Style(FEditorStyle::Get(), "ContentBrowser.AssetListView.TableRow")
.Padding(FMargin(5.0f, 5.0f, 5.0f, 25.0f))
[
SNew(SAssetTileItem)
.AssetItem(AssetItem)
];
}
TSharedRef<ITableRow> SLoaderWindow::MakeTagFilterViewWidget(FTagFilteringItemPtr inTag, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(STagFilterRow, OwnerTable)
.TagData(inTag)
.ParentWindow(SharedThis(this));
}
TSharedRef<ITableRow> SLoaderWindow::MakeDeveloperFilterViewWidget(FDeveloperFilteringItemPtr Entry, const TSharedRef<STableViewBase>& OwnerTable)
{
return SNew(SDeveloperFilterRow, OwnerTable)
.Entry(Entry)
.ParentWindow(SharedThis(this));
}
void SLoaderWindow::OnAssetTileSelectionChanged(TSharedPtr<FVaultMetadata> InItem, ESelectInfo::Type SelectInfo)
{
// Checks if anything is selected
if (TileView->GetNumItemsSelected() > 0)
{
ConstructMetadataWidget(InItem);
return;
}
// If no selection, clear the active metadata.
MetadataWidget->ClearChildren();
}
void SLoaderWindow::OnAssetTileDoubleClicked(TSharedPtr<FVaultMetadata> InItem)
{
// #todo Add Item to Project on Double Click
LoadAssetPackIntoProject(InItem);
}
TSharedPtr<SWidget> SLoaderWindow::OnAssetTileContextMenuOpened()
{
// Lets check we have stuff selected, we only want the context menu on selected items. No need to open on a blank area
if (TileView->GetNumItemsSelected() == 0)
{
return SNullWidget::NullWidget;
}
// Store our selected item for any future operations.
TSharedPtr<FVaultMetadata> SelectedAsset = TileView->GetSelectedItems()[0];
FMenuBuilder MenuBuilder(true, nullptr, nullptr, true);
static const FName FilterSelectionHook("AssetContextMenu");
MenuBuilder.BeginSection(FilterSelectionHook, LOCTEXT("AssetContextMenuLabel", "Vault Asset"));
{
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_AddToProjectLabel", "Add To Project"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
LoadAssetPackIntoProject(SelectedAsset);
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_EditVaultAssetDetailsLabel", "Edit Asset"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
const FString MetaFilePath = LibraryPath / SelectedAsset->PackName.ToString() + ".meta";
// Rather than provide a tonne of edit options in engine and a load of extra UI support, for the time being lets just open the file in a text editor
FPlatformProcess::LaunchFileInDefaultExternalApplication(*MetaFilePath);
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
MenuBuilder.AddMenuEntry(LOCTEXT("ACM_DeleteVaultAssetLabel", "Delete Asset"), FText::GetEmpty(), FSlateIcon(),
FUIAction(FExecuteAction::CreateLambda([this, SelectedAsset]()
{
// Open a Msg dialog to confirm deletion
const EAppReturnType::Type Confirmation = FMessageDialog::Open(EAppMsgType::YesNo, LOCTEXT("DeleteViaContextMsg", "Are you sure you want to delete this asset from the Vault Library \nThis option cannot be undone." ));
if (Confirmation == EAppReturnType::Yes)
{
// Delete Pack. Handles all the UI stuff from here as well as the file deletes.
DeleteAssetPack(SelectedAsset);
}
}),
FCanExecuteAction(),
FGetActionCheckState(),
FIsActionButtonVisible()));
}
MenuBuilder.EndSection();
return MenuBuilder.MakeWidget();
}
void SLoaderWindow::OnSearchBoxChanged(const FText& inSearchText)
{
//FilteredAssetItems.Empty();
// If its now empty, it was probably cleared or backspaced through, so we need to reapply just the filter based results.
if (inSearchText.IsEmpty())
{
UpdateFilteredAssets();
return;
}
// Store Strict Search - This controls if we only search pack name, or various data entries.
const bool bStrictSearch = StrictSearchCheckBox->GetCheckedState() == ECheckBoxState::Checked;
const FString SearchString = inSearchText.ToString();
// Holder for the newly filtered Results:
TArray<TSharedPtr<FVaultMetadata>> SearchMatchingEntries;
// Instead of searching raw meta, we search the filtered results, so this respects the tag and dev filters first, and we search within that.
for (auto Meta : FilteredAssetItems)
{
if (Meta->PackName.ToString().Contains(SearchString))
{
SearchMatchingEntries.Add(Meta);
continue;
}
if (bStrictSearch == false)
{
if (Meta->Author.ToString().Contains(SearchString) || Meta->Description.Contains(SearchString))
{
SearchMatchingEntries.Add(Meta);
}
}
}
FilteredAssetItems = SearchMatchingEntries;
TileView->RebuildList();
TileView->ScrollToTop();
}
void SLoaderWindow::OnSearchBoxCommitted(const FText& InFilterText, ETextCommit::Type CommitType)
{
OnSearchBoxChanged(InFilterText);
}
void SLoaderWindow::ConstructMetadataWidget(TSharedPtr<FVaultMetadata> AssetMeta)
{
// Safety Catches for Null Assets. Should never occur.
if (!MetadataWidget.IsValid())
{
UE_LOG(LogVault, Error, TEXT("Error - Metadata Ptr is Null."));
return;
}
if (!AssetMeta.IsValid() || !AssetMeta->IsMetaValid())
{
UE_LOG(LogVault, Error, TEXT("Error - Metadata Incoming Data is Null."));
return;
}
// Padding between words
const FMargin WordPadding = FMargin(0.f,12.f,0.f,0.f);
MetadataWidget->ClearChildren();
// Pack Name
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::FromName(AssetMeta->PackName))
];
// Description
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
//.Text(FText::Format(LOCTEXT("Meta_DescLbl", "Description: \n{0}"), FText::FromString(AssetMeta->Description)))
.Text(FText::FromString(AssetMeta->Description))
];
// Author
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_AuthorLbl", "Author: {0}"), FText::FromName(AssetMeta->Author)))
];
// Creation Date
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_CreationLbl", "Created: {0}"), FText::FromString(AssetMeta->CreationDate.ToString())))
];
// Last Modified Date
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("Meta_LastModifiedLbl", "Last Modified: {0}"), FText::FromString(AssetMeta->LastModified.ToString())))
];
// Tags List - Header
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
//.Text(FText::Format(LOCTEXT("Meta_TagsLbl", "Tags: {0}"), FText::FromString(FString::Join(AssetMeta->Tags.Array(), TEXT(",")))))
.Text(LOCTEXT("Meta_TagsLbl", "Tags:"))
];
// Tags, Per Tag. Instead of using Join, we add them as separate lines for ease of reading
for (auto MyTag : AssetMeta->Tags)
{
MyTag.TrimStartAndEndInline();
const FText TagName = FText::FromString(MyTag);
//MyTag.RemoveSpacesInline();
MetadataWidget->AddSlot()
.AutoHeight()
[
SNew(STextBlock)
.Text(FText::Format(LOCTEXT("PerTagKeyFor{0}", "- {1}"), TagName, TagName))
];
}
// Object List
MetadataWidget->AddSlot()
.AutoHeight()
.Padding(WordPadding)
[
SNew(STextBlock)
.AutoWrapText(true)
.Text(FText::Format(LOCTEXT("Meta_FilesLbl", "Files: {0}"), FText::FromString(FString::Join(AssetMeta->ObjectsInPack.Array(), TEXT(",")))))
];
}
void SLoaderWindow::LoadAssetPackIntoProject(TSharedPtr<FVaultMetadata> InPack)
{
// Root Directory
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
// All files live in same directory, so we just do some string mods to get the pack file that matches the meta file.
const FString AssetToImportTemp = LibraryPath / InPack->PackName.ToString() + ".upack";
// UPacks import natively with Unreal, so no need to try to use the PakUtilities, better to use the native importer and let Unreal handle the Pak concepts.
FAssetToolsModule& AssetToolsModule = FModuleManager::Get().LoadModuleChecked<FAssetToolsModule>("AssetTools");
// Set up our Import Task
UAssetImportTask* Task = NewObject<UAssetImportTask>();
Task->AddToRoot();
Task->bAutomated = true;
Task->bReplaceExisting = true;
Task->bSave = true;
Task->Filename = AssetToImportTemp;
Task->DestinationPath = "/Game";
TArray<UAssetImportTask*> Tasks;
Tasks.Add(Task);
AssetToolsModule.Get().ImportAssetTasks(Tasks);
// Allow GC to collect
Task->RemoveFromRoot();
}
void SLoaderWindow::DeleteAssetPack(TSharedPtr<FVaultMetadata> InPack)
{
// Confirmation will have occurred already for this operation (Might be changed in future to have confirmation here)
UE_LOG(LogVault, Display, TEXT("Deleting File(s) from Vault: %s"), *InPack->PackName.ToString());
const FString LibraryPath = FVaultSettings::Get().GetAssetLibraryRoot();
const FString FilePathAbsNoExt = LibraryPath / InPack->PackName.ToString();
const FString AbsThumbnailPath = FilePathAbsNoExt + ".png";
const FString AbsMetaPath = FilePathAbsNoExt + ".meta";
const FString AbsPackPath = FilePathAbsNoExt + ".upack";
IFileManager::Get().Delete(*AbsThumbnailPath, true);
IFileManager::Get().Delete(*AbsMetaPath, true);
IFileManager::Get().Delete(*AbsPackPath, true);
MetaFilesCache.Remove(*InPack);
RefreshLibrary();
//UpdateFilteredAssets();
//TileView->RebuildList();
}
void SLoaderWindow::RefreshAvailableFiles()
{
MetaFilesCache = FMetadataOps::FindAllMetadataInLibrary();
}
// Applies the List of filters all together.
void SLoaderWindow::UpdateFilteredAssets()
{
FilteredAssetItems.Empty();
// Special Condition to check if all boxes are cleared:
if (ActiveTagFilters.Num() == 0 && ActiveDevFilters.Num() == 0)
{
PopulateBaseAssetList();
TileView->RebuildList();
TileView->ScrollToTop();
return;
}
for (auto Asset : MetaFilesCache)
{
// Apply all filtered Tags
for (auto UserTag : Asset.Tags)
{
if (ActiveTagFilters.Contains(UserTag))
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Asset)));
break;
}
}
// Apply All Developer Tags
if (ActiveDevFilters.Contains(Asset.Author))
{
FilteredAssetItems.Add(MakeShareable(new FVaultMetadata(Asset)));
continue;
}
}
TileView->RebuildList();
TileView->ScrollToTop();
}
void SLoaderWindow::OnThumbnailSliderValueChanged(float Value)
{
TileUserScale = Value;
TileView->SetItemWidth(TILE_BASE_WIDTH * TileUserScale);
TileView->SetItemHeight(TILE_BASE_HEIGHT * TileUserScale);
TileView->RebuildList();
}
FText SLoaderWindow::DisplayTotalAssetsInLibrary() const
{
int assetCount = FMetadataOps::FindAllMetadataInLibrary().Num();
FText Display = FText::Format(LOCTEXT("displayassetcountlabel", "Total Assets in library: {0}"),assetCount);
return Display;
}
FReply SLoaderWindow::OnRefreshLibraryClicked()
{
RefreshLibrary();
return FReply::Handled();
}
void SLoaderWindow::RefreshLibrary()
{
RefreshAvailableFiles();
PopulateTagArray();
PopulateDeveloperNameArray();
//SearchBox->AdvanceSearch//
//TileView->RebuildList();
UpdateFilteredAssets();
}
void SLoaderWindow::OnNewAssetPublished()
{
RefreshLibrary();
}
void SLoaderWindow::ModifyActiveTagFilters(FString TagModified, bool bFilterThis)
{
UE_LOG(LogVault, Display, TEXT("Enabling Tag Filter For %s"), *TagModified);
if (bFilterThis)
{
// Push our Active Tag into our Set of Tags currently being searched
ActiveTagFilters.Add(TagModified);
UpdateFilteredAssets();
return;
}
ActiveTagFilters.Remove(TagModified);
UpdateFilteredAssets();
}
void SLoaderWindow::ModifyActiveDevFilters(FName DevModified, bool bFilterThis)
{
UE_LOG(LogVault, Display, TEXT("Enabling Dev Filter %s"), *DevModified.ToString());
if (bFilterThis)
{
ActiveDevFilters.Add(DevModified);
UpdateFilteredAssets();
return;
}
ActiveDevFilters.Remove(DevModified);
UpdateFilteredAssets();
}
#undef LOCTEXT_NAMESPACE
| 27.685263
| 222
| 0.705943
|
Unreal-Vault
|
54ab167058ce125f5fa40b23910f9857416f3ac2
| 276
|
hpp
|
C++
|
src/Time.hpp
|
matheuscscp/parallel-programming-final-project
|
088934d2cf188e2953de773424e877d78933ae3f
|
[
"MIT"
] | 2
|
2019-05-26T17:13:23.000Z
|
2019-06-09T05:48:57.000Z
|
src/Time.hpp
|
matheuscscp/delta-stepping
|
088934d2cf188e2953de773424e877d78933ae3f
|
[
"MIT"
] | null | null | null |
src/Time.hpp
|
matheuscscp/delta-stepping
|
088934d2cf188e2953de773424e877d78933ae3f
|
[
"MIT"
] | null | null | null |
/*
* Time.hpp
*
* Created on: Nov 20, 2014
* Author: matheus
*/
#ifndef TIME_HPP_
#define TIME_HPP_
#include <sys/time.h>
class Stopwatch {
private:
timeval i;
public:
Stopwatch();
void start();
float time() const;
};
#endif /* TIME_HPP_ */
| 12
| 28
| 0.594203
|
matheuscscp
|
54ab7ccc3f96c9c82b3d77678a96f0a80fb2ec06
| 51
|
hpp
|
C++
|
src/boost_metaparse_limit_sequence_size.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_metaparse_limit_sequence_size.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_metaparse_limit_sequence_size.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/metaparse/limit_sequence_size.hpp>
| 25.5
| 50
| 0.843137
|
miathedev
|
54b018813113477897e3df2360859fed801e2c3f
| 18,212
|
cpp
|
C++
|
source/tflite-model/trained_model_compiled.cpp
|
LetsOKdo/dance-activated-microbit
|
812c14169f4b8c61acbfc1ff0a7aeed4546eda13
|
[
"MIT"
] | 3
|
2021-07-12T05:38:00.000Z
|
2022-03-02T14:55:23.000Z
|
source/tflite-model/trained_model_compiled.cpp
|
LetsOKdo/dance-activated-microbit
|
812c14169f4b8c61acbfc1ff0a7aeed4546eda13
|
[
"MIT"
] | null | null | null |
source/tflite-model/trained_model_compiled.cpp
|
LetsOKdo/dance-activated-microbit
|
812c14169f4b8c61acbfc1ff0a7aeed4546eda13
|
[
"MIT"
] | null | null | null |
/* Generated by Edge Impulse
*
* 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.
*/
// Generated on: 11.11.2020 18:46:14
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include "edge-impulse-sdk/tensorflow/lite/c/builtin_op_data.h"
#include "edge-impulse-sdk/tensorflow/lite/c/common.h"
#include "edge-impulse-sdk/tensorflow/lite/micro/kernels/micro_ops.h"
#if defined __GNUC__
#define ALIGN(X) __attribute__((aligned(X)))
#elif defined _MSC_VER
#define ALIGN(X) __declspec(align(X))
#elif defined __TASKING__
#define ALIGN(X) __align(X)
#endif
namespace {
constexpr int kTensorArenaSize = 144;
uint8_t* tensor_arena = NULL;
static uint8_t* current_location;
static uint8_t* tensor_boundary;
template <int SZ, class T> struct TfArray {
int sz; T elem[SZ];
};
enum used_operators_e {
OP_FULLY_CONNECTED, OP_SOFTMAX, OP_LAST
};
struct TensorInfo_t { // subset of TfLiteTensor used for initialization from constant memory
TfLiteAllocationType allocation_type;
TfLiteType type;
void* data;
TfLiteIntArray* dims;
size_t bytes;
TfLiteQuantization quantization;
};
struct NodeInfo_t { // subset of TfLiteNode used for initialization from constant memory
struct TfLiteIntArray* inputs;
struct TfLiteIntArray* outputs;
void* builtin_data;
used_operators_e used_op_index;
};
TfLiteContext ctx{};
TfLiteTensor tflTensors[11];
TfLiteRegistration registrations[OP_LAST];
TfLiteNode tflNodes[4];
const TfArray<2, int> tensor_dimension0 = { 2, { 1,33 } };
const TfArray<1, float> quant0_scale = { 1, { 359.61181640625, } };
const TfArray<1, int> quant0_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant0 = { (TfLiteFloatArray*)&quant0_scale, (TfLiteIntArray*)&quant0_zero, 0 };
const ALIGN(8) int32_t tensor_data1[20] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
const TfArray<1, int> tensor_dimension1 = { 1, { 20 } };
const TfArray<1, float> quant1_scale = { 1, { 0.99230742454528809, } };
const TfArray<1, int> quant1_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant1 = { (TfLiteFloatArray*)&quant1_scale, (TfLiteIntArray*)&quant1_zero, 0 };
const ALIGN(8) int32_t tensor_data2[10] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
const TfArray<1, int> tensor_dimension2 = { 1, { 10 } };
const TfArray<1, float> quant2_scale = { 1, { 0.73306155204772949, } };
const TfArray<1, int> quant2_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant2 = { (TfLiteFloatArray*)&quant2_scale, (TfLiteIntArray*)&quant2_zero, 0 };
const ALIGN(8) int32_t tensor_data3[2] = { 0, 0, };
const TfArray<1, int> tensor_dimension3 = { 1, { 2 } };
const TfArray<1, float> quant3_scale = { 1, { 1.3037328720092773, } };
const TfArray<1, int> quant3_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant3 = { (TfLiteFloatArray*)&quant3_scale, (TfLiteIntArray*)&quant3_zero, 0 };
const ALIGN(8) int8_t tensor_data4[20*33] = {
-82, -76, -66, 21, -13, 18, -95, -81, -91, 24, 114, -53, -74, 113, 57, 125, 117, -32, 89, -70, 111, -102, 120, -80, -62, -62, -102, 56, -40, -35, -69, -100, 29,
10, 20, -6, -53, 19, 107, 70, 95, -102, 72, 58, -60, -31, -105, -75, -49, -52, -102, 86, 55, -5, -68, -102, -73, 32, -75, 26, 51, -70, -1, 92, 104, -119,
8, -109, -86, 58, 9, 34, -106, -20, -72, 21, -32, -27, -80, -26, 74, -98, -75, -28, 97, -113, 74, -13, -52, 33, -45, 111, 20, -55, -10, -68, -72, 99, -97,
-125, -41, -103, 41, 26, 29, -90, 15, 13, 95, -5, -108, 14, 50, 1, -60, -38, -29, 115, 70, -117, -77, 114, -15, -23, 103, 3, -47, 87, 14, -6, 82, 5,
-5, 62, -78, 69, 30, 101, -99, -53, 18, 32, 33, -4, -13, -32, -106, -13, -67, -61, 23, 15, 10, -51, -52, 20, -19, -59, 97, 42, 103, -7, 4, -70, -68,
69, -60, -14, -12, 5, 52, 37, 47, 5, -92, -52, -70, 117, -52, 98, 24, -55, 46, 79, 103, -60, -109, -16, -32, -74, 64, 26, -40, 72, 47, 60, 121, 12,
-81, 118, -6, -32, -37, 45, 45, -24, -49, 74, -91, -84, -112, -79, 114, 33, -18, 67, 36, -42, 23, -9, 121, -85, 40, 10, -50, 32, 38, -22, 61, -26, -70,
-40, 118, -80, -24, -102, 113, 17, -111, 101, -96, 73, -58, -86, -44, -67, -7, 2, -91, 15, -29, -26, -91, -118, -27, -22, -101, 83, 37, 44, 88, -102, 94, -111,
40, 49, 48, -115, 74, 58, -39, -22, 55, -90, -121, 120, 7, -40, -124, -69, 23, -18, 95, 7, -6, -30, -23, -64, -52, 108, -103, 30, 94, -1, -37, 40, -52,
0, 29, 17, 61, -99, -3, -5, -41, 57, -15, 10, -41, -53, -9, 16, -52, 34, 104, 93, -101, 66, -74, -3, 108, 99, -86, -37, -72, 110, 69, -97, 44, 5,
-88, -91, -106, -84, 121, -33, 46, 3, 21, 90, 16, 109, 30, 107, -4, -82, -69, 80, -32, -7, -67, 12, 85, -100, -44, 48, -80, 76, 49, -92, 120, -12, -104,
98, 64, -7, -18, 9, 121, 28, 80, 99, 108, -30, 104, 12, -76, -74, 54, 12, 76, 98, 90, 71, -50, -9, 21, 79, -85, -26, 99, -80, 76, -100, 41, -86,
41, 78, 16, -72, 89, -43, 28, -57, -20, 107, -12, -63, -90, 96, 103, -120, 57, -10, -119, -31, -116, -26, 104, -24, -104, -18, -93, 32, 90, -53, 78, -44, -42,
6, 22, -42, 75, 9, -35, 53, -28, 32, 83, 110, 103, 53, -52, -3, 24, -75, -65, 36, 98, -112, -47, 44, -54, -125, 89, 61, 15, 99, -59, -123, 115, 29,
-70, -119, 119, -53, 63, -42, 66, 76, 8, -48, -94, -20, -94, -33, 17, -15, -61, -55, -54, -69, 21, 56, -65, 50, 73, 4, -85, -16, -45, 13, 18, 0, 93,
-79, 109, -43, 42, -32, 105, -79, -66, -16, 91, -74, 54, -53, -35, 115, -93, -16, 87, 77, 80, 31, -57, 25, -104, -59, -44, 70, 41, 6, 15, -112, -103, -114,
-82, 111, 80, 26, 3, 8, -5, -49, -6, 46, 12, -90, -61, -100, -70, 66, 91, 66, -95, -8, -49, -101, -46, 99, 83, 55, -19, 23, 127, 118, 15, -14, -4,
-43, 17, -103, -94, 117, -40, 31, 97, -59, 21, 21, 61, 35, -27, -8, -27, 15, -12, -59, 102, -104, -25, 78, -87, 117, -4, -76, 127, 80, 72, 77, 32, 31,
-74, -18, 104, 111, 80, 52, 5, -76, -28, -23, -95, -79, 95, -10, -45, 87, -41, -19, -104, -20, 70, -102, -29, 125, -70, -93, 96, -26, 30, -1, 72, 53, 105,
-42, 48, 76, 52, 19, -11, -6, -107, 100, 101, -32, 87, -13, -41, 93, 35, 24, -120, 27, -24, -39, 69, 98, -110, 75, 106, -8, 103, -113, -124, -121, -94, 125,
};
const TfArray<2, int> tensor_dimension4 = { 2, { 20,33 } };
const TfArray<1, float> quant4_scale = { 1, { 0.002759384922683239, } };
const TfArray<1, int> quant4_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant4 = { (TfLiteFloatArray*)&quant4_scale, (TfLiteIntArray*)&quant4_zero, 0 };
const ALIGN(8) int8_t tensor_data5[10*20] = {
-82, -9, 29, 16, 98, -76, -37, 17, -101, -114, -43, -71, 102, 91, -33, -2, -109, 12, -39, 10,
-77, 15, -62, 44, 21, 9, 81, -52, -53, -88, 17, -94, -30, -39, -96, -109, -51, 76, 54, -103,
-86, 89, 35, -53, 77, 5, 56, -45, 100, 97, -81, -47, 28, -106, 39, -33, -23, 122, -98, -34,
-88, -23, -80, -94, -11, 54, 78, 88, 103, -82, 96, 51, 5, -78, -29, 114, 31, 32, 28, -74,
18, 3, -69, -93, -123, 98, -50, -10, -73, 113, 3, -119, -106, 40, -23, 22, 17, -111, 110, 28,
78, 91, -99, 4, -74, -27, -1, -32, 115, -111, -127, 109, -96, 48, -62, 94, -107, -17, -107, 88,
91, -39, 11, 90, 73, -36, 12, 53, 48, 97, -60, 66, -121, -13, -6, -15, 44, -27, 41, -55,
-73, 112, -60, -107, -33, -15, -31, -90, 99, 77, 80, 112, -16, 1, -26, -47, -64, 26, -44, 48,
-74, 72, 3, 49, 118, -8, 63, -119, -23, -85, 45, 84, 101, 111, -20, 57, -98, 101, -6, 9,
-40, 43, 30, 97, -95, 74, 87, -60, 87, -42, -19, 39, -95, -33, -94, 25, 120, 118, -34, 105,
};
const TfArray<2, int> tensor_dimension5 = { 2, { 10,20 } };
const TfArray<1, float> quant5_scale = { 1, { 0.0036247593816369772, } };
const TfArray<1, int> quant5_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant5 = { (TfLiteFloatArray*)&quant5_scale, (TfLiteIntArray*)&quant5_zero, 0 };
const ALIGN(8) int8_t tensor_data6[2*10] = {
-36, -127, -16, -118, 11, -83, 59, 80, 4, 51,
73, -117, -7, 109, 101, 66, 59, -3, 27, -6,
};
const TfArray<2, int> tensor_dimension6 = { 2, { 2,10 } };
const TfArray<1, float> quant6_scale = { 1, { 0.0054330769926309586, } };
const TfArray<1, int> quant6_zero = { 1, { 0 } };
const TfLiteAffineQuantization quant6 = { (TfLiteFloatArray*)&quant6_scale, (TfLiteIntArray*)&quant6_zero, 0 };
const TfArray<2, int> tensor_dimension7 = { 2, { 1,20 } };
const TfArray<1, float> quant7_scale = { 1, { 202.2373046875, } };
const TfArray<1, int> quant7_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant7 = { (TfLiteFloatArray*)&quant7_scale, (TfLiteIntArray*)&quant7_zero, 0 };
const TfArray<2, int> tensor_dimension8 = { 2, { 1,10 } };
const TfArray<1, float> quant8_scale = { 1, { 239.962158203125, } };
const TfArray<1, int> quant8_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant8 = { (TfLiteFloatArray*)&quant8_scale, (TfLiteIntArray*)&quant8_zero, 0 };
const TfArray<2, int> tensor_dimension9 = { 2, { 1,2 } };
const TfArray<1, float> quant9_scale = { 1, { 83.309806823730469, } };
const TfArray<1, int> quant9_zero = { 1, { -115 } };
const TfLiteAffineQuantization quant9 = { (TfLiteFloatArray*)&quant9_scale, (TfLiteIntArray*)&quant9_zero, 0 };
const TfArray<2, int> tensor_dimension10 = { 2, { 1,2 } };
const TfArray<1, float> quant10_scale = { 1, { 0.00390625, } };
const TfArray<1, int> quant10_zero = { 1, { -128 } };
const TfLiteAffineQuantization quant10 = { (TfLiteFloatArray*)&quant10_scale, (TfLiteIntArray*)&quant10_zero, 0 };
const TfLiteFullyConnectedParams opdata0 = { kTfLiteActRelu, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs0 = { 3, { 0,4,1 } };
const TfArray<1, int> outputs0 = { 1, { 7 } };
const TfLiteFullyConnectedParams opdata1 = { kTfLiteActRelu, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs1 = { 3, { 7,5,2 } };
const TfArray<1, int> outputs1 = { 1, { 8 } };
const TfLiteFullyConnectedParams opdata2 = { kTfLiteActNone, kTfLiteFullyConnectedWeightsFormatDefault, false, false };
const TfArray<3, int> inputs2 = { 3, { 8,6,3 } };
const TfArray<1, int> outputs2 = { 1, { 9 } };
const TfLiteSoftmaxParams opdata3 = { 1 };
const TfArray<1, int> inputs3 = { 1, { 9 } };
const TfArray<1, int> outputs3 = { 1, { 10 } };
const TensorInfo_t tensorData[] = {
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension0, 33, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant0))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data1, (TfLiteIntArray*)&tensor_dimension1, 80, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant1))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data2, (TfLiteIntArray*)&tensor_dimension2, 40, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant2))}, },
{ kTfLiteMmapRo, kTfLiteInt32, (void*)tensor_data3, (TfLiteIntArray*)&tensor_dimension3, 8, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant3))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data4, (TfLiteIntArray*)&tensor_dimension4, 660, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant4))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data5, (TfLiteIntArray*)&tensor_dimension5, 200, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant5))}, },
{ kTfLiteMmapRo, kTfLiteInt8, (void*)tensor_data6, (TfLiteIntArray*)&tensor_dimension6, 20, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant6))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 48, (TfLiteIntArray*)&tensor_dimension7, 20, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant7))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension8, 10, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant8))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 16, (TfLiteIntArray*)&tensor_dimension9, 2, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant9))}, },
{ kTfLiteArenaRw, kTfLiteInt8, tensor_arena + 0, (TfLiteIntArray*)&tensor_dimension10, 2, {kTfLiteAffineQuantization, const_cast<void*>(static_cast<const void*>(&quant10))}, },
};const NodeInfo_t nodeData[] = {
{ (TfLiteIntArray*)&inputs0, (TfLiteIntArray*)&outputs0, const_cast<void*>(static_cast<const void*>(&opdata0)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs1, (TfLiteIntArray*)&outputs1, const_cast<void*>(static_cast<const void*>(&opdata1)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs2, (TfLiteIntArray*)&outputs2, const_cast<void*>(static_cast<const void*>(&opdata2)), OP_FULLY_CONNECTED, },
{ (TfLiteIntArray*)&inputs3, (TfLiteIntArray*)&outputs3, const_cast<void*>(static_cast<const void*>(&opdata3)), OP_SOFTMAX, },
};
static std::vector<void*> overflow_buffers;
static TfLiteStatus AllocatePersistentBuffer(struct TfLiteContext* ctx,
size_t bytes, void** ptr) {
if (current_location - bytes < tensor_boundary) {
// OK, this will look super weird, but.... we have CMSIS-NN buffers which
// we cannot calculate beforehand easily.
*ptr = malloc(bytes);
if (*ptr == NULL) {
printf("ERR: Failed to allocate persistent buffer of size %u\n", bytes);
return kTfLiteError;
}
overflow_buffers.push_back(*ptr);
return kTfLiteOk;
}
current_location -= bytes;
*ptr = current_location;
return kTfLiteOk;
}
typedef struct {
size_t bytes;
void *ptr;
} scratch_buffer_t;
static std::vector<scratch_buffer_t> scratch_buffers;
static TfLiteStatus RequestScratchBufferInArena(struct TfLiteContext* ctx, size_t bytes,
int* buffer_idx) {
scratch_buffer_t b;
b.bytes = bytes;
TfLiteStatus s = AllocatePersistentBuffer(ctx, b.bytes, &b.ptr);
if (s != kTfLiteOk) {
return s;
}
scratch_buffers.push_back(b);
*buffer_idx = scratch_buffers.size() - 1;
return kTfLiteOk;
}
static void* GetScratchBuffer(struct TfLiteContext* ctx, int buffer_idx) {
if (buffer_idx > static_cast<int>(scratch_buffers.size()) - 1) {
return NULL;
}
return scratch_buffers[buffer_idx].ptr;
}
} // namespace
TfLiteStatus trained_model_init( void*(*alloc_fnc)(size_t,size_t) ) {
tensor_arena = (uint8_t*) alloc_fnc(16, kTensorArenaSize);
current_location = tensor_arena + kTensorArenaSize;
tensor_boundary = tensor_arena;
ctx.AllocatePersistentBuffer = &AllocatePersistentBuffer;
ctx.RequestScratchBufferInArena = &RequestScratchBufferInArena;
ctx.GetScratchBuffer = &GetScratchBuffer;
ctx.tensors = tflTensors;
ctx.tensors_size = 11;
for(size_t i = 0; i < 11; ++i) {
tflTensors[i].type = tensorData[i].type;
tflTensors[i].is_variable = 0;
tflTensors[i].allocation_type = tensorData[i].allocation_type;
tflTensors[i].bytes = tensorData[i].bytes;
tflTensors[i].dims = tensorData[i].dims;
if(tflTensors[i].allocation_type == kTfLiteArenaRw){
uint8_t* start = (uint8_t*) ((uintptr_t)tensorData[i].data + (uintptr_t) tensor_arena);
uint8_t* end = start + tensorData[i].bytes;
tflTensors[i].data.data = start;
if (end > tensor_boundary) {
tensor_boundary = end;
}
}
else{
tflTensors[i].data.data = tensorData[i].data;
}
tflTensors[i].quantization = tensorData[i].quantization;
if (tflTensors[i].quantization.type == kTfLiteAffineQuantization) {
TfLiteAffineQuantization const* quant = ((TfLiteAffineQuantization const*)(tensorData[i].quantization.params));
tflTensors[i].params.scale = quant->scale->data[0];
tflTensors[i].params.zero_point = quant->zero_point->data[0];
}
}
registrations[OP_FULLY_CONNECTED] = *tflite::ops::micro::Register_FULLY_CONNECTED();
registrations[OP_SOFTMAX] = *tflite::ops::micro::Register_SOFTMAX();
for(size_t i = 0; i < 4; ++i) {
tflNodes[i].inputs = nodeData[i].inputs;
tflNodes[i].outputs = nodeData[i].outputs;
tflNodes[i].builtin_data = nodeData[i].builtin_data;
tflNodes[i].custom_initial_data = nullptr;
tflNodes[i].custom_initial_data_size = 0;
if (registrations[nodeData[i].used_op_index].init) {
tflNodes[i].user_data = registrations[nodeData[i].used_op_index].init(&ctx, (const char*)tflNodes[i].builtin_data, 0);
}
}
for(size_t i = 0; i < 4; ++i) {
if (registrations[nodeData[i].used_op_index].prepare) {
TfLiteStatus status = registrations[nodeData[i].used_op_index].prepare(&ctx, &tflNodes[i]);
if (status != kTfLiteOk) {
return status;
}
}
}
return kTfLiteOk;
}
static const int inTensorIndices[] = {
0,
};
TfLiteTensor* trained_model_input(int index) {
return &ctx.tensors[inTensorIndices[index]];
}
static const int outTensorIndices[] = {
10,
};
TfLiteTensor* trained_model_output(int index) {
return &ctx.tensors[outTensorIndices[index]];
}
TfLiteStatus trained_model_invoke() {
for(size_t i = 0; i < 4; ++i) {
TfLiteStatus status = registrations[nodeData[i].used_op_index].invoke(&ctx, &tflNodes[i]);
if (status != kTfLiteOk) {
return status;
}
}
return kTfLiteOk;
}
TfLiteStatus trained_model_reset( void (*free_fnc)(void* ptr) ) {
free_fnc(tensor_arena);
scratch_buffers.clear();
for (size_t ix = 0; ix < overflow_buffers.size(); ix++) {
free(overflow_buffers[ix]);
}
overflow_buffers.clear();
return kTfLiteOk;
}
| 55.52439
| 180
| 0.652152
|
LetsOKdo
|
2a664c5cf5e630d6683e8571819067dd25e5e2cf
| 1,044
|
cpp
|
C++
|
src/utils/chrono.cpp
|
Ymagis/EclairLooks
|
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
|
[
"BSD-3-Clause"
] | 9
|
2019-07-03T13:11:33.000Z
|
2021-10-06T13:55:31.000Z
|
src/utils/chrono.cpp
|
Ymagis/EclairLooks
|
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
|
[
"BSD-3-Clause"
] | 1
|
2019-07-09T09:04:59.000Z
|
2019-08-06T13:23:47.000Z
|
src/utils/chrono.cpp
|
Ymagis/EclairLooks
|
c04fb1af1160305fb1dbffb2ea92cc478cd70b31
|
[
"BSD-3-Clause"
] | 4
|
2019-07-02T15:03:43.000Z
|
2019-09-28T14:33:03.000Z
|
#include "chrono.h"
using namespace std::chrono;
Chrono::Chrono()
: _paused(false)
{
}
Chrono::~Chrono()
{
}
void Chrono::start()
{
// reset chrono if already running
_startTime = ClockT::now();
_current_duration = DurationT::zero();
}
void Chrono::pause()
{
if(!_paused)
{
_current_duration = ClockT::now() - _startTime;
_paused = true;
}
}
void Chrono::resume()
{
if(_paused == true)
{
_startTime = ClockT::now();
_paused = false;
}
}
float Chrono::ellapsed(DurationType dt)
{
if(!_paused)
{
_current_duration += ClockT::now() - _startTime;
_startTime = ClockT::now();
}
float ellapsed = 0;
switch(dt)
{
case MINUTES :
ellapsed = duration_cast<minutes>(_current_duration).count();
break;
case SECONDS :
ellapsed = duration_cast<seconds>(_current_duration).count();
break;
case MILLISECONDS :
ellapsed = duration_cast<milliseconds>(_current_duration).count();
break;
case NANOSECONDS :
ellapsed = duration_cast<nanoseconds>(_current_duration).count();
}
return ellapsed;
}
| 15.58209
| 69
| 0.675287
|
Ymagis
|
2a67473bd414db7b92dafbc301b5b719af1fa3eb
| 1,372
|
cpp
|
C++
|
tps_base_link/src/tps_base_link.cpp
|
WRS-TNK/wrs_tnk_robot
|
9cfaa5b1fab2c5a707ee434effe5a838b62424b7
|
[
"MIT"
] | 1
|
2019-08-16T07:10:24.000Z
|
2019-08-16T07:10:24.000Z
|
tps_base_link/src/tps_base_link.cpp
|
WRS-TNK/wrs_tnk_robot
|
9cfaa5b1fab2c5a707ee434effe5a838b62424b7
|
[
"MIT"
] | null | null | null |
tps_base_link/src/tps_base_link.cpp
|
WRS-TNK/wrs_tnk_robot
|
9cfaa5b1fab2c5a707ee434effe5a838b62424b7
|
[
"MIT"
] | null | null | null |
#include <ros/ros.h>
#include <tf2/LinearMath/Vector3.h>
#include <tf2/LinearMath/Quaternion.h>
#include <tf2/LinearMath/Matrix3x3.h>
#include <tf2_ros/transform_listener.h>
#include <geometry_msgs/TransformStamped.h>
#include <tf2_ros/transform_broadcaster.h>
int main(int argc, char** argv)
{
ros::init(argc, argv, "tps_base_link");
ros::NodeHandle n;
tf2_ros::Buffer tfBuffer;
tf2_ros::TransformListener tfListener(tfBuffer);
tf2_ros::TransformBroadcaster tb;
geometry_msgs::TransformStamped ts;
ros::Rate r(25.0);
while(ros::ok()){
geometry_msgs::TransformStamped transform;
try{
transform = tfBuffer.lookupTransform("map", "base_link", ros::Time(0));
}
catch (tf2::TransformException &ex){
ROS_ERROR("%s", ex.what());
ros::Duration(1.0).sleep();
continue;
}
ts.header.stamp = transform.header.stamp;
ts.header.frame_id = "map";
ts.child_frame_id = "tps_base_link";
ts.transform.translation.x = transform.transform.translation.x;
ts.transform.translation.y = transform.transform.translation.y;
ts.transform.translation.z = 0;
tf2::Quaternion rotation;
rotation.setRPY(0, 0, 0);
ts.transform.rotation.x = rotation.x();
ts.transform.rotation.y = rotation.y();
ts.transform.rotation.z = rotation.z();
ts.transform.rotation.w = rotation.w();
tb.sendTransform(ts);
r.sleep();
}
return 0;
}
| 24.945455
| 74
| 0.710641
|
WRS-TNK
|
2a716f151aa21b1f2c44232d9976c37867ed224e
| 981
|
cpp
|
C++
|
USACO/2014/feb/hopscotch_bronze.cpp
|
nalinbhardwaj/olympiad
|
6b640d8cef2fa16fb4e9776f8416575519357edf
|
[
"MIT"
] | 1
|
2018-12-14T07:51:26.000Z
|
2018-12-14T07:51:26.000Z
|
USACO/2014/feb/hopscotch_bronze.cpp
|
nalinbhardwaj/olympiad
|
6b640d8cef2fa16fb4e9776f8416575519357edf
|
[
"MIT"
] | null | null | null |
USACO/2014/feb/hopscotch_bronze.cpp
|
nalinbhardwaj/olympiad
|
6b640d8cef2fa16fb4e9776f8416575519357edf
|
[
"MIT"
] | 1
|
2019-06-23T10:34:19.000Z
|
2019-06-23T10:34:19.000Z
|
/*
PROG: COW
LANG: C++
ID: nibnalin
*/
//USACO February Contest
#include <fstream>
#include <vector>
#include <climits>
using namespace std;
vector<vector<int> > grid;
vector< vector<long> > memtable;
int ans(long x, long y) {
if(memtable[x][y] == INT_MIN)
{
long paths = 0;
for(long i = (x-1);i >= 0;i--)
{
for(long j = (y-1);j >= 0;j--)
{
if(grid[x][y] != grid[i][j])
{
paths += ans(i, j);
}
}
}
memtable[x][y] = paths;
return paths;
}
else
return memtable[x][y];
}
int main(void)
{
ifstream fin ("hopscotch.in");
ofstream fout ("hopscotch.out");
long r, c;
fin >> r >> c;
grid.clear();
grid.resize(r, vector<int>(c));
memtable.clear();
memtable.resize(r, vector<long>(c, INT_MIN));
for(int i = 0;i < r;i++)
{
string tmp;
fin >> tmp;
for(int j = 0;j < c;j++)
{
if(tmp[j] == 'R')
grid[i][j] = 1;
else
grid[i][j] = 0;
}
}
memtable[0][0] = 1;
fout << ans(r-1, c-1) << endl; //Recurse, memoize
}
| 16.081967
| 50
| 0.540265
|
nalinbhardwaj
|
2a75e213076961ba296d5a5866f686977fed0115
| 1,045
|
hpp
|
C++
|
dart/utils/amc/ReadSkeleton.hpp
|
jyf588/nimblephysics
|
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
|
[
"BSD-2-Clause"
] | 2
|
2021-09-30T06:23:29.000Z
|
2022-03-09T09:59:09.000Z
|
dart/utils/amc/ReadSkeleton.hpp
|
jyf588/nimblephysics
|
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
|
[
"BSD-2-Clause"
] | null | null | null |
dart/utils/amc/ReadSkeleton.hpp
|
jyf588/nimblephysics
|
6c09228f0abcf7aa3526a8dd65cd2541aff32c4a
|
[
"BSD-2-Clause"
] | 1
|
2021-08-20T13:56:14.000Z
|
2021-08-20T13:56:14.000Z
|
#ifndef AMC_READSKELETON_HPP
#define AMC_READSKELETON_HPP
#include <string>
#include <vector>
#include "Skeleton.hpp"
using std::string;
using std::vector;
bool ReadSkeleton(string filename, Library::Skeleton& into);
bool ReadSkeletonV(string filename, Library::Skeleton& into);
// read 'amc' file format (automatically will call below on '.bmc' and '.v',
// though):
bool ReadAnimation(
string filename, Library::Skeleton const& on, vector<double>& positions);
// read the 'bmc' binary format (somewhat faster, probably):
bool ReadAnimationBin(
string filename, Library::Skeleton const& on, vector<double>& positions);
// read the '.v' file format:
bool ReadAnimationV(
string filename, Library::Skeleton const& on, vector<double>& positions);
// copies skel into transformer, but making it into an euler-angle skeleton
// pose.skeleton = &transformer;
// pose.to_angles(angles);
// angles.to_pose(pose);
void get_euler_skeleton(
Library::Skeleton& transformer, const Library::Skeleton& skel);
#endif // READSKELETON_HPP
| 30.735294
| 77
| 0.747368
|
jyf588
|
2a760ab3d73648d5df9057572aa0c23fb98e8d87
| 9,193
|
cpp
|
C++
|
src/storage/http/StorageHttpDownloadHandler.cpp
|
xuguruogu/nebula
|
50af1ae440415f89cc98b2b2567b53771310ac63
|
[
"Apache-2.0"
] | null | null | null |
src/storage/http/StorageHttpDownloadHandler.cpp
|
xuguruogu/nebula
|
50af1ae440415f89cc98b2b2567b53771310ac63
|
[
"Apache-2.0"
] | null | null | null |
src/storage/http/StorageHttpDownloadHandler.cpp
|
xuguruogu/nebula
|
50af1ae440415f89cc98b2b2567b53771310ac63
|
[
"Apache-2.0"
] | null | null | null |
/* Copyright (c) 2019 vesoft inc. All rights reserved.
*
* This source code is licensed under Apache 2.0 License,
* attached with Common Clause Condition 1.0, found in the LICENSES directory.
*/
#include "storage/http/StorageHttpDownloadHandler.h"
#include "webservice/Common.h"
#include "process/ProcessUtils.h"
#include "fs/FileUtils.h"
#include "hdfs/HdfsHelper.h"
#include "kvstore/Part.h"
#include "thread/GenericThreadPool.h"
#include <proxygen/httpserver/RequestHandler.h>
#include <proxygen/lib/http/ProxygenErrorEnum.h>
#include <proxygen/httpserver/ResponseBuilder.h>
#include <mutex>
DEFINE_int32(download_thread_num, 3, "download thread number");
namespace nebula {
namespace storage {
using proxygen::HTTPMessage;
using proxygen::HTTPMethod;
using proxygen::ProxygenError;
using proxygen::UpgradeProtocol;
using proxygen::ResponseBuilder;
void StorageHttpDownloadHandler::init(nebula::hdfs::HdfsHelper *helper,
nebula::thread::GenericThreadPool *pool,
nebula::kvstore::KVStore *kvstore,
std::vector<std::string> paths) {
helper_ = helper;
pool_ = pool;
kvstore_ = kvstore;
paths_ = paths;
CHECK_NOTNULL(helper_);
CHECK_NOTNULL(pool_);
CHECK_NOTNULL(kvstore_);
CHECK(!paths_.empty());
}
void StorageHttpDownloadHandler::onRequest(std::unique_ptr<HTTPMessage> headers) noexcept {
if (headers->getMethod().value() != HTTPMethod::GET) {
// Unsupported method
err_ = HttpCode::E_UNSUPPORTED_METHOD;
return;
}
if (!headers->hasQueryParam("host") ||
!headers->hasQueryParam("port") ||
!headers->hasQueryParam("path") ||
!headers->hasQueryParam("parts") ||
!headers->hasQueryParam("space")) {
LOG(ERROR) << "Illegal Argument";
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
hdfsHost_ = headers->getQueryParam("host");
hdfsPort_ = headers->getIntQueryParam("port");
hdfsPath_ = headers->getQueryParam("path");
if (headers->hasQueryParam("options")) {
options_.assign(headers->getQueryParam("options"));
}
auto existStatus = helper_->exist(hdfsHost_, hdfsPort_, hdfsPath_, options_);
if (!existStatus.ok()) {
LOG(ERROR) << "Run Hdfs Test failed. " << existStatus.status().toString();
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
}
bool exist = existStatus.value();
if (!exist) {
LOG(ERROR) << "Hdfs non exist. hdfs://" << hdfsHost_ << ":" << hdfsPort_ << hdfsPath_;
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
spaceID_ = headers->getIntQueryParam("space");
auto partitions = headers->getQueryParam("parts");
folly::split(",", partitions, parts_, true);
if (parts_.empty()) {
LOG(ERROR) << "Partitions should be not empty";
err_ = HttpCode::E_ILLEGAL_ARGUMENT;
return;
}
if (headers->hasQueryParam("tag")) {
auto& tag = headers->getQueryParam("tag");
tag_.assign(folly::to<TagID>(tag));
}
if (headers->hasQueryParam("edge")) {
auto& edge = headers->getQueryParam("edge");
edge_.assign(folly::to<EdgeType>(edge));
}
for (auto &path : paths_) {
std::string downloadRootPath = folly::stringPrintf(
"%s/nebula/%d/download", path.c_str(), spaceID_);
std::string downloadRootPathEdge = downloadRootPath + "/edge";
std::string downloadRootPathTag = downloadRootPath + "/tag";
std::string downloadRootPathGeneral = downloadRootPath + "/general";
std::string downloadPath;
if (edge_.has_value()) {
downloadPath = folly::stringPrintf(
"%s/%d",
downloadRootPathEdge.c_str(), edge_.value());
} else if (tag_.has_value()) {
downloadPath = folly::stringPrintf(
"%s/%d",
downloadRootPathTag.c_str(), tag_.value());
} else {
downloadPath = downloadRootPathGeneral;
}
fs::FileUtils::remove(downloadPath.c_str(), true);
fs::FileUtils::makeDir(downloadPath);
}
}
void StorageHttpDownloadHandler::onBody(std::unique_ptr<folly::IOBuf>) noexcept {
// Do nothing, we only support GET
}
void StorageHttpDownloadHandler::onEOM() noexcept {
switch (err_) {
case HttpCode::E_UNSUPPORTED_METHOD:
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::METHOD_NOT_ALLOWED),
WebServiceUtils::toString(HttpStatusCode::METHOD_NOT_ALLOWED))
.sendWithEOM();
return;
case HttpCode::E_ILLEGAL_ARGUMENT:
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::BAD_REQUEST),
WebServiceUtils::toString(HttpStatusCode::BAD_REQUEST))
.sendWithEOM();
return;
default:
break;
}
if (helper_->checkHadoopPath()) {
if (downloadSSTFiles()) {
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::OK),
WebServiceUtils::toString(HttpStatusCode::OK))
.body("SSTFile download successfully")
.sendWithEOM();
} else {
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::FORBIDDEN),
WebServiceUtils::toString(HttpStatusCode::FORBIDDEN))
.body("SSTFile download failed")
.sendWithEOM();
}
} else {
LOG(ERROR) << "HADOOP_HOME not exist";
ResponseBuilder(downstream_)
.status(WebServiceUtils::to(HttpStatusCode::NOT_FOUND),
WebServiceUtils::toString(HttpStatusCode::NOT_FOUND))
.sendWithEOM();
}
}
void StorageHttpDownloadHandler::onUpgrade(UpgradeProtocol) noexcept {
// Do nothing
}
void StorageHttpDownloadHandler::requestComplete() noexcept {
delete this;
}
void StorageHttpDownloadHandler::onError(ProxygenError error) noexcept {
LOG(ERROR) << "Web Service StorageHttpDownloadHandler got error: "
<< proxygen::getErrorString(error);
}
bool StorageHttpDownloadHandler::downloadSSTFiles() {
std::vector<folly::SemiFuture<bool>> futures;
for (auto& part : parts_) {
PartitionID partId;
try {
partId = folly::to<PartitionID>(part);
} catch (const std::exception& ex) {
LOG(ERROR) << "Invalid part: \"" << part << "\"";
return false;
}
auto hdfsPartPath = folly::stringPrintf("%s/%d", hdfsPath_.c_str(), partId);
auto existStatus = helper_->exist(hdfsHost_, hdfsPort_, hdfsPartPath, options_);
if (!existStatus.ok()) {
LOG(ERROR) << "Run Hdfs Test failed. " << existStatus.status().toString();
return false;
}
bool exist = existStatus.value();
if (!exist) {
LOG(WARNING) << "Hdfs path non exist. hdfs://"
<< hdfsHost_ << ":" << hdfsPort_ << hdfsPartPath;
continue;
}
auto partResult = kvstore_->part(spaceID_, partId);
if (!ok(partResult)) {
LOG(ERROR) << "Can't found space: " << spaceID_ << ", part: " << partId;
return false;
}
auto partDataRoot = value(partResult)->engine()->getDataRoot();
std::string localPath;
if (edge_.has_value()) {
localPath = folly::stringPrintf(
"%s/download/edge/%d", partDataRoot, edge_.value());
} else if (tag_.has_value()) {
localPath = folly::stringPrintf(
"%s/download/tag/%d", partDataRoot, tag_.value());
} else {
localPath = folly::stringPrintf(
"%s/download/general", partDataRoot);
}
auto downloader = [this, hdfsPartPath, localPath] {
auto resultStatus = this->helper_->copyToLocal(
hdfsHost_, hdfsPort_, hdfsPartPath, localPath, options_);
if (!resultStatus.ok()) {
LOG(ERROR) << "Run Hdfs CopyToLocal failed. "
<< resultStatus.status().toString();
return false;
}
auto result = std::move(resultStatus).value();
return result.empty();
};
auto future = pool_->addTask(downloader);
futures.push_back(std::move(future));
}
bool successfully{true};
folly::collectAll(futures).thenValue([&](const std::vector<folly::Try<bool>>& tries) {
for (const auto& t : tries) {
if (t.hasException()) {
LOG(ERROR) << "Download Failed: " << t.exception();
successfully = false;
break;
}
if (!t.value()) {
successfully = false;
break;
}
}
}).wait();
LOG(INFO) << "Download tasks have finished";
return successfully;
}
} // namespace storage
} // namespace nebula
| 34.82197
| 94
| 0.589579
|
xuguruogu
|
2a76f8f4ffcc98ceb57bede3502eab783f260a31
| 562
|
hh
|
C++
|
mimosa/git/commit.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 24
|
2015-01-19T16:38:24.000Z
|
2022-01-15T01:25:30.000Z
|
mimosa/git/commit.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 2
|
2017-01-07T10:47:06.000Z
|
2018-01-16T07:19:57.000Z
|
mimosa/git/commit.hh
|
abique/mimosa
|
42c0041b570b55a24c606a7da79c70c9933c07d4
|
[
"MIT"
] | 7
|
2015-01-19T16:38:31.000Z
|
2020-12-12T19:10:30.000Z
|
#pragma once
# include <git2.h>
# include "../mimosa/mimosa/non-copyable.hh"
namespace mimosa
{
namespace git
{
class Commit : public NonCopyable
{
public:
inline Commit() : commit_(nullptr) {}
inline Commit(git_repository *repo, const git_oid *id) {
git_commit_lookup(&commit_, repo, id);
}
inline ~Commit() { git_commit_free(commit_); }
inline git_commit** ref() { return &commit_; }
inline operator git_commit *() const { return commit_; }
private:
git_commit *commit_;
};
}
}
| 19.37931
| 62
| 0.617438
|
abique
|
2a7a17eb32aa76f1824c22d26b9978c1c654c6b4
| 1,152
|
cpp
|
C++
|
algospot/starforce/main.cpp
|
seirion/code
|
3b8bf79764107255185061cec33decbc2235d03a
|
[
"Apache-2.0"
] | 13
|
2015-06-07T09:26:26.000Z
|
2019-05-01T13:23:38.000Z
|
algospot/starforce/main.cpp
|
seirion/code
|
3b8bf79764107255185061cec33decbc2235d03a
|
[
"Apache-2.0"
] | null | null | null |
algospot/starforce/main.cpp
|
seirion/code
|
3b8bf79764107255185061cec33decbc2235d03a
|
[
"Apache-2.0"
] | 4
|
2016-03-05T06:21:05.000Z
|
2017-02-17T15:34:18.000Z
|
// http://algospot.com/judge/problem/read/STARFORCE
#include <cstdio>
#include <iostream>
using namespace std;
int n, m, s, best;
int in[200];
int pre[200][200]; // pre processed : or
void input() {
scanf("%d %d", &n, &m);
int i, j;
for (i = 0; i < n; i++) {
scanf("%d", &in[i]);
}
for (i = 0; i < n; i++) {
pre[i][i] = in[i];
for (j = i + 1; j < n; j++) {
pre[i][j] = pre[i][j-1] | in[j];
}
}
}
bool possible(int all, int start, int remain) {
if (remain == 0) return true;
for (int i = start; i <= n - remain; i++) {
if ((all & pre[start][i]) == all) {
return possible(all, i+1, remain-1);
}
}
return false;
}
int next(int v) {
unsigned int t = (v | (v - 1)) + 1;
return t | ((((t & -t) / (v & -v)) >> 1) - 1);
}
void solve() {
int now = 0xFFFF;
while (now > 0) {
if (possible(now, 0, m)) break;
now = next(now) & 0xFFFF;
}
printf("%d\n", __builtin_popcount(now));
}
int main() {
int num;
scanf("%d", &num);
for (int i = 0; i < num; i++) {input(); solve();}
return 0;
}
| 19.525424
| 53
| 0.454861
|
seirion
|
2a84f22684d7b564d74896a34f15a6aa02daef67
| 4,930
|
cpp
|
C++
|
Libraries/libvitaboy/vbparse.cpp
|
daddesio/Niotso
|
66ce47351427fa37c683f61003e0d3aa6b84e4f7
|
[
"ISC"
] | 10
|
2017-04-28T08:09:25.000Z
|
2022-03-28T11:08:18.000Z
|
Libraries/libvitaboy/vbparse.cpp
|
Fatbag/Niotso
|
66ce47351427fa37c683f61003e0d3aa6b84e4f7
|
[
"ISC"
] | null | null | null |
Libraries/libvitaboy/vbparse.cpp
|
Fatbag/Niotso
|
66ce47351427fa37c683f61003e0d3aa6b84e4f7
|
[
"ISC"
] | 4
|
2015-06-23T11:06:34.000Z
|
2017-01-17T03:50:08.000Z
|
/*
libvitaboy - Open source OpenGL TSO character animation library
vbparse.cpp - Copyright (c) 2012 Niotso Project <http://niotso.org/>
Author(s): Fatbag <X-Fi6@phppoll.org>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <strings.h>
#include <FileHandler.hpp>
#include "libvitaboy.hpp"
enum VBFileType {
VBFILE_ANIM,
VBFILE_APR,
VBFILE_BND,
VBFILE_COL,
VBFILE_HAG,
VBFILE_MESH,
VBFILE_OFT,
VBFILE_PO,
VBFILE_SKEL
};
int main(int argc, char *argv[]){
int type;
char * InFile;
if(argc == 1 || !strcmp(argv[1], "-h") || !strcmp(argv[1], "--help")){
printf("Usage: vbparse [-t type] infile\n"
"Parse a TSO VitaBoy file.\n"
"\n"
"Supported types:\n"
" (*) ANIM - Animation\n"
" (*) APR - Appearance\n"
" (*) BND - Binding\n"
" (*) COL - Collection\n"
" (*) HAG - Hand group\n"
" (*) MESH - Mesh\n"
" (*) OFT - Outfit\n"
" (*) PO - Purchasable object\n"
" (*) SKEL - Skeleton\n"
"\n"
"Report bugs to <X-Fi6@phppoll.org>.\n"
"vbparse is maintained by the Niotso project.\n"
"Home page: <http://www.niotso.org/>");
return 0;
}
if(argc >= 4 && !strcmp(argv[1], "-t")){
if(!stricmp(argv[2], "anim")) type = 0;
else if(!stricmp(argv[2], "apr")) type = 1;
else if(!stricmp(argv[2], "bnd")) type = 2;
else if(!stricmp(argv[2], "col")) type = 3;
else if(!stricmp(argv[2], "hag")) type = 4;
else if(!stricmp(argv[2], "mesh")) type = 5;
else if(!stricmp(argv[2], "oft")) type = 6;
else if(!stricmp(argv[2], "po")) type = 7;
else if(!stricmp(argv[2], "skel")) type = 8;
else{
printf("%sUnrecognized type '%s'", "vbparse: Error: ", argv[2]);
return -1;
}
InFile = argv[3];
}else{
char * pos = strrchr(argv[1], '.') + 1;
if(!stricmp(pos, "anim")) type = 0;
else if(!stricmp(pos, "apr")) type = 1;
else if(!stricmp(pos, "bnd")) type = 2;
else if(!stricmp(pos, "col")) type = 3;
else if(!stricmp(pos, "hag")) type = 4;
else if(!stricmp(pos, "mesh")) type = 5;
else if(!stricmp(pos, "oft")) type = 6;
else if(!stricmp(pos, "po")) type = 7;
else if(!stricmp(pos, "skel")) type = 8;
else{
printf("%sUnrecognized type", "vbparse: Error: ");
return -1;
}
InFile = argv[1];
}
uint8_t *InData = File::ReadFile(InFile);
if(InData == NULL){
const char * Message;
switch(File::Error){
case FERR_NOT_FOUND:
Message = "%s does not exist.";
break;
case FERR_OPEN:
Message = "%s could not be opened for reading.";
break;
case FERR_BLANK:
Message = "%s is corrupt or invalid.";
break;
case FERR_MEMORY:
Message = "Memory for %s could not be allocated.";
break;
default:
Message = "%s could not be read.";
break;
}
printf(Message, InFile);
return -1;
}
VBFile.set(InData, File::FileSize);
switch(type){
case VBFILE_ANIM:
Animation_t Animation;
ReadAnimation(Animation);
break;
case VBFILE_APR:
Appearance_t Appearance;
ReadAppearance(Appearance);
break;
case VBFILE_BND:
Binding_t Binding;
ReadBinding(Binding);
break;
case VBFILE_COL:
Collection_t Collection;
ReadCollection(Collection);
break;
case VBFILE_HAG:
HandGroup_t HandGroup;
ReadHandGroup(HandGroup);
break;
case VBFILE_MESH:
Mesh_t Mesh;
ReadMesh(Mesh);
break;
case VBFILE_OFT:
Outfit_t Outfit;
ReadOutfit(Outfit);
break;
case VBFILE_PO:
PurchasableOutfit_t PurchasableOutfit;
ReadPurchasableOutfit(PurchasableOutfit);
break;
case VBFILE_SKEL:
Skeleton_t Skeleton;
ReadSkeleton(Skeleton);
}
return 0;
}
| 30.8125
| 76
| 0.558621
|
daddesio
|
2a8c25a01728f4ae28a96fee151383affdcce969
| 6,100
|
cpp
|
C++
|
TricksterEngine/src/Rendering/Text/Internal/Font.cpp
|
Trickje/Trickster
|
ab73f15ec1b45676a20793ad6d4e9acfc2ba944e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
TricksterEngine/src/Rendering/Text/Internal/Font.cpp
|
Trickje/Trickster
|
ab73f15ec1b45676a20793ad6d4e9acfc2ba944e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
TricksterEngine/src/Rendering/Text/Internal/Font.cpp
|
Trickje/Trickster
|
ab73f15ec1b45676a20793ad6d4e9acfc2ba944e
|
[
"ECL-2.0",
"Apache-2.0"
] | null | null | null |
#include "pch.h"
#include "Rendering/Text/Internal/Font.h"
#include "Core/Application.h"
#include "Rendering/ShaderManager.h"
#include "Rendering/Shader.h"
#include "Rendering/Window.h"
#include <glm/gtc/type_ptr.hpp>
using namespace TE;
#ifdef TRICKSTER_OPENGL
void Font::Initialize()
{
// configure VAO/VBO for texture quads
// -----------------------------------
glGenVertexArrays(1, &m_VAO);
glGenBuffers(1, &m_VBO);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
/*
* The size of each vertex
* Position: x, y, z = 3
* Color: r, g, b, a = 4
* TODO: implement batch rendering
*
*/
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(float) * 9, 0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(float) * 9, (const GLvoid*)(3 * sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 4, GL_FLOAT, GL_FALSE, sizeof(float) * 9, (const GLvoid*)(5 * sizeof(float)));
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
}
void Font::LoadFromFile(const std::string& a_FileName)
{
FT_Error m_Error;
FT_Library m_Library;
FT_Face m_Face;
if (FT_Init_FreeType(&m_Library))
{
LOG_ERROR("[Font] " + a_FileName + " Could not init FreeType Library");
return;
}
if (FT_New_Face(m_Library, ("Resources/Fonts/" + a_FileName + ".ttf").c_str(), 0, &m_Face)) {
LOG_ERROR("[Font] " + a_FileName + " Failed to load font");
return;
}
// set size to load glyphs as
FT_Set_Pixel_Sizes(m_Face, 0, 48);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // disable byte-alignment restriction
FT_GlyphSlot g = m_Face->glyph;
int w = 0;
int h = 0;
for (int i = 0; i < 128; i++) {
if (FT_Load_Char(m_Face, i, FT_LOAD_RENDER)) {
fprintf(stderr, "Loading character %c failed!\n", i);
continue;
}
w += g->bitmap.width;
h = max(h, static_cast<int>(g->bitmap.rows));
}
/* you might as well save this value as it is needed later on */
atlas_width = static_cast<float>(w);
atlas_height = static_cast<float>(h);
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &tex);
glBindTexture(GL_TEXTURE_2D, tex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, 0);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
int x = 0;
for (unsigned char c = 0; c < 128; c++) {
if (FT_Load_Char(m_Face, c, FT_LOAD_RENDER))
continue;
m_Characters[c].ax = g->advance.x >> 6;
m_Characters[c].ay = g->advance.y >> 6;
m_Characters[c].bw = g->bitmap.width;
m_Characters[c].bh = g->bitmap.rows;
m_Characters[c].bl = g->bitmap_left;
m_Characters[c].bt = g->bitmap_top;
m_Characters[c].tx = static_cast<float>(x) / static_cast<float>(w);
glTexSubImage2D(GL_TEXTURE_2D, 0, x, 0, g->bitmap.width, g->bitmap.rows, GL_RED, GL_UNSIGNED_BYTE, g->bitmap.buffer);
x += g->bitmap.width;
}
glBindTexture(GL_TEXTURE_2D, 0);
// destroy FreeType once we're finished
FT_Done_Face(m_Face);
FT_Done_FreeType(m_Library);
}
void Font::Render()
{
Shader* shader = ShaderManager::GetShader("BasicFont");
shader->Bind();
glm::mat4 projection = glm::ortho(0.0f, static_cast<float>(Application::Get()->GetWindow()->GetWidth()), 0.0f, static_cast<float>(Application::Get()->GetWindow()->GetHeight()));
// activate corresponding render state
glUniformMatrix4fv(shader->GetUniformLocation("projection"), 1, GL_FALSE, glm::value_ptr(projection));
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex);
glBindVertexArray(m_VAO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, coords.size() * 9 * sizeof(float), &coords[0], GL_DYNAMIC_DRAW);
glDrawArrays(GL_TRIANGLES, 0, coords.size());
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindTexture(GL_TEXTURE_2D, 0);
coords.clear();
}
bool Font::operator==(const Font& other)
{
return m_FileName == other.m_FileName;
}
void Font::AddVertexData(std::string text, float x, float y, float scale, glm::vec4 color)
{
// iterate through all characters
std::string::const_iterator c;
for (c = text.begin(); c != text.end(); c++)
{
Character* ch = &m_Characters[*c];
float x2 = x + ch->bl * scale;
float y2 = -y - ch->bt * scale;
float w = ch->bw * scale;
float h = ch->bh * scale;
/* Advance the cursor to the start of the next character */
x += ch->ax * scale;
y += ch->ay * scale;
float z = 0.f;
coords.push_back({ x2, -y2 , z, ch->tx, 0, color.r, color.g, color.b, color.a });
coords.push_back({ x2 + w, -y2 , z,ch->tx + ch->bw / atlas_width, 0 , color.r, color.g, color.b, color.a });
coords.push_back({ x2, -y2 - h, z, ch->tx, ch->bh / atlas_height, color.r, color.g, color.b, color.a }); //remember: each glyph occupies a different amount of vertical space
coords.push_back({ x2 + w, -y2 , z, ch->tx + ch->bw / atlas_width, 0 , color.r, color.g, color.b, color.a });
coords.push_back({ x2, -y2 - h, z, ch->tx, ch->bh / atlas_height , color.r, color.g, color.b, color.a });
coords.push_back({ x2 + w, -y2 - h, z, ch->tx + ch->bw / atlas_width, ch->bh / atlas_height , color.r, color.g, color.b, color.a });
}
}
#endif
#ifdef TRICKSTER_VULKAN
void Font::AddVertexData(std::string text, float x, float y, float scale, glm::vec4 color)
{
}
void Font::Initialize()
{
}
void Font::LoadFromFile(const std::string& a_FileName)
{
}
void Font::Render()
{
}
bool Font::operator==(const Font& other)
{
return true;
}
#endif
Font::Font()
{
Initialize();
}
Font::~Font()
{
}
| 28.240741
| 187
| 0.62623
|
Trickje
|
2a90974d03cbd0acc93682c3cb5ca024d5f5cc92
| 3,348
|
cc
|
C++
|
src/statement.cc
|
xukl/BASIC-Compiler
|
3b0f752df5b9301aa116811729e362bfeaa05e58
|
[
"MIT"
] | null | null | null |
src/statement.cc
|
xukl/BASIC-Compiler
|
3b0f752df5b9301aa116811729e362bfeaa05e58
|
[
"MIT"
] | null | null | null |
src/statement.cc
|
xukl/BASIC-Compiler
|
3b0f752df5b9301aa116811729e362bfeaa05e58
|
[
"MIT"
] | null | null | null |
#include "statement.hpp"
#include <sstream>
#include <stack>
#include <memory>
#include <utility>
#include <typeinfo>
namespace statement
{
std::ostream &operator<< (std::ostream &os, const statement &x)
{
x.print(os);
return os;
}
std::ostream &operator<< (std::ostream &os, const assignment &x)
{
x.print(os);
return os;
}
program_type read_program(std::istream &is)
{
std::map<line_num, std::unique_ptr<statement>> ret;
line_num line;
std::stack<std::pair<line_num, std::string>> FOR_stack;
while (is >> line)
{
auto attemp_insert
= ret.insert(std::make_pair(line, std::unique_ptr<statement>()));
if (!attemp_insert.second)
throw "Line number repeated.";
std::string statement_type;
is >> statement_type;
std::unique_ptr<statement> sentence;
std::string sentence_str;
getline(is, sentence_str);
if (statement_type == "REM")
sentence = std::make_unique<REM>();
else if (statement_type == "LET")
sentence = std::make_unique<LET>(sentence_str);
else if (statement_type == "INPUT")
sentence = std::make_unique<INPUT>(sentence_str);
else if (statement_type == "EXIT")
sentence = std::make_unique<EXIT>(sentence_str);
else if (statement_type == "GOTO")
sentence = std::make_unique<GOTO>(sentence_str);
else if (statement_type == "IF")
sentence = std::make_unique<IF>(sentence_str);
else if (statement_type == "FOR")
{
FOR_stack.push(std::make_pair(line, sentence_str));
continue;
}
else if (statement_type == "END")
{
std::istringstream iss(sentence_str);
std::string for_expected;
iss >> for_expected;
if (for_expected != "FOR")
throw "Unknown token.";
char tmp;
if (iss >> tmp)
throw "Extra trailing characters.";
if (FOR_stack.empty())
throw "Unpaired \"END FOR\".";
auto &&FOR_info = FOR_stack.top();
const auto &str = FOR_info.second;
ret[FOR_info.first] = std::make_unique<FOR>(str, line);
sentence = std::make_unique<END_FOR>(FOR_info.first,
assignment(std::string(str, 0, str.find(';'))));
FOR_stack.pop();
}
else
throw "Unknown token.";
attemp_insert.first->second = std::move(sentence);
}
for (auto &[line, sent] : ret)
{
const auto &sent_type = typeid(*sent);
if (sent_type == typeid(IF))
{
line_num &target_line = static_cast<IF&>(*sent).line;
if (typeid(*ret[target_line]) == typeid(FOR))
{
line_num end_for_line =
static_cast<FOR&>(*ret[target_line]).end_for_line;
if (line >= target_line && line <= end_for_line)
target_line = end_for_line;
}
}
if (sent_type == typeid(GOTO))
{
line_num &target_line = static_cast<GOTO&>(*sent).line;
if (typeid(*ret[target_line]) == typeid(FOR))
{
line_num end_for_line =
static_cast<FOR&>(*ret[target_line]).end_for_line;
if (line >= target_line && line <= end_for_line)
target_line = end_for_line;
}
}
}
if (!is.eof())
throw "Error when reading program. Probably caused by missing line number.";
if (!FOR_stack.empty())
throw "Unpaired \"FOR\".";
if (ret.count(INT_MAX) != 0)
throw ":-( Line number too big.";
ret[additional_exit_line]
= std::make_unique<EXIT>(std::make_unique<expr::imm_num>(0));
return ret;
}
void print_program(std::ostream &os, const program_type &prog)
{
for (const auto &[line, sent] : prog)
os << '#' << line << ":\t" << *sent << std::endl;
}
}
| 28.615385
| 78
| 0.660992
|
xukl
|
2a914457d6f2022d1e593143d3b2c188989b1327
| 5,715
|
cc
|
C++
|
elements/analysis/aggcountervector.cc
|
timmytimj/fastclick
|
260dfa7285e5fff3c916b8272249d6d393e61179
|
[
"BSD-3-Clause-Clear"
] | 129
|
2015-10-08T14:38:35.000Z
|
2022-03-06T14:54:44.000Z
|
elements/analysis/aggcountervector.cc
|
nic-bench/fastclick
|
2812f0684050cec07e08f30d643ed121871cf25d
|
[
"BSD-3-Clause-Clear"
] | 241
|
2016-02-17T16:17:58.000Z
|
2022-03-15T09:08:33.000Z
|
elements/analysis/aggcountervector.cc
|
nic-bench/fastclick
|
2812f0684050cec07e08f30d643ed121871cf25d
|
[
"BSD-3-Clause-Clear"
] | 61
|
2015-12-17T01:46:58.000Z
|
2022-02-07T22:25:19.000Z
|
/*
* aggcountervector.{cc,hh} -- count packets/bytes with given aggregate
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "aggcountervector.hh"
#include <click/handlercall.hh>
#include <click/args.hh>
#include <click/error.hh>
#include <click/packet_anno.hh>
#include <click/integers.hh> // for first_bit_set
#include <click/router.hh>
CLICK_DECLS
AggregateCounterVector::AggregateCounterVector() : _epoch(0)
{
}
AggregateCounterVector::~AggregateCounterVector()
{
}
int
AggregateCounterVector::configure(Vector<String> &conf, ErrorHandler *errh)
{
bool bytes = false;
bool ip_bytes = false;
bool packet_count = true;
bool extra_length = true;
uint32_t freeze_nnz, stop_nnz;
uint32_t mask = (uint32_t)-1;
uint64_t freeze_count, stop_count;
bool mark = false;
String call_nnz, call_count;
if (Args(conf, this, errh)
.read_mp("MASK", mask)
.read("MARK", mark)
.read("BYTES", bytes)
.read("IP_BYTES", ip_bytes)
.read("MULTIPACKET", packet_count)
.read("EXTRA_LENGTH", extra_length)
.complete() < 0)
return -1;
_bytes = bytes;
_ip_bytes = ip_bytes;
_use_packet_count = packet_count;
_use_extra_length = extra_length;
_mask = mask;
_mark = mark;
_nodes.resize(mask + 1);
return 0;
}
int
AggregateCounterVector::initialize(ErrorHandler *errh)
{
_active = true;
return 0;
}
void
AggregateCounterVector::cleanup(CleanupStage)
{
}
inline bool
AggregateCounterVector::update_batch(PacketBatch *batch)
{
if (!_active)
return false;
uint32_t last_agg = 0;
Node *n = 0;
FOR_EACH_PACKET(batch,p) {
// AGGREGATE_ANNO is already in host byte order!
uint32_t agg = AGGREGATE_ANNO(p) & _mask;
if (agg == last_agg && n) {
} else {
bool outdated =false;
n = &find_node(last_agg,p,outdated);
if (outdated)
return true;
if (!n)
return false;
last_agg = agg;
}
uint32_t amount;
if (!_bytes)
amount = 1 + (_use_packet_count ? EXTRA_PACKETS_ANNO(p) : 0);
else {
amount = p->length() + (_use_extra_length ? EXTRA_LENGTH_ANNO(p) : 0);
if (_ip_bytes && p->has_network_header())
amount -= p->network_header_offset();
}
n->count += amount;
#if COUNT_FLOWS
n->add_flow(AGGREGATE_ANNO(p));
#endif
}
return true;
}
inline bool
AggregateCounterVector::update(Packet *p)
{
if (!_active)
return false;
// AGGREGATE_ANNO is already in host byte order!
uint32_t agg = AGGREGATE_ANNO(p) & _mask;
bool outdated = false;
Node &n = find_node(agg, p, outdated);
if (outdated)
return true;
uint32_t amount;
if (!_bytes)
amount = 1 + (_use_packet_count ? EXTRA_PACKETS_ANNO(p) : 0);
else {
amount = p->length() + (_use_extra_length ? EXTRA_LENGTH_ANNO(p) : 0);
if (_ip_bytes && p->has_network_header())
amount -= p->network_header_offset();
}
#if COUNT_FLOWS
n.add_flow(AGGREGATE_ANNO(p));
#endif
n.count += amount;
return true;
}
void
AggregateCounterVector::push(int port, Packet *p)
{
port = !update(p);
output(noutputs() == 1 ? 0 : port).push(p);
}
Packet *
AggregateCounterVector::pull(int)
{
Packet *p = input(0).pull();
if (p && _active)
update(p);
return p;
}
#if HAVE_BATCH
void
AggregateCounterVector::push_batch(int port, PacketBatch *batch)
{
auto fnt = [this,port](Packet*p){return !update(p);};
CLASSIFY_EACH_PACKET(2,fnt,batch,[this](int port, PacketBatch* batch){ output(0).push_batch(batch);});
}
PacketBatch *
AggregateCounterVector::pull_batch(int port,unsigned max)
{
PacketBatch *batch = input(0).pull_batch(max);
if (batch && _active) {
FOR_EACH_PACKET(batch,p) {
update(p);
}
}
return batch;
}
#endif
enum {
AC_ACTIVE, AC_STOP,
};
String
AggregateCounterVector::read_handler(Element *e, void *thunk)
{
AggregateCounterVector *ac = static_cast<AggregateCounterVector *>(e);
switch ((intptr_t)thunk) {
default:
return "<error>";
}
}
int
AggregateCounterVector::write_handler(const String &data, Element *e, void *thunk, ErrorHandler *errh)
{
AggregateCounterVector *ac = static_cast<AggregateCounterVector *>(e);
String s = cp_uncomment(data);
switch ((intptr_t)thunk) {
case AC_ACTIVE: {
bool val;
if (!BoolArg().parse(s, val))
return errh->error("type mismatch");
ac->_active = val;
return 0;
}
case AC_STOP:
ac->_active = false;
ac->router()->please_stop_driver();
return 0;
default:
return errh->error("internal error");
}
}
void
AggregateCounterVector::add_handlers()
{
add_data_handlers("active", Handler::f_read | Handler::f_checkbox, &_active);
add_write_handler("active", write_handler, AC_ACTIVE);
add_write_handler("stop", write_handler, AC_STOP, Handler::f_button);
}
ELEMENT_REQUIRES(userlevel int64)
EXPORT_ELEMENT(AggregateCounterVector)
ELEMENT_MT_SAFE(AggregateCounterVector)
CLICK_ENDDECLS
| 22.951807
| 106
| 0.665267
|
timmytimj
|
2a9962ad8459dd796b9b7bb9f7d2e9a7ff9d9fc4
| 9,610
|
cpp
|
C++
|
engine/map/map.cpp
|
fcarreiro/genesis
|
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
|
[
"MIT"
] | null | null | null |
engine/map/map.cpp
|
fcarreiro/genesis
|
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
|
[
"MIT"
] | null | null | null |
engine/map/map.cpp
|
fcarreiro/genesis
|
48b5c3bac888d999fb1ae17f1a864b59e2c85bc8
|
[
"MIT"
] | null | null | null |
#include "../precompiled/stdafx.h"
#include "../engine/base.h"
#include "../../common/utility/ext_xml.h"
#include "../../common/utility/ext_util.h"
//////////////////////////////////////////////////////////////////////////
// CMap default constructor & destructor
//////////////////////////////////////////////////////////////////////////
CMap::CMap()
{
// sub-modules
m_pSky = NULL;
m_pSea = NULL;
m_pLandscape = NULL;
// variables
m_fVisibility = 0.0f;
m_fFogDensity = 0.0f;
m_fBarAlpha = 0.0f;
}
CMap::~CMap()
{
// free data
Free();
}
//////////////////////////////////////////////////////////////////////////
// Free() : Unloads all map-related data from memmory
//////////////////////////////////////////////////////////////////////////
void CMap::Free()
{
// destroy sky
delete m_pSky;
m_pSky = NULL;
// destroy sea
delete m_pSea;
m_pSea = NULL;
// destroy landscape
delete m_pLandscape;
m_pLandscape = NULL;
// reset variables
m_fVisibility = 0.0f;
m_fFogDensity = 0.0f;
m_fBarAlpha = 0.0f;
m_Timer.Update();
m_strTitle.erase();
// free players list
m_Players.clear();
}
//////////////////////////////////////////////////////////////////////////
// Load() : Loads a map
//////////////////////////////////////////////////////////////////////////
bool CMap::Load(int iMap, TMapWarp iProcedence)
{
// format the string
std::ostringstream temp;
temp << "maps/map" << iMap << ".pak";
// load the map
return Load(temp.str(), iProcedence);
}
//////////////////////////////////////////////////////////////////////////
// Load() : Loads a map
//////////////////////////////////////////////////////////////////////////
bool CMap::Load(const std::string & strFile, TMapWarp iProcedence)
{
// temporary variables
xmlDocPtr doc;
xmlNodePtr node;
std::string strTemp;
// map info variables
std::string name;
std::string music;
int length;
int hm_length;
int shoreline;
int min_stars;
int max_stars;
float fog_density;
float visibility;
float scale;
CVector3 vDayBaseColor;
CVector3 vNightBaseColor;
CVector3 vDayBaseAmbient;
CVector3 vNightBaseAmbient;
// PHASE 0: free everything
Free();
// PHASE 1: open xml file
strTemp = strFile + "/settings.xml";
doc = ext::xml_parse_file(strTemp);
// check for document
if(!doc) return false;
// get root element and check for map
node = xmlDocGetRootElement(doc);
if(!node || xmlStrcmp(node->name, (const xmlChar *) "map"))
{
xmlFreeDoc(doc);
return false;
}
// get directly to first node
node = node->children->next;
// retrieve map settings
name = ext::xml_get_string(doc, node, "name");
music = ext::xml_get_string(doc, node, "music");
length = ext::xml_get_int(doc, node, "length");
hm_length = ext::xml_get_int(doc, node, "heightmap_length");
shoreline = ext::xml_get_int(doc, node, "shoreline");
min_stars = ext::xml_get_int(doc, node, "min_stars");
max_stars = ext::xml_get_int(doc, node, "max_stars");
fog_density = ext::xml_get_float(doc, node, "fog_density");
visibility = ext::xml_get_float(doc, node, "visibility");
scale = ext::xml_get_float(doc, node, "scale");
// retrieve sky settings
vDayBaseColor.x = ext::xml_get_prop_float(doc, node, "sky_day_color", "r");
vDayBaseColor.y = ext::xml_get_prop_float(doc, node, "sky_day_color", "g");
vDayBaseColor.z = ext::xml_get_prop_float(doc, node, "sky_day_color", "b");
vNightBaseColor.x = ext::xml_get_prop_float(doc, node, "sky_night_color", "r");
vNightBaseColor.y = ext::xml_get_prop_float(doc, node, "sky_night_color", "g");
vNightBaseColor.z = ext::xml_get_prop_float(doc, node, "sky_night_color", "b");
vDayBaseAmbient.x = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "r");
vDayBaseAmbient.y = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "g");
vDayBaseAmbient.z = ext::xml_get_prop_float(doc, node, "sky_day_ambient", "b");
vNightBaseAmbient.x = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "r");
vNightBaseAmbient.y = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "g");
vNightBaseAmbient.z = ext::xml_get_prop_float(doc, node, "sky_night_ambient", "b");
// free file
xmlFreeDoc(doc);
// PHASE 2: Sky allocation
m_pSky = new CSky();
if(!m_pSky) return false;
// place slightly under the player
CVector3 vCenter = CVector3(0.0f, 20.0f, 0.0f);
// create sky
m_pSky->Create(200, 200, 20,
min_stars, max_stars,
0.5f, vCenter,
vNightBaseColor, vDayBaseColor,
vNightBaseAmbient, vDayBaseAmbient);
// set null time (night)
m_pSky->SetDayTime(0.0f);
// PHASE 3: Landscape allocation
m_pLandscape = new CLandscape();
if(!m_pLandscape) return false;
// create landsape
strTemp = strFile + "/texture.tex";
std::string strHeightmap = strFile + "/heightmap.raw";
if(!m_pLandscape->Create(hm_length, scale,
strHeightmap.c_str(), strTemp.c_str())) return false;
// PHASE 5: create the sea
if(shoreline)
{
// allocate sea
m_pSea = new CSea();
if(!m_pSea) return false;
// create sea
if(!m_pSea->Create(length, shoreline * scale, m_pLandscape))
return false;
}
/*
// PHASE 6: player posistion
float py;
// where do we come from?
switch(iProcedence)
{
case FROM_NORTH:
py = m_pLandscape.HeightAt(vPosition.x, iMapLength - 300) + 2;
g_Player->SetPosition(vPosition.x, py, 300 - iMapLength);
break;
case FROM_SOUTH:
py = m_pLandscape.HeightAt(vPosition.x, 300) + 2;
g_Player->SetPosition(vPosition.x, py, -300);
break;
case FROM_EAST:
py = m_pLandscape.HeightAt(iMapLength - 300, -vPosition.z) + 2;
g_Player->SetPosition(iMapLength - 300, py, vPosition.z);
break;
case FROM_WEST:
py = m_pLandscape.HeightAt(300, -vPosition.z) + 2;
g_Player->SetPosition(300, py, vPosition.z);
break;
}
*/
// PHASE 7: set local values
m_strTitle = name;
m_fVisibility = visibility;
m_fFogDensity = fog_density;
// no errors
return true;
}
//////////////////////////////////////////////////////////////////////////
// Render() : Renders the map
//////////////////////////////////////////////////////////////////////////
void CMap::Render()
{
float fFogColor[4];
bool bUnderWater = false;
// set fog parameters
if(bUnderWater)
{
// set fog color
fFogColor[0] = 0.1f;
fFogColor[1] = 0.1f;
fFogColor[2] = 0.3f;
fFogColor[3] = 1.0f;
// set fog options
glFogf(GL_FOG_DENSITY, m_fFogDensity);
glFogf(GL_FOG_START, 50.0f);
glFogf(GL_FOG_END, 100.0f);
glFogfv(GL_FOG_COLOR, fFogColor);
glEnable(GL_FOG);
}
else
{
// set fog color
fFogColor[0] = 0.6f;
fFogColor[1] = 0.6f;
fFogColor[2] = 0.6f;
fFogColor[3] = 1.0f;
// set fog options
glFogf(GL_FOG_DENSITY, m_fFogDensity);
glFogf(GL_FOG_START, m_fVisibility * 200.0f);
glFogf(GL_FOG_END, 300.0f);
glFogfv(GL_FOG_COLOR, fFogColor);
}
glEnable(GL_FOG);
// set player's viewpoint
g_Player->Look();
// update frustum
g_Frustum->CalculateFrustum();
// render sky
m_pSky->Render(g_Player->GetPosition(), m_pSea ? m_pSea->GetShoreLine() : 0.0f,
CVector3(fFogColor[0], fFogColor[1], fFogColor[2]));
// render landscape
m_pLandscape->Render();
// render sea
if(m_pSea) m_pSea->Render();
// render bar with name
if(m_fBarAlpha >= 0.0f) RenderBar();
glDisable(GL_FOG);
}
//////////////////////////////////////////////////////////////////////////
// RenderBar() : Draws the bar with the map title
//////////////////////////////////////////////////////////////////////////
void CMap::RenderBar()
{
static CFont barFont("blackletter", 20, FONT_TEXTURE);
// calculate alpha
if(m_fBarAlpha < 1.0f)
{
m_fBarAlpha += 0.01f;
m_Timer.Update();
}
else
{
if(m_Timer.GetTimePassed() >= 5000) m_fBarAlpha -= 0.01f;
}
// get width & height
static const int iWidth = ext::get_option_int("screen_width");
static const int iHeight = ext::get_option_int("screen_height");
// overlay begin
g_OpenGL->OverlayBegin(iWidth, iHeight, true);
// enable blending
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
// set alpha
glColor4f(0.0f, 0.0f, 0.0f, m_fBarAlpha);
// draw bar background
glBegin(GL_TRIANGLE_STRIP);
glVertex2i(iWidth, 35);
glVertex2i(0, 35);
glVertex2i(iWidth, 0);
glVertex2i(0, 0);
glEnd();
// set white
glColor4f(1.0f, 1.0f, 1.0f, m_fBarAlpha);
// draw map name
barFont.Print(10, 8, m_strTitle);
// disable blending
glDisable(GL_BLEND);
// overlay ending
g_OpenGL->OverlayEnd();
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
void CMap::AddPlayer(unsigned long dwId, CPlayer *p)
{
// if we *DON'T* have the player
if(m_Players.find(dwId) == m_Players.end())
{
// add it
m_Players.insert(std::make_pair(dwId, p));
}
}
//////////////////////////////////////////////////////////////////////////
//
//////////////////////////////////////////////////////////////////////////
void CMap::RemovePlayer(unsigned long dwId)
{
// if we *DO* have the player
if(m_Players.find(dwId) != m_Players.end())
{
// delete it
m_Players.erase(dwId);
}
}
//////////////////////////////////////////////////////////////////////////
// End
//////////////////////////////////////////////////////////////////////////
| 25.695187
| 85
| 0.564828
|
fcarreiro
|
2a9aafba3c5d61dd0f6dbd47296f721c6961ab66
| 1,844
|
cpp
|
C++
|
Interactive/InpaintingIterationRecord.cpp
|
jingtangliao/ff
|
d308fe62045e241a4822bb855df97ee087420d9b
|
[
"Apache-2.0"
] | 39
|
2015-01-01T07:59:51.000Z
|
2021-10-01T18:11:46.000Z
|
Interactive/InpaintingIterationRecord.cpp
|
jingtangliao/ff
|
d308fe62045e241a4822bb855df97ee087420d9b
|
[
"Apache-2.0"
] | 1
|
2019-04-24T09:56:15.000Z
|
2019-04-24T14:45:46.000Z
|
Interactive/InpaintingIterationRecord.cpp
|
jingtangliao/ff
|
d308fe62045e241a4822bb855df97ee087420d9b
|
[
"Apache-2.0"
] | 18
|
2015-01-11T15:10:23.000Z
|
2022-02-24T20:02:10.000Z
|
/*=========================================================================
*
* Copyright David Doria 2011 daviddoria@gmail.com
*
* 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.txt
*
* 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 "InpaintingIterationRecord.h"
InpaintingIterationRecord::InpaintingIterationRecord()
{
}
NamedITKImageCollection& InpaintingIterationRecord::GetImages()
{
return this->Images;
}
// void InpaintingIterationRecord::SetDisplayed(const unsigned int imageId, const bool displayed)
// {
// this->Display[imageId] = displayed;
// }
//
// bool InpaintingIterationRecord::IsDisplayed(const unsigned int imageId) const
// {
// return this->Display[imageId];
// }
void InpaintingIterationRecord::AddImage(const NamedITKImage& namedImage, const bool display)
{
this->Images.push_back(namedImage);
this->Display.push_back(display);
}
// NamedITKImage InpaintingIterationRecord::GetImage(const unsigned int imageId) const
// {
// return this->Images[imageId];
// }
//
// NamedITKImage InpaintingIterationRecord::GetImageByName(const std::string& imageName) const
// {
// return this->Images.FindImageByName(imageName);
// }
//
// unsigned int InpaintingIterationRecord::GetNumberOfImages() const
// {
// return this->Images.size();
// }
| 30.229508
| 97
| 0.677332
|
jingtangliao
|
2a9aeaa398ef199bf8d61594d1cedc358518551e
| 211
|
hpp
|
C++
|
Source/panels/spell_book.hpp
|
stefanmielke/devilutionX
|
074f191be80db73b1158dd137f7bee4c767e48ce
|
[
"Unlicense"
] | 2
|
2022-01-14T06:10:31.000Z
|
2022-02-28T23:30:26.000Z
|
Source/panels/spell_book.hpp
|
stefanmielke/devilutionX
|
074f191be80db73b1158dd137f7bee4c767e48ce
|
[
"Unlicense"
] | 1
|
2022-01-31T07:44:04.000Z
|
2022-01-31T07:44:04.000Z
|
Source/panels/spell_book.hpp
|
stefanmielke/devilutionX
|
074f191be80db73b1158dd137f7bee4c767e48ce
|
[
"Unlicense"
] | 1
|
2021-10-31T01:32:43.000Z
|
2021-10-31T01:32:43.000Z
|
#pragma once
#include "engine/surface.hpp"
namespace devilution {
void InitSpellBook();
void FreeSpellBook();
void CheckSBook();
void DrawSpellBook(const Surface &out);
} // namespace devilution
| 16.230769
| 40
| 0.71564
|
stefanmielke
|
2aa173d69c8bd5fad30c1658343077bad18134fb
| 5,215
|
cpp
|
C++
|
src/dtkWidgets/dtkWidgetsTagCloudView.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
src/dtkWidgets/dtkWidgetsTagCloudView.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
src/dtkWidgets/dtkWidgetsTagCloudView.cpp
|
eti-nne/dtk
|
b5095c7a181e7497391a6a1fa0bb37e71dfa4b56
|
[
"BSD-3-Clause"
] | null | null | null |
/* dtkWidgetsTagCloudView.cpp ---
*
* Author: Julien Wintz
* Created: Mon Apr 15 14:39:34 2013 (+0200)
* Version:
* Last-Updated: Mon Apr 15 14:44:56 2013 (+0200)
* By: Julien Wintz
* Update #: 7
*/
/* Change Log:
*
*/
#include "dtkWidgetsTagCloudDesc.h"
#include "dtkWidgetsTagCloudList.h"
#include "dtkWidgetsTagCloudView.h"
class dtkWidgetsTagCloudViewPrivate
{
public:
QWidget *parent;
public:
QEasingCurve::Type type;
public:
bool vertical;
bool wrap;
bool active;
public:
int speed;
int now;
int next;
public:
QPoint pnow;
public:
dtkWidgetsTagCloudList *list;
dtkWidgetsTagCloudDesc *desc;
};
dtkWidgetsTagCloudView::dtkWidgetsTagCloudView(QWidget *parent) : QStackedWidget(parent), d(new dtkWidgetsTagCloudViewPrivate)
{
d->list = new dtkWidgetsTagCloudList(this);
d->desc = new dtkWidgetsTagCloudDesc(this);
if (parent != 0)
d->parent = parent;
else
d->parent = this;
d->vertical = false;
d->speed = 500;
d->type = QEasingCurve::OutBack;
d->now = 0;
d->next = 0;
d->wrap = false;
d->pnow = QPoint(0,0);
d->active = false;
this->addWidget(d->list);
this->addWidget(d->desc);
connect(d->list, SIGNAL(itemClicked(const QString&)), this, SLOT(onItemClicked(const QString&)));
connect(d->desc, SIGNAL(back()), this, SLOT(slideInPrev()));
}
dtkWidgetsTagCloudView::~dtkWidgetsTagCloudView(void)
{
delete d;
d = NULL;
}
dtkWidgetsTagCloudList *dtkWidgetsTagCloudView::list(void)
{
return d->list;
}
dtkWidgetsTagCloudDesc *dtkWidgetsTagCloudView::desc(void)
{
return d->desc;
}
void dtkWidgetsTagCloudView::setDark(void)
{
d->list->setDark();
}
void dtkWidgetsTagCloudView::onItemClicked(const QString& description)
{
d->desc->setDescription(description);
this->slideInNext();
}
void dtkWidgetsTagCloudView::setVerticalMode(bool vertical)
{
d->vertical = vertical;
}
void dtkWidgetsTagCloudView::setSpeed(int speed)
{
d->speed = speed;
}
void dtkWidgetsTagCloudView::setAnimation(QEasingCurve::Type type)
{
d->type = type;
}
void dtkWidgetsTagCloudView::setWrap(bool wrap)
{
d->wrap = wrap;
}
void dtkWidgetsTagCloudView::slideInNext(void)
{
int now = currentIndex();
if (d->wrap||(now<count()-1))
slideInIdx(now+1);
}
void dtkWidgetsTagCloudView::slideInPrev(void)
{
int now = currentIndex();
if (d->wrap||(now>0))
slideInIdx(now-1);
}
void dtkWidgetsTagCloudView::slideInIdx(int idx, Direction direction)
{
if (idx>count()-1) {
direction = d->vertical ? Top2Bottom : Right2Left;
idx = (idx)%count();
} else if (idx<0) {
direction = d->vertical ? Bottom2Top: Left2Right;
idx = (idx+count())%count();
}
slideInWgt(widget ( idx ),direction);
}
void dtkWidgetsTagCloudView::slideInWgt(QWidget *newwidget, Direction direction)
{
if (d->active)
return;
else
d->active = true;
Direction directionhint;
int now = currentIndex();
int next = indexOf(newwidget);
if (now==next) {
d->active = false;
return;
}
else if (now<next){
directionhint = d->vertical ? Top2Bottom : Right2Left;
}
else {
directionhint = d->vertical ? Bottom2Top : Left2Right;
}
if (direction == Automatic) {
direction = directionhint;
}
int offsetx = frameRect().width();
int offsety = frameRect().height();
widget(next)->setGeometry ( 0, 0, offsetx, offsety );
if (direction==Bottom2Top) {
offsetx = 0;
offsety = -offsety;
}
else if (direction==Top2Bottom) {
offsetx = 0;
}
else if (direction==Right2Left) {
offsetx = -offsetx;
offsety = 0;
}
else if (direction==Left2Right) {
offsety = 0;
}
QPoint pnext = widget(next)->pos();
QPoint pnow = widget(now)->pos();
d->pnow = pnow;
widget(next)->move(pnext.x()-offsetx,pnext.y()-offsety);
widget(next)->show();
widget(next)->raise();
QPropertyAnimation *animnow = new QPropertyAnimation(widget(now), "pos");
animnow->setDuration(d->speed);
animnow->setEasingCurve(d->type);
animnow->setStartValue(QPoint(pnow.x(), pnow.y()));
animnow->setEndValue(QPoint(offsetx+pnow.x(), offsety+pnow.y()));
QPropertyAnimation *animnext = new QPropertyAnimation(widget(next), "pos");
animnext->setDuration(d->speed);
animnext->setEasingCurve(d->type);
animnext->setStartValue(QPoint(-offsetx+pnext.x(), offsety+pnext.y()));
animnext->setEndValue(QPoint(pnext.x(), pnext.y()));
QParallelAnimationGroup *animgroup = new QParallelAnimationGroup;
animgroup->addAnimation(animnow);
animgroup->addAnimation(animnext);
QObject::connect(animgroup, SIGNAL(finished()),this,SLOT(animationDoneSlot()));
d->next = next;
d->now = now;
d->active = true;
animgroup->start();
}
void dtkWidgetsTagCloudView::animationDoneSlot(void)
{
setCurrentIndex(d->next);
widget(d->now)->hide();
widget(d->now)->move(d->pnow);
d->active = false;
emit animationFinished();
}
| 22.286325
| 126
| 0.635858
|
eti-nne
|
2aa2010afd6be7798a9d1041d28c63f6924839fd
| 1,777
|
hpp
|
C++
|
include/veriblock/entities/popdata.hpp
|
overcookedpanda/alt-integration-cpp
|
7932e79a77d9514ca0e0354636e77fba1845d707
|
[
"MIT"
] | null | null | null |
include/veriblock/entities/popdata.hpp
|
overcookedpanda/alt-integration-cpp
|
7932e79a77d9514ca0e0354636e77fba1845d707
|
[
"MIT"
] | null | null | null |
include/veriblock/entities/popdata.hpp
|
overcookedpanda/alt-integration-cpp
|
7932e79a77d9514ca0e0354636e77fba1845d707
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2019-2020 Xenios SEZC
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_ALT_POP_TRANSACTION_HPP_
#define ALT_INTEGRATION_INCLUDE_VERIBLOCK_ENTITIES_ALT_POP_TRANSACTION_HPP_
#include <stdint.h>
#include <vector>
#include "veriblock/entities/atv.hpp"
#include "veriblock/entities/vtb.hpp"
#include "veriblock/serde.hpp"
#include "veriblock/slice.hpp"
namespace altintegration {
struct PopData {
int32_t version{};
std::vector<VbkBlock> vbk_context;
bool hasAtv{false};
ATV atv{};
std::vector<VTB> vtbs{};
/**
* Read VBK data from the stream and convert it to PopData
* @param stream data stream to read from
* @return PopData
*/
static PopData fromVbkEncoding(ReadStream& stream);
/**
* Read VBK data from the raw byte representation and convert it to PopData
* @param string data bytes to read from
* @return PopData
*/
static PopData fromVbkEncoding(Slice<const uint8_t> bytes);
/**
* Convert PopData to data stream using Vbk byte format
* @param stream data stream to write into
*/
void toVbkEncoding(WriteStream& stream) const;
/**
* Convert PopData to raw bytes data using Vbk byte format
* @return bytes data
*/
std::vector<uint8_t> toVbkEncoding() const;
/**
* Return true if contains endorsement data
* @return true if contains endorsement data
*/
bool containsEndorsements() const;
friend bool operator==(const PopData& a, const PopData& b) {
// clang-format off
return a.toVbkEncoding() == b.toVbkEncoding();
// clang-format on
}
};
} // namespace altintegration
#endif
| 25.385714
| 77
| 0.720878
|
overcookedpanda
|
2aa9c6bd380b1487f674bc761d7efc628e018703
| 7,631
|
cpp
|
C++
|
UnitTests/CommandBuffer/src/CommandBuffer.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
UnitTests/CommandBuffer/src/CommandBuffer.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
UnitTests/CommandBuffer/src/CommandBuffer.cpp
|
Gpinchon/OCRA
|
341bb07facc616f1f8a27350054d1e86f022d7c6
|
[
"Apache-2.0"
] | null | null | null |
#include <Instance.hpp>
#include <PhysicalDevice.hpp>
#include <Device.hpp>
#include <Queue/Queue.hpp>
#include <Queue/Fence.hpp>
#include <Queue/Semaphore.hpp>
#include <Command/Pool.hpp>
#include <Command/Buffer.hpp>
#include <Memory.hpp>
#include <Buffer.hpp>
#include <Common.hpp>
#include <future>
#include <iostream>
#define FENCE_VERSION
#define CHUNK_SIZE 256
#define SENTENCE0 std::string("Hello World !")
#define SENTENCE1 std::string("All your base are belong to us")
#define SWAP_NBR 1
using namespace OCRA;
#ifdef FENCE_VERSION
static inline void SubmitCommandBuffer(const Device::Handle& a_Device, const Queue::Handle& a_Queue, const Command::Buffer::Handle& a_CommandBuffer)
{
auto fence = Queue::Fence::Create(a_Device);
Queue::SubmitInfo submitInfo;
for (auto i = 0u; i < 1; ++i)
submitInfo.commandBuffers.push_back(a_CommandBuffer);
std::cout << "========== Command Buffer submit ==========\n";
//test multithreaded submit
std::async([a_Queue, submitInfo, fence] {
VerboseTimer("Queue Submission");
Queue::Submit(a_Queue, { submitInfo }, fence);
});
//make sure GPU is done
{
VerboseTimer bufferCopiesTimer("Buffer Copies");
Queue::Fence::WaitFor(a_Device, fence, std::chrono::nanoseconds(15000000));
}
//test for function time itself
{
auto timer = Timer();
int waitNbr = 100000;
for (auto i = 0; i < waitNbr; ++i)
Queue::Fence::WaitFor(a_Device, fence, std::chrono::nanoseconds(15000000));
std::cout << "Already signaled Fence mean wait time : " << timer.Elapsed().count() / double(waitNbr) << " nanoseconds\n";
}
std::cout << "===========================================\n";
std::cout << "\n";
}
#else //FENCE_VERSION
static inline void SubmitCommandBuffer(const Device::Handle& a_Device, const Queue::Handle& a_Queue, const Command::Buffer::Handle& a_CommandBuffer)
{
Queue::Semaphore::Info semaphoreInfo;
semaphoreInfo.type = Queue::Semaphore::Type::Timeline;
semaphoreInfo.initialValue = 0;
Queue::Semaphore::Handle semaphore = Queue::Semaphore::Create(a_Device, semaphoreInfo);
Queue::TimelineSemaphoreSubmitInfo timelineValues;
timelineValues.waitSemaphoreValues.push_back(1);
timelineValues.signalSemaphoreValues.push_back(2);
Queue::SubmitInfo submitInfo;
for (auto i = 0u; i < SWAP_NBR; ++i)
submitInfo.commandBuffers.push_back(a_CommandBuffer);
submitInfo.waitSemaphores.push_back(semaphore);
submitInfo.signalSemaphores.push_back(semaphore);
submitInfo.timelineSemaphoreValues = timelineValues;
std::cout << "========== Command Buffer submit ==========\n";
//test multithreaded submit
std::async([a_Queue, submitInfo] {
VerboseTimer("Queue Submission");
Queue::Submit(a_Queue, { submitInfo });
});
Queue::Semaphore::Signal(a_Device, semaphore, 1);
//make sure GPU is done
{
VerboseTimer bufferCopiesTimer("Buffer Copies");
Queue::Semaphore::Wait(a_Device, { semaphore }, { 2 }, std::chrono::nanoseconds(15000000));
}
std::cout << "===========================================\n";
std::cout << "\n";
}
#endif
static inline void RecordSwapCommandBuffer(
const Command::Buffer::Handle& a_CommandBuffer,
const Buffer::Handle& a_Buffer0,
const Buffer::Handle& a_Buffer1,
const Buffer::Handle& a_BufferT)
{
Command::Buffer::BeginInfo bufferbeginInfo;
bufferbeginInfo.flags = Command::Buffer::UsageFlagBits::None;
Command::Buffer::Begin(a_CommandBuffer, bufferbeginInfo);
{
Command::BufferCopyRegion copyRegions;
copyRegions.size = CHUNK_SIZE;
Command::CopyBuffer(a_CommandBuffer, a_Buffer0, a_BufferT, { copyRegions });
Command::CopyBuffer(a_CommandBuffer, a_Buffer1, a_Buffer0, { copyRegions });
Command::CopyBuffer(a_CommandBuffer, a_BufferT, a_Buffer1, { copyRegions });
}
Command::Buffer::End(a_CommandBuffer);
}
int main()
{
const auto instance = CreateInstance("Test_CommandBuffer");
const auto physicalDevice = Instance::EnumeratePhysicalDevices(instance).front();
const auto device = CreateDevice(physicalDevice);
const auto queueFamily = FindQueueFamily(physicalDevice, PhysicalDevice::QueueFlagsBits::Transfer);
const auto queue = Device::GetQueue(device, queueFamily, 0); //Get first available queue
const auto memory = AllocateMemory(physicalDevice, device, CHUNK_SIZE * 3, PhysicalDevice::MemoryPropertyFlagBits::HostVisible | PhysicalDevice::MemoryPropertyFlagBits::HostCached);
const auto commandPool = CreateCommandPool(device, queueFamily);
const auto commandBuffer = CreateCommandBuffer(device, commandPool, Command::Pool::AllocateInfo::Level::Primary);
//create test buffers
Buffer::Info bufferInfo;
bufferInfo.size = CHUNK_SIZE;
bufferInfo.usage = Buffer::UsageFlagBits::TransferDst | Buffer::UsageFlagBits::TransferSrc;
const auto buffer0 = Buffer::Create(device, bufferInfo);
const auto buffer1 = Buffer::Create(device, bufferInfo);
const auto bufferT = Buffer::Create(device, bufferInfo);
Buffer::BindMemory(device, buffer0, memory, CHUNK_SIZE * 0);
Buffer::BindMemory(device, buffer1, memory, CHUNK_SIZE * 1);
Buffer::BindMemory(device, bufferT, memory, CHUNK_SIZE * 2);
//write some value to the buffer0
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 0;
mappedRange.length = CHUNK_SIZE;
auto bufferPtr = Memory::Map(device, mappedRange);
memcpy(bufferPtr, SENTENCE0.c_str(), SENTENCE0.size());
Memory::Unmap(device, memory);
}
//write some value to the buffer1
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 1;
mappedRange.length = CHUNK_SIZE;
auto bufferPtr = Memory::Map(device, mappedRange);
memcpy(bufferPtr, SENTENCE1.c_str(), SENTENCE1.size());
Memory::Unmap(device, memory);
}
RecordSwapCommandBuffer(commandBuffer, buffer0, buffer1, bufferT);
SubmitCommandBuffer(device, queue, commandBuffer);
std::cout << "========== Sentences to swap ==========\n";
std::cout << " Sentence 0 : " << SENTENCE0 << "\n";
std::cout << " Sentence 1 : " << SENTENCE1 << "\n";
std::cout << "=======================================\n";
std::cout << "\n";
std::cout << "===== Check if sentences were swapped =====\n";
int success = 0;
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 0;
mappedRange.length = CHUNK_SIZE;
std::string buffer0String = (char*)Memory::Map(device, mappedRange);
success += buffer0String == SENTENCE1 ? 0 : 1;
std::cout << " Buffer 0 value : " << buffer0String << "\n";
Memory::Unmap(device, memory);
}
{
Memory::MappedRange mappedRange;
mappedRange.memory = memory;
mappedRange.offset = CHUNK_SIZE * 1;
mappedRange.length = CHUNK_SIZE;
std::string buffer1String = (char*)Memory::Map(device, mappedRange);
success += buffer1String == SENTENCE0 ? 0 : 1;
std::cout << " Buffer 1 value : " << buffer1String << "\n";
Memory::Unmap(device, memory);
}
std::cout << " " << (success == 0 ? "***** Great success ! *****" : "XXXXX Failure will not be tolerated. XXXXX") << "\n";
std::cout << "===========================================\n";
return success;
}
| 42.394444
| 185
| 0.653781
|
Gpinchon
|
2aada408721b2630a046925c15f9e820d8849fe7
| 2,813
|
hpp
|
C++
|
PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 6
|
2019-08-15T09:48:55.000Z
|
2021-07-25T14:40:59.000Z
|
PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 43
|
2019-12-25T14:54:52.000Z
|
2022-02-24T17:22:48.000Z
|
PlanetaMatchMakerServer/library/minimal_serializer/type_traits.hpp
|
InstytutXR/PlanetaMatchMaker
|
4bf7503c031aea467c191c3a0d14c6dd58354f99
|
[
"MIT"
] | 2
|
2020-05-06T20:14:44.000Z
|
2020-06-02T21:21:10.000Z
|
/*
The MIT License (MIT)
Copyright (c) 2019 Cdec
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <type_traits>
#include <memory>
#include <boost/tti/has_member_function.hpp>
namespace minimal_serializer {
class serializer;
// Remove const, volatile and reference
template <typename T>
using remove_cvref_t = std::remove_cv_t<std::remove_reference_t<T>>;
BOOST_TTI_HAS_MEMBER_FUNCTION(on_serialize)
template <typename T>
constexpr bool has_member_on_serialize_v = has_member_function_on_serialize<T, void, boost::mpl::vector<serializer&>
, boost::function_types::non_cv>::value;
struct has_global_on_serialize_impl {
template <class T>
static auto check(T&& x) -> decltype(on_serialize(std::declval<T&>(), std::declval<serializer&>()), std::true_type());
template <class T>
static std::false_type check(...);
};
template <class T>
constexpr bool has_global_on_serialize_v
= decltype(has_global_on_serialize_impl::check<T>(std::declval<T>()))::value;
template <class T>
constexpr bool is_serializable_v = has_global_on_serialize_v<T> && std::is_trivial_v<T>;
struct is_fixed_array_container_impl {
template <class T>
static auto check(T&& x) -> decltype(x.operator[](std::declval<size_t>()), x.max_size(), std::true_type{});
template <class T>
static auto check(...)->std::false_type;
};
template <class T>
struct is_fixed_array_container final : decltype(is_fixed_array_container_impl::check<T>(std::declval<T>())) {};
template <class T>
constexpr bool is_fixed_array_container_v = is_fixed_array_container<T>::value;
template <typename T>
struct is_shared_ptr : std::false_type {};
template <typename T>
struct is_shared_ptr<std::shared_ptr<T>> : std::true_type {};
template <typename T>
constexpr bool is_shared_ptr_v = is_shared_ptr<T>::value;
}
| 40.768116
| 460
| 0.766086
|
InstytutXR
|
2aaf1393cc24731b2409395aefa6e0433686823d
| 15,716
|
cpp
|
C++
|
mergeBathy/Error_Estimator/Bathy_Grid.cpp
|
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
|
9996f5ee40e40e892ce5eb77dc4bb67930af4005
|
[
"CC0-1.0"
] | 4
|
2017-05-04T15:50:48.000Z
|
2020-07-30T03:52:07.000Z
|
mergeBathy/Error_Estimator/Bathy_Grid.cpp
|
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
|
9996f5ee40e40e892ce5eb77dc4bb67930af4005
|
[
"CC0-1.0"
] | null | null | null |
mergeBathy/Error_Estimator/Bathy_Grid.cpp
|
Sammie-Jo/MergeBathy_Repos-MergeBathy_CPP
|
9996f5ee40e40e892ce5eb77dc4bb67930af4005
|
[
"CC0-1.0"
] | 2
|
2017-01-11T09:53:26.000Z
|
2020-07-30T03:52:09.000Z
|
/**********************************************************************
* CC0 License
**********************************************************************
* MergeBathy - Tool to combine one or more bathymetric data files onto a single input grid.
* Written in 2015 by Samantha J.Zambo(samantha.zambo@gmail.com) while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Todd Holland while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Nathaniel Plant while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Kevin Duvieilh while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Paul Elmore while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Will Avera while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by Brian Bourgeois while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by A.Louise Perkins while employed by the U.S.Naval Research Laboratory.
* Written in 2015 by David Lalejini while employed by the U.S.Naval Research Laboratory.
* To the extent possible under law, the author(s) and the U.S.Naval Research Laboratory have dedicated all copyright and related and neighboring rights to this software to the public domain worldwide.This software is distributed without any warranty.
* You should have received a copy of the CC0 Public Domain Dedication along with this software.If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
**********************************************************************/
#include "Bathy_Grid.h"
#include "GradientGrid.h"
#include <fstream>
#include <iostream>
#include <sstream>
#include <list>
#include <math.h>
#include <list>
#include <vector>
#include "../grid.h"
#include "pointList.h"
#include "sHullDelaunay.h"
void Bathy_Grid::clear()
{
if(ptl != NULL)
{
delete ptl;
ptl = NULL;
}
if(tin != NULL)
{
delete tin;
tin = NULL;
}
size_t sz = interpGrids.size();
for(size_t i = 0; i < sz; ++i){
delete interpGrids[i];
interpGrids[i] = NULL;
}
interpGrids.clear();
ensemble_X.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_Y.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_Z.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_H.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_V.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_U.clear();//sam added 12/28/15 don't know why it wasnt already here
ensemble_U2.clear();
ensemble_U3.clear();
ensemble_U4.clear();
ensemble_U5.clear();
}
void InterpGrid::clear()
{
if(ptlSurface != NULL)
{
delete ptlSurface;
ptlSurface = NULL;
}
if(grads != NULL)
{
delete grads;
grads = NULL;
}
triangles.clear();
e.clear();
e2.clear();
e3.clear();
e4.clear();
e5.clear();
z.clear();
s.clear();
//For Raster/Bag Interpolation SJZ
z0.clear();
e0.clear();
zK.clear();
eK.clear();
nei.clear();
rei.clear();
}
void Bathy_Grid::Construct_TinRaster(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *eInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectorsRaster(*xInit, *yInit, *zInit, *eInit/*, *z0Init, *e0Init, *zKInit, *eKInit*/);
tin = new SHullDelaunay();
std::cout << "Initializing triangle for Raster Conversion." << std::endl;
tin->insert(*ptl);
std::cout << "Done Converting to Raster." << std::endl;
}
void Bathy_Grid::Construct_TinRaster(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *eInit, vector<double> *neiInit, vector<double> *reiInit, vector<double> *z0Init, vector<double> *e0Init, vector<double> *zKInit, vector<double> *eKInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectorsRaster(*xInit, *yInit, *zInit, *eInit, *neiInit, *reiInit, *z0Init, *e0Init, *zKInit, *eKInit);
tin = new SHullDelaunay();
std::cout << "Initializing triangle for Raster Conversion." << std::endl;
tin->insert(*ptl);
std::cout << "Done Converting to Raster." << std::endl;
}
//void InterpGrid::estimateRaster(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf, const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string interpMethod)
//{
// ptlSurface = new PointList();
// ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
//
// grads = new GradientGrid();
//
// //triangles = vector<Triangle>();
// triangles.reserve(ptlSurface->size());
//
// //Compute Gradients if depths are known.
// if(ptlSurface->getAvgZ() != 0.00)
// (*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
// //Compute Depths and Gradients
// else
// {
// this->scaleFactor = sH;
// this->alpha = alpha;
// this->deltaMin = deltaMin;
// vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, interpMethod));
//
// e.reserve(pVec.size());
// z.reserve(pVec.size());
// //s.reserve(pVec.size());
//
// for (int i = 0; i < (int) pVec.size(); i++)
// {
// e.push_back(pVec[i].u);
// z.push_back(pVec[i].z);
// //s.push_back(pVec[i].s);
// }
// }
//}
void Bathy_Grid::Construct_Tin(vector<double> *xInit, vector<double> *yInit, vector<double> *zInit, vector<double> *hInit, vector<double> *vInit)
{
//Each BathyGrid object gets its own copy.
ptl = new PointList();
ptl->setFromVectors(*xInit, *yInit, *zInit, *hInit, *vInit);
tin = new SHullDelaunay();
//std::cout << "Initializing triangle for error computation" << std::endl;
tin->insert(*ptl);
//std::cout << "Done initializing" << std::endl;
}
void InterpGrid::estimate(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf, const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string depthInterpMethod, string errorInterpMethod, string extrapMethod)
{
ptlSurface = new PointList();
ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
grads = new GradientGrid();
//triangles = vector<Triangle>();
triangles.reserve(ptlSurface->size());
//Compute Gradients before-hand if depths are known.
//This catches if we pre-splined.
if(ptlSurface->getAvgZ() != 0.00)
(*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
//Compute Depths, Gradients, and uncertainties
this->scaleFactor = sH;
this->alpha = alpha;
this->deltaMin = deltaMin;
vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, depthInterpMethod, errorInterpMethod, extrapMethod));
e.reserve(pVec.size());
e2.reserve(pVec.size());
e3.reserve(pVec.size());
e4.reserve(pVec.size());
e5.reserve(pVec.size());
z.reserve(pVec.size());
s.reserve(pVec.size());
nei.reserve(pVec.size());
rei.reserve(pVec.size());
z0.reserve(pVec.size());
e0.reserve(pVec.size());
eK.reserve(pVec.size());
eK.reserve(pVec.size());
for (int i = 0; i < (int) pVec.size(); i++)
{
e.push_back(pVec[i].u);
e2.push_back(pVec[i].u2);
e3.push_back(pVec[i].u3);
e4.push_back(pVec[i].u4);
e5.push_back(pVec[i].u5);
z.push_back(pVec[i].z);
s.push_back(pVec[i].s);
// e.push_back(pVec[i].e);
nei.push_back(pVec[i].nei);
rei.push_back(pVec[i].rei);
z0.push_back(pVec[i].z0);
e0.push_back(pVec[i].e0);
zK.push_back(pVec[i].zK);
eK.push_back(pVec[i].eK);
}
}
//void InterpGrid::estimate(vector<double> *xSurf, vector<double> *ySurf, vector<double> *zSurf,vector<double> *eSurf,vector<double> *hSurf,vector<double> *vSurf, vector<double> *nmseiSurf,vector<double> *reiSurf,const double& sH, const double& alpha, const double& deltaMin, SHullDelaunay* tin, string interpMethod)
//{
// ptlSurface = new PointList();
// ptlSurface->setFromVectors(*xSurf, *ySurf, *zSurf, tin->getOffsetX(), tin->getOffsetY());
//
// grads = new GradientGrid();
//
// //triangles = vector<Triangle>();
// triangles.reserve(ptlSurface->size());
//
// //Compute Gradients if depths are known.
// if(ptlSurface->getAvgZ() != 0.00)
// (*grads).calc_GradientGrid(*xSurf, *ySurf, *zSurf);
// //Compute Depths and Gradients
// else
// {
// this->scaleFactor = sH;
// this->alpha = alpha;
// this->deltaMin = deltaMin;
// vector<Point> pVec(tin->determinePingLocationInTriangle(*ptlSurface, sH, alpha, deltaMin,*grads, triangles, interpMethod));
//
// e.reserve(pVec.size());
// e2.reserve(pVec.size());
// e3.reserve(pVec.size());
// e4.reserve(pVec.size());
// e5.reserve(pVec.size());
// z.reserve(pVec.size());
// s.reserve(pVec.size());
//
// for (int i = 0; i < (int) pVec.size(); i++)
// {
// e.push_back(pVec[i].u);
// e2.push_back(pVec[i].u2);
// e3.push_back(pVec[i].u3);
// e4.push_back(pVec[i].u4);
// e5.push_back(pVec[i].u5);
// z.push_back(pVec[i].z);
// s.push_back(pVec[i].s);
// }
// }
//}
bool Bathy_Grid::ensemble()
{
//This assumes that the correct grid is MBZ
//and the extra leading rows in GMT need to
//be ignored for calculations. These rows
//are in the beginning and provide extra lats for 1 extra lon.
//**This is believed to be fixed;verify before removing! SJZ 12/28/15.
int i, k, j, diff = 0;
double temp = 0;//,n,h;
InterpGrid *kInd;
int cnt = (const int)interpGrids.size();//3;// {MBZ,GMT,ALG} //
double sigma = 0, sigma2 = 0, sigma3 = 0, sigma4 = 0, sigma5 = 0;
vector<int> row, js, jsInit;
vector<int> xcols, yrows;
row.reserve(cnt);
xcols.reserve(cnt); //# rows (x) in each grid
yrows.reserve(cnt); //#cols (y) in each grid
js.reserve(cnt);
jsInit.reserve(cnt); //last index pos at in the set of uniq. new starting index
vector<InterpGrid*>::iterator it = interpGrids.begin();
vector<InterpGrid*>::iterator kIt;
k = (const int)(*it)->e.size();
vector<double> sortGrid1;
vector<double> sortGrid2;
vector<double> sortGrid3;
//find the max grid in order to know the number of extra rows to skip in GMT beginning
for(it = interpGrids.begin()++; it != interpGrids.end(); it++)
{
j = (const int)(*it)->e.size();
if(j < k)
{
k = j;
diff = k - j;
kInd = *&*it;
kIt = it;
}
//xcols and yrows are indices starting at 0. Add +1 to get dimensions.
xcols.push_back((const int)(((*it)->ptlSurface->getPositions().back().x
- (*it)->ptlSurface->getPositions().front().x)/(*it)->deltaMin)+1);
yrows.push_back((const int)(abs(((*it)->ptlSurface->getPositions().back().y
- (*it)->ptlSurface->getPositions().front().y)/(*it)->deltaMin))+1);
js.push_back((const int)(*it)->e.size()-1);
jsInit.push_back((const int)(*it)->e.size()-1);//beginning row index
}
vector<Point> mbzItXY;
vector<Point> algItXY;
vector<Point> gmtItXY;
int mbzflag = 0;
int masterGrid = 0;;
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
{
switch((*it)->gtype)
{
case ALGSpline:
if(!mbzflag)
masterGrid = 1; //because there is only GMT then ALG
algItXY = (*it)->ptlSurface->getPositions();
break;
case GMT:
gmtItXY = (*it)->ptlSurface->getPositions();
break;//sorted by y min to max
case MBZ:
mbzflag = 1;
masterGrid = MBZ; //should be 0
mbzItXY = (*it)->ptlSurface->getPositions();
break;
}
}
it = interpGrids.begin();
ensemble_H.reserve(k);
ensemble_V.reserve(k);
ensemble_U.reserve(k);
ensemble_U2.reserve(k);
ensemble_U3.reserve(k);
ensemble_U4.reserve(k);
ensemble_U5.reserve(k);
vector<int> js2;
int j2;
js2.reserve(cnt);
int counter = 0;
int counter1 = 0, counter2 = 0;
int counter3 = 0, counter4 = 0;
js[0] = 0; //last visited index
jsInit[0] = 0; //index at beginning of current row visited
js2.assign(js.begin(),js.end());
//i = MBZ, k = GMT, j = same x,y loc in both
for(i =0; i < k; i++)
{
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
{
switch((*it)->gtype)
{
case ALGSpline:
//ALGSpline j should be the same x,y as MBZ
//counter = 2;
j = xcols[counter]*(counter3)+counter4;
js[counter] = j;
counter3++;
if(counter3==abs(yrows[masterGrid]))
{
counter3=0;
counter4++;
}
if(counter4==xcols[masterGrid])
counter4=0;
break; //sorted by y max to min
case GMT:
//GMT j should be the same x,y as MBZ
//counter = 1;
j = xcols[counter]*(abs(yrows[counter])-counter1)-(xcols[counter]-counter2);
js[counter] = j;
counter1++;
if(counter1==abs(yrows[masterGrid]))
{
counter1=0;
counter2++;
}
if(counter2==xcols[masterGrid])
counter2=0;
break;//sorted by y min to max
case MBZ:
//j index is always i since MBZ is assumed to be correct.
//counter = 0;
j = i;
js[counter] = j;
break;//sorted by x min to max
}
if(mbzflag)
{
if(counter==ALGSpline){//2
if(! (mbzItXY[js[masterGrid]].x == algItXY[js[ALGSpline]].x && mbzItXY[js[masterGrid]].y == algItXY[js[ALGSpline]].y))
{
std::cout<< "Error: ALG and MBZ X, Y locations do not align!" << std::endl;
return false;
}
}
if(counter==GMT){//1
if(! (mbzItXY[js[masterGrid]].x == gmtItXY[js[GMT]].x && mbzItXY[js[masterGrid]].y == gmtItXY[js[GMT]].y))
{
std::cout<< "Error: GMT and MBZ X, Y locations do not align!" << std::endl;
return false;
}
}
}
else
{
if(counter==masterGrid){
if(! (algItXY[js[masterGrid]].x == gmtItXY[js[counter-1]].x && algItXY[js[masterGrid]].y == gmtItXY[js[counter-1]].y))
{
std::cout<< "Error: ALG and GMT X, Y locations do not align!" << std::endl;
return false;
}
}
}
sigma += (*it)->e[j];
sigma2 += (*it)->e2[j];
sigma3 += (*it)->e3[j];
sigma4 += (*it)->e4[j];
sigma5 += (*it)->e5[j];
counter++;
}
if(mbzflag)
{
ensemble_X.push_back(mbzItXY[js[masterGrid]].x);
ensemble_Y.push_back(mbzItXY[js[masterGrid]].y);
ensemble_Z.push_back(mbzItXY[js[masterGrid]].z);
}
else
{
ensemble_X.push_back(algItXY[js[masterGrid]].x);
ensemble_Y.push_back(algItXY[js[masterGrid]].y);
ensemble_Z.push_back(algItXY[js[masterGrid]].z);
}
ensemble_U.push_back(sigma/cnt);
ensemble_U2.push_back(sigma2/cnt);
ensemble_U3.push_back(sigma3/cnt);
ensemble_U4.push_back(sigma4/cnt);
ensemble_U5.push_back(sigma5/cnt);
//SJZ
temp = sqrt(pow(ensemble_U[i],2)/2);
ensemble_H.push_back(temp);
ensemble_V.push_back(temp);
sigma = 0, sigma2 = 0, sigma3 = 0, sigma4 = 0, sigma5 = 0; counter = 0;
}
//printensemble("../Output_Files/ensemble_Test.txt");
return true;
}
void Bathy_Grid::printensemble(string z_OutputFileName)
{
std::ofstream outFile;
//vector<InterpGrid*>::iterator it = interpGrids.begin();
//vector<Point> ps;
outFile.open(z_OutputFileName.c_str());
outFile.precision(6);
outFile.setf(std::ios::fixed, std::ios::floatfield);
std::cout << "Writing file to " << z_OutputFileName.c_str() << std::endl;
if (outFile.is_open())
{
//it = interpGrids.begin();
//ps=(*it)->ptlSurface->getPositions();
for(int i = 0; i < (int) ensemble_X.size(); i++){
outFile << ensemble_X[i] << "\t" << ensemble_Y[i] << "\t" << ensemble_Z[i]
<< "\t" << ensemble_U[i] << "\t" << ensemble_U2[i]
<< "\t" << ensemble_U3[i]<< "\t" << ensemble_U4[i]
<< "\t" << ensemble_U5[i] << std::endl;
}
}
outFile.close();
}
void Bathy_Grid::addToList( InterpGrid* g)
{
interpGrids.push_back(&*g);
}
//Get the first interpGrid of type g
InterpGrid* Bathy_Grid::getGrid(GridType g)
{
vector<InterpGrid*>::iterator it;
for(it = interpGrids.begin(); it != interpGrids.end(); it++)
if((*it)->gtype == g) return *it;
}
//Get all interpGrids
vector<InterpGrid*> Bathy_Grid::getGrids()
{
return interpGrids;
}
| 31.62173
| 316
| 0.65042
|
Sammie-Jo
|
2ababea0ef23519b966cf9c4d85576fa04565f94
| 3,055
|
cpp
|
C++
|
projects/InjectDLL/features/launch_no_deceleration.cpp
|
Mawex/wotw-client
|
19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca
|
[
"MIT"
] | null | null | null |
projects/InjectDLL/features/launch_no_deceleration.cpp
|
Mawex/wotw-client
|
19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca
|
[
"MIT"
] | null | null | null |
projects/InjectDLL/features/launch_no_deceleration.cpp
|
Mawex/wotw-client
|
19cd13a5cfab0b504d5f1aa3da6eb11e631bd9ca
|
[
"MIT"
] | null | null | null |
#include <dll_main.h>
#include <Il2CppModLoader/il2cpp_helpers.h>
#include <Il2CppModLoader/interception_macros.h>
using namespace modloader;
INJECT_C_DLLEXPORT bool in_menu();
namespace
{
constexpr float NO_AIR_DECELERATION_DURATION = 0.2f;
constexpr float NO_AIR_DECELERATION_RESET_DURATION = 0.2f;
float aim_timer = 0.0f;
float reset_timer = 0.0f;
STATIC_IL2CPP_BINDING(Game, UI, bool, get_MainMenuVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, get_WorldMapVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, get_ShardShopVisible, ());
STATIC_IL2CPP_BINDING(Game, UI, bool, IsInventoryVisible, ());
STATIC_IL2CPP_BINDING(, TimeUtility, float, get_deltaTime, ());
bool is_aiming_launch(app::CharacterAirNoDeceleration* this_ptr)
{
if (!in_menu())
{
if (aim_timer >= 0.0f)
aim_timer -= TimeUtility::get_deltaTime();
if (reset_timer >= 0.0f)
reset_timer -= TimeUtility::get_deltaTime();
}
auto* sein = get_sein();
auto* wrapper = sein->fields.Abilities->fields.ChargeJumpWrapper;
if (wrapper->fields.HasState && wrapper->fields.State->fields.m_state == app::SeinChargeJump_State__Enum_Aiming)
{
aim_timer = NO_AIR_DECELERATION_DURATION;
if (reset_timer > 0.0f)
this_ptr->fields.m_noDeceleration = true;
}
return aim_timer > 0.0f;
}
IL2CPP_INTERCEPT(, CharacterAirNoDeceleration, void, UpdateCharacterState, (app::CharacterAirNoDeceleration* this_ptr)) {
auto* platform_behaviour = this_ptr->fields.PlatformBehaviour;
auto* platform_movement = platform_behaviour->fields.PlatformMovement;
if (!il2cpp::invoke<app::Boolean__Boxed>(platform_movement, "get_IsSuspended")->fields)
{
if (il2cpp::invoke<app::Boolean__Boxed>(platform_movement, "get_IsOnGround")->fields)
this_ptr->fields.m_noDeceleration = false;
if (0.00000000 <= il2cpp::invoke<app::Single__Boxed>(platform_movement, "get_LocalSpeedY")->fields &&
platform_movement->fields._.Ceiling->fields.IsOn)
this_ptr->fields.m_noDeceleration = false;
auto* left_right_movement = platform_behaviour->fields.LeftRightMovement;
if (!left_right_movement->fields.m_settings->fields.LockInput &&
!is_aiming_launch(this_ptr) &&
left_right_movement->fields.m_horizontalInput != 0.0)
{
if (this_ptr->fields.m_noDeceleration)
reset_timer = NO_AIR_DECELERATION_RESET_DURATION;
this_ptr->fields.m_noDeceleration = false;
}
}
}
}
INJECT_C_DLLEXPORT bool in_menu()
{
return il2cpp::get_class<app::UI__Class>("Game", "UI")->static_fields->m_sMenu->fields.m_equipmentWhellVisible
|| UI::get_MainMenuVisible()
|| UI::get_WorldMapVisible()
|| UI::get_ShardShopVisible()
|| UI::IsInventoryVisible();
}
| 39.166667
| 125
| 0.656301
|
Mawex
|
2abeb9fd1d1143367447899d45b6634125850eb3
| 903
|
hpp
|
C++
|
server/src/static_controller.hpp
|
R0nd/beefweb
|
d61e03eef97e089f36847ac34bba4ec59c1bb5cd
|
[
"MIT"
] | 148
|
2017-08-25T13:32:05.000Z
|
2022-03-17T18:40:49.000Z
|
server/src/static_controller.hpp
|
R0nd/beefweb
|
d61e03eef97e089f36847ac34bba4ec59c1bb5cd
|
[
"MIT"
] | 160
|
2017-08-16T19:58:53.000Z
|
2022-02-26T09:57:38.000Z
|
server/src/static_controller.hpp
|
R0nd/beefweb
|
d61e03eef97e089f36847ac34bba4ec59c1bb5cd
|
[
"MIT"
] | 24
|
2018-05-23T18:59:47.000Z
|
2022-03-23T17:25:01.000Z
|
#pragma once
#include "controller.hpp"
#include "settings.hpp"
namespace msrv {
class Router;
class ContentTypeMap;
class WorkQueue;
class StaticController : public ControllerBase
{
public:
StaticController(
Request* request,
const Path& targetDir,
const ContentTypeMap& contentTypes);
~StaticController();
ResponsePtr getFile();
static void defineRoutes(
Router* router,
WorkQueue* workQueue,
SettingsDataPtr settings,
const ContentTypeMap& contentTypes);
static void defineRoutes(
Router* router,
WorkQueue* workQueue,
const std::string& urlPrefix,
const std::string& targetDir,
const ContentTypeMap& contentTypes);
private:
std::string getNormalizedPath();
ResponsePtr redirectToDirectory();
const Path& targetDir_;
const ContentTypeMap& contentTypes_;
};
}
| 20.066667
| 46
| 0.679956
|
R0nd
|
2abfff4018ad1033983ed6c1d115a1c39441d92c
| 948
|
cpp
|
C++
|
lib/matrix/MatrixOperators.cpp
|
frndmg/simplex-method
|
0fe509d43ac794344b5d95f7e4faacd0dd444d56
|
[
"MIT"
] | 2
|
2019-11-25T20:54:56.000Z
|
2019-11-25T20:55:20.000Z
|
lib/matrix/MatrixOperators.cpp
|
frndmg/simplex-method
|
0fe509d43ac794344b5d95f7e4faacd0dd444d56
|
[
"MIT"
] | null | null | null |
lib/matrix/MatrixOperators.cpp
|
frndmg/simplex-method
|
0fe509d43ac794344b5d95f7e4faacd0dd444d56
|
[
"MIT"
] | 1
|
2019-11-25T23:14:18.000Z
|
2019-11-25T23:14:18.000Z
|
#include "Matrix.hpp"
Matrix Matrix::operator+ () const {
return *this;
}
Matrix Matrix::operator- () const {
return operator*(-1.);
}
Matrix Matrix::operator+ (const real_t &scalar) const {
Matrix A = *this;
for(size_t y = 0; y < A.Height(); ++y)
A[y] = A[y] + scalar;
return A;
}
Matrix Matrix::operator- (const real_t &scalar) const {
return operator+ (-scalar);
}
Matrix Matrix::operator* (const real_t &scalar) const {
Matrix A = *this;
for(size_t y = 0; y < A.Height(); ++y)
A[y] = A[y] * scalar;
return A;
}
Matrix Matrix::operator/ (const real_t &scalar) const {
ASSERT_DOMAIN(scalar != 0.);
return operator* (1 / scalar);
}
Matrix Matrix::operator+ (const Matrix &B) const {
Matrix A = *this;
ASSERT_DOMAIN(A.Width() == B.Width() && A.Height() == B.Height());
for(size_t y = 0; y < Height(); ++y)
A[y] = A[y] + B[y];
return A;
}
Matrix Matrix::operator- (const Matrix &B) const {
return operator+ (-B);
}
| 19.346939
| 67
| 0.619198
|
frndmg
|
2ac265cf382f478e608bd8422b037015ab3bcd7e
| 1,949
|
hpp
|
C++
|
include/crab/cfg/cfg_operators.hpp
|
LinerSu/crab
|
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
|
[
"Apache-2.0"
] | null | null | null |
include/crab/cfg/cfg_operators.hpp
|
LinerSu/crab
|
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
|
[
"Apache-2.0"
] | null | null | null |
include/crab/cfg/cfg_operators.hpp
|
LinerSu/crab
|
8f3516f4b4765f4a093bb3c3a94ac2daa174130c
|
[
"Apache-2.0"
] | null | null | null |
#pragma once
#include <crab/support/debug.hpp>
#include <crab/support/os.hpp>
namespace crab {
namespace cfg {
// To group together statements over integers or real
typedef enum {
BINOP_ADD,
BINOP_SUB,
BINOP_MUL,
BINOP_SDIV,
BINOP_UDIV,
BINOP_SREM,
BINOP_UREM,
BINOP_AND,
BINOP_OR,
BINOP_XOR,
BINOP_SHL,
BINOP_LSHR,
BINOP_ASHR,
} binary_operation_t;
typedef enum { BINOP_BAND, BINOP_BOR, BINOP_BXOR } bool_binary_operation_t;
typedef enum { CAST_TRUNC, CAST_SEXT, CAST_ZEXT } cast_operation_t;
inline crab::crab_os &operator<<(crab::crab_os &o, binary_operation_t op) {
switch (op) {
case BINOP_ADD:
o << "+";
break;
case BINOP_SUB:
o << "-";
break;
case BINOP_MUL:
o << "*";
break;
case BINOP_SDIV:
o << "/";
break;
case BINOP_UDIV:
o << "/_u";
break;
case BINOP_SREM:
o << "%";
break;
case BINOP_UREM:
o << "%_u";
break;
case BINOP_AND:
o << "&";
break;
case BINOP_OR:
o << "|";
break;
case BINOP_XOR:
o << "^";
break;
case BINOP_SHL:
o << "<<";
break;
case BINOP_LSHR:
o << ">>_l";
break;
case BINOP_ASHR:
o << ">>_r";
break;
default:
CRAB_ERROR("unexpected binary operation ", op);
}
return o;
}
inline crab::crab_os &operator<<(crab::crab_os &o, bool_binary_operation_t op) {
switch (op) {
case BINOP_BAND:
o << "&";
break;
case BINOP_BOR:
o << "|";
break;
case BINOP_BXOR:
o << "^";
break;
default:
CRAB_ERROR("unexpected boolean binary operation ", op);
}
return o;
}
inline crab::crab_os &operator<<(crab::crab_os &o, cast_operation_t op) {
switch (op) {
case CAST_TRUNC:
o << "trunc";
break;
case CAST_SEXT:
o << "sext";
break;
case CAST_ZEXT:
o << "zext";
break;
default:
CRAB_ERROR("unexpected cast operation", op);
}
return o;
}
} // end namespace cfg
} // end namespace crab
| 17.247788
| 80
| 0.601847
|
LinerSu
|
2ac9d9b284c80fb4fcb117ac935242dc593aea35
| 1,825
|
hpp
|
C++
|
src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp
|
timow-gh/Geometry
|
6b46b107355cd76fbb9c3a86db23dc891e868a3b
|
[
"Apache-2.0"
] | null | null | null |
src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp
|
timow-gh/Geometry
|
6b46b107355cd76fbb9c3a86db23dc891e868a3b
|
[
"Apache-2.0"
] | null | null | null |
src/include/Geometry/HalfedgeMeshBuilder/MeshBuilderBase.hpp
|
timow-gh/Geometry
|
6b46b107355cd76fbb9c3a86db23dc891e868a3b
|
[
"Apache-2.0"
] | null | null | null |
#ifndef GEOMETRY_MESHBUILDERBASE_HPP
#define GEOMETRY_MESHBUILDERBASE_HPP
#include <Core/Types/TVector.hpp>
#include <Geometry/HalfedgeMesh/HalfedgeMesh.hpp>
#include <Geometry/HalfedgeMeshBuilder/MeshTriangleAdder.hpp>
#include <LinAl/LinearAlgebra.hpp>
namespace Geometry
{
template <typename T, typename Derived>
class MeshBuilderBase {
protected:
LinAl::HMatrix<double_t> m_transformation = {{1, 0, 0, 0},
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 0, 0, 1}};
std::unique_ptr<HalfedgeMesh<T>>
buildTriangleHeMesh(const LinAl::Vec3Vector<T>& points,
const Core::TVector<uint32_t>& triangleIndices) const
{
auto heMesh = std::make_unique<HalfedgeMesh<T>>();
MeshTriangleAdder<T> meshTriangleAdder{*heMesh};
std::size_t size = triangleIndices.size();
for (std::size_t i{2}; i < size; i += 3)
{
LinAl::VecArray<T, 3, 3> trianglePoints;
for (std::size_t j{0}; j < 3; ++j)
{
const std::size_t idx = triangleIndices[i - j];
const LinAl::Vec3<T>& point = points[idx];
LinAl::HVec<T> tPoint =
m_transformation * LinAl::HVec<T>{point[0], point[1], point[2], 1.0};
trianglePoints[j] = LinAl::Vec3<T>{tPoint[0], tPoint[1], tPoint[2]};
}
meshTriangleAdder(Triangle<T, 3>(trianglePoints));
}
return heMesh;
}
Derived& setTransformation(const LinAl::HMatrix<T>& transformation)
{
m_transformation = transformation;
return *static_cast<Derived*>(this);
}
};
} // namespace Geometry
#endif // GEOMETRY_MESHBUILDERBASE_HPP
| 35.096154
| 89
| 0.564384
|
timow-gh
|
2acdb257016405c6b7cea49c82cc62ea4fa18a86
| 6,326
|
cpp
|
C++
|
Lab02_03c.cpp
|
xinyizou/school-projects
|
10adc544faf45446ef99d8e1a74acbe16c88c7b5
|
[
"MIT"
] | 1
|
2020-01-21T00:46:48.000Z
|
2020-01-21T00:46:48.000Z
|
Lab02_03c.cpp
|
xinyizou/school-projects
|
10adc544faf45446ef99d8e1a74acbe16c88c7b5
|
[
"MIT"
] | null | null | null |
Lab02_03c.cpp
|
xinyizou/school-projects
|
10adc544faf45446ef99d8e1a74acbe16c88c7b5
|
[
"MIT"
] | null | null | null |
//
// Student name: Xinyi Zou
// Student number: 20765197
//
// SYDE 121 Lab: Lab Assignment #1 Exercise #3
// Filename: lab02_03c
//
// I hereby declare that this code, submitted for credit for the course
// SYDE121, is a product of my own efforts. This coded solution has
// not been plagiarized from other sources and has not been knowingly
// plagiarized by others.
//
// Project: calculating sum of consecutive numbers
// Purpose: verifying the correctness of programs created by comparing program results with manual computation
// Due date: Friday, September 21, 2018
// Evaluation of program
//
// First number: 1
// Last number: 100
// Program output: The sum of 1 to 100 is 5050
// Manual calculation: (100 / 2) * (2 * 1 + (100 - 1) * 1) = 5050
//
// First number: 1
// Last number: 3000
// Program output: The sum of 1 to 3000 is 4501500
// Manual calculation: (3000 / 2) * (2 * 1 + (3000 - 1) * 1) = 4501500
//
// First number: 5
// Last number: 10000
// Program output: The sum of 1 to 10000 is 50004990
// Manual calculation: (9996 / 2) * (2 * 5 + (9996 - 1) * 1) = 50004990
//
//
// Since the program's outputted values and manually calculated values are the same, the program is correct
#include <iostream>
using namespace std;
int main()
{
// INPUT: finite arithmetic series defined by starting number, ending number, and interval
// OUTPUT: sum of arithmetic series
// calculate as per the formula: sum = (n / 2) * (2 * a + (n - 1) * d
// where n is number of integers to be added, a is the first number, and d is the difference between each number
// declare variables
int first_num;
int last_num;
const int INTERVAL = 1;
int sum;
double num_of_int; // must be double to accommodate cases where num_of_int / 2 is not a whole number since int / int will return an integer value that will cut off decimal values
//initialize variables with appropriate values given in the question
first_num = 1;
last_num = 100;
// calculate variable value using given formulas
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
// output result to user
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
// repeat with each consequent arithmetic series
first_num = 1;
last_num = 3000;
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
first_num = 5;
last_num = 10000;
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
//terminate
return 0;
}
// Limits
// The input limits for this function are the limits of the int variable
// As previously determined, an integer can take any value between (but not
// including) -2147483649 and 2147483647
//
// Example:
// First number: -2147483648
// Last number: 2147483649
// Program output: The sum of -2147483648 to 2147483647 is 0
// Manual calculation: (4294967298 / 2) * (2 * -2147483648 + (4294967298 - 1) * 1) = -2147483649
//
// This error in calculation can be attributed to the overloading of the variables,
// as seen, the values initiated into the variable is not fully outputted (2147483649 became 2147483647)
// nor is the final sum correct.
//
// Therefore, when any of the inputted values exceeds the allowable limit for the
// integer variable, the program is not correct.
//
// Similarly, since the value of the resulting sum is also stored in an integer its
// value must also be between (but not including) -2147483649 and 2147483647
//
// Example:
// First number: -2147483647
// Last number: -2147483646
// Program output: The sum of -2147483647 to -2147483646 with an interval of 1 is 3
// Manual calculation: (2 / 2) * (2 * -2147483647 + (2 - 1) * 1) = -4294967293
//
// Once the sum has exceeded the limits of the int variable, the program is no longer correct.
//
// This also makes sense given the expressible limit of an integer variable is -2147483648 to 2147483647 [1]
// Source [1]: corob-msft. 2016. "Data Type Ranges | Microsoft Doc". Available from
// https://github.com/mozillascience/code-research-object/issues/12
//
//
// Decimals
//
// First number: 42.42
// Last number: 84.42
// Program output: The sum of 42 to 84 with an interval of 1 is 2646
//
// As seen above, when a non-integer value is inputted into the int variable, the
// decimal values are cut off to make an integer, meaning the program is incorrect. This could be corrected by changing the variable type to from int to double.
//
//
// Therefore, this program is only correct when all integer variables (inputs and outputs) have an integer value between (but not including) -2147483649 and 2147483647.
#include <iostream>
using namespace std;
int main()
{
// INPUT: user inputs starting number, ending number, and interval
// OUTPUT: sum of numbers from starting number to ending number
// calculate as per the formula: sum = (n / 2) * (2 * a + (n - 1) * d
// where n is number of integers to be added, a is the first number, and d is the difference between each number
// declare variables
int first_num;
int last_num;
const int INTERVAL = 1;
int sum;
double num_of_int; // must be double to accommodate cases where num_of_int / 2 is not a whole number since int / int will return an integer value that will cut off decimal values
// ask user for input and initialize variables
cout << "Enter the starting value: " << endl;
cin >> first_num;
cout << "Enter the ending value: " << endl;
cin >> last_num;
// initialize variable with a formula
num_of_int = last_num - first_num + 1;
sum = (num_of_int / 2) * (2 * first_num + (num_of_int - 1) * INTERVAL);
// output result to user
cout << "The sum of " << first_num << " to " << last_num << " is " << sum << endl;
// terminate
return 0;
}
| 37.654762
| 188
| 0.659026
|
xinyizou
|
2ad5e71ed708caeab1e5aa79f61f9bf9fd376894
| 1,802
|
hpp
|
C++
|
misc/bit_operation.hpp
|
hly1204/library
|
b62c47a8f20623c1f1edd892b980714e8587f40e
|
[
"Unlicense"
] | 7
|
2021-07-20T15:25:00.000Z
|
2022-03-13T11:58:25.000Z
|
misc/bit_operation.hpp
|
hly1204/library
|
b62c47a8f20623c1f1edd892b980714e8587f40e
|
[
"Unlicense"
] | 10
|
2021-03-11T16:08:22.000Z
|
2022-03-13T08:40:36.000Z
|
misc/bit_operation.hpp
|
hly1204/library
|
b62c47a8f20623c1f1edd892b980714e8587f40e
|
[
"Unlicense"
] | null | null | null |
#ifndef BIT_OPERATION_HEADER_HPP
#define BIT_OPERATION_HEADER_HPP
/**
* @brief bit operations
*
*/
#include <cassert>
#include <cstdint>
#include "deBruijn_sequence.hpp"
namespace lib {
/**
* @brief 在二进制最高的 1 后面填充满 1
* @param x
* @return std::uint32_t
*/
std::uint32_t fill_one_after_msb(std::uint32_t x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
return x | x >> 16;
}
std::uint64_t fill_one_after_msb(std::uint64_t x) {
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x | x >> 32;
}
/**
* @brief 计算 x 的二进制表示中 least significant 1-bit 的索引加一
* @param x
* @return int 若 x=0 则返回 0 。
*/
int ffs(std::uint32_t x) { return x == 0 ? 0 : deBruijn_log2(x & ~(x - 1)) + 1; }
int ffs(std::uint64_t x) { return x == 0 ? 0 : deBruijn_log2(x & ~(x - 1)) + 1; }
/**
* @brief 计算 x 的二进制表示中从 most significant bit 位置开始有多少个 0
* @param x
* @return int 若 x=0 则未定义。
*
*/
int clz(std::uint32_t x) {
assert(x != 0);
return 31 - deBruijn_log2(fill_one_after_msb(x >> 1) + 1);
}
int clz(std::uint64_t x) {
assert(x != 0);
return 63 - deBruijn_log2(fill_one_after_msb(x >> 1) + 1);
}
/**
* @brief 计算 x 的二进制表示中从 least significant bit 位置开始有多少个 0
* @param x
* @return int 若 x=0 则返回未定义
*/
int ctz(std::uint32_t x) {
assert(x != 0);
return deBruijn_log2(x & ~(x - 1));
}
int ctz(std::uint64_t x) {
assert(x != 0);
return deBruijn_log2(x & ~(x - 1));
}
/**
* @brief 计算 x 的二进制表示中 1 的个数
* @param x
* @return int
*/
int popcount(std::uint32_t x) {
int cnt = 0;
while (x) ++cnt, x &= x - 1;
return cnt;
}
int popcount(std::uint64_t x) {
int cnt = 0;
while (x) ++cnt, x &= x - 1;
return cnt;
}
} // namespace lib
#endif
| 18.57732
| 82
| 0.546615
|
hly1204
|
2ad5fbbb2684206d87b47e0f76ddc9b0da67b001
| 2,845
|
cpp
|
C++
|
godgame2/Sphere.cpp
|
magnificus/godgame
|
cafb36830263d95516eb014f432319cabf50bda7
|
[
"Unlicense"
] | 5
|
2017-10-31T17:36:13.000Z
|
2021-11-05T21:01:04.000Z
|
godgame2/Sphere.cpp
|
magnificus/godgame
|
cafb36830263d95516eb014f432319cabf50bda7
|
[
"Unlicense"
] | null | null | null |
godgame2/Sphere.cpp
|
magnificus/godgame
|
cafb36830263d95516eb014f432319cabf50bda7
|
[
"Unlicense"
] | null | null | null |
#include "Sphere.h"
#include "math.h"
#include <map>
#include <array>
struct Triangle
{
unsigned int vertex[3];
};
using TriangleList = std::vector<Triangle>;
using VertexList = std::vector<glm::vec3>;
using NormalList = std::vector<glm::vec3>;
#define Index unsigned int
namespace icosahedron
{
const float X = .525731112119133606f;
const float Z = .850650808352039932f;
const float N = 0.f;
static const VertexList vertices =
{
{ -X,N,Z },{ X,N,Z },{ -X,N,-Z },{ X,N,-Z },
{ N,Z,X },{ N,Z,-X },{ N,-Z,X },{ N,-Z,-X },
{ Z,X,N },{ -Z,X, N },{ Z,-X,N },{ -Z,-X, N }
};
static const std::vector<Triangle> triangles =
{
{ 0,4,1 },{ 0,9,4 },{ 9,5,4 },{ 4,5,8 },{ 4,8,1 },
{ 8,10,1 },{ 8,3,10 },{ 5,3,8 },{ 5,2,3 },{ 2,7,3 },
{ 7,10,3 },{ 7,6,10 },{ 7,11,6 },{ 11,0,6 },{ 0,1,6 },
{ 6,1,10 },{ 9,0,11 },{ 9,11,2 },{ 9,2,5 },{ 7,2,11 }
};
}
using Lookup = std::map<std::pair<Index, Index>, Index>;
Index vertex_for_edge(Lookup& lookup,
VertexList& vertices, Index first, Index second)
{
Lookup::key_type key(first, second);
if (key.first>key.second)
std::swap(key.first, key.second);
auto inserted = lookup.insert({ key, vertices.size() });
if (inserted.second)
{
auto& edge0 = vertices[first];
auto& edge1 = vertices[second];
auto point = normalize(edge0 + edge1);
vertices.push_back(point);
}
return inserted.first->second;
}
TriangleList subdivide(VertexList& vertices,
TriangleList triangles)
{
Lookup lookup;
TriangleList result;
for (auto&& each : triangles)
{
std::array<Index, 3> mid;
for (int edge = 0; edge<3; ++edge)
{
mid[edge] = vertex_for_edge(lookup, vertices,
each.vertex[edge], each.vertex[(edge + 1) % 3]);
}
result.push_back({ each.vertex[0], mid[0], mid[2] });
result.push_back({ each.vertex[1], mid[1], mid[0] });
result.push_back({ each.vertex[2], mid[2], mid[1] });
result.push_back({ mid[0], mid[1], mid[2] });
}
return result;
}
struct IndexedMesh {
VertexList vertList;
TriangleList triList;
};
//using IndexedMesh = std::pair<VertexList, TriangleList>;
IndexedMesh make_icosphere(int subdivisions)
{
VertexList vertices = icosahedron::vertices;
TriangleList triangles = icosahedron::triangles;
for (int i = 0; i<subdivisions; ++i)
{
triangles = subdivide(vertices, triangles);
}
return{ vertices, triangles };
}
Sphere::Sphere(Shader *s) : Model(s)
{
IndexedMesh mesh = make_icosphere(2);
vertices = mesh.vertList;
//normals = mesh.vertList;
for (glm::vec3 t : mesh.vertList) {
normals.push_back(t);
}
for (Triangle t : mesh.triList) {
for (int i = 2; i >= 0; i--)
indicies.push_back(t.vertex[i]);
}
//for (int i = 0; i < vertices.size(); i++) {
// glm::vec3 vert = vertices[i];
//}
}
| 23.708333
| 59
| 0.599297
|
magnificus
|
2adb800c632a7ae555e16819d86333554fafdb11
| 5,691
|
cpp
|
C++
|
PostLib/GMeshImport.cpp
|
chunkeey/FEBioStudio
|
f342d4ac2bc3581db792373c4265454109af92b3
|
[
"MIT"
] | 27
|
2020-06-25T06:34:52.000Z
|
2022-03-11T08:58:57.000Z
|
PostLib/GMeshImport.cpp
|
chunkeey/FEBioStudio
|
f342d4ac2bc3581db792373c4265454109af92b3
|
[
"MIT"
] | 42
|
2020-06-15T18:40:57.000Z
|
2022-03-24T05:38:54.000Z
|
PostLib/GMeshImport.cpp
|
chunkeey/FEBioStudio
|
f342d4ac2bc3581db792373c4265454109af92b3
|
[
"MIT"
] | 12
|
2020-06-27T13:58:57.000Z
|
2022-03-24T05:39:10.000Z
|
/*This file is part of the FEBio Studio source code and is licensed under the MIT license
listed below.
See Copyright-FEBio-Studio.txt for details.
Copyright (c) 2020 University of Utah, The Trustees of Columbia University in
the City of New York, and others.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
#include "stdafx.h"
#include "GMeshImport.h"
#include <FSCore/color.h>
#include "FEPostModel.h"
#include "FEPostMesh.h"
using namespace Post;
GMeshImport::GMeshImport(FEPostModel* fem) : FEFileReader(fem)
{
}
GMeshImport::~GMeshImport(void)
{
}
bool GMeshImport::Load(const char* szfile)
{
// open the file
if (Open(szfile, "rt") == false) return false;
bool bret = true;
char szline[256] = {0};
while (fgets(szline, 255, m_fp))
{
if (strncmp(szline, "$Nodes" , 6) == 0) bret = ReadNodes();
else if (strncmp(szline, "$Elements" , 9) == 0) bret = ReadElements();
if (bret == false) return false;
}
// close the file
Close();
return BuildMesh(*m_fem);
}
bool GMeshImport::ReadNodes()
{
m_Node.clear();
char szline[256] = {0};
fgets(szline, 255, m_fp);
int nodes = 0;
int nread = sscanf(szline, "%d", &nodes);
if (nread != 1) return errf("Error while reading Nodes section");
m_Node.resize(nodes);
// read the nodes
for (int i=0; i<nodes; ++i)
{
vec3f& r = m_Node[i].r;
fgets(szline, 255, m_fp);
int nread = sscanf(szline, "%*d %g %g %g", &r.x, &r.y, &r.z);
if (nread != 3) return errf("Error while reading Nodes section");
}
// read the end of the mesh format
fgets(szline, 255, m_fp);
if (strncmp(szline, "$EndNodes", 9) != 0) return errf("Failed finding EndNodes");
return true;
}
bool GMeshImport::ReadElements()
{
m_Elem.clear();
char szline[256] = {0};
fgets(szline, 255, m_fp);
int elems = 0;
int nread = sscanf(szline, "%d", &elems);
if (nread != 1) return errf("Error while reading Element section");
m_Elem.reserve(elems);
// read the elements
ELEM el;
int n[13];
for (int i=0; i<elems; ++i)
{
fgets(szline, 255, m_fp);
sscanf(szline,"%d%d%d%d%d%d%d%d%d%d%d%d%d",n,n+1,n+2,n+3,n+4,n+5,n+6,n+7,n+8,n+9,n+10,n+11,n+12);
switch (n[1])
{
case 4: // tetrahedron
el.ntype = FE_TET4;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
m_Elem.push_back(el);
break;
case 5:
el.ntype = FE_HEX8;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
el.node[4] = n[ 3 + n[2] + 4] - 1;
el.node[5] = n[ 3 + n[2] + 5] - 1;
el.node[6] = n[ 3 + n[2] + 6] - 1;
el.node[7] = n[ 3 + n[2] + 7] - 1;
m_Elem.push_back(el);
break;
case 6:
el.ntype = FE_PENTA6;
el.node[0] = n[ 3 + n[2] ] - 1;
el.node[1] = n[ 3 + n[2] + 1] - 1;
el.node[2] = n[ 3 + n[2] + 2] - 1;
el.node[3] = n[ 3 + n[2] + 3] - 1;
el.node[4] = n[ 3 + n[2] + 4] - 1;
el.node[5] = n[ 3 + n[2] + 5] - 1;
m_Elem.push_back(el);
break;
}
}
// read the end of the mesh format
fgets(szline, 255, m_fp);
if (strncmp(szline, "$EndElements", 12) != 0) return errf("Failed finding EndElements");
return true;
}
bool GMeshImport::BuildMesh(FEPostModel& fem)
{
int i;
int nodes = (int)m_Node.size();
int elems = (int)m_Elem.size();
if (nodes == 0) return errf("FATAL ERROR: No nodal data defined in file.");
if (elems == 0) return errf("FATAL ERROR: No element data defined in file.");
// clear the model
fem.Clear();
// add a materials
FEMaterial mat;
fem.AddMaterial(mat);
// build the mesh
FEPostMesh* pm = new FEPostMesh;
pm->Create(nodes, elems);
// create nodes
for (i=0; i<nodes; ++i)
{
FENode& n = pm->Node(i);
NODE& node = m_Node[i];
n.r.x = node.r.x;
n.r.y = node.r.y;
n.r.z = node.r.z;
}
// create elements
for (i=0; i<elems; ++i)
{
FEElement& el = static_cast<FEElement&>(pm->ElementRef(i));
ELEM& E = m_Elem[i];
el.m_MatID = 0;
switch (E.ntype)
{
case FE_TET4 : el.SetType(FE_TET4); break;
case FE_HEX8 : el.SetType(FE_HEX8); break;
case FE_PENTA6: el.SetType(FE_PENTA6); break;
default:
assert(false);
return false;
}
el.m_node[0] = E.node[0];
el.m_node[1] = E.node[1];
el.m_node[2] = E.node[2];
el.m_node[3] = E.node[3];
el.m_node[4] = E.node[4];
el.m_node[5] = E.node[5];
el.m_node[6] = E.node[6];
el.m_node[7] = E.node[7];
}
// update the mesh
fem.AddMesh(pm);
pm->BuildMesh();
fem.UpdateBoundingBox();
// we need a single state
FEState* ps = new FEState(0.f, &fem, fem.GetFEMesh(0));
fem.AddState(ps);
// clean up
m_Node.clear();
m_Elem.clear();
// we're good!
return true;
}
| 25.070485
| 99
| 0.628712
|
chunkeey
|
2adca25a6559cdf343d960f039d6d2b4feb0ddfa
| 4,219
|
cpp
|
C++
|
SDK/PUBG_SoundOptionWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 7
|
2019-03-06T11:04:52.000Z
|
2019-07-10T20:00:51.000Z
|
SDK/PUBG_SoundOptionWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | null | null | null |
SDK/PUBG_SoundOptionWidget_functions.cpp
|
realrespecter/PUBG-FULL-SDK
|
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
|
[
"MIT"
] | 10
|
2019-03-06T11:53:46.000Z
|
2021-02-18T14:01:11.000Z
|
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_SoundOptionWidget_parameters.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function SoundOptionWidget.SoundOptionWidget_C.IsEnable_VoiceSetting
// ()
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsEnable_VoiceSetting()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsEnable_VoiceSetting");
USoundOptionWidget_C_IsEnable_VoiceSetting_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.IsKeyUp
// (Event)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsKeyUp()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsKeyUp");
USoundOptionWidget_C_IsKeyUp_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.IsChanged
// (Event)
// Parameters:
// bool ReturnValue (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
bool USoundOptionWidget_C::IsChanged()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.IsChanged");
USoundOptionWidget_C_IsChanged_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
return params.ReturnValue;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnApply
// (Event)
void USoundOptionWidget_C::OnApply()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnApply");
USoundOptionWidget_C_OnApply_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnDefault
// (Event)
void USoundOptionWidget_C::OnDefault()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnDefault");
USoundOptionWidget_C_OnDefault_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.OnReset
// (Event)
void USoundOptionWidget_C::OnReset()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.OnReset");
USoundOptionWidget_C_OnReset_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.Construct
// (BlueprintCosmetic, Event)
void USoundOptionWidget_C::Construct()
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.Construct");
USoundOptionWidget_C_Construct_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function SoundOptionWidget.SoundOptionWidget_C.ExecuteUbergraph_SoundOptionWidget
// ()
// Parameters:
// int* EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void USoundOptionWidget_C::ExecuteUbergraph_SoundOptionWidget(int* EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function SoundOptionWidget.SoundOptionWidget_C.ExecuteUbergraph_SoundOptionWidget");
USoundOptionWidget_C_ExecuteUbergraph_SoundOptionWidget_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 24.672515
| 134
| 0.726475
|
realrespecter
|
2ae8821c883a13bc5a2b3fae0f8a9d88ca472eea
| 808
|
hh
|
C++
|
include/muensterTPCRunAction.hh
|
l-althueser/MuensterTPC-Simulation
|
7a086ab330cd5905f3c78c324936cdc36951e9bd
|
[
"BSD-2-Clause"
] | null | null | null |
include/muensterTPCRunAction.hh
|
l-althueser/MuensterTPC-Simulation
|
7a086ab330cd5905f3c78c324936cdc36951e9bd
|
[
"BSD-2-Clause"
] | 2
|
2017-01-24T21:18:46.000Z
|
2017-01-27T13:24:48.000Z
|
include/muensterTPCRunAction.hh
|
l-althueser/MuensterTPC-Simulation
|
7a086ab330cd5905f3c78c324936cdc36951e9bd
|
[
"BSD-2-Clause"
] | 4
|
2017-04-28T12:18:58.000Z
|
2019-04-10T21:15:00.000Z
|
/******************************************************************
* muensterTPCsim
*
* Simulations of the Muenster TPC
*
* @author Lutz Althüser
* @date 2015-04-14
*
* @update 2015-11-02 - added comments
*
* @comment
******************************************************************/
#ifndef __muensterTPCPRUNACTION_H__
#define __muensterTPCPRUNACTION_H__
#include <G4UserRunAction.hh>
class G4Run;
class muensterTPCAnalysisManager;
class muensterTPCRunAction: public G4UserRunAction {
public:
muensterTPCRunAction(muensterTPCAnalysisManager *pAnalysisManager=0);
~muensterTPCRunAction();
public:
void BeginOfRunAction(const G4Run *pRun);
void EndOfRunAction(const G4Run *pRun);
private:
muensterTPCAnalysisManager *m_pAnalysisManager;
};
#endif // __muensterTPCPRUNACTION_H__
| 21.837838
| 70
| 0.65099
|
l-althueser
|
2aeaf60025deb5b258232b5f76df3ed43b233b3d
| 5,403
|
cpp
|
C++
|
2_Package/imu/dev_bmp085.cpp
|
HANDS-FREE/OpenRE
|
fbd4cfa7a12bb43679db23422e79da69aaef1fce
|
[
"BSD-2-Clause"
] | 56
|
2016-08-13T11:26:51.000Z
|
2022-02-17T08:45:40.000Z
|
2_Package/imu/dev_bmp085.cpp
|
HANDS-FREE/OpenRE
|
fbd4cfa7a12bb43679db23422e79da69aaef1fce
|
[
"BSD-2-Clause"
] | 3
|
2017-03-04T11:55:26.000Z
|
2018-05-03T08:34:52.000Z
|
2_Package/imu/dev_bmp085.cpp
|
HANDS-FREE/OpenRE
|
fbd4cfa7a12bb43679db23422e79da69aaef1fce
|
[
"BSD-2-Clause"
] | 51
|
2016-08-15T14:00:44.000Z
|
2022-02-17T08:45:41.000Z
|
/***********************************************************************************************************************
* Copyright (c) Hands Free Team. All rights reserved.
* Contact: QQ Exchange Group -- 521037187
*
* LICENSING TERMS:
* The Hands Free is licensed generally under a permissive 3-clause BSD license.
* Contributions are requiredto be made under the same license.
*
* History:
* <author> <time> <version> <desc>
* mawenke 2015.10.1 V1.0 creat this file
* chenyingbing 2015.12.1 V1.6 update
* Description: 本文件封装了IMU中 气压计模块bmp085的驱动代码
*
***********************************************************************************************************************/
#include "dev_bmp085.h"
#include "math.h"
#define BMP085_ADDRESS 0xee
#define OSS 0
BMP085 bmp085;
void BMP085::readBuffer(void)
{
}
void BMP085::writeByte(unsigned char reg_address,unsigned char reg_data)
{
Board::getInstance()->iicDeviceWriteByte(IIC_IMU , BMP085_ADDRESS, reg_address, reg_data);
}
unsigned char BMP085::readByte(unsigned char reg_address)
{
return(Board::getInstance()->iicDeviceReadByte(IIC_IMU , BMP085_ADDRESS, reg_address));
}
/***********************************************************************************************************************
*
*
*
***********************************************************************************************************************/
//滑动平均滤波 算术平均滤波算法 输入最近采样值,返回最近NUM个值的平均值 NUM < 30
#define AAF_NUM_MAX 30
template<typename TYPE> TYPE Arithmetic_Average_F ( TYPE new_value , unsigned short int NUM)
{
static TYPE value_buf[AAF_NUM_MAX];
static unsigned short int count;
TYPE SUM;
unsigned short int i;
value_buf[count] = new_value;
count++;
if(count >= NUM) count=0; //滑动更新窗口
for ( i=0;i<NUM;i++)
{
SUM += value_buf[i];
}
return SUM/NUM;
}
unsigned char BMP085::checkDeviceState(void)
{
device_state = 1;
return device_state;
}
/***********************************************************************************************************************
* Function: void BMP085::deviceInit(void)
*
* Scope: public
*
* Description:
*
* Arguments:
*
* Return:
*
* Cpu_Time:
*
* History:
* mawenke 2015.10.1 V1.0 creat
***********************************************************************************************************************/
unsigned char BMP085::deviceInit(void)
{
ac1 = readByte(0xAA);
ac1 = (ac1<<8)|readByte(0xAB);
ac2 = readByte(0xAC);
ac2 = (ac2<<8)| readByte(0xAD);
ac3 = readByte(0xAE);
ac3 = (ac3<<8)| readByte(0xAF);
ac4 = readByte(0xB0);
ac4 = (ac4<<8)| readByte(0xB1);
ac5 = readByte(0xB2);
ac5 = (ac5<<8)| readByte(0xB3);
ac6 = readByte(0xB4);
ac6 = (ac6<<8)| readByte(0xB5);
b1 = readByte(0xB6);
b1 = (b1<<8)| readByte(0xB7);
b2 = readByte(0xB8);
b2 = (b2<<8)| readByte(0xB9);
mb = readByte(0xBA);
mb = (mb<<8)| readByte(0xBB);
mc = readByte(0xBC);
mc = (mc<<8)| readByte(0xBD);
md = readByte(0xBE);
md = (md<<8)| readByte(0xBF);
writeByte(0xF4,0x2E); //选择了BMP085模块,写入读温度指令
checkDeviceState();
return device_state;
}
/***********************************************************************************************************************
* Function: void BMP085::dataUpdate(void)
*
* Scope: private
*
* Description: 处理BMP的数据 循环调用 建议5ms 运行一次(200hz) 气压和温度更新速度各为100hz
*
* Arguments:
*
* Return:
*
* Cpu_Time: stm32f1(140 us) stm32f4+nofpu(unknow us) stm32f4+fpu(unknow us)
*
* History:
* mawenke 2015.10.1 V1.0 creat
***********************************************************************************************************************/
void BMP085::dataUpdate(void)
{
if(data_update_i == 0)
{
data_update_i = 1;
ut = ( readByte(0xF6) <<8 ) | readByte(0xF7); //读取数据低八位
writeByte(0xF4,0x34); //选择了BMP085模块,写入读气压指令
}
else
{
data_update_i = 0;
up = ( readByte(0xF6) <<8 ) | readByte(0xF7);
up &= 0x0000FFFF;
writeByte(0xF4,0x2E); //选择了BMP085模块,写入读温度指令
//以下为温补代码
x1 = ((int)ut - ac6) * ac5 >> 15;
x2 = ((int) mc << 11) / (x1 + md);
b5 = x1 + x2;
temperature = (b5 + 8) >> 4;
temperature = temperature/10 ;
b6 = b5 - 4000;
x1 = (b2 * (b6 * b6 >> 12)) >> 11;
x2 = ac2 * b6 >> 11;
x3 = x1 + x2;
b3 = (((int)ac1 * 4 + x3) + 2)/4;
x1 = ac3 * b6 >> 13;
x2 = (b1 * (b6 * b6 >> 12)) >> 16;
x3 = ((x1 + x2) + 2) >> 2;
b4 = (ac4 * (unsigned int) (x3 + 32768)) >> 15;
b7 = ((unsigned int) up - b3) * (50000 >> OSS);
if( b7 < 0x80000000)
p = (b7 * 2) / b4 ;
else
p = (b7 / b4) * 2;
x1 = (p >> 8) * (p >> 8);
x1 = (x1 * 3038) >> 16;
x2 = (-7357 * p) >> 16;
pressure = p + ((x1 + x2 + 3791) >> 4);
//以下为计算海拔的代码
altitude = (float)44330.0 * (1 - pow( (float)( pressure / (float)101325 ) , (float)0.1903 ) );
//altitude = Arithmetic_Average_F ( altitude , 10);
}
}
| 29.850829
| 121
| 0.446604
|
HANDS-FREE
|
2af1887a721bdeb858258afbb3e4d04e60fb56d6
| 2,977
|
cpp
|
C++
|
TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 1
|
2019-07-15T01:14:15.000Z
|
2019-07-15T01:14:15.000Z
|
TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 76
|
2018-10-27T16:59:36.000Z
|
2022-03-30T17:40:39.000Z
|
TDEngine2/source/core/CConfigFileEngineCoreBuilder.cpp
|
bnoazx005/TDEngine2
|
93ebfecf8af791ff5ecd4f57525a6935e34cd05c
|
[
"Apache-2.0"
] | 1
|
2019-07-29T02:02:08.000Z
|
2019-07-29T02:02:08.000Z
|
#include "../../include/core/CConfigFileEngineCoreBuilder.h"
#include "../../include/core/IFileSystem.h"
#include "../../include/platform/CConfigFileReader.h"
#include <memory>
#include <thread>
#include <functional>
namespace TDEngine2
{
CConfigFileEngineCoreBuilder::CConfigFileEngineCoreBuilder() :
CBaseEngineCoreBuilder()
{
}
/*!
\brief The method initialized the builder's object
\param[in] A callback to a factory's function of IEngineCore's objects
\return RC_OK if everything went ok, or some other code, which describes an error
*/
E_RESULT_CODE CConfigFileEngineCoreBuilder::Init(TCreateEngineCoreCallback pEngineCoreFactoryCallback, const std::string& configFilename)
{
if (mIsInitialized)
{
return RC_OK;
}
if (!pEngineCoreFactoryCallback || configFilename.empty())
{
return RC_INVALID_ARGS;
}
E_RESULT_CODE result = RC_OK;
mConfigFilename = configFilename;
mpEngineCoreInstance = pEngineCoreFactoryCallback(result);
if (result != RC_OK)
{
return result;
}
mIsInitialized = true;
return RC_OK;
}
TResult<TEngineSettings> CConfigFileEngineCoreBuilder::_readConfigurationFile(IFileSystem* pFileSystem, const std::string& configFilename)
{
TFileEntryId configFileHandle = pFileSystem->Open<IConfigFileReader>(configFilename, false).Get();
IConfigFileReader* pConfigFileReader = pFileSystem->Get<IConfigFileReader>(configFileHandle);
TEngineSettings settings;
settings.mApplicationName = pConfigFileReader->GetString("main", "name", "Default App");
settings.mWindowWidth = pConfigFileReader->GetInt("main", "width", 640);
settings.mWindowHeight = pConfigFileReader->GetInt("main", "height", 480);
settings.mFlags = pConfigFileReader->GetInt("main", "flags", 0x0);
settings.mMaxNumOfWorkerThreads = pConfigFileReader->GetInt("main", "max-num-worker-threads", std::thread::hardware_concurrency() - 1);
settings.mTotalPreallocatedMemorySize = pConfigFileReader->GetInt("memory", "total-preallocated-memory-size", DefaultGlobalMemoryBlockSize);
settings.mGraphicsContextType = StringToGraphicsContextType(pConfigFileReader->GetString("graphics", "context-type", "unknown"));
settings.mAudioContextType = E_AUDIO_CONTEXT_API_TYPE::FMOD;
pConfigFileReader->Close();
return Wrench::TOkValue<TEngineSettings>(settings);
}
TEngineSettings CConfigFileEngineCoreBuilder::_initEngineSettings()
{
if (auto readConfigResult = _readConfigurationFile(mpFileSystemInstance, mConfigFilename))
{
return (mEngineSettings = readConfigResult.Get());
}
TDE2_ASSERT(false);
return mEngineSettings;
}
TDE2_API IEngineCoreBuilder* CreateConfigFileEngineCoreBuilder(TCreateEngineCoreCallback pEngineCoreFactoryCallback, const std::string& configFilename, E_RESULT_CODE& result)
{
return CREATE_IMPL(IEngineCoreBuilder, CConfigFileEngineCoreBuilder, result, pEngineCoreFactoryCallback, configFilename);
}
}
| 32.358696
| 175
| 0.762177
|
bnoazx005
|
2af323f0acf239b7f37307f9ff8a65783bd92f7a
| 710
|
cpp
|
C++
|
Codechef/VisitTheCities.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | 1
|
2019-09-29T03:58:35.000Z
|
2019-09-29T03:58:35.000Z
|
Codechef/VisitTheCities.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | null | null | null |
Codechef/VisitTheCities.cpp
|
MartinAparicioPons/Competitive-Programming
|
58151df0ed08a5e4e605abefdd69fef1ecc10fa0
|
[
"Apache-2.0"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 10010;
int n, P, Pi;
vector<int> E[MAXN];
bool vis[MAXN];
void dfs(int u, int p){
if(vis[u]) return;
vis[u] = true;
if(p > P){
P = p;
Pi = u;
}
for(int i = 0; i < E[u].size(); i++){
dfs(E[u][i], p + 1);
}
}
int main(){
ios_base::sync_with_stdio(0);
int T, i, u, v;
cin >> T;
while(T--){
cin >> n;
if(n <= 0){
cout << 0 << endl;
continue;
}
for(i = 0; i <= n; i++){
E[i].clear();
}
for(i = 0; i < n-1; i++){
cin >> u >> v;
E[u].push_back(v);
E[v].push_back(u);
}
memset(vis, 0, sizeof vis);
P = 0;
dfs(1, 0);
memset(vis, 0, sizeof vis);
P = 0;
dfs(Pi, 0);
cout << P << endl;
}
}
| 14.2
| 38
| 0.476056
|
MartinAparicioPons
|
2af50f0fe6ae885ca83997d8da58c9840370afa1
| 3,521
|
hpp
|
C++
|
src/simple_graph/algorithm/bellman_ford.hpp
|
sfod/simple-graph
|
b07ac266296f44238ee02f7cc1042f079f4eac9d
|
[
"MIT"
] | 1
|
2016-01-25T09:54:38.000Z
|
2016-01-25T09:54:38.000Z
|
src/simple_graph/algorithm/bellman_ford.hpp
|
sfod/simple-graph
|
b07ac266296f44238ee02f7cc1042f079f4eac9d
|
[
"MIT"
] | 1
|
2019-04-08T10:40:00.000Z
|
2019-04-08T10:40:00.000Z
|
src/simple_graph/algorithm/bellman_ford.hpp
|
sfod/simple-graph
|
b07ac266296f44238ee02f7cc1042f079f4eac9d
|
[
"MIT"
] | null | null | null |
#pragma once
#include <algorithm>
#include <cassert>
#include <set>
#include <vector>
#include "simple_graph/graph.hpp"
namespace simple_graph {
template<typename W>
bool check_distance(const W &d, const W &w)
{
return !((d > 0) && (w > 0) && (std::numeric_limits<W>::max() - d < w));
}
template<bool Dir, typename V, typename E, typename W>
bool bellman_ford(const Graph<Dir, V, E, W> &g, vertex_index_t start_idx, vertex_index_t goal_idx,
std::vector<vertex_index_t> *path)
{
// TODO add utility function to check passed vertex indices
if ((start_idx < 0) || (goal_idx < 0)) {
return false;
}
std::vector<W> distance(g.vertex_num(), std::numeric_limits<W>::max());
std::vector<vertex_index_t> predecessor(g.vertex_num(), -1);
distance[start_idx] = 0;
auto fg = const_cast<Graph<Dir, V, E, W>*>(&g);
std::vector<Edge<E, W>> asc_edges;
std::vector<Edge<E, W>> desc_edges;
for (const auto &edge : fg->edges()) {
if (Dir) {
if (edge.idx1() < edge.idx2()) {
asc_edges.push_back(edge);
}
else {
desc_edges.push_back(edge);
}
}
else {
asc_edges.push_back(edge);
desc_edges.push_back(edge);
}
}
std::sort(asc_edges.begin(), asc_edges.end(), [](const Edge<E, W> &a, const Edge<E, W> &b) {
vertex_index_t a_idx = std::min(a.idx1(), a.idx2());
vertex_index_t b_idx = std::min(b.idx1(), b.idx2());
return a_idx < b_idx;
});
std::sort(desc_edges.begin(), desc_edges.end(), [](const Edge<E, W> &a, const Edge<E, W> &b) {
vertex_index_t a_idx = std::max(a.idx1(), a.idx2());
vertex_index_t b_idx = std::max(b.idx1(), b.idx2());
return b_idx < a_idx;
});
for (size_t i = 0; i < g.vertex_num(); ++i) {
bool changed = false;
for (const auto &edge : asc_edges) {
std::pair<vertex_index_t, vertex_index_t> e = std::minmax(edge.idx1(), edge.idx2());
if (check_distance(distance[e.first], edge.weight())
&& (distance[e.first] + edge.weight() < distance[e.second])) {
distance[e.second] = distance[e.first] + edge.weight();
predecessor[e.second] = e.first;
changed = true;
}
}
for (const auto &edge : desc_edges) {
std::pair<vertex_index_t, vertex_index_t> e = std::minmax(edge.idx1(), edge.idx2());
if (check_distance(distance[e.second], edge.weight())
&& (distance[e.second] + edge.weight() < distance[e.first])) {
distance[e.first] = distance[e.second] + edge.weight();
predecessor[e.first] = e.second;
changed = true;
}
}
if (!changed) {
break;
}
}
for (const auto &edge : fg->edges()) {
if (check_distance(distance[edge.idx1()], edge.weight())
&& (distance[edge.idx1()] + edge.weight() < distance[edge.idx2()])) {
return false;
}
}
if (distance[goal_idx] == std::numeric_limits<W>::max()) {
return false;
}
vertex_index_t idx = goal_idx;
while (idx != start_idx) {
path->push_back(idx);
idx = predecessor[idx];
assert(idx != static_cast<vertex_index_t>(-1));
}
path->push_back(idx);
std::reverse(path->begin(), path->end());
return true;
}
} // simple_graph
| 32.302752
| 98
| 0.545016
|
sfod
|
2af686437eda8ab8178fd1a9174f42768e3f51d5
| 4,200
|
cc
|
C++
|
testing/gsgts_test.cc
|
shgalus/shg
|
0318d0126cf12c3236183447d130969c468a02fa
|
[
"MIT"
] | 9
|
2015-05-21T04:14:50.000Z
|
2021-05-31T17:15:15.000Z
|
testing/gsgts_test.cc
|
shgalus/shg
|
0318d0126cf12c3236183447d130969c468a02fa
|
[
"MIT"
] | 1
|
2015-05-21T05:31:04.000Z
|
2015-05-21T05:31:04.000Z
|
testing/gsgts_test.cc
|
shgalus/shg
|
0318d0126cf12c3236183447d130969c468a02fa
|
[
"MIT"
] | 2
|
2015-05-21T04:14:44.000Z
|
2020-08-18T12:35:22.000Z
|
#include <shg/gsgts.h>
#include <shg/mzt.h>
#include <shg/utils.h>
#include "testing.h"
namespace SHG::Testing {
BOOST_AUTO_TEST_SUITE(gsgts_test)
BOOST_AUTO_TEST_CASE(basic_test) {
const std::vector<double> result1{
-0.1853455, -0.1532896, -0.1108232, -0.2036469, -0.1754326,
-0.1098344, -0.1704000, -0.1704131, -0.1563406, -0.1918795,
-0.0037222, 0.0975940, 0.0355298, -0.0634263, 0.0374293,
0.0977770, 0.0736954, 0.2835564, 0.2788326, 0.2212461,
0.1910693, 0.1717203, 0.1263446, 0.0584663, -0.1037948,
-0.2123793, -0.3292821, -0.2957615, -0.0796072, -0.0078135,
0.1049731, -0.1195140, 0.0005337, -0.0356647, 0.2934005,
0.2276349, 0.4457550, 0.4160869, 0.4105583, 0.1995325,
0.0474566, 0.1518003, 0.2249002, 0.1612962, 0.1916418,
0.1283362, 0.0949260, 0.1025253, 0.1695968, 0.3228145,
0.0881576, 0.2352667, 0.2379230, 0.0875150, -0.1102473,
-0.2148395, -0.0491461, -0.1555136, -0.0795668, 0.0525286,
0.0295757, 0.2391820, 0.1089352, 0.2395681, 0.1216882,
0.2793094, 0.3333728, 0.1691596, -0.0416942, 0.1816499,
0.4151612, 0.2889556, 0.2731870, 0.3562827, 0.1409797,
0.1811236, 0.1518109, 0.0900939, 0.1209136, 0.0668564,
0.1764099, 0.2728195, 0.2470544, 0.1540218, 0.0997584,
0.1230065, -0.0144507, 0.1192095, 0.1224003, 0.1762245,
0.1806781, 0.1696920, -0.0684979, -0.1765898, -0.1535255,
-0.0453403, -0.0492510, 0.0043458, 0.0749827, 0.0774716,
0.1105852, 0.1633152, 0.3711041, 0.3320104, 0.3874592,
0.2527283, 0.0685019, 0.0296893, -0.1128779, -0.1337343,
-0.0479861, -0.0095436, -0.0649834, -0.0609462, -0.1011171,
-0.1103539, -0.0297745, 0.0183672, 0.1219624, 0.3562367,
0.4008174, 0.4294983, 0.2980393, 0.1350898, -0.0283490,
-0.0908774, -0.0056641, -0.0478976, 0.1339543};
const std::vector<double> result2{
-0.6316450, -0.5236583, -0.6450972, -0.6190345, -0.5010952,
-0.9558759, -0.1537523, 0.4321690, -0.2066403, 0.1795031,
0.6131393, 1.3266019, 0.8642400, 0.7363808, 0.3988882,
-0.6462101, -1.5355407, -1.0049679, 0.3972050, -0.2645621,
-0.3155533, 0.8387987, 1.5328002, 2.0032490, 0.8197588,
0.0549526, 0.9641574, 0.4819636, 0.5519046, 0.0725050,
1.2768633, 0.4071369, 1.3226040, -0.3431683, -0.7920558,
-0.6202403, -0.2992066, 0.3171086, 0.8226870, 0.5258867,
1.0262011, 1.1781231, -0.4041209, 1.4476297, 1.2358308,
1.1499674, 0.5927083, 0.4290790, 0.2877266, 0.2509648,
1.2343851, 0.6633968, 0.4232300, -0.0151701, 0.4706398,
0.6900624, 0.8829870, -0.7137435, -0.7393445, -0.2582170,
0.0220044, 0.3048083, 0.4480417, 1.4495389, 1.7003893,
0.8326820, -0.1140906, -0.6896338, -0.2440786, -0.1348664,
-0.4987745, -0.4856796, -0.1759956, 0.7788311, 1.9449494,
1.6053352, 0.3524270, -0.6395870, -0.1899812, -0.0128994};
const GSGTS::Cosine_transform ct{nullptr};
const GSGTS::Real_transform rt{nullptr};
const double eps = 5e-8;
const std::vector<double> acf1 = acfar1(1.0 / 64.0, 0.8, 129);
const std::vector<double> acf2 = acfar1(0.5, 0.6, 80);
std::vector<double>::size_type i;
MZT mzt;
auto normal = [&mzt]() { return mzt.normal(); };
std::vector<double> X;
mzt = MZT();
X.resize(acf1.size());
GSGTS gsgts1(acf1, ct);
gsgts1.generate(X, normal, rt);
BOOST_CHECK(X.size() == acf1.size());
BOOST_REQUIRE(X.size() == result1.size());
for (i = 0; i < X.size(); i++)
BOOST_CHECK(faeq(X[i], result1[i], eps));
mzt = MZT();
X.resize(acf2.size());
GSGTS gsgts2(acf2, ct);
gsgts2.generate(X, normal, rt);
BOOST_CHECK(X.size() == acf2.size());
BOOST_REQUIRE(X.size() == result2.size());
for (i = 0; i < X.size(); i++)
BOOST_CHECK(faeq(X[i], result2[i], eps));
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace SHG::Testing
| 48.275862
| 70
| 0.584524
|
shgalus
|
2afdf7b06a66366ec7c1cbf55fb56779ea03d8f0
| 9,465
|
cpp
|
C++
|
pure_pursuit_core/test/GeometryTest.cpp
|
Idate96/se2_navigation
|
0fabe002742add5e4d716776b13704aa9c1aa339
|
[
"BSD-3-Clause"
] | 216
|
2020-04-14T22:32:45.000Z
|
2022-03-30T17:56:12.000Z
|
pure_pursuit_core/test/GeometryTest.cpp
|
Idate96/se2_navigation
|
0fabe002742add5e4d716776b13704aa9c1aa339
|
[
"BSD-3-Clause"
] | 5
|
2020-09-23T08:41:38.000Z
|
2021-11-11T09:58:00.000Z
|
pure_pursuit_core/test/GeometryTest.cpp
|
Idate96/se2_navigation
|
0fabe002742add5e4d716776b13704aa9c1aa339
|
[
"BSD-3-Clause"
] | 56
|
2020-04-29T00:26:20.000Z
|
2022-03-30T17:27:55.000Z
|
/*
* GeometryTest.cpp
*
* Created on: Mar 19, 2020
* Author: jelavice
*/
#include <gtest/gtest.h>
// Math
#include <cmath>
#include "test_helpers.hpp"
#include "pure_pursuit_core/math.hpp"
namespace ppt = pure_pursuit_test;
namespace pp = pure_pursuit;
using SolutionCase = pp::Intersection::SolutionCase;
template<typename T>
int toInt(T t)
{
return static_cast<int>(t);
}
constexpr unsigned int numCasesPerTest = 2000;
TEST(Geoemtry, CircleValid)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
EXPECT_GE(circle.r_, 0.0);
EXPECT_LE(std::fabs(circle.center_.x()), ppt::testPlaneWidth);
EXPECT_LE(std::fabs(circle.center_.y()), ppt::testPlaneWidth);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleValid failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PointOutsideCircle)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto point = ppt::createRandomPointOutside(circle);
const double d = (circle.center_ - point).norm();
EXPECT_GT(d, circle.r_);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PointOutsideCircle failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PointInsideCircle)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto point = ppt::createRandomPointInside(circle);
const double d = (circle.center_ - point).norm();
EXPECT_LT(d, circle.r_);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PointInsideCircle failed with seed: " << seed << std::endl;
}
}
TEST(Geoemtry, PerpendicularVector)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
ppt::Line l;
l.p1_ = ppt::createRandomPoint();
l.p2_ = ppt::createRandomPoint();
const auto v = ppt::createUnitVectorPerpendicularToLine(l);
EXPECT_NEAR(v.norm(), 1.0, 1e-5);
ppt::Vector v_hat = l.p2_ - l.p1_;
v_hat.normalize();
EXPECT_NEAR(v.transpose() * v_hat, 0.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, PerpendicularVector failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_0)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWithoutIntersection(circle);
EXPECT_GT((line.p1_ - circle.center_).norm(), circle.r_);
EXPECT_GT((line.p2_ - circle.center_).norm(), circle.r_);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::NO_SOLUTION));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_0 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_1)
{
const int seed = 558104554; //ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWitOneIntersection(circle);
const bool atLeastOnePointAtcircleRadiusDistance = pp::isClose(
(line.p1_ - circle.center_).norm(), circle.r_)
|| pp::isClose((line.p2_ - circle.center_).norm(), circle.r_);
EXPECT_TRUE(atLeastOnePointAtcircleRadiusDistance);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::ONE_SOLUTION));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_1 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CircleIntersection_2)
{
const int seed = ppt::seedRndGenerator();
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const auto circle = ppt::createRandomCircle();
const auto line = ppt::createRandomLineWithTwoIntersections(circle);
pp::Intersection intersection;
pp::computeIntersection(line, circle, &intersection);
EXPECT_EQ(toInt(intersection.solutionCase_), toInt(SolutionCase::TWO_SOLUTIONS));
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, CircleIntersection_2 failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, DesiredHeadingForward)
{
using DrivingDirection = pp::DrivingDirection;
const int seed = ppt::seedRndGenerator();
std::uniform_real_distribution<double> yawDist(-M_PI, M_PI);
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const double desiredYaw = yawDist(ppt::rndGenerator);
ppt::Vector desiredHeading = computeDesiredHeadingVector(desiredYaw, DrivingDirection::FWD);
desiredHeading.normalize();
ppt::Vector headingGroundTruth(std::cos(desiredYaw), std::sin(desiredYaw));
EXPECT_NEAR(headingGroundTruth.transpose() * desiredHeading, 1.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, DesiredHeadingForward failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, DesiredHeadingReverse)
{
using DrivingDirection = pp::DrivingDirection;
const int seed = ppt::seedRndGenerator();
std::uniform_real_distribution<double> yawDist(-M_PI, M_PI);
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const double desiredYaw = yawDist(ppt::rndGenerator);
ppt::Vector desiredHeading = computeDesiredHeadingVector(desiredYaw, DrivingDirection::BCK);
desiredHeading.normalize();
const ppt::Vector headingGroundTruth(std::cos(desiredYaw), std::sin(desiredYaw));
EXPECT_NEAR(headingGroundTruth.transpose() * desiredHeading, -1.0, 1e-5);
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, DesiredHeadingReverse failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, IsPastLastPoint)
{
using PathPoint = pp::PathPoint;
const int seed = ppt::seedRndGenerator();
pp::PathSegment segment;
segment.point_.resize(1);
EXPECT_THROW(pp::isPastLastPoint(segment, ppt::createRandomPoint()), std::runtime_error);
segment.point_.resize(2);
EXPECT_NO_THROW(pp::isPastLastPoint(segment, ppt::createRandomPoint()));
segment.point_ = {PathPoint(-1.0,0.0), PathPoint(0.0,0.0)};
for (unsigned int i = 0; i < numCasesPerTest; ++i) {
const PathPoint queryPoint(ppt::createRandomPoint());
if (queryPoint.position_.x() > 0.0){
EXPECT_TRUE(pp::isPastLastPoint(segment, queryPoint.position_));
} else {
EXPECT_FALSE(pp::isPastLastPoint(segment, queryPoint.position_));
}
}
if (::testing::Test::HasFailure()) {
std::cout << "\n Test Geometry, IsPastLastPoint failed with seed: " << seed << std::endl;
}
}
TEST(Geometry, CoarseWaypoints1)
{
/* this test addresses the ISSUE #3
* https://github.com/leggedrobotics/se2_navigation/issues/3
*/
using namespace pp;
RobotState robotState;
robotState.pose_ = RobotPose(-7.52288223073, 0.383239928729, 0.5042049);
PathSegment pathSegment;
pathSegment.drivingDirection_ = DrivingDirection::FWD;
pathSegment.point_.push_back(PathPoint(-9.64970568409, 0.036127697624)); // 0
pathSegment.point_.push_back(PathPoint(-6.11220568409, 2.16112769762)); // 1
pathSegment.point_.push_back(PathPoint(0.0, 5.0)); // 2
pathSegment.point_.push_back(PathPoint(6.11220568409, 2.16112769762)); // 3
pathSegment.point_.push_back(PathPoint(9.64970568409, 0.036127697624)); // 4
pathSegment.point_.push_back(PathPoint(13.9358333817, -2.53857798646)); // 5
const double lookaheadDistance = 2.5;
appendPointAlongFinalApproachDirection(5.0 * lookaheadDistance, &pathSegment);
unsigned int closerPointId=0, fartherPointId=0;
const Point anchorPoint(-7.08510279935,0.624795656177 );
findIdsOfTwoPointsDefiningALine(robotState, pathSegment, anchorPoint, 0, lookaheadDistance, &closerPointId, &fartherPointId);
EXPECT_EQ(closerPointId,1);
EXPECT_EQ(fartherPointId,2);
}
TEST(Geometry, CoarseWaypoints2)
{
/* this test addresses the ISSUE #3
* https://github.com/leggedrobotics/se2_navigation/issues/3
*/
using namespace pp;
RobotState robotState;
robotState.pose_ = RobotPose(2.25228492629, 4.33692721322, -0.2410715);
PathSegment pathSegment;
pathSegment.drivingDirection_ = DrivingDirection::FWD;
pathSegment.point_.push_back(PathPoint(-9.64970568409, 0.036127697624)); // 0
pathSegment.point_.push_back(PathPoint(-6.11220568409, 2.16112769762)); // 1
pathSegment.point_.push_back(PathPoint(0.0, 5.0)); // 2
pathSegment.point_.push_back(PathPoint(6.11220568409, 2.16112769762)); // 3
pathSegment.point_.push_back(PathPoint(9.64970568409, 0.036127697624)); // 4
pathSegment.point_.push_back(PathPoint(13.9358333817, -2.53857798646)); // 5
const double lookaheadDistance = 2.5;
appendPointAlongFinalApproachDirection(5.0 * lookaheadDistance, &pathSegment);
unsigned int closerPointId=0, fartherPointId=0;
const Point anchorPoint(2.737826287315, 4.21755558031 );
findIdsOfTwoPointsDefiningALine(robotState, pathSegment, anchorPoint, 0, lookaheadDistance, &closerPointId, &fartherPointId);
EXPECT_EQ(closerPointId,2);
EXPECT_EQ(fartherPointId,3);
}
| 36.686047
| 127
| 0.709773
|
Idate96
|
63021073c1c0f32186c24ec364ce2c943ccf648c
| 1,712
|
cpp
|
C++
|
src/web/tests/test_libaeon_web/test_url_encoding.cpp
|
aeon-engine/libaeon
|
e42b39e621dcd0a0fba05e1c166fc688288fb69b
|
[
"BSD-2-Clause"
] | 7
|
2017-02-19T16:22:16.000Z
|
2021-03-02T05:47:39.000Z
|
src/web/tests/test_libaeon_web/test_url_encoding.cpp
|
aeon-engine/libaeon
|
e42b39e621dcd0a0fba05e1c166fc688288fb69b
|
[
"BSD-2-Clause"
] | 61
|
2017-05-29T06:11:17.000Z
|
2021-03-28T21:51:44.000Z
|
src/web/tests/test_libaeon_web/test_url_encoding.cpp
|
aeon-engine/libaeon
|
e42b39e621dcd0a0fba05e1c166fc688288fb69b
|
[
"BSD-2-Clause"
] | 2
|
2017-05-28T17:17:40.000Z
|
2017-07-14T21:45:16.000Z
|
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen
#include <aeon/web/http/url_encoding.h>
#include <aeon/web/http/validators.h>
#include <gtest/gtest.h>
#include <random>
using namespace aeon;
TEST(test_url_encoding, encode_regular_string)
{
const std::u8string test_str = u8"ThisIsATestString123";
ASSERT_EQ(test_str, web::http::url_encode(test_str));
}
TEST(test_url_encoding, encode_spaces)
{
const std::u8string test_str = u8"This Is A Test String 123";
const std::u8string expected_str = u8"This%20Is%20A%20Test%20String%20123";
ASSERT_EQ(expected_str, web::http::url_encode(test_str));
}
static auto generate_random_string(const int length) -> std::u8string
{
std::u8string str;
str.reserve(length);
std::random_device r;
std::default_random_engine e1(r());
std::uniform_int_distribution<unsigned long> uniform_dist;
int offset = 0;
auto random_value = uniform_dist(e1);
for (auto i = 0; i < length; ++i)
{
if (offset == sizeof(unsigned long))
{
random_value = uniform_dist(e1);
i = 0;
}
str += static_cast<char>((random_value >> (i * 8)) & 0xFF);
++offset;
}
return str;
}
TEST(test_url_encoding, encode_decode_random)
{
for (auto i = 0; i < 100; ++i)
{
for (auto j = 5; j < 20; ++j)
{
const auto str = generate_random_string(j);
const auto str_encoded = web::http::url_encode(str);
ASSERT_TRUE(web::http::detail::validate_uri(str_encoded));
const auto str_decoded = web::http::url_decode(str_encoded);
ASSERT_EQ(str, str_decoded);
}
}
}
| 25.939394
| 79
| 0.638435
|
aeon-engine
|
6304a393a27ce668de2d43bd5d1b5530919ee665
| 326
|
hpp
|
C++
|
DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp
|
meraz/doremi
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | 1
|
2020-03-23T15:42:05.000Z
|
2020-03-23T15:42:05.000Z
|
DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp
|
Meraz/ssp15
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | null | null | null |
DoremiEngine/AI/Include/Interface/SubModule/AStarSubModule.hpp
|
Meraz/ssp15
|
452d08ebd10db50d9563c1cf97699571889ab18f
|
[
"MIT"
] | 1
|
2020-03-23T15:42:06.000Z
|
2020-03-23T15:42:06.000Z
|
#pragma once
namespace DoremiEngine
{
namespace AI
{
/**
TODOKO docs
*/
class MapGrid;
class AStarSubModule
{
public:
virtual void GetPath(int p_startPos, const MapGrid& p_map) = 0;
virtual MapGrid* BuildMapGrid() = 0;
};
}
}
| 18.111111
| 75
| 0.506135
|
meraz
|
630642a798f5254c0a521c6019c0031bcdbc86d9
| 5,515
|
cpp
|
C++
|
src/ui/Style.cpp
|
CedricGuillemet/gemoni
|
76ca371d509791dd9d560d3f9f701f96e209ca5e
|
[
"MIT"
] | null | null | null |
src/ui/Style.cpp
|
CedricGuillemet/gemoni
|
76ca371d509791dd9d560d3f9f701f96e209ca5e
|
[
"MIT"
] | null | null | null |
src/ui/Style.cpp
|
CedricGuillemet/gemoni
|
76ca371d509791dd9d560d3f9f701f96e209ca5e
|
[
"MIT"
] | null | null | null |
#include "imgui.h"
#include "IconsFontAwesome5.h"
void SetStyle()
{
ImGuiStyle& st = ImGui::GetStyle();
st.FrameBorderSize = 1.0f;
st.FramePadding = ImVec2(4.0f, 2.0f);
st.ItemSpacing = ImVec2(8.0f, 2.0f);
st.WindowBorderSize = 1.0f;
st.TabBorderSize = 1.0f;
st.WindowRounding = 1.0f;
st.ChildRounding = 1.0f;
st.FrameRounding = 1.0f;
st.ScrollbarRounding = 1.0f;
st.GrabRounding = 1.0f;
st.TabRounding = 1.0f;
// Setup style
ImVec4* colors = ImGui::GetStyle().Colors;
colors[ImGuiCol_Text] = ImVec4(1.00f, 1.00f, 1.00f, 0.95f);
colors[ImGuiCol_TextDisabled] = ImVec4(0.50f, 0.50f, 0.50f, 1.00f);
colors[ImGuiCol_WindowBg] = ImVec4(0.13f, 0.12f, 0.12f, 1.00f);
colors[ImGuiCol_ChildBg] = ImVec4(1.00f, 1.00f, 1.00f, 0.00f);
colors[ImGuiCol_PopupBg] = ImVec4(0.05f, 0.05f, 0.05f, 0.94f);
colors[ImGuiCol_Border] = ImVec4(0.53f, 0.53f, 0.53f, 0.46f);
colors[ImGuiCol_BorderShadow] = ImVec4(0.00f, 0.00f, 0.00f, 0.00f);
colors[ImGuiCol_FrameBg] = ImVec4(0.00f, 0.00f, 0.00f, 0.85f);
colors[ImGuiCol_FrameBgHovered] = ImVec4(0.22f, 0.22f, 0.22f, 0.40f);
colors[ImGuiCol_FrameBgActive] = ImVec4(0.16f, 0.16f, 0.16f, 0.53f);
colors[ImGuiCol_TitleBg] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
colors[ImGuiCol_TitleBgActive] = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
colors[ImGuiCol_TitleBgCollapsed] = ImVec4(0.00f, 0.00f, 0.00f, 0.51f);
colors[ImGuiCol_MenuBarBg] = ImVec4(0.12f, 0.12f, 0.12f, 1.00f);
colors[ImGuiCol_ScrollbarBg] = ImVec4(0.02f, 0.02f, 0.02f, 0.53f);
colors[ImGuiCol_ScrollbarGrab] = ImVec4(0.31f, 0.31f, 0.31f, 1.00f);
colors[ImGuiCol_ScrollbarGrabHovered] = ImVec4(0.41f, 0.41f, 0.41f, 1.00f);
colors[ImGuiCol_ScrollbarGrabActive] = ImVec4(0.48f, 0.48f, 0.48f, 1.00f);
colors[ImGuiCol_CheckMark] = ImVec4(0.79f, 0.79f, 0.79f, 1.00f);
colors[ImGuiCol_SliderGrab] = ImVec4(0.48f, 0.47f, 0.47f, 0.91f);
colors[ImGuiCol_SliderGrabActive] = ImVec4(0.56f, 0.55f, 0.55f, 0.62f);
colors[ImGuiCol_Button] = ImVec4(0.50f, 0.50f, 0.50f, 0.63f);
colors[ImGuiCol_ButtonHovered] = ImVec4(0.67f, 0.67f, 0.68f, 0.63f);
colors[ImGuiCol_ButtonActive] = ImVec4(0.26f, 0.26f, 0.26f, 0.63f);
colors[ImGuiCol_Header] = ImVec4(0.54f, 0.54f, 0.54f, 0.58f);
colors[ImGuiCol_HeaderHovered] = ImVec4(0.64f, 0.65f, 0.65f, 0.80f);
colors[ImGuiCol_HeaderActive] = ImVec4(0.25f, 0.25f, 0.25f, 0.80f);
colors[ImGuiCol_Separator] = ImVec4(0.58f, 0.58f, 0.58f, 0.50f);
colors[ImGuiCol_SeparatorHovered] = ImVec4(0.81f, 0.81f, 0.81f, 0.64f);
colors[ImGuiCol_SeparatorActive] = ImVec4(0.81f, 0.81f, 0.81f, 0.64f);
colors[ImGuiCol_ResizeGrip] = ImVec4(0.87f, 0.87f, 0.87f, 0.53f);
colors[ImGuiCol_ResizeGripHovered] = ImVec4(0.87f, 0.87f, 0.87f, 0.74f);
colors[ImGuiCol_ResizeGripActive] = ImVec4(0.87f, 0.87f, 0.87f, 0.74f);
colors[ImGuiCol_Tab] = ImVec4(0.01f, 0.01f, 0.01f, 0.86f);
colors[ImGuiCol_TabHovered] = ImVec4(0.29f, 0.29f, 0.79f, 1.00f);
colors[ImGuiCol_TabActive] = ImVec4(0.31f, 0.31f, 0.91f, 1.00f);
colors[ImGuiCol_TabUnfocused] = ImVec4(0.02f, 0.02f, 0.02f, 1.00f);
colors[ImGuiCol_TabUnfocusedActive] = ImVec4(0.19f, 0.19f, 0.19f, 1.00f);
colors[ImGuiCol_DockingPreview] = ImVec4(0.38f, 0.48f, 0.60f, 1.00f);
colors[ImGuiCol_DockingEmptyBg] = ImVec4(0.20f, 0.20f, 0.20f, 1.00f);
colors[ImGuiCol_PlotLines] = ImVec4(0.61f, 0.61f, 0.61f, 1.00f);
colors[ImGuiCol_PlotLinesHovered] = ImVec4(0.68f, 0.68f, 0.68f, 1.00f);
colors[ImGuiCol_PlotHistogram] = ImVec4(0.90f, 0.77f, 0.33f, 1.00f);
colors[ImGuiCol_PlotHistogramHovered] = ImVec4(0.87f, 0.55f, 0.08f, 1.00f);
colors[ImGuiCol_TextSelectedBg] = ImVec4(0.47f, 0.60f, 0.76f, 0.47f);
colors[ImGuiCol_DragDropTarget] = ImVec4(0.58f, 0.58f, 0.58f, 0.90f);
colors[ImGuiCol_NavHighlight] = ImVec4(0.60f, 0.60f, 0.60f, 1.00f);
colors[ImGuiCol_NavWindowingHighlight] = ImVec4(1.00f, 1.00f, 1.00f, 0.70f);
colors[ImGuiCol_NavWindowingDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.20f);
colors[ImGuiCol_ModalWindowDimBg] = ImVec4(0.80f, 0.80f, 0.80f, 0.35f);
}
//extern ImGui::MarkdownConfig mdConfig;
ImFont* smallAF, * bigAF, * mediumAF;
void InitFonts()
{
ImGuiIO& io = ImGui::GetIO();
io.Fonts->Clear();
static const ImWchar icons_ranges[] = { ICON_MIN_FA, ICON_MAX_FA, 0 };
ImFontConfig icons_config;
icons_config.MergeMode = true;
icons_config.PixelSnapH = true;
float fontSize_ = 16.f;
static const char* defaultFontPath = "Fonts/OpenSans-SemiBold.ttf";
io.Fonts->AddFontFromFileTTF(defaultFontPath, fontSize_);
smallAF = io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, fontSize_, &icons_config, icons_ranges);
mediumAF = io.Fonts->AddFontFromFileTTF(defaultFontPath, 20.f);
io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, 20.f, &icons_config, icons_ranges);
bigAF = io.Fonts->AddFontFromFileTTF(defaultFontPath, 24.f);
io.Fonts->AddFontFromFileTTF("Fonts/" FONT_ICON_FILE_NAME_FAS, 24.f, &icons_config, icons_ranges);
/*
// Bold headings H2 and H3
mdConfig.headingFormats[1].font = io.Fonts->AddFontFromFileTTF("Stock/Fonts/OpenSans-ExtraBold.ttf", fontSize_);
mdConfig.headingFormats[2].font = mdConfig.headingFormats[1].font;
// bold heading H1
float fontSizeH1 = fontSize_ * 1.2f;
mdConfig.headingFormats[0].font = io.Fonts->AddFontFromFileTTF("Stock/Fonts/OpenSans-ExtraBold.ttf", fontSizeH1);
*/
}
| 51.542056
| 117
| 0.688123
|
CedricGuillemet
|
deb89d9db31f248c546602d7996ccbd4f783a53d
| 269
|
cpp
|
C++
|
examples/algos/subset-xor-maximization/example-1.cpp
|
parth-07/dragon
|
2e771d698398303c8ae6d603d28bc3acfa116181
|
[
"MIT"
] | 1
|
2021-02-24T17:51:32.000Z
|
2021-02-24T17:51:32.000Z
|
examples/algos/subset-xor-maximization/example-1.cpp
|
parth-07/dragon
|
2e771d698398303c8ae6d603d28bc3acfa116181
|
[
"MIT"
] | 1
|
2021-02-24T17:57:04.000Z
|
2021-05-17T11:09:40.000Z
|
examples/algos/subset-xor-maximization/example-1.cpp
|
parth-07/ds-and-algos
|
2e771d698398303c8ae6d603d28bc3acfa116181
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include "dragon/algos/subset-xor-maximization.hpp"
int main() {
std::vector<int> v{48, 32, 31};
std::cout<<dragon::maximum_subset_xor_value(v)<<"\n";
std::cout<<dragon::maximum_subset_xor_value(v.begin(), v.end())<<"\n";
}
| 26.9
| 72
| 0.680297
|
parth-07
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.