blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
7dc6939d9ee23c84a7f95ec32d7268d1dab7062c
d6a078b6b108a48c65c674e733020911cd5e026d
/Baekjoon/b1238.cpp
1289a1e9bd9f82b5a6dbd2e9b90b05c98898a70c
[]
no_license
doobee98/Algorithm
bffdef4c50d8a825993de0303cb436fbac8746a8
514b9aec42d67517eee20a1be863bde4eb60d230
refs/heads/main
2023-07-27T11:09:35.101830
2021-09-11T12:04:18
2021-09-11T12:32:57
342,802,779
0
0
null
null
null
null
UTF-8
C++
false
false
1,376
cpp
#include <iostream> #include <algorithm> #include <vector> #include <queue> #include <map> #include <climits> #include <cmath> #include <cstring> using namespace std; #define endl "\n" #define ends " " #define mk_p(x,y) make_pair((x), (y)) typedef long long ll; typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef tuple<int, int, int> tpi; typedef tuple<ll, ll, ll> tpl; typedef pair<double, ll> pdl; typedef unsigned long long ull; const int MOD = 1000000007; // PLZ check const ll LMOD = 1000000007; const int INF = 0x3f3f3f3f; const ll LINF = 0x3f3f3f3f3f3f3f3f; const double pi = acos(-1); const double eps = 1e-10; const pii dxdy[] = { {0, 1}, {1, 0}, {0, -1}, {-1, 0} }; const int dx[] = { 0, 1, 0, -1 }; const int dy[] = { 1, 0, -1, 0 }; int n, m, x; int dp[1005][1005]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); cin >> n >> m >> x; memset(dp, 0x3f, sizeof(int) * 1005 * 1005); for (int i = 0; i < m; i++) { int from, to, t; cin >> from >> to >> t; dp[from][to] = t; } for (int k = 1; k <= n; k++) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j]); } } } int max_d = -1; for (int i = 1; i <= n; i++) { int d; if (i == x) d = 0; else d = dp[i][x] + dp[x][i]; if (max_d < d) max_d = d; } cout << max_d << endl; }
[ "doobee98@naver.com" ]
doobee98@naver.com
30f5bf5ee70860a6b81bd0050f51880b3059a424
bb7eb313f6214ba1f4501b378d3c0ddd265daeb7
/code/公共/ConnectedComponent.cpp
0dee8c09d91fb4f1de25772784d358c31a453032
[]
no_license
RedSorghum/Template
ce6865a030c05a99e517913cac2ac1d207658ac0
366d127f2dc2e36c53fd573d30296a3e58a5cfe5
refs/heads/master
2020-03-26T20:07:16.442676
2018-10-31T10:42:45
2018-10-31T10:42:45
145,305,965
0
0
null
null
null
null
UTF-8
C++
false
false
2,001
cpp
#include<bits/stdc++.h> using namespace std; #define repb(i,s,t) for(int i=(s);i<=(t);++i) #define mst(a,b) memset(a,b,sizeof(a)) #define all(x) x.begin(),x.end() #define pb push_back #define mp make_pair typedef pair<int,int> pii; const int maxn = 1000; //原图点从1到n,使用init初始化点数n与图N //使用run运行,生成各个点所属的集合的标号fa //割点存储在cut中,桥存储在bridge中 struct BCC{ BCC(){init(0,0);} int n,t,dfn[maxn],low[maxn],fa[maxn],s[maxn]; vector<int>*N,cut;vector<pii> bridge; void init(int _n,vector<int>*_N){ n=_n;t=-1;N=_N;mst(dfn,0);mst(low,0);cut.clear();bridge.clear();} void dfs(int u,int d,int p){ int sec=0,son=d>1;dfn[u]=low[u]=d;s[++t]=u; for(auto v:N[u]){ if(!dfn[v]){ dfs(v,d+1,u);low[u]=min(low[u],low[v]); if(low[v]>dfn[u])bridge.pb(mp(u,v)); if(low[v]>=dfn[u]&&++son==2)cut.pb(u);} else if(v!=p||sec++)low[u]=min(low[u],dfn[v]);} if(dfn[u]==low[u])do fa[s[t]]=u;while(s[t--]!=u);} void run(){repb(i,1,n)if(!dfn[i])dfs(i,1,0);}}; //原图点从1到n,使用init初始化点数n与图N //使用run运行,生成点联通分量数目m,各点联通分量存储在D[1,m]中 //run过程中默认使用gen生成对应边数信息存储在e[1,m] //割点存储在cut中 struct DCC{ DCC(){init(0,0);} int n,t,m,dfn[maxn],low[maxn],s[maxn],e[maxn]; vector<int>*N,cut,D[maxn]; void init(int _n,vector<int>* _N){ n=_n;N=_N;t=-1;m=0;mst(dfn,0);mst(low,0);cut.clear();} void dfs(int u,int d,int p){ int sec=0,son=d>1;dfn[u]=low[u]=d;s[++t]=u; for(auto v:N[u]){ if(!dfn[v]){ dfs(v,d+1,u);low[u]=min(low[u],low[v]); if(low[v]>=dfn[u]){ if(++son==2)cut.pb(u); m+=1;D[m].clear();D[m].pb(u); do D[m].pb(s[t]);while(s[t--]!=v);}} else if(v!=p||sec++)low[u]=min(low[u],dfn[v]);}} void run(){repb(i,1,n)if(!dfn[i])dfs(i,1,0);gen();} void gen(){ mst(s,-1);mst(e,0); repb(i,1,m){ for(auto j:D[i])s[j]=i; for(auto j:D[i])for(auto k:N[j])if(s[k]==i)e[i]+=1;}}};
[ "741674999@qq.com" ]
741674999@qq.com
0ece6afc0ae270d4d6d43a2e7b89b6672c306aa2
89fb1b03c7af5a290879edb4eca271c37ec6ef3a
/ast/expressions/binary/xor/xor_expression.h
055b2f7da5267e78c43ac39176263992a6def7ae
[]
no_license
AleKiller21/Tiny-C
a598899fe130c0843a540a3eb47499dfda4a0123
96d389593873c63fe30b343fe85d426a303cc844
refs/heads/master
2021-09-01T15:17:51.924005
2017-09-22T19:46:46
2017-09-22T19:46:46
115,540,128
0
0
null
null
null
null
UTF-8
C++
false
false
374
h
#ifndef XOR_EXPRESSION #define XOR_EXPRESSION #include "../bit_operator.h" class xor_expression : public bit_operator { public: xor_expression(expression* expr1, expression* expr2, int position) : bit_operator(expr1, expr2, position, "^") {} string to_string(); int get_kind(); asm_code *generate_code(stack_manager *manager); }; #endif // XOR_EXPRESSION
[ "aleferrera@hotmail.com" ]
aleferrera@hotmail.com
b4f1638de5f3abb97467af15035903023513fb42
e8face9d41375f7ed4e6cfa960fac6ba7ed6c152
/src/options.cpp
9fcc9dca9346beee0d86d6b0a4d2eb113cfdcd17
[ "MIT" ]
permissive
iguyong/cppmark
264f1ef90b333abc830a375a46886fdbb1ccf9e4
e26cc85f276d06decd52be25be9d87d40e0bde99
refs/heads/master
2021-09-14T07:23:24.748539
2018-05-09T16:43:19
2018-05-09T16:43:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
61
cpp
// // Created by yong gu on 5/8/18. // #include "options.h"
[ "dujcel@icloud.com" ]
dujcel@icloud.com
4a7d78f16123fee1946bea03a57e70e69bd918ee
ed91c77afaeb0e075da38153aa89c6ee8382d3fc
/mediasoup-client/deps/webrtc/src/modules/audio_processing/logging/apm_data_dumper.cc
445248b0bfb770feaae09fdc6e47a70829e4b306
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-google-patent-license-webrtc", "LicenseRef-scancode-google-patent-license-webm", "MIT" ]
permissive
whatisor/mediasoup-client-android
37bf1aeaadc8db642cff449a26545bf15da27539
dc3d812974991d9b94efbc303aa2deb358928546
refs/heads/master
2023-04-26T12:24:18.355241
2023-01-02T16:55:19
2023-01-02T16:55:19
243,833,549
0
0
MIT
2020-02-28T18:56:36
2020-02-28T18:56:36
null
UTF-8
C++
false
false
2,879
cc
/* * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "modules/audio_processing/logging/apm_data_dumper.h" #include "rtc_base/strings/string_builder.h" // Check to verify that the define is properly set. #if !defined(WEBRTC_APM_DEBUG_DUMP) || \ (WEBRTC_APM_DEBUG_DUMP != 0 && WEBRTC_APM_DEBUG_DUMP != 1) #error "Set WEBRTC_APM_DEBUG_DUMP to either 0 or 1" #endif namespace webrtc { namespace { #if WEBRTC_APM_DEBUG_DUMP == 1 #if defined(WEBRTC_WIN) constexpr char kPathDelimiter = '\\'; #else constexpr char kPathDelimiter = '/'; #endif std::string FormFileName(const char* output_dir, const char* name, int instance_index, int reinit_index, const std::string& suffix) { char buf[1024]; rtc::SimpleStringBuilder ss(buf); const size_t output_dir_size = strlen(output_dir); if (output_dir_size > 0) { ss << output_dir; if (output_dir[output_dir_size - 1] != kPathDelimiter) { ss << kPathDelimiter; } } ss << name << "_" << instance_index << "-" << reinit_index << suffix; return ss.str(); } #endif } // namespace #if WEBRTC_APM_DEBUG_DUMP == 1 ApmDataDumper::ApmDataDumper(int instance_index) : instance_index_(instance_index) {} #else ApmDataDumper::ApmDataDumper(int instance_index) {} #endif ApmDataDumper::~ApmDataDumper() = default; #if WEBRTC_APM_DEBUG_DUMP == 1 bool ApmDataDumper::recording_activated_ = false; absl::optional<int> ApmDataDumper::dump_set_to_use_; char ApmDataDumper::output_dir_[] = ""; FILE* ApmDataDumper::GetRawFile(const char* name) { std::string filename = FormFileName(output_dir_, name, instance_index_, recording_set_index_, ".dat"); auto& f = raw_files_[filename]; if (!f) { f.reset(fopen(filename.c_str(), "wb")); RTC_CHECK(f.get()) << "Cannot write to " << filename << "."; } return f.get(); } WavWriter* ApmDataDumper::GetWavFile(const char* name, int sample_rate_hz, int num_channels, WavFile::SampleFormat format) { std::string filename = FormFileName(output_dir_, name, instance_index_, recording_set_index_, ".wav"); auto& f = wav_files_[filename]; if (!f) { f.reset( new WavWriter(filename.c_str(), sample_rate_hz, num_channels, format)); } return f.get(); } #endif } // namespace webrtc
[ "wuhaiyang1213@gmail.com" ]
wuhaiyang1213@gmail.com
da1ecb53cf8e7cd9afb0342b31465d2b765be9a7
da3ca05b1e740d5e6edde62e6ef811e760bdc35f
/Source/src/Engine/CoreSystems/RenderingSystem.cpp
a1bbddaf30634a3b68164b607467dfed1da564c9
[]
no_license
Patrikgyllvin/Car-Evolution
88c86676905cc0715546d12c51073001a91a6146
24e34dc8e541bd09461cdc7850256c0c2db87ab2
refs/heads/master
2021-01-04T02:48:25.749073
2020-02-13T22:13:36
2020-02-14T21:58:55
240,343,337
0
0
null
null
null
null
UTF-8
C++
false
false
475
cpp
// // RenderingSystem.cpp // GameEngine // // Created by Patrik Gyllvin on 2017-09-13. // Copyright © 2017 Patrik Gyllvin. All rights reserved. // #include "../../../include/Engine/CoreSystems/RenderingSystem.h" namespace Engine { RenderingSystem::RenderingSystem() {} RenderingSystem::~RenderingSystem() {} void RenderingSystem::render( Entity& entity ) { preRender(); renderEntity( entity ); postRender(); } }
[ "patrikgyllvin@icloud.com" ]
patrikgyllvin@icloud.com
b3aeb307cc9100f5777453713156ac90106a11ec
fa02b91ef961aa5fdd5a25eef7b3d1e2f70c652f
/Code/engine/Public/AABoundingBox.h
75f9052182ce21ac033993b4a2d2f1d8e60b5d98
[]
no_license
zhxhxlzt/CG_Learning
87d5499b9bf1a6c09715e6fea58be4a8fd4d3381
0425d7dad403cbf8fbd39325feea5794b8f54b65
refs/heads/master
2023-02-09T14:50:43.705301
2021-01-07T17:06:53
2021-01-07T17:06:53
313,043,723
0
0
null
null
null
null
UTF-8
C++
false
false
472
h
#pragma once #include <vector> #include "RayCast.h" #include "Shader.h" #include "glad/glad.h" class CAABoundingBox : public CRayCastable { public: void Build(const std::vector<glm::vec3>& vertices); bool RayCast(const CRay& ray, CRayCastInfo& info) override; void Draw(CShader& shader); private: glm::vec3 m_minPos; glm::vec3 m_maxPos; bool m_inited = false; GLuint vao, vbo, ebo; std::vector<glm::vec3> m_vertices; std::vector<unsigned int> m_indices; };
[ "2284174996@qq.com" ]
2284174996@qq.com
a2862ed14246b92559097664a0df8814ccde9d2a
c9e32374ecc46eac59437a068d424e6eb28ca849
/hcp/test/forward-declared-nested-class/main.cc
c210f404dc590382887e8f466d0b5ac7cab8f12c
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
urnest/urnest
261884b2ee71d64748c9e2afe7e78c9df61d91e7
6ec484080222f27a33070fa3b65593645f94a575
refs/heads/master
2023-07-13T06:16:41.566253
2023-07-06T11:04:34
2023-07-06T11:04:34
6,716,252
1
1
MIT
2023-06-11T03:06:14
2012-11-16T04:12:22
C++
UTF-8
C++
false
false
72
cc
#include "x.hh" int main(int argc,char*argv[]) { return A::B::x(); }
[ "urnest@onthenet.com.au" ]
urnest@onthenet.com.au
6dfddfe285521021dc2dc91addf0142a8fa65151
b5a9d42f7ea5e26cd82b3be2b26c324d5da79ba1
/tensorflow/compiler/xla/tests/local_client_execute_test.cc
f295afb09e6d33581a207a9a5e16092a150ce86f
[ "Apache-2.0" ]
permissive
uve/tensorflow
e48cb29f39ed24ee27e81afd1687960682e1fbef
e08079463bf43e5963acc41da1f57e95603f8080
refs/heads/master
2020-11-29T11:30:40.391232
2020-01-11T13:43:10
2020-01-11T13:43:10
230,088,347
0
0
Apache-2.0
2019-12-25T10:49:15
2019-12-25T10:49:14
null
UTF-8
C++
false
false
41,555
cc
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include <initializer_list> #include <memory> #include <vector> #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/client/local_client.h" #include "tensorflow/compiler/xla/client/xla_builder.h" #include "tensorflow/compiler/xla/layout_util.h" #include "tensorflow/compiler/xla/literal.h" #include "tensorflow/compiler/xla/service/local_service.h" #include "tensorflow/compiler/xla/service/platform_util.h" #include "tensorflow/compiler/xla/service/shaped_buffer.h" #include "tensorflow/compiler/xla/service/transfer_manager.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/test_helpers.h" #include "tensorflow/compiler/xla/tests/literal_test_util.h" #include "tensorflow/compiler/xla/tests/local_client_test_base.h" #include "tensorflow/compiler/xla/tests/test_macros.h" #include "tensorflow/compiler/xla/tests/test_utils.h" #include "tensorflow/compiler/xla/xla_data.pb.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/logging.h" #include "tensorflow/core/platform/stream_executor_no_cuda.h" #include "tensorflow/core/platform/test.h" #include "tensorflow/core/platform/test_benchmark.h" #include "tensorflow/stream_executor/device_memory_allocator.h" namespace xla { namespace { using ::testing::ContainsRegex; class LocalClientExecuteTest : public LocalClientTestBase { protected: ErrorSpec error_spec_{0.0001}; }; XLA_TEST_F(LocalClientExecuteTest, Constant) { XlaBuilder builder(TestName()); ConstantR0<float>(&builder, 123.0f); ScopedShapedBuffer result = ExecuteLocallyOrDie(builder.Build().ValueOrDie(), {}); LiteralTestUtil::ExpectR0Near<float>(123.f, ShapedBufferToLiteral(result), error_spec_); } XLA_TEST_F(LocalClientExecuteTest, AddScalars) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {}), "x"); auto y = ConstantR0<float>(&builder, 123.0f); Add(x, y); auto x_value = LiteralToShapedBuffer(LiteralUtil::CreateR0<float>(42.0f)); ScopedShapedBuffer result = ExecuteLocallyOrDie(builder.Build().ValueOrDie(), {&x_value}); LiteralTestUtil::ExpectR0Near<float>(165.f, ShapedBufferToLiteral(result), error_spec_); } XLA_TEST_F(LocalClientExecuteTest, AddZeroElementVectors) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {0}), "x"); auto y = ConstantR1<float>(&builder, {}); Add(x, y); auto x_array = LiteralToShapedBuffer(LiteralUtil::CreateR1<float>({})); ScopedShapedBuffer result = ExecuteLocallyOrDie(builder.Build().ValueOrDie(), {&x_array}); LiteralTestUtil::ExpectR1Near<float>({}, ShapedBufferToLiteral(result), error_spec_); } XLA_TEST_F(LocalClientExecuteTest, AddVectors) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {3}), "x"); auto y = ConstantR1<float>(&builder, {2.0f, 3.0f, 4.0f}); Add(x, y); auto x_array = LiteralToShapedBuffer(LiteralUtil::CreateR1<float>({0.0f, 1.0f, 2.0f})); ScopedShapedBuffer result = ExecuteLocallyOrDie(builder.Build().ValueOrDie(), {&x_array}); LiteralTestUtil::ExpectR1Near<float>( {2.0f, 4.0f, 6.0f}, ShapedBufferToLiteral(result), error_spec_); } XLA_TEST_F(LocalClientExecuteTest, AddVectorsWithProfile) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {3}), "x"); auto y = ConstantR1<float>(&builder, {2.0f, 3.0f, 4.0f}); Add(x, y); auto x_array = LiteralToShapedBuffer(LiteralUtil::CreateR1<float>({0.0f, 1.0f, 2.0f})); ExecutionProfile profile; ScopedShapedBuffer result = ExecuteLocallyOrDie( builder.Build().ValueOrDie(), {&x_array}, DefaultExecutableBuildOptions(), DefaultExecutableRunOptions().set_execution_profile(&profile)); LiteralTestUtil::ExpectR1Near<float>( {2.0f, 4.0f, 6.0f}, ShapedBufferToLiteral(result), error_spec_); EXPECT_GT(profile.compute_and_transfer_time_ns(), 0); } XLA_TEST_F(LocalClientExecuteTest, AddArraysWithDifferentInputLayouts) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {2, 2}), "x"); auto y = Parameter(&builder, 1, ShapeUtil::MakeShape(F32, {2, 2}), "y"); Add(x, y); auto computation = builder.Build().ConsumeValueOrDie(); // Create x as a col-major array. auto x_array = LiteralToShapedBuffer(LiteralUtil::CreateR2WithLayout( {{1.0f, 2.0f}, {3.0f, 4.0f}}, LayoutUtil::MakeLayout({0, 1}))); EXPECT_TRUE(Layout::Equal().MinorToMajorOnly()( x_array.on_device_shape().layout(), LayoutUtil::MakeLayout({0, 1}))); // Create y as a row-major array. auto y_array = LiteralToShapedBuffer(LiteralUtil::CreateR2WithLayout( {{10.0f, 20.0f}, {30.0f, 40.0f}}, LayoutUtil::MakeLayout({1, 0}))); EXPECT_TRUE(Layout::Equal().MinorToMajorOnly()( y_array.on_device_shape().layout(), LayoutUtil::MakeLayout({1, 0}))); ScopedShapedBuffer result_colmaj = ExecuteLocallyOrDie(computation, {&x_array, &y_array}); LiteralTestUtil::ExpectR2Near<float>({{11.0f, 22.0f}, {33.0f, 44.0f}}, ShapedBufferToLiteral(result_colmaj), error_spec_); // Run with the parameter values in a different order. ScopedShapedBuffer result_param_swap = ExecuteLocallyOrDie(computation, {&y_array, &x_array}); LiteralTestUtil::ExpectR2Near<float>({{11.0f, 22.0f}, {33.0f, 44.0f}}, ShapedBufferToLiteral(result_param_swap), error_spec_); } XLA_TEST_F(LocalClientExecuteTest, AddArraysWithDifferentOutputLayouts) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {2, 2}), "x"); auto y = Parameter(&builder, 1, ShapeUtil::MakeShape(F32, {2, 2}), "y"); Add(x, y); auto computation = builder.Build().ConsumeValueOrDie(); auto x_array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{1.0f, 2.0f}, {3.0f, 4.0f}})); auto y_array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{10.0f, 20.0f}, {30.0f, 40.0f}})); // Run with col-major result layout. ScopedShapedBuffer result_colmaj = ExecuteLocallyOrDie( computation, {&x_array, &y_array}, DefaultExecutableBuildOptions().set_result_layout( ShapeUtil::MakeShapeWithLayout(F32, /*dimensions=*/{2, 2}, {0, 1})), DefaultExecutableRunOptions()); EXPECT_TRUE(Layout::Equal().MinorToMajorOnly()( result_colmaj.on_device_shape().layout(), LayoutUtil::MakeLayout({0, 1}))); LiteralTestUtil::ExpectR2Near<float>({{11.0f, 22.0f}, {33.0f, 44.0f}}, ShapedBufferToLiteral(result_colmaj), error_spec_); // Run with row-major result layout. ScopedShapedBuffer result_rowmaj = ExecuteLocallyOrDie( computation, {&x_array, &y_array}, DefaultExecutableBuildOptions().set_result_layout( ShapeUtil::MakeShapeWithLayout(F32, /*dimensions=*/{2, 2}, {1, 0})), DefaultExecutableRunOptions()); EXPECT_TRUE(Layout::Equal().MinorToMajorOnly()( result_rowmaj.on_device_shape().layout(), LayoutUtil::MakeLayout({1, 0}))); LiteralTestUtil::ExpectR2Near<float>({{11.0f, 22.0f}, {33.0f, 44.0f}}, ShapedBufferToLiteral(result_rowmaj), error_spec_); } XLA_TEST_F(LocalClientExecuteTest, TupleResult) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {2, 2}), "x"); auto y = Parameter(&builder, 1, ShapeUtil::MakeShape(F32, {2, 2}), "y"); Tuple(&builder, {x, y, x}); auto computation = builder.Build().ConsumeValueOrDie(); auto x_array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{1.0f, 2.0f}, {3.0f, 4.0f}})); auto y_array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{10.0f, 20.0f}, {30.0f, 40.0f}})); ScopedShapedBuffer result = ExecuteLocallyOrDie(computation, {&x_array, &y_array}); EXPECT_TRUE(result.on_host_shape().IsTuple()); EXPECT_EQ(3, ShapeUtil::TupleElementCount(result.on_host_shape())); Literal result_literal = ShapedBufferToLiteral(result); LiteralTestUtil::ExpectR2Equal<float>({{1.0f, 2.0f}, {3.0f, 4.0f}}, LiteralSlice(result_literal, {0})); LiteralTestUtil::ExpectR2Equal<float>({{10.0f, 20.0f}, {30.0f, 40.0f}}, LiteralSlice(result_literal, {1})); LiteralTestUtil::ExpectR2Equal<float>({{1.0f, 2.0f}, {3.0f, 4.0f}}, LiteralSlice(result_literal, {2})); } XLA_TEST_F(LocalClientExecuteTest, NestedTupleResult) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {2, 2}), "x"); auto y = Parameter(&builder, 1, ShapeUtil::MakeShape(F32, {2, 2}), "y"); auto inner_tuple = Tuple(&builder, {x, y, x}); Tuple(&builder, {inner_tuple, x}); auto computation = builder.Build().ConsumeValueOrDie(); auto x_array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{1.0f, 2.0f}, {3.0f, 4.0f}})); auto y_array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{10.0f, 20.0f}, {30.0f, 40.0f}})); ScopedShapedBuffer result = ExecuteLocallyOrDie(computation, {&x_array, &y_array}); EXPECT_TRUE(result.on_host_shape().IsTuple()); EXPECT_EQ(2, ShapeUtil::TupleElementCount(result.on_host_shape())); Literal result_literal = ShapedBufferToLiteral(result); LiteralTestUtil::ExpectR2Equal<float>({{1.0f, 2.0f}, {3.0f, 4.0f}}, LiteralSlice(result_literal, {1})); LiteralTestUtil::ExpectR2Equal<float>({{1.0f, 2.0f}, {3.0f, 4.0f}}, LiteralSlice(result_literal, {0, 0})); LiteralTestUtil::ExpectR2Equal<float>({{10.0f, 20.0f}, {30.0f, 40.0f}}, LiteralSlice(result_literal, {0, 1})); LiteralTestUtil::ExpectR2Equal<float>({{1.0f, 2.0f}, {3.0f, 4.0f}}, LiteralSlice(result_literal, {0, 2})); } XLA_TEST_F(LocalClientExecuteTest, TupleResultWithLayout) { // Verify setting the result layout of a computation with a tuple output. XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {2, 2}), "x"); auto y = Parameter(&builder, 1, ShapeUtil::MakeShape(F32, {2, 2}), "y"); Tuple(&builder, {x, y}); auto array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{1.0f, 2.0f}, {3.0f, 4.0f}})); ExecutableBuildOptions options = DefaultExecutableBuildOptions(); Shape shape_with_layout = ShapeUtil::MakeTupleShape( {ShapeUtil::MakeShapeWithLayout(F32, /*dimensions=*/{2, 2}, /*minor_to_major=*/{0, 1}), ShapeUtil::MakeShapeWithLayout(F32, /*dimensions=*/{2, 2}, /*minor_to_major=*/{1, 0})}); options.set_result_layout(shape_with_layout); ScopedShapedBuffer result = ExecuteLocallyOrDie(builder.Build().ValueOrDie(), {&array, &array}, options, DefaultExecutableRunOptions()); Literal result_literal = ShapedBufferToLiteral(result); LiteralTestUtil::ExpectR2Equal<float>({{1.0f, 2.0f}, {3.0f, 4.0f}}, LiteralSlice(result_literal, {0})); LiteralTestUtil::ExpectR2Equal<float>({{1.0f, 2.0f}, {3.0f, 4.0f}}, LiteralSlice(result_literal, {1})); } XLA_TEST_F(LocalClientExecuteTest, TupleArguments) { const Shape array_shape = ShapeUtil::MakeShape(F32, {2, 2}); const Shape vector_shape = ShapeUtil::MakeShape(F32, {3}); const Shape tuple_shape0 = ShapeUtil::MakeTupleShape({array_shape, vector_shape}); const Shape tuple_shape1 = ShapeUtil::MakeTupleShape({vector_shape, array_shape}); // Computation adds the respective array and vector elements from each tuple // argument and returns the results as a tuple. XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, tuple_shape0, "x"); auto y = Parameter(&builder, 1, tuple_shape1, "y"); auto x_0 = GetTupleElement(x, 0); auto x_1 = GetTupleElement(x, 1); auto y_0 = GetTupleElement(y, 0); auto y_1 = GetTupleElement(y, 1); auto array_sum = Add(x_0, y_1); auto vector_diff = Sub(x_1, y_0); Tuple(&builder, {array_sum, vector_diff}); auto computation = builder.Build().ConsumeValueOrDie(); auto x_literal = LiteralUtil::MakeTupleFromSlices( {LiteralUtil::CreateR2<float>({{1.0, 2.0}, {3.0, 4.0}}), LiteralUtil::CreateR1<float>({42.0, 75.0, 123.0})}); auto y_literal = LiteralUtil::MakeTupleFromSlices( {LiteralUtil::CreateR1<float>({2.0, 4.0, 6.0}), LiteralUtil::CreateR2<float>({{55.0, 44.0}, {33.0, 22.0}})}); auto x_buffer = LiteralToShapedBuffer(x_literal); auto y_buffer = LiteralToShapedBuffer(y_literal); ScopedShapedBuffer result = ExecuteLocallyOrDie(computation, {&x_buffer, &y_buffer}); EXPECT_TRUE(result.on_host_shape().IsTuple()); EXPECT_EQ(2, ShapeUtil::TupleElementCount(result.on_host_shape())); Literal result_literal = ShapedBufferToLiteral(result); LiteralTestUtil::ExpectR2Equal<float>({{56.0f, 46.0f}, {36.0f, 26.0f}}, LiteralSlice(result_literal, {0})); LiteralTestUtil::ExpectR1Equal<float>({40.0f, 71.0f, 117.0f}, LiteralSlice(result_literal, {1})); } XLA_TEST_F(LocalClientExecuteTest, NestedTupleArgument) { const Shape array_shape = ShapeUtil::MakeShape(F32, {2, 2}); const Shape vector_shape = ShapeUtil::MakeShape(F32, {3}); const Shape inner_tuple_shape = ShapeUtil::MakeTupleShape({array_shape, vector_shape}); const Shape nested_tuple_shape = ShapeUtil::MakeTupleShape({inner_tuple_shape, vector_shape}); // Computation negates the array element and sums the two vector elements in // the nested tuple. The resulting array and vector are returned as a tuple. XlaBuilder builder(TestName()); auto param = Parameter(&builder, 0, nested_tuple_shape, "param"); auto inner_tuple = GetTupleElement(param, 0); auto inner_array = GetTupleElement(inner_tuple, 0); auto inner_vector = GetTupleElement(inner_tuple, 1); auto outer_vector = GetTupleElement(param, 1); auto negate_array = Neg(inner_array); auto vector_sum = Add(inner_vector, outer_vector); Tuple(&builder, {negate_array, vector_sum}); auto computation = builder.Build().ConsumeValueOrDie(); auto arg_literal = LiteralUtil::MakeTupleFromSlices( {LiteralUtil::MakeTupleFromSlices( {LiteralUtil::CreateR2<float>({{1.0, 2.0}, {3.0, 4.0}}), LiteralUtil::CreateR1<float>({42.0, 75.0, 123.0})}), LiteralUtil::CreateR1<float>({222.0, -2.0, 10.0})}); auto arg_buffer = LiteralToShapedBuffer(arg_literal); ScopedShapedBuffer result = ExecuteLocallyOrDie(computation, {&arg_buffer}); Literal result_literal = ShapedBufferToLiteral(result); LiteralTestUtil::ExpectR2Equal<float>({{-1.0, -2.0}, {-3.0, -4}}, LiteralSlice(result_literal, {0})); LiteralTestUtil::ExpectR1Equal<float>({264.0, 73.0, 133.0}, LiteralSlice(result_literal, {1})); } XLA_TEST_F(LocalClientExecuteTest, PassingTupleResultBackIntoComputation) { // Construct a computation which takes and returns the same shape (a // tuple). Feed the result of the computation back into the input. This // provides additional verification that the returned tuple is properly // constructed. const Shape array_shape = ShapeUtil::MakeShape(F32, {2, 2}); const Shape tuple_shape = ShapeUtil::MakeTupleShape({array_shape, array_shape}); XlaBuilder builder(TestName()); auto param = Parameter(&builder, 0, tuple_shape, "param"); auto element_0 = GetTupleElement(param, 0); auto element_1 = GetTupleElement(param, 1); Tuple(&builder, {Neg(element_0), Add(element_1, element_1)}); auto computation = builder.Build().ConsumeValueOrDie(); auto arg_literal = LiteralUtil::MakeTupleFromSlices( {LiteralUtil::CreateR2<float>({{1.0, 2.0}, {3.0, 4.0}}), LiteralUtil::CreateR2<float>({{11.0, 3.0}, {4.0, 5.0}})}); auto arg_buffer = LiteralToShapedBuffer(arg_literal); ScopedShapedBuffer result_0 = ExecuteLocallyOrDie(computation, {&arg_buffer}); Literal result_0_literal = ShapedBufferToLiteral(result_0); LiteralTestUtil::ExpectR2Equal<float>({{-1.0, -2.0}, {-3.0, -4.0}}, LiteralSlice(result_0_literal, {0})); LiteralTestUtil::ExpectR2Equal<float>({{22.0, 6.0}, {8.0, 10}}, LiteralSlice(result_0_literal, {1})); ScopedShapedBuffer result_1 = ExecuteLocallyOrDie(computation, {&result_0}); Literal result_1_literal = ShapedBufferToLiteral(result_1); LiteralTestUtil::ExpectR2Equal<float>({{1.0, 2.0}, {3.0, 4.0}}, LiteralSlice(result_1_literal, {0})); LiteralTestUtil::ExpectR2Equal<float>({{44.0, 12.0}, {16.0, 20}}, LiteralSlice(result_1_literal, {1})); } XLA_TEST_F(LocalClientExecuteTest, LargeTuple) { // Construct a computation which takes a tuple parameter with a very large // number of elements. // A larger number of elements would make for a better, more strenuous test, // but: // TODO(b/66959878): On cpu a large number of elements results in long // compilation time. // TODO(b/66954197): On gpu a large number of elements OOMs. const int kElementCount = 100; // Each element is a 2-element vector. const Shape element_shape = ShapeUtil::MakeShape(F32, {2}); std::vector<Shape> element_shapes(kElementCount, element_shape); const Shape tuple_shape = ShapeUtil::MakeTupleShape(element_shapes); XlaBuilder builder(TestName()); auto param = Parameter(&builder, 0, tuple_shape, "param"); // Add each element's tuple index value to every element. std::vector<XlaOp> result_elements; for (int i = 0; i < kElementCount; ++i) { auto element = GetTupleElement(param, i); result_elements.push_back(Add(element, ConstantR0<float>(&builder, i))); } Tuple(&builder, result_elements); auto computation = builder.Build().ConsumeValueOrDie(); // Feed in a tuple where each two-element vector element is {tuple_index, // -tuple_index}. std::vector<Literal> arg_elements; for (int i = 0; i < kElementCount; ++i) { arg_elements.push_back(LiteralUtil::CreateR1<float>({1.0f * i, -1.0f * i})); } Literal arg_literal = LiteralUtil::MakeTupleOwned(std::move(arg_elements)); auto arg_buffer = LiteralToShapedBuffer(arg_literal); ScopedShapedBuffer result = ExecuteLocallyOrDie(computation, {&arg_buffer}); Literal result_literal = ShapedBufferToLiteral(result); for (int i = 0; i < kElementCount; ++i) { LiteralTestUtil::ExpectR1Near<float>( {2.0f * i, 0.0f}, LiteralSlice(result_literal, {i}), error_spec_); } } XLA_TEST_F(LocalClientExecuteTest, LargeNestedTuple) { // Construct and run a computation which takes a two-level nested tuple // parameter with a large fanout. const int kFanout = 40; // Tuple shape is full two-level tree with the given fanout. const Shape element_shape = ShapeUtil::MakeShape(F32, {}); std::vector<Shape> element_shapes(kFanout, element_shape); const Shape inner_tuple_shape = ShapeUtil::MakeTupleShape(element_shapes); std::vector<Shape> inner_tuple_shapes(kFanout, inner_tuple_shape); const Shape tuple_shape = ShapeUtil::MakeTupleShape(inner_tuple_shapes); XlaBuilder builder(TestName()); auto param = Parameter(&builder, 0, tuple_shape, "param"); // The computation increments each leaf value by an amount equal to the leaf's // ordinal position in a traversal of the tuple. std::vector<XlaOp> result_elements; for (int i = 0; i < kFanout; ++i) { auto outer_element = GetTupleElement(param, i); std::vector<XlaOp> inner_result_elements; for (int j = 0; j < kFanout; ++j) { auto inner_element = GetTupleElement(outer_element, j); inner_result_elements.push_back( Add(inner_element, ConstantR0<float>(&builder, i * kFanout + j))); } result_elements.push_back(Tuple(&builder, inner_result_elements)); } Tuple(&builder, result_elements); auto computation = builder.Build().ConsumeValueOrDie(); // Construct the argument to pass to the computation. std::vector<Literal> outer_tuple_elements; for (int i = 0; i < kFanout; ++i) { std::vector<Literal> inner_tuple_elements; for (int j = 0; j < kFanout; ++j) { inner_tuple_elements.push_back(LiteralUtil::CreateR0<float>(i + j)); } outer_tuple_elements.push_back( LiteralUtil::MakeTupleOwned(std::move(inner_tuple_elements))); } auto arg_literal = LiteralUtil::MakeTupleOwned(std::move(outer_tuple_elements)); auto arg_buffer = LiteralToShapedBuffer(arg_literal); ScopedShapedBuffer result = ExecuteLocallyOrDie(computation, {&arg_buffer}); Literal result_literal = ShapedBufferToLiteral(result); for (int i = 0; i < kFanout; ++i) { for (int j = 0; j < kFanout; ++j) { LiteralTestUtil::ExpectR0Near<float>(i + j + i * kFanout + j, LiteralSlice(result_literal, {i, j}), error_spec_); } } } XLA_TEST_F(LocalClientExecuteTest, DeepTuple) { // Construct and run a computation which takes a very deep tuple. The tuple // has no fan out and a single scalar element at the bottom. const int kTupleDepth = 100; // Tuple shape is full two-level tree with the given fanout. Shape shape = ShapeUtil::MakeShape(F32, {}); for (int i = 0; i < kTupleDepth; ++i) { shape = ShapeUtil::MakeTupleShape({shape}); } XlaBuilder builder(TestName()); auto element = Parameter(&builder, 0, shape, "param"); for (int i = 0; i < kTupleDepth; ++i) { element = GetTupleElement(element, 0); } auto output = Add(element, ConstantR0<float>(&builder, 42.0)); for (int i = 0; i < kTupleDepth; ++i) { output = Tuple(&builder, {output}); } auto computation = builder.Build().ConsumeValueOrDie(); // Construct the argument to pass to the computation. Literal arg_literal = LiteralUtil::CreateR0<float>(123.0); for (int i = 0; i < kTupleDepth; ++i) { std::vector<Literal> arg_vector; arg_vector.push_back(std::move(arg_literal)); arg_literal = LiteralUtil::MakeTupleOwned(std::move(arg_vector)); } auto arg_buffer = LiteralToShapedBuffer(arg_literal); ScopedShapedBuffer result = ExecuteLocallyOrDie(computation, {&arg_buffer}); Literal result_literal = ShapedBufferToLiteral(result); ShapeIndex index; for (int i = 0; i < kTupleDepth; ++i) { index.push_back(0); } LiteralTestUtil::ExpectR0Equal<float>(165.0, LiteralSlice(result_literal, index)); } XLA_TEST_F(LocalClientExecuteTest, InvalidNumberOfArguments) { // Test passing in an invalid number of arguments. XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {3}), "x"); auto y = Parameter(&builder, 1, ShapeUtil::MakeShape(F32, {3}), "y"); Add(x, y); auto x_array = LiteralToShapedBuffer(LiteralUtil::CreateR1<float>({1.0f, 2.0f, 3.0f})); auto execute_status = ExecuteLocally(builder.Build().ValueOrDie(), {&x_array}); EXPECT_FALSE(execute_status.ok()); EXPECT_THAT(execute_status.status().error_message(), ContainsRegex("Invalid number of arguments")); } XLA_TEST_F(LocalClientExecuteTest, IncorrectArgumentShape) { // Test passing in an argument with the wrong shape. XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {3}), "x"); Neg(x); auto x_array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{0.0f, 1.0f}, {2.0f, 3.0f}})); auto execute_status = ExecuteLocally(builder.Build().ValueOrDie(), {&x_array}); EXPECT_FALSE(execute_status.ok()); EXPECT_THAT(execute_status.status().error_message(), ContainsRegex("Invalid argument shape")) << execute_status.status(); } XLA_TEST_F(LocalClientExecuteTest, InvalidResultLayout) { // Test passing in an invalid result layout parameter. XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {2, 2}), "x"); Neg(x); auto x_array = LiteralToShapedBuffer( LiteralUtil::CreateR2<float>({{0.0f, 1.0f}, {2.0f, 3.0f}})); auto execute_status = ExecuteLocally( builder.Build().ValueOrDie(), {&x_array}, DefaultExecutableBuildOptions().set_result_layout( ShapeUtil::MakeShapeWithLayout(F32, /*dimensions=*/{1, 2, 3, 4}, /*minor_to_major=*/{0, 1, 2, 3})), DefaultExecutableRunOptions()); EXPECT_FALSE(execute_status.ok()); EXPECT_THAT(execute_status.status().error_message(), ContainsRegex("not compatible with result shape")) << execute_status.status(); } XLA_TEST_F(LocalClientExecuteTest, RunOnAllDeviceOrdinals) { // Try to run a trivial computation on every device on the system. If a // specific device is not supported, check that the right error is returned. XlaBuilder builder(TestName()); ConstantR0<float>(&builder, 42.0f); auto computation = builder.Build().ConsumeValueOrDie(); for (int d = 0; d < local_client_->device_count(); ++d) { if (!local_client_->device_ordinal_supported(d)) { auto execute_status = ExecuteLocally(computation, {}, DefaultExecutableBuildOptions().set_device_ordinal(d), DefaultExecutableRunOptions().set_device_ordinal(d)); EXPECT_FALSE(execute_status.ok()); EXPECT_THAT(execute_status.status().error_message(), ContainsRegex("device .* not supported")); } else { auto result = ExecuteLocallyOrDie( computation, {}, DefaultExecutableBuildOptions().set_device_ordinal(d), DefaultExecutableRunOptions().set_device_ordinal(d)); EXPECT_EQ(d, result.device_ordinal()); LiteralTestUtil::ExpectR0Equal<float>(42.0f, ShapedBufferToLiteral(result)); } } } XLA_TEST_F(LocalClientExecuteTest, InvalidDeviceOrdinalValues) { // Try running computations on devices with device ordinal values which do not // exist. XlaBuilder builder(TestName()); ConstantR0<float>(&builder, 42.0f); auto computation = builder.Build().ConsumeValueOrDie(); auto execute_status = ExecuteLocally(computation, {}, DefaultExecutableBuildOptions().set_device_ordinal( local_client_->device_count()), DefaultExecutableRunOptions().set_device_ordinal( local_client_->device_count())); EXPECT_FALSE(execute_status.ok()); EXPECT_THAT(execute_status.status().error_message(), ContainsRegex("Invalid device ordinal value")); } XLA_TEST_F(LocalClientExecuteTest, RunOnStream) { // Run a computation on a specific stream on each device on the system. XlaBuilder builder(TestName()); ConstantR0<float>(&builder, 42.0f); auto computation = builder.Build().ConsumeValueOrDie(); for (int d = 0; d < local_client_->device_count(); ++d) { if (!local_client_->device_ordinal_supported(d)) { continue; } se::StreamExecutor* executor = local_client_->platform()->ExecutorForDevice(d).ValueOrDie(); se::Stream stream(executor); stream.Init(); auto result = ExecuteLocallyOrDie(computation, {}, DefaultExecutableBuildOptions(), DefaultExecutableRunOptions().set_stream(&stream)); // As a check to verify that the computation ran of the device associated // with the stream. This is a weak check, but stronger verification is hard. EXPECT_EQ(d, result.device_ordinal()); LiteralTestUtil::ExpectR0Equal<float>(42.0f, ShapedBufferToLiteral(result)); } } // Disable this test on CPU because we're using the CPU as the platform // which does not match the service platform. XLA_TEST_F(LocalClientExecuteTest, DISABLED_ON_CPU(RunOnStreamForWrongPlatform)) { // Try to run a computation on a stream for a platform (CPU) which does not // match the platform of the service (!= CPU). se::Platform* wrong_platform = se::MultiPlatformManager::PlatformWithId(se::host::kHostPlatformId) .ValueOrDie(); se::Stream wrong_stream(wrong_platform->ExecutorForDevice(0).ValueOrDie()); wrong_stream.Init(); XlaBuilder builder(TestName()); ConstantR0<float>(&builder, 42.0f); auto execute_status = ExecuteLocally( builder.Build().ValueOrDie(), {}, DefaultExecutableBuildOptions(), DefaultExecutableRunOptions().set_stream(&wrong_stream)); EXPECT_FALSE(execute_status.ok()); EXPECT_THAT(execute_status.status().error_message(), ContainsRegex("stream is for platform .*, but service targets")); } XLA_TEST_F(LocalClientExecuteTest, DISABLED_ON_CPU(AllocatorDoesNotMatchPlatform)) { se::Platform* wrong_platform = se::MultiPlatformManager::PlatformWithId(se::host::kHostPlatformId) .ValueOrDie(); TestAllocator allocator(wrong_platform); XlaBuilder builder(TestName()); ConstantR0<float>(&builder, 123.0f); auto execute_status = ExecuteLocally( builder.Build().ValueOrDie(), {}, DefaultExecutableBuildOptions(), DefaultExecutableRunOptions().set_allocator(&allocator)); EXPECT_FALSE(execute_status.ok()); EXPECT_THAT(execute_status.status().error_message(), ContainsRegex("allocator platform .* does not match service")); } XLA_TEST_F(LocalClientExecuteTest, RunOnUninitializedStream) { // Try to run a computation on a stream that has not been initialized. XlaBuilder builder(TestName()); ConstantR0<float>(&builder, 42.0f); LOG(INFO) << "default device = " << local_client_->default_device_ordinal(); se::StreamExecutor* executor = local_client_->platform() ->ExecutorForDevice(local_client_->default_device_ordinal()) .ValueOrDie(); se::Stream stream(executor); // Don't call stream.Init(). auto execute_status = ExecuteLocally( builder.Build().ValueOrDie(), {}, DefaultExecutableBuildOptions(), DefaultExecutableRunOptions().set_stream(&stream)); EXPECT_FALSE(execute_status.ok()); EXPECT_THAT(execute_status.status().error_message(), ContainsRegex("stream is uninitialized or in an error state")); } XLA_TEST_F(LocalClientExecuteTest, SelectBetweenTuples) { XlaBuilder builder(TestName()); std::initializer_list<float> vec1 = {1.f, 2.f, 3.f}; std::initializer_list<float> vec2 = {2.f, 4.f, 6.f}; auto tuple12 = Tuple(&builder, {ConstantR1<float>(&builder, vec1), ConstantR1<float>(&builder, vec2)}); auto tuple21 = Tuple(&builder, {ConstantR1<float>(&builder, vec2), ConstantR1<float>(&builder, vec1)}); Select(ConstantR0<bool>(&builder, false), tuple12, tuple21); ScopedShapedBuffer result = ExecuteLocallyOrDie(builder.Build().ValueOrDie(), {}); Literal tuple_literal = ShapedBufferToLiteral(result); LiteralTestUtil::ExpectR1Equal<float>({2.0f, 4.0f, 6.0f}, LiteralSlice(tuple_literal, {0})); LiteralTestUtil::ExpectR1Equal<float>({1.0f, 2.0f, 3.0f}, LiteralSlice(tuple_literal, {1})); } XLA_TEST_F(LocalClientExecuteTest, CompileExecutable) { XlaBuilder builder(TestName()); auto x = Parameter(&builder, 0, ShapeUtil::MakeShape(F32, {3}), "x"); auto y = ConstantR1<float>(&builder, {2.0f, 3.0f, 4.0f}); Add(x, y); Shape argument_layout = ShapeUtil::MakeShapeWithLayout(F32, /*dimensions=*/{3}, {0}); auto executable_status = local_client_->Compile(builder.Build().ValueOrDie(), {&argument_layout}, ExecutableBuildOptions()); ASSERT_IS_OK(executable_status); std::unique_ptr<LocalExecutable> executable = executable_status.ConsumeValueOrDie(); auto x_array = LiteralToShapedBuffer(LiteralUtil::CreateR1<float>({0.0f, 1.0f, 2.0f})); ScopedShapedBuffer result = executable->Run({&x_array}, DefaultExecutableRunOptions()) .ConsumeValueOrDie(); ASSERT_IS_OK(local_client_->mutable_backend() ->BorrowStream(0) .ValueOrDie() ->BlockHostUntilDone()); LiteralTestUtil::ExpectR1Near<float>( {2.0f, 4.0f, 6.0f}, ShapedBufferToLiteral(result), error_spec_); } XLA_TEST_F(LocalClientExecuteTest, ShapeBufferToLiteralConversion) { // Test copying Literals to the device as ShapedBuffers, then copying them // back again to Literals. auto test_to_device_and_back = [this](const Literal& literal) { TF_ASSERT_OK_AND_ASSIGN( auto shaped_buffer, local_client_->LiteralToShapedBuffer( literal, local_client_->default_device_ordinal(), allocator_)); TF_ASSERT_OK_AND_ASSIGN( auto transferred_literal, local_client_->ShapedBufferToLiteral(shaped_buffer)); EXPECT_EQ(literal, transferred_literal); }; // Array shapes. test_to_device_and_back(LiteralUtil::CreateR0<float>(42.0)); test_to_device_and_back(LiteralUtil::CreateR0<bool>(true)); test_to_device_and_back(LiteralUtil::CreateR1<float>({1.0, 42.0, 744.4})); test_to_device_and_back( LiteralUtil::CreateR2<float>({{1.0, 2.0, 3.0}, {44.0, 0.1, -3}})); test_to_device_and_back(LiteralUtil::CreateR2<int32>({{2, 1}, {4444, 56}})); // Null shape (empty tuple). test_to_device_and_back(LiteralUtil::MakeTuple({})); // Non-nested tuples. test_to_device_and_back(LiteralUtil::MakeTupleFromSlices( {LiteralUtil::CreateR0<float>(12223.0)})); test_to_device_and_back(LiteralUtil::MakeTupleFromSlices( {LiteralUtil::CreateR1<float>({1.0, -42.0}), LiteralUtil::CreateR0<float>(123456.0)})); // Nested tuple. test_to_device_and_back(LiteralUtil::MakeTupleFromSlices( {LiteralUtil::MakeTupleFromSlices( {LiteralUtil::CreateR1<float>({1.0, -42.0}), LiteralUtil::CreateR0<float>(123456.0)}), LiteralUtil::CreateR0<bool>(false)})); } XLA_TEST_F(LocalClientExecuteTest, ShapeBufferToLiteralConversion64bit) { // Test copying Literals to the device as ShapedBuffers, then copying them // back again to Literals for 64-bit values. auto test_to_device_and_back = [this](const Literal& literal) { TF_ASSERT_OK_AND_ASSIGN( auto shaped_buffer, local_client_->LiteralToShapedBuffer( literal, local_client_->default_device_ordinal(), allocator_)); TF_ASSERT_OK_AND_ASSIGN( auto transferred_literal, local_client_->ShapedBufferToLiteral(shaped_buffer)); EXPECT_EQ(literal, transferred_literal); }; test_to_device_and_back( LiteralUtil::CreateR2<double>({{1.0, 2.0, 3.0}, {44.0, 0.1, -3}})); test_to_device_and_back(LiteralUtil::CreateR2<int64>({{2, 1}, {4444, 56}})); test_to_device_and_back( LiteralUtil::CreateR2<uint64>({{20000000000ULL, 1}, {4444, 56}})); test_to_device_and_back(LiteralUtil::MakeTupleFromSlices( {LiteralUtil::CreateR1<double>({1.0, -42.0}), LiteralUtil::CreateR0<int64>(123456789000LL)})); } // Disabled on interpreter backend since infeed HLO is unsupported. XLA_TEST_F(LocalClientExecuteTest, DISABLED_ON_INTERPRETER(InfeedTest)) { XlaBuilder builder(TestName()); const Shape shape = ShapeUtil::MakeShape(F32, {3}); auto in = Infeed(&builder, shape); auto constant = ConstantR1<float>(&builder, {1.0f, 2.0f, 3.0f}); Add(in, constant); Literal result; std::unique_ptr<tensorflow::Thread> thread( tensorflow::Env::Default()->StartThread( tensorflow::ThreadOptions(), "execute_thread", [&] { result = ShapedBufferToLiteral(ExecuteLocallyOrDie( builder.Build().ValueOrDie(), /*arguments=*/{})); })); ASSERT_IS_OK(local_client_->TransferToInfeedLocal( LiteralUtil::CreateR1<float>({-5.0, 123.0, 42.0}), local_client_->default_device_ordinal())); // Join the thread. thread.reset(); LiteralTestUtil::ExpectR1Equal<float>({-4.0, 125.0, 45.0}, result); } // Disabled on interpreter backend since infeed/outfeed HLOs are unsupported. XLA_TEST_F(LocalClientExecuteTest, DISABLED_ON_INTERPRETER(InfeedOutfeedTest)) { XlaBuilder builder(TestName()); const Shape shape = ShapeUtil::MakeShape(F32, {3}); auto in = Infeed(&builder, shape); auto constant = ConstantR1<float>(&builder, {1.0f, 2.0f, 3.0f}); auto sum = Add(in, constant); Outfeed(sum, shape, /*outfeed_config=*/""); std::unique_ptr<tensorflow::Thread> thread( tensorflow::Env::Default()->StartThread( tensorflow::ThreadOptions(), "execute_thread", [&] { ExecuteLocallyOrDie(builder.Build().ValueOrDie(), {}); })); ASSERT_IS_OK(local_client_->TransferToInfeedLocal( LiteralUtil::CreateR1<float>({-5.0, 123.0, 42.0}), local_client_->default_device_ordinal())); TF_ASSERT_OK_AND_ASSIGN(Literal result, local_client_->TransferFromOutfeedLocal( shape, local_client_->default_device_ordinal())); LiteralTestUtil::ExpectR1Equal<float>({-4.0, 125.0, 45.0}, result); } // Benchmark that measures the overhead of the LocalClient API when running a // trivial computation void BM_LocalClientOverhead(int num_iters) { tensorflow::testing::StopTiming(); se::Platform* platform = PlatformUtil::GetDefaultPlatform().ValueOrDie(); auto executors = PlatformUtil::GetStreamExecutors(platform).ValueOrDie(); se::StreamExecutorMemoryAllocator allocator(platform, executors); LocalClient* client = ClientLibrary::GetOrCreateLocalClient(platform).ValueOrDie(); auto* transfer_manager = TransferManager::GetForPlatform(platform).ValueOrDie(); int device_ordinal = client->default_device_ordinal(); // Use a tiny add operation as the computation. XlaBuilder builder("Add"); auto shape = ShapeUtil::MakeShape(F32, {2, 3}); auto x = Parameter(&builder, 0, shape, "x"); Add(x, x); auto computation = builder.Build().ConsumeValueOrDie(); auto buffer = transfer_manager ->AllocateScopedShapedBuffer(shape, &allocator, /*device_ordinal=*/0) .ConsumeValueOrDie(); auto literal = LiteralUtil::CreateR2<float>({{0, 0, 0}, {0, 0, 0}}); auto stream = client->mutable_backend()->BorrowStream(device_ordinal).ValueOrDie(); ASSERT_IS_OK( transfer_manager->TransferLiteralToDevice(stream.get(), literal, buffer)); const int kWarmups = 2; auto executable_status = client->Compile( computation, {&buffer.on_host_shape()}, ExecutableBuildOptions()); ASSERT_IS_OK(executable_status); std::unique_ptr<LocalExecutable> executable = executable_status.ConsumeValueOrDie(); ExecutableRunOptions run_options; run_options.set_allocator(&allocator).set_stream(stream.get()); for (int i = 0; i < kWarmups; ++i) { auto result = executable->Run({&buffer}, run_options); ASSERT_IS_OK(result); } tensorflow::testing::StartTiming(); for (int i = 0; i < num_iters; ++i) { auto result = executable->Run({&buffer}, run_options); ASSERT_IS_OK(result); } } BENCHMARK(BM_LocalClientOverhead); } // namespace } // namespace xla
[ "v-grniki@microsoft.com" ]
v-grniki@microsoft.com
4096d148194162cff50fd4da3d93fdac39f5c297
ef52999968f7ef99b0e8c33a268002c53c809fa4
/push_energy_per_second_reconnect_stringfix_rejoin_sendstate_sws/push_energy_per_second_reconnect_stringfix_rejoin_sendstate_sws.ino
b0b9cade043143729f812eb151b3f2682b083bcd
[]
no_license
mattfelsen/quantified_dog
196af211628937e8f8f600242e017488594666d4
d98934f3e6e9fd55031a2d49cf560d1d44020442
refs/heads/master
2021-01-10T20:47:26.786398
2013-07-01T16:41:43
2013-07-01T16:41:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,422
ino
/* Quantified Dog v0.1 Matt Felsen Sensemakers Collaboration Studio Spring 2013 */ #include <WiFlyHQ.h> #include <SoftwareSerial.h> SoftwareSerial wifiSerial(8,9); // RX, TX // WiFi & network settings WiFly wifly; //const char wifiSSID[] = "babymatt"; //const char wifiPassword[] = "lookyhere6"; const char wifiSSID[] = "Comfort_Zone"; const char wifiPassword[] = "1441dekalbno8"; //const char wifiSSID[] = "internetz"; //const char wifiPassword[] = "1nt3rn3tz"; const char site[] = "api.cosm.com"; const int port = 8081; // COSM settings //char feedId[] = "119738"; //char feedId[] = "104810"; char feedId[] = "124246"; //char cosmKey[] = "a9qsdmAkt7Fm1ffn9BGCzbE2RRaSAKxaN2N1M3pVMkxCRT0g"; //char cosmKey[] = "ewTCG0qri8i6jXsXxwXxnrAZpnKSAKxHL0tnbndNeEpPdz0g"; char cosmKey[] = "lRRvQT0QkYTbTz1vGMCvavaG0uiSAKxaZU9JYW5LdUNDST0g"; // Set up accelerometer pins const int accelerometerXPin = A0; const int accelerometerYPin = A1; const int accelerometerZPin = A2; float xEnergy; float yEnergy; float zEnergy; float accelerometerEnergy; int currentState = 1; int prevState = 1; const int thresholdLowToMed = 100; const int thresholdMedtoHigh = 1000; static String accX = "x"; static String accY = "y"; static String accZ = "z"; static String accE = "e"; // Use analog pins as ground for accelerometer const int ground = 15; const int power = 14; // Counter for which position of the array is being written to int counter = 0; // Timing settings //#define SAMPLE_FREQUENCY 85 #define SAMPLE_FREQUENCY 10 // Frequency of sampling sensor long interval = ceil(1000 / SAMPLE_FREQUENCY); long prevMillis = 0; // Frequency of sending data long intervalPush = 1000; long prevMillisPush = 0; // Sample storage float accelerometerX[SAMPLE_FREQUENCY]; float accelerometerY[SAMPLE_FREQUENCY]; float accelerometerZ[SAMPLE_FREQUENCY]; void setup() { // Begin serial for WiFly // MUST BE 9600! Serial.begin(9600); wifiSerial.begin(9600); wifly.begin(&wifiSerial, &Serial); // Join wifi network if not already associated if (!wifly.isAssociated()) { wifly.setSSID(wifiSSID); wifly.setPassphrase(wifiPassword); wifly.setJoin(WIFLY_WLAN_JOIN_AUTO); wifly.enableDHCP(); if (wifly.join()) { Serial.println("Joined network."); } else { Serial.println("Could not associate with network."); } } else { Serial.println("Already associated with network."); } wifly.setDeviceID("Wifly-WebClient"); if (wifly.isConnected()) { Serial.println("Closing existing connection."); wifly.close(); } // if (wifly.open(site, port)) { // // Connected // } // else { // // Couldn't connect // } // Set up pin for accelerometer ground pinMode(ground, OUTPUT); pinMode(power, OUTPUT); } void loop() { // Check sonnection if(wifly.isAssociated()){ if (wifly.isConnected() == false) { Serial.println("Not connected to network, trying to connect..."); if (wifly.open(site, port)) { Serial.println("Opened network connection."); } else { Serial.println("Failed to open connection."); } delay(1000); } } else { Serial.println("Not associated within run loop."); } // Set state for accelerometer ground pin digitalWrite(ground, LOW); digitalWrite(power, HIGH); // Grab current time so we can check if we need to sample or calculate anything unsigned long currentMillis = millis(); // Run this code n times per second according to delay if ((currentMillis - prevMillis) > interval) { // Store current sensor values in arrays accelerometerX[counter] = analogRead(accelerometerXPin); accelerometerY[counter] = analogRead(accelerometerYPin); accelerometerZ[counter] = analogRead(accelerometerZPin); // wait 2 milliseconds before the next loop // for the analog-to-digital converter to settle // after the last reading: delay(2); // Serial.print(counter); // Serial.print(": accel x: "); // Serial.print(accelerometerX[counter]); //if (counter != 0) { //Serial.print("\tdelta: "); //Serial.print(accelerometerX[counter] - accelerometerX[counter-1]); //} // Serial.print("\n"); counter++; // If we've filled up the sample array, then calculate energy if (counter == SAMPLE_FREQUENCY) { xEnergy = 0; yEnergy = 0; zEnergy = 0; for (int i = 1; i < SAMPLE_FREQUENCY; i++) { // high pass // for i from 1 to n // y[i] := α * (y[i-1] + x[i] - x[i-1]) // Serial.print(i); // Serial.print(": old xEnergy: "); // Serial.print(xEnergy); // Serial.print("\tdelta: "); // Serial.print(abs(accelerometerX[i] - accelerometerX[i-1])); // // Serial.print("\tcurrent: "); // Serial.print(accelerometerX[i]); // // Serial.print("\tprevious: "); // Serial.print(accelerometerX[i-1]); xEnergy += abs(accelerometerX[i] - accelerometerX[i-1]); yEnergy += abs(accelerometerY[i] - accelerometerY[i-1]); zEnergy += abs(accelerometerZ[i] - accelerometerZ[i-1]); } accelerometerEnergy = xEnergy + yEnergy + zEnergy; if (accelerometerEnergy < thresholdLowToMed) { currentState = 1; } if (accelerometerEnergy >= thresholdLowToMed && accelerometerEnergy < thresholdMedtoHigh) { currentState = 2; } if (accelerometerEnergy >= thresholdMedtoHigh) { currentState = 3; } if (currentState != prevState) { sendStateToCOSM(); } prevState = currentState; // Reset counter to begin storing at beginning of array counter = 0; } prevMillis = currentMillis; } // Send to COSM if it's time if ((currentMillis - prevMillisPush) > intervalPush) { pushToCOSM(); prevMillisPush = currentMillis; } } void pushToCOSM() { // wifly.print("{"); // wifly.print("\"method\" : \"put\","); // wifly.print("\"resource\" : \"/feeds/"); // wifly.print(feedId); // wifly.print("\", "); // wifly.print("\"headers\" : {"); // wifly.print("\"X-ApiKey\" : \""); // wifly.print(cosmKey); // wifly.print("\"},"); // wifly.print("\"body\" : { "); // wifly.print("\"version\" : \"1.0.0\","); // wifly.print("\"datastreams\" : ["); // // wifly.print("{\"id\" : \""); // wifly.print("accelerometer_x"); // wifly.print("\", \"current_value\" : \""); // wifly.print(xEnergy); // wifly.print("\"},"); // // wifly.print("{\"id\" : \""); // wifly.print("accelerometer_y"); // wifly.print("\", \"current_value\" : \""); // wifly.print(yEnergy); // wifly.print("\"}"); // // wifly.print("{\"id\" : \""); // wifly.print("accelerometer_z"); // wifly.print("\", \"current_value\" : \""); // wifly.print(zEnergy); // wifly.print("\"},"); // // wifly.print("{\"id\" : \""); // wifly.print("accelerometer_energy"); // wifly.print("\", \"current_value\" : \""); // wifly.print(accelerometerEnergy); // wifly.print("\"}"); // // wifly.print("]}}"); // wifly.println(); wifly.print("{\"method\":\"put\",\"resource\":\"/feeds/"); wifly.print(feedId); wifly.print("\",\"headers\":{\"X-ApiKey\":\""); wifly.print(cosmKey); wifly.print("\"},\"body\":{\"version\":\"1.0.0\",\"datastreams\":["); wifly.print("{\"id\":\""); wifly.print(accX); wifly.print("\",\"current_value\":\""); wifly.print(xEnergy); wifly.print("\"},{\"id\":\""); wifly.print(accY); wifly.print("\",\"current_value\":\""); wifly.print(yEnergy); wifly.print("\"},{\"id\":\""); wifly.print(accZ); wifly.print("\",\"current_value\":\""); wifly.print(zEnergy); wifly.print("\"},{\"id\":\""); wifly.print(accE); wifly.print("\",\"current_value\":\""); wifly.print(accelerometerEnergy); wifly.print("\"}]}}"); wifly.println(); } void sendStateToCOSM() { wifly.print("{\"method\":\"put\",\"resource\":\"/feeds/"); wifly.print(feedId); wifly.print("\",\"headers\":{\"X-ApiKey\":\""); wifly.print(cosmKey); wifly.print("\"},\"body\":{\"version\":\"1.0.0\",\"datastreams\":["); wifly.print("{\"id\":\"state\",\"current_value\":\""); wifly.print(currentState); wifly.print("\"}]}}"); wifly.println(); }
[ "mattfelsen@gmail.com" ]
mattfelsen@gmail.com
680a055b8ce1ed3409dbc883e4abed92275aa6d8
43e42f048456ac8ac41f6951dd93282188b7b6c9
/src/rpcdump.cpp
395c4663358bbd78f38390711adc0251c0ac1058
[ "MIT" ]
permissive
Frenchh/French-core
7a0f28ae8475b9adba3acfc2c5865a18d4d19243
0da631eeced40d9d21146703cf80f569350ee1a5
refs/heads/master
2020-04-05T20:57:43.559095
2018-11-13T00:46:04
2018-11-13T00:46:04
157,201,580
0
1
null
null
null
null
UTF-8
C++
false
false
20,013
cpp
// Copyright (c) 2009-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2017 The PIVX developers // Copyright (c) 2017-2018 The French developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "bip38.h" #include "init.h" #include "main.h" #include "rpcserver.h" #include "script/script.h" #include "script/standard.h" #include "sync.h" #include "util.h" #include "utilstrencodings.h" #include "utiltime.h" #include "wallet.h" #include <fstream> #include <secp256k1.h> #include <stdint.h> #include <boost/algorithm/string.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <openssl/aes.h> #include <openssl/sha.h> #include <univalue.h> using namespace std; void EnsureWalletIsUnlocked(); std::string static EncodeDumpTime(int64_t nTime) { return DateTimeStrFormat("%Y-%m-%dT%H:%M:%SZ", nTime); } int64_t static DecodeDumpTime(const std::string& str) { static const boost::posix_time::ptime epoch = boost::posix_time::from_time_t(0); static const std::locale loc(std::locale::classic(), new boost::posix_time::time_input_facet("%Y-%m-%dT%H:%M:%SZ")); std::istringstream iss(str); iss.imbue(loc); boost::posix_time::ptime ptime(boost::date_time::not_a_date_time); iss >> ptime; if (ptime.is_not_a_date_time()) return 0; return (ptime - epoch).total_seconds(); } std::string static EncodeDumpString(const std::string& str) { std::stringstream ret; BOOST_FOREACH (unsigned char c, str) { if (c <= 32 || c >= 128 || c == '%') { ret << '%' << HexStr(&c, &c + 1); } else { ret << c; } } return ret.str(); } std::string DecodeDumpString(const std::string& str) { std::stringstream ret; for (unsigned int pos = 0; pos < str.length(); pos++) { unsigned char c = str[pos]; if (c == '%' && pos + 2 < str.length()) { c = (((str[pos + 1] >> 6) * 9 + ((str[pos + 1] - '0') & 15)) << 4) | ((str[pos + 2] >> 6) * 9 + ((str[pos + 2] - '0') & 15)); pos += 2; } ret << c; } return ret.str(); } UniValue importprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importprivkey \"frcprivkey\" ( \"label\" rescan )\n" "\nAdds a private key (as returned by dumpprivkey) to your wallet.\n" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"frcprivkey\" (string, required) The private key (see dumpprivkey)\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nDump a private key\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + "\nImport the private key with rescan\n" + HelpExampleCli("importprivkey", "\"mykey\"") + "\nImport using a label and without rescan\n" + HelpExampleCli("importprivkey", "\"mykey\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importprivkey", "\"mykey\", \"testing\", false")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strSecret = params[0].get_str(); string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); CBitcoinSecret vchSecret; bool fGood = vchSecret.SetString(strSecret); if (!fGood) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid private key encoding"); CKey key = vchSecret.GetKey(); if (!key.IsValid()) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Private key outside allowed range"); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, strLabel, "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) return NullUniValue; pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } } return NullUniValue; } UniValue importaddress(const UniValue& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 3) throw runtime_error( "importaddress \"address\" ( \"label\" rescan )\n" "\nAdds an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.\n" "\nArguments:\n" "1. \"address\" (string, required) The address\n" "2. \"label\" (string, optional, default=\"\") An optional label\n" "3. rescan (boolean, optional, default=true) Rescan the wallet for transactions\n" "\nNote: This call can take minutes to complete if rescan is true.\n" "\nExamples:\n" "\nImport an address with rescan\n" + HelpExampleCli("importaddress", "\"myaddress\"") + "\nImport using a label without rescan\n" + HelpExampleCli("importaddress", "\"myaddress\" \"testing\" false") + "\nAs a JSON-RPC call\n" + HelpExampleRpc("importaddress", "\"myaddress\", \"testing\", false")); LOCK2(cs_main, pwalletMain->cs_wallet); CScript script; CBitcoinAddress address(params[0].get_str()); if (address.IsValid()) { script = GetScriptForDestination(address.Get()); } else if (IsHex(params[0].get_str())) { std::vector<unsigned char> data(ParseHex(params[0].get_str())); script = CScript(data.begin(), data.end()); } else { throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid FRC address or script"); } string strLabel = ""; if (params.size() > 1) strLabel = params[1].get_str(); // Whether to perform rescan after import bool fRescan = true; if (params.size() > 2) fRescan = params[2].get_bool(); { if (::IsMine(*pwalletMain, script) == ISMINE_SPENDABLE) throw JSONRPCError(RPC_WALLET_ERROR, "The wallet already contains the private key for this address or script"); // add to address book or update label if (address.IsValid()) pwalletMain->SetAddressBook(address.Get(), strLabel, "receive"); // Don't throw error in case an address is already there if (pwalletMain->HaveWatchOnly(script)) return NullUniValue; pwalletMain->MarkDirty(); if (!pwalletMain->AddWatchOnly(script)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding address to wallet"); if (fRescan) { pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); pwalletMain->ReacceptWalletTransactions(); } } return NullUniValue; } UniValue importwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "importwallet \"filename\"\n" "\nImports keys from a wallet dump file (see dumpwallet).\n" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"filename\" (string, required) The wallet file\n" "\nExamples:\n" "\nDump the wallet\n" + HelpExampleCli("dumpwallet", "\"test\"") + "\nImport the wallet\n" + HelpExampleCli("importwallet", "\"test\"") + "\nImport using the json rpc call\n" + HelpExampleRpc("importwallet", "\"test\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ifstream file; file.open(params[0].get_str().c_str(), std::ios::in | std::ios::ate); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); int64_t nTimeBegin = chainActive.Tip()->GetBlockTime(); bool fGood = true; int64_t nFilesize = std::max((int64_t)1, (int64_t)file.tellg()); file.seekg(0, file.beg); pwalletMain->ShowProgress(_("Importing..."), 0); // show progress dialog in GUI while (file.good()) { pwalletMain->ShowProgress("", std::max(1, std::min(99, (int)(((double)file.tellg() / (double)nFilesize) * 100)))); std::string line; std::getline(file, line); if (line.empty() || line[0] == '#') continue; std::vector<std::string> vstr; boost::split(vstr, line, boost::is_any_of(" ")); if (vstr.size() < 2) continue; CBitcoinSecret vchSecret; if (!vchSecret.SetString(vstr[0])) continue; CKey key = vchSecret.GetKey(); CPubKey pubkey = key.GetPubKey(); assert(key.VerifyPubKey(pubkey)); CKeyID keyid = pubkey.GetID(); if (pwalletMain->HaveKey(keyid)) { LogPrintf("Skipping import of %s (key already present)\n", CBitcoinAddress(keyid).ToString()); continue; } int64_t nTime = DecodeDumpTime(vstr[1]); std::string strLabel; bool fLabel = true; for (unsigned int nStr = 2; nStr < vstr.size(); nStr++) { if (boost::algorithm::starts_with(vstr[nStr], "#")) break; if (vstr[nStr] == "change=1") fLabel = false; if (vstr[nStr] == "reserve=1") fLabel = false; if (boost::algorithm::starts_with(vstr[nStr], "label=")) { strLabel = DecodeDumpString(vstr[nStr].substr(6)); fLabel = true; } } LogPrintf("Importing %s...\n", CBitcoinAddress(keyid).ToString()); if (!pwalletMain->AddKeyPubKey(key, pubkey)) { fGood = false; continue; } pwalletMain->mapKeyMetadata[keyid].nCreateTime = nTime; if (fLabel) pwalletMain->SetAddressBook(keyid, strLabel, "receive"); nTimeBegin = std::min(nTimeBegin, nTime); } file.close(); pwalletMain->ShowProgress("", 100); // hide progress dialog in GUI CBlockIndex* pindex = chainActive.Tip(); while (pindex && pindex->pprev && pindex->GetBlockTime() > nTimeBegin - 7200) pindex = pindex->pprev; if (!pwalletMain->nTimeFirstKey || nTimeBegin < pwalletMain->nTimeFirstKey) pwalletMain->nTimeFirstKey = nTimeBegin; LogPrintf("Rescanning last %i blocks\n", chainActive.Height() - pindex->nHeight + 1); pwalletMain->ScanForWalletTransactions(pindex); pwalletMain->MarkDirty(); if (!fGood) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding some keys to wallet"); return NullUniValue; } UniValue dumpprivkey(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpprivkey \"frcaddress\"\n" "\nReveals the private key corresponding to 'frcaddress'.\n" "Then the importprivkey can be used with this output\n" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"frcaddress\" (string, required) The frc address for the private key\n" "\nResult:\n" "\"key\" (string) The private key\n" "\nExamples:\n" + HelpExampleCli("dumpprivkey", "\"myaddress\"") + HelpExampleCli("importprivkey", "\"mykey\"") + HelpExampleRpc("dumpprivkey", "\"myaddress\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid FRC address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); return CBitcoinSecret(vchSecret).ToString(); } UniValue dumpwallet(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 1) throw runtime_error( "dumpwallet \"filename\"\n" "\nDumps all wallet keys in a human-readable format.\n" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"filename\" (string, required) The filename\n" "\nExamples:\n" + HelpExampleCli("dumpwallet", "\"test\"") + HelpExampleRpc("dumpwallet", "\"test\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); ofstream file; file.open(params[0].get_str().c_str()); if (!file.is_open()) throw JSONRPCError(RPC_INVALID_PARAMETER, "Cannot open wallet dump file"); std::map<CKeyID, int64_t> mapKeyBirth; std::set<CKeyID> setKeyPool; pwalletMain->GetKeyBirthTimes(mapKeyBirth); pwalletMain->GetAllReserveKeys(setKeyPool); // sort time/key pairs std::vector<std::pair<int64_t, CKeyID> > vKeyBirth; for (std::map<CKeyID, int64_t>::const_iterator it = mapKeyBirth.begin(); it != mapKeyBirth.end(); it++) { vKeyBirth.push_back(std::make_pair(it->second, it->first)); } mapKeyBirth.clear(); std::sort(vKeyBirth.begin(), vKeyBirth.end()); // produce output file << strprintf("# Wallet dump created by French %s (%s)\n", CLIENT_BUILD, CLIENT_DATE); file << strprintf("# * Created on %s\n", EncodeDumpTime(GetTime())); file << strprintf("# * Best block at time of backup was %i (%s),\n", chainActive.Height(), chainActive.Tip()->GetBlockHash().ToString()); file << strprintf("# mined on %s\n", EncodeDumpTime(chainActive.Tip()->GetBlockTime())); file << "\n"; for (std::vector<std::pair<int64_t, CKeyID> >::const_iterator it = vKeyBirth.begin(); it != vKeyBirth.end(); it++) { const CKeyID& keyid = it->second; std::string strTime = EncodeDumpTime(it->first); std::string strAddr = CBitcoinAddress(keyid).ToString(); CKey key; if (pwalletMain->GetKey(keyid, key)) { if (pwalletMain->mapAddressBook.count(keyid)) { file << strprintf("%s %s label=%s # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, EncodeDumpString(pwalletMain->mapAddressBook[keyid].name), strAddr); } else if (setKeyPool.count(keyid)) { file << strprintf("%s %s reserve=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } else { file << strprintf("%s %s change=1 # addr=%s\n", CBitcoinSecret(key).ToString(), strTime, strAddr); } } } file << "\n"; file << "# End of dump\n"; file.close(); return NullUniValue; } UniValue bip38encrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38encrypt \"frcaddress\"\n" "\nEncrypts a private key corresponding to 'frcaddress'.\n" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"frcaddress\" (string, required) The frc address for the private key (you must hold the key already)\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with - Valid special chars: !#$%&'()*+,-./:;<=>?`{|}~ \n" "\nResult:\n" "\"key\" (string) The encrypted private key\n" "\nExamples:\n" + HelpExampleCli("bip38encrypt", "\"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\" \"mypasphrase\"") + HelpExampleRpc("bip38encrypt", "\"DMJRSsuU9zfyrvxVaAEFQqK4MxZg6vgeS6\" \"mypasphrase\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); string strAddress = params[0].get_str(); string strPassphrase = params[1].get_str(); CBitcoinAddress address; if (!address.SetString(strAddress)) throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid FRC address"); CKeyID keyID; if (!address.GetKeyID(keyID)) throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key"); CKey vchSecret; if (!pwalletMain->GetKey(keyID, vchSecret)) throw JSONRPCError(RPC_WALLET_ERROR, "Private key for address " + strAddress + " is not known"); uint256 privKey = vchSecret.GetPrivKey_256(); string encryptedOut = BIP38_Encrypt(strAddress, strPassphrase, privKey, vchSecret.IsCompressed()); UniValue result(UniValue::VOBJ); result.push_back(Pair("Addess", strAddress)); result.push_back(Pair("Encrypted Key", encryptedOut)); return result; } UniValue bip38decrypt(const UniValue& params, bool fHelp) { if (fHelp || params.size() != 2) throw runtime_error( "bip38decrypt \"frcaddress\" \"passphrase\"\n" "\nDecrypts and then imports password protected private key.\n" + HelpRequiringPassphrase() + "\n" "\nArguments:\n" "1. \"encryptedkey\" (string, required) The encrypted private key\n" "2. \"passphrase\" (string, required) The passphrase you want the private key to be encrypted with\n" "\nResult:\n" "\"key\" (string) The decrypted private key\n" "\nExamples:\n" + HelpExampleCli("bip38decrypt", "\"encryptedkey\" \"mypassphrase\"") + HelpExampleRpc("bip38decrypt", "\"encryptedkey\" \"mypassphrase\"")); LOCK2(cs_main, pwalletMain->cs_wallet); EnsureWalletIsUnlocked(); /** Collect private key and passphrase **/ string strKey = params[0].get_str(); string strPassphrase = params[1].get_str(); uint256 privKey; bool fCompressed; if (!BIP38_Decrypt(strPassphrase, strKey, privKey, fCompressed)) throw JSONRPCError(RPC_WALLET_ERROR, "Failed To Decrypt"); UniValue result(UniValue::VOBJ); result.push_back(Pair("privatekey", HexStr(privKey))); CKey key; key.Set(privKey.begin(), privKey.end(), fCompressed); if (!key.IsValid()) throw JSONRPCError(RPC_WALLET_ERROR, "Private Key Not Valid"); CPubKey pubkey = key.GetPubKey(); pubkey.IsCompressed(); assert(key.VerifyPubKey(pubkey)); result.push_back(Pair("Address", CBitcoinAddress(pubkey.GetID()).ToString())); CKeyID vchAddress = pubkey.GetID(); { pwalletMain->MarkDirty(); pwalletMain->SetAddressBook(vchAddress, "", "receive"); // Don't throw error in case a key is already there if (pwalletMain->HaveKey(vchAddress)) throw JSONRPCError(RPC_WALLET_ERROR, "Key already held by wallet"); pwalletMain->mapKeyMetadata[vchAddress].nCreateTime = 1; if (!pwalletMain->AddKeyPubKey(key, pubkey)) throw JSONRPCError(RPC_WALLET_ERROR, "Error adding key to wallet"); // whenever a key is imported, we need to scan the whole chain pwalletMain->nTimeFirstKey = 1; // 0 would be considered 'no value' pwalletMain->ScanForWalletTransactions(chainActive.Genesis(), true); } return result; }
[ "florent.accault@gmail.com" ]
florent.accault@gmail.com
ffa687181964a79180a9412b9ecf8f2caf82be54
ffde864d4d72cdeef58ae81758f67bb27decdb07
/rill/type/type_detail.hpp
b727f18c62d1401b5844262883897f6cad167a31
[ "BSL-1.0" ]
permissive
rhysd/rill
a7a96cf9803c126cb18b4288ee8693f556036f5a
cb16e511c6bdd4ea0b2bcbec51bd43724cc7ddcb
refs/heads/master
2020-07-11T00:25:39.939972
2015-01-13T16:54:27
2015-01-13T16:54:37
26,599,001
0
0
null
null
null
null
UTF-8
C++
false
false
4,267
hpp
// // Copyright yutopp 2013 - . // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // #pragma once #ifndef RILL_SEMANTIC_ANALYSIS_TYPE_DETAIL_HPP #define RILL_SEMANTIC_ANALYSIS_TYPE_DETAIL_HPP #include <memory> #include <vector> #include "type_detail_pool_t.hpp" #include "../ast/value_fwd.hpp" #include "../ast/expression_fwd.hpp" #include "../type/type.hpp" #include "../type/type_registry_fwd.hpp" namespace rill { struct type_detail; using type_detail_ptr = type_detail*; using const_type_detail_ptr = type_detail const*; struct raw_value_holder { explicit raw_value_holder( std::shared_ptr<void> p, environment_base_ptr const& e = nullptr ) : ptr_to_raw_value( std::move( p ) ) , target_env( e ) , is_placeholder( false ) {} std::shared_ptr<void> ptr_to_raw_value; environment_base_ptr target_env; bool is_placeholder; }; using raw_value_holder_ptr = raw_value_holder*; using const_raw_value_holder_ptr = raw_value_holder const*; enum class dependent_value_kind { k_type = 0, k_alias = 1,/*unused*/ k_int8 = 4, k_int32 = 10, k_string = 11, k_array = 12, k_none = 404 }; struct type_detail { typedef std::vector<type_detail_ptr> nest_type; typedef std::shared_ptr<nest_type> nest_pointer; // dependent_type will holds type_detail_ptr or "TODO: write" struct dependent_type { type_detail_ptr element_type_detail; union { void* dummy; type_detail_ptr as_type_detail; raw_value_holder_ptr as_value_holder; } element; dependent_value_kind kind; type_id_t type_id; inline auto is_type() const -> bool { return kind == dependent_value_kind::k_type; } inline auto has_placeholder() const -> bool { if ( is_type() ) { return element.as_type_detail->is_placeholder || element.as_type_detail->has_placeholder(); } else { return element.as_value_holder->is_placeholder; } } }; typedef std::vector<dependent_type> template_args_type; typedef std::shared_ptr<template_args_type> template_args_pointer; enum class evaluate_mode { k_only_runtime, k_runtime, k_meta, k_only_meta, }; explicit type_detail( type_id_t const& w, environment_base_ptr const& e, nest_pointer const& st = nullptr, template_args_pointer const& sd = nullptr, bool const ix = false, evaluate_mode const& em = evaluate_mode::k_runtime ) : type_id( w ) , target_env( e ) , nest( st ) , template_args( sd ) , is_xvalue( ix ) , eval_mode( em ) , is_placeholder( false ) {} type_id_t type_id; environment_base_ptr target_env; nest_pointer nest; template_args_pointer template_args; bool is_xvalue; evaluate_mode eval_mode; bool is_placeholder; public: inline auto has_template_args() const -> bool { return template_args != nullptr; } inline auto has_placeholder() const -> bool { if ( template_args ) { bool has_placeholder = false; for( auto&& arg : *template_args ) { has_placeholder |= arg.has_placeholder(); } return has_placeholder; } return false; } }; } // namespace rill #endif /*RILL_SEMANTIC_ANALYSIS_TYPE_DETAIL_HPP*/
[ "yutopp@gmail.com" ]
yutopp@gmail.com
cb2cf92fac474557bba4e2f456ae0c5ff24fb012
af5bd30d59fec67fcb32930896615272c453f379
/191.cpp
70ca69f36012ce94eeb1632f3ff69cdd7203ca97
[]
no_license
FuHongbao/OJ_Code
e656e970855661f0b0d4e5ea719eed5b020903c5
bf54e32ceb4468dc15e8251e83317c03e16b8888
refs/heads/master
2020-08-04T23:56:12.680917
2019-10-02T11:28:17
2019-10-02T11:28:17
212,321,572
0
0
null
null
null
null
UTF-8
C++
false
false
1,472
cpp
/************************************************************************* > File Name: 191.cpp > Author: victoria > Mail: 1105847344@qq.com > Created Time: 2019年07月06日 星期六 11时37分22秒 ************************************************************************/ #include <iostream> #include <algorithm> #include <string.h> #include <stdio.h> using namespace std; #define MAX_N 8000000 int prime[MAX_N + 5] = {0}; int main() { int l, r; cin >> l >> r; for (int i = 2; i <= r; i++) { if (!prime[i]) { prime[++prime[0]] = i; } for (int j = 1; j <= prime[0]; j++) { if (i * prime[j] > r) break; prime[i * prime[j]] = 1; if (i % prime[j] == 0) break; } } int min = MAX_N; int max = -9999; int a, b, c, d; int cnt = 0; for (int j = 1; prime[j + 1] <= r && j + 1 <= prime[0]; j++) { if (prime[j] < l) continue; cnt ++; if (prime[j + 1] - prime[j] < min) { a = prime[j]; b = prime[j + 1]; min = prime[j + 1] - prime[j]; } if (prime[j + 1] - prime[j] > max) { c = prime[j]; d = prime[j + 1]; max = prime[j + 1] - prime[j]; } } if (cnt < 2) { cout << "There are no adjacent primes." << endl; } else { printf("%d,%d are closest, %d,%d are most distant.\n", a, b, c, d); } return 0; }
[ "FuHongbao@FuHongbao.com" ]
FuHongbao@FuHongbao.com
d425f023178dc5ff42597df6012e1dfaa12248af
62869fe5152bbe07fbe9f0b61166be32e4f5016c
/3rdparty/CGAL/include/CGAL/simplest_rational_in_interval.h
245475aa521e19275b831892d636bd2e9ee54675
[ "LicenseRef-scancode-warranty-disclaimer", "LGPL-3.0-or-later", "LGPL-2.0-or-later", "GPL-1.0-or-later", "LicenseRef-scancode-commercial-license", "MIT" ]
permissive
daergoth/SubdivisionSandbox
aef65eab0e1ab3dfecb2f9254c36d26c71ecd4fd
d67386980eb978a552e5a98ba1c4b25cf5a9a328
refs/heads/master
2020-03-30T09:19:07.121847
2019-01-08T16:42:53
2019-01-08T16:42:53
151,070,972
0
0
MIT
2018-12-03T11:10:03
2018-10-01T10:26:28
C++
UTF-8
C++
false
false
3,814
h
// Copyright (c) 2002 // Utrecht University (The Netherlands), // ETH Zurich (Switzerland), // INRIA Sophia-Antipolis (France), // Max-Planck-Institute Saarbruecken (Germany), // and Tel-Aviv University (Israel). All rights reserved. // // This file is part of CGAL (www.cgal.org); you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 3 of the License, // or (at your option) any later version. // // Licensees holding a valid commercial license may use this file in // accordance with the commercial license agreement provided with the software. // // This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE // WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. // // $URL$ // $Id$ // // // Author(s) : Andreas Fabri, Susan Hert, Sylvain Pion #ifndef CGAL_SIMPLEST_RATIONAL_IN_INTERVAL_H #define CGAL_SIMPLEST_RATIONAL_IN_INTERVAL_H #include <CGAL/number_type_basic.h> #include <CGAL/to_rational.h> #include <CGAL/use.h> #include <climits> #include <cmath> namespace CGAL { /* simplest_rational_in_interval(x,y) returns the rational number with the smallest denominator in the interval [x,y]. See Knuth, "Seminumerical algorithms", page 654, answer to exercise 4.53-39. */ template <class Rational> Rational simplest_rational_in_interval(double x, double y) { typedef Fraction_traits<Rational> FT; typedef typename FT::Is_fraction Is_fraction; typedef typename FT::Numerator_type Numerator_type; typedef typename FT::Denominator_type Denominator_type; typedef typename FT::Decompose Decompose; typedef typename FT::Compose Compose; // Must be a fraction CGAL_USE_TYPE(Is_fraction); CGAL_static_assertion((::boost::is_same<Is_fraction, Tag_true>::value)); // Numerator_type,Denominator_type must be the same CGAL_USE_TYPE(Denominator_type); CGAL_static_assertion((::boost::is_same<Numerator_type, Denominator_type>::value)); if(x == y){ return to_rational<Rational>(x); } if(x > y){ std::swap(x,y); } Rational r; // Return value. Numerator_type r_numerator, r_denominator; // Deal with negative arguments. We only have to deal with the case // where both x and y are negative -- when exactly one is negative // the best rational in the interval [x,y] is 0. if (x < 0 && y < 0) { // Both arguments are negative: solve positive case and negate return - simplest_rational_in_interval<Rational>(CGAL::abs(x),CGAL::abs(y)); } else if (x <= 0 || y <= 0) { // One argument is 0, or arguments are on opposite sides of 0: // simplest rational in interval is 0 exactly. r_numerator = 0; r_denominator = 1; } else { // x > 0 && y > 0 double xc = std::floor(1/x); // First coefficient of cf for x. double xr = std::fmod(1/x,1); // Remaining fractional part of x. double yc = std::floor(1/y); // First coefficient of cf for y. double yr = std::fmod(1/y,1); // Remaining fractional part of y. if (xc < yc) { // Return 1/(xc+1). r_numerator = 1; r_denominator = xc + 1; } else if (yc < xc) { // Return 1/(yc+1). r_numerator = 1; r_denominator = yc + 1; } else { // xc == yc // Recurse to find s, the rational with the lowest denominator // between xr and yr. Rational s(simplest_rational_in_interval<Rational>(xr,yr)); // Return 1/(xc + s). Numerator_type xc_rt(xc); Numerator_type s_num,s_den; Decompose()(s,s_num,s_den); r_numerator = s_den; r_denominator = s_num + xc_rt * s_den; } } return Compose()(r_numerator, r_denominator); } } //namespace CGAL #endif //CGAL_SIMPLEST_RATIONAL_IN_INTERVAL_H
[ "bodonyiandi94@gmail.com" ]
bodonyiandi94@gmail.com
9d1b5b87962c6c20929225f2cb4c72d5c3696050
48ac9bad85667ec95f8280ea587ac85f3442d07e
/src/datastore.h
98280cd1de5a55f785447a43b09d7b8b85048e28
[]
no_license
thuckate96/CppQmlUQ_Property
db0a4631e0c65610d4f16954f3b0240dff877623
fef181546225d86c357a3970a3114816ee9b69ab
refs/heads/master
2021-01-11T14:10:28.488299
2017-06-21T10:27:15
2017-06-21T10:27:15
94,992,235
0
0
null
null
null
null
UTF-8
C++
false
false
471
h
#ifndef DATASTORE_H #define DATASTORE_H #include <QObject> class DataStore : public QObject { Q_OBJECT Q_PROPERTY(QString message READ message WRITE setMessage NOTIFY messageChanged) public: explicit DataStore(QObject* parent = 0); QString message(){ return msg; } void setMessage(QString str); signals: void messageChanged(); public slots: void callMeFromQml(); private : int count; QString msg; }; #endif // DATASTORE_H
[ "thucuet@gmail.com" ]
thucuet@gmail.com
05b0e185d6253e5c46f45387e405dc81778599b9
18488c64ea8073545133e78a884cac4d6669ccf0
/contest/Contest9/bai29.cpp
b47e04345a7f3aeaf5c6f32c5df9877b561efebb
[]
no_license
manhtung001/Datastructure-Algorithm-PTIT
f6b1c3bbc2476af3989b8796696dbbb7750e91fe
c41a344d4fbfd92bf587eac14861568d2029321b
refs/heads/master
2023-06-24T07:19:33.970580
2021-07-21T13:44:54
2021-07-21T13:44:54
344,992,505
1
1
null
null
null
null
UTF-8
C++
false
false
515
cpp
#include<bits/stdc++.h> using namespace std; int n, m; vector<int> adj[1005]; int isEulerian(){ int odd = 0; for (int i=1; i<=n; i++){ if (adj[i].size()%2 != 0) odd++; } if (odd > 2) return 0; return (odd == 2)? 1 : 2; } int main(){ int T; cin >> T; while (T--){ cin >> n >> m; for (int i=0; i<1005; i++) adj[i].clear(); for (int i=1; i<=m; i++){ int x, y; cin >> x >> y; adj[x].push_back(y); adj[y].push_back(x); } cout << isEulerian() << endl; } }
[ "khongtung001@gmail.com" ]
khongtung001@gmail.com
a8efc00addb99d850ec190a405c48fc1a0ff62a4
4d4822b29e666cea6b2d99d5b9d9c41916b455a9
/Example/Pods/Headers/Private/GeoFeatures/boost/graph/distributed/two_bit_color_map.hpp
2ea9bb9b53d97b75b44401f7e0f6bd4626a8ac0f
[ "BSL-1.0", "Apache-2.0" ]
permissive
eswiss/geofeatures
7346210128358cca5001a04b0e380afc9d19663b
1ffd5fdc49d859b829bdb8a9147ba6543d8d46c4
refs/heads/master
2020-04-05T19:45:33.653377
2016-01-28T20:11:44
2016-01-28T20:11:44
50,859,811
0
0
null
2016-02-01T18:12:28
2016-02-01T18:12:28
null
UTF-8
C++
false
false
81
hpp
../../../../../../../../GeoFeatures/boost/graph/distributed/two_bit_color_map.hpp
[ "hatter24@gmail.com" ]
hatter24@gmail.com
809a4c2e06d8bafe1cbe1f1d2475737f8ff74985
f7fe19a26aa9a0f084882f6790ed4e738db8234b
/SolvedProblem/boj10026.cpp
819c1d18243ae58bc5a985cb550b0712be9b1f96
[]
no_license
thisfetch/Study_ProblemSolving
6cb3172f36c1c787f31f870e38b446cb3a186d82
79e7bc732255af1a737577c50ed6e19fd360fc46
refs/heads/master
2023-04-04T06:34:34.057741
2021-04-17T14:07:09
2021-04-17T14:07:09
333,099,420
0
0
null
null
null
null
UTF-8
C++
false
false
1,595
cpp
#include <bits/stdc++.h> using namespace std; #define X first #define Y second string board[100]; bool vis[100][100]; bool visx[100][100]; int n; int dx[4] = { 1, 0, -1, 0 }; int dy[4] = { 0, 1, 0, -1 }; int main(void) { ios::sync_with_stdio(0), cin.tie(0); int color = 0, colorx = 0; cin >> n; for (int i = 0; i < n; i++) cin >> board[i]; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (vis[i][j]) continue; color++; queue<pair<int, int>> q; vis[i][j] = true; q.push({ i, j }); while (!q.empty()) { auto cur = q.front(); q.pop(); for (int dir = 0; dir < 4; dir++) { int nx = cur.X + dx[dir]; int ny = cur.Y + dy[dir]; if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue; if (vis[nx][ny] == true || board[nx][ny] != board[cur.X][cur.Y]) continue; vis[nx][ny] = true; q.push({ nx, ny }); } } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (board[i][j] == 'G') { board[i][j] = 'R'; } } } for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (visx[i][j]) continue; colorx++; queue<pair<int, int>> q; visx[i][j] = true; q.push({ i, j }); while (!q.empty()) { auto cur = q.front(); q.pop(); for (int dir = 0; dir < 4; dir++) { int nx = cur.X + dx[dir]; int ny = cur.Y + dy[dir]; if (nx < 0 || nx >= n || ny < 0 || ny >= n) continue; if (visx[nx][ny] == true || board[nx][ny] != board[cur.X][cur.Y]) continue; visx[nx][ny] = true; q.push({ nx, ny }); } } } } cout << color << ' ' << colorx; }
[ "thisfetch@kakao.com" ]
thisfetch@kakao.com
bc2b1b591a0abad99b10298ec9cfc206de578aa5
94e8f7c119dc9485d1ce972d7a7d7f88b9f73c23
/tp1/ProjectMIV2017/src/lib_simu/maths/Matrix.cpp
7ed473a33e2443f9e845dc09f8f40cdd7a7b4caa
[]
no_license
HUANGManutea/MIV
053c6fdf06e996b97b4fed085e42fe0d2b8cc50d
1ba05f90def00510723d4c6bb37442e67cef6d2f
refs/heads/master
2021-01-11T00:35:49.677152
2016-10-10T17:25:46
2016-10-10T17:25:46
70,511,088
0
0
null
null
null
null
UTF-8
C++
false
false
757
cpp
#include "Matrix.h" namespace Maths { Matrix::Matrix(int n, int m) { nb = n*m; allocateMemory(n, m); } Matrix::Matrix(const Matrix& src) { copy(src); } Matrix::~Matrix() { freeMemory(); } void Matrix::allocateMemory(int n, int m) { data = new number[nb]; } void Matrix::freeMemory() { delete[] data; } void Matrix::copy(const Matrix& src) { this->n = src.n; this->m = src.m; this->nb = src.nb; allocateMemory(n, m); for (int i = 0 ; i < nb ; i++) this->data[i] = src.data[i]; } void Matrix::set(int i, int j, number val) { data[i*m + j] = val; } number Matrix::get(int i, int j) const { return data[i*m + j]; } Matrix& Matrix::operator=(const Matrix& src) { if (this != &src) { freeMemory(); copy(src); } return *this; } }
[ "huang.manutea@gmail.com" ]
huang.manutea@gmail.com
213a928bb4f971ec543179c83343f7a4564b45e1
d38bae0b3f25df5ab3e2c1e70bf807608cb12dcf
/apeng/apeng.cpp
46153679de4580265c34efaaea57930516467a82
[ "MIT" ]
permissive
bigpot/apeng
84187359564b46c88400469c652830d1d745b887
ce0fb0721e6b9a3533147ca12facff735a2f6801
refs/heads/master
2021-06-09T11:48:54.903183
2016-11-29T01:32:57
2016-11-29T01:32:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,067
cpp
#include "apeng.h" #include <cassert> #include <cstdio> #include <cstdlib> #include <png.h> //! MUST point to apng-patched libpng/png.h #include <memory> /////////////////////////////////////////////////////////////////////////////// //! make sure we have proper support for APNG through patched libpng //! rationale: yes, there are other ways to load APNG even with the unpatched libpng, but what gives #ifndef PNG_APNG_SUPPORTED #error "libPNG missing support for APNG. Make sure you use the PATCHED version" #endif // PNG_APNG_SUPPORTED /////////////////////////////////////////////////////////////////////////////// //! globals enum struct APENG_ERROR : unsigned int { no_error = 0, file_invalid, data_invalid, }; /////////////////////////////////////////////////////////////////////////////// //! writer //--- save API //! apeng_save_frames_file_blob //! saves all frames from large buffer frame_blob //! frame_blob must be deleted by user using free() APENG_DLLIMPORT unsigned int APENG_API apeng_save_frames_file_blob(FILE* file, const uint8_t* frames_blob, unsigned int frames_blob_size, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes, unsigned int frames) { assert(frames_blob); assert(frames_blob_size % (height * rowbytes) == 0); assert(frames_blob_size / (height * rowbytes * frames) == 1); uint8_t** frames_array = (uint8_t**)malloc(frames * sizeof(uint8_t*)); for (unsigned int i = 0; i < frames; ++i) { frames_array[i] = (uint8_t*)&frames_blob[i * height * rowbytes]; } unsigned int err = apeng_save_frames_file(file, (const uint8_t**)frames_array, frames, width, height, colortype, rowbytes); free(frames_array); return err; } //! apeng_save_frames_file_nt //! saves all frames from nullptr-terminated array of buffers //! all buffers and the returned array must be deleted using free() APENG_DLLIMPORT unsigned int APENG_API apeng_save_frames_file_nt( FILE* file, const uint8_t** frames_array, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes) { assert(frames_array); unsigned int frames = 0; const uint8_t* cur_frames = *frames_array; while (cur_frames != nullptr) { ++frames; } return apeng_save_frames_file(file, frames_array, frames, width, height, colortype, rowbytes); } //! apeng_save_frames_file //! saves all frames array of buffers //! all buffers and the returned array must be deleted using free() APENG_DLLIMPORT unsigned int APENG_API apeng_save_frames_file(FILE* file, const uint8_t** frames_array, unsigned int frames, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes) { assert(file); assert(frames_array); // void save_png(unsigned char* p_frame, unsigned int w, unsigned int h, unsigned int d, unsigned int t, unsigned // int frames) png_structp png_ptr = png_create_write_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); assert(png_ptr); png_infop info_ptr = png_create_info_struct(png_ptr); assert(info_ptr); if (png_ptr != nullptr && info_ptr != nullptr && setjmp(png_jmpbuf(png_ptr)) == 0) { png_init_io(png_ptr, file); png_set_compression_level(png_ptr, 9); unsigned int channels = rowbytes / width; unsigned int bitdepth = 8; //TODO: compute from channels png_set_IHDR(png_ptr, info_ptr, width, height, bitdepth, colortype, 0, 0, 0); #ifdef PNG_APNG_SUPPORTED png_set_acTL(png_ptr, info_ptr, frames, 0); // png_set_first_frame_is_hidden(png_ptr, info_ptr, 1); #endif // PNG_APNG_SUPPORTED png_write_info(png_ptr, info_ptr); png_bytepp rows = (png_bytepp)malloc(height * sizeof(png_bytep)); assert(rows); for (unsigned int frameIdx = 0; frameIdx < frames; ++frameIdx) { for (unsigned int rowIdx = 0; rowIdx < height; ++rowIdx) { rows[rowIdx] = (png_bytep)(frames_array[frameIdx] + (rowIdx * rowbytes)); } #ifdef PNG_APNG_SUPPORTED png_write_frame_head(png_ptr, info_ptr, nullptr, width, height, 0, 0, 12, 100, PNG_DISPOSE_OP_NONE, PNG_BLEND_OP_SOURCE); #endif // PNG_APNG_SUPPORTED png_write_image(png_ptr, rows); #ifdef PNG_APNG_SUPPORTED png_write_frame_tail(png_ptr, info_ptr); #endif // PNG_APNG_SUPPORTED } free(rows); png_write_end(png_ptr, info_ptr); } png_destroy_write_struct(&png_ptr, &info_ptr); return (unsigned int)APENG_ERROR::no_error; } //! apeng_save_frames_blob //! saves all frames from large buffer frame_blob //! frame_blob must be deleted by user using free() APENG_DLLIMPORT unsigned int APENG_API apeng_save_frames_blob(const char* filename, const uint8_t* frames_blob, unsigned int frames_blob_size, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes, unsigned int frames) { std::shared_ptr<FILE> file(fopen(filename, "wb"), fclose); assert(file); return apeng_save_frames_file_blob(file.get(), frames_blob, frames_blob_size, width, height, colortype, rowbytes, frames); } //! apeng_save_frames_nt //! saves all frames from nullptr-terminated array of buffers //! all buffers and the returned array must be deleted using free() APENG_DLLIMPORT unsigned int APENG_API apeng_save_frames_nt( const char* filename, const uint8_t** frames_array, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes) { std::shared_ptr<FILE> file(fopen(filename, "wb"), fclose); assert(file); return apeng_save_frames_file_nt(file.get(), frames_array, width, height, colortype, rowbytes); } //! apeng_save_frames //! saves all frames array of buffers //! all buffers and the returned array must be deleted using free() APENG_DLLIMPORT unsigned int APENG_API apeng_save_frames(const char* filename, const uint8_t** frames_array, unsigned int frames, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes) { std::shared_ptr<FILE> file(fopen(filename, "wb"), fclose); assert(file); return apeng_save_frames_file(file.get(), frames_array, frames, width, height, colortype, rowbytes); } /////////////////////////////////////////////////////////////////////////////// //! loader //! apeng_load_frames_file_blob //! loads all frames into large buffer frame_blob //! frame_blob must be deleted by user using free() APENG_DLLIMPORT unsigned int APENG_API apeng_load_frames_file_blob(FILE* file, uint8_t** frames_blob, unsigned int* frames_blob_size, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes, unsigned int* frames) { uint8_t** temp_frames_array; unsigned int err = apeng_load_frames_file(file, &temp_frames_array, frames, width, height, channels, rowbytes); *frames_blob = (uint8_t*)malloc((*frames) * (*height) * (*rowbytes) * sizeof(uint8_t)); for (unsigned int i = 0; i < *frames; ++i) { memcpy(&frames_blob[i * (*height) * (*rowbytes)], temp_frames_array[i], (*height) * (*rowbytes)); free(temp_frames_array[i]); } free(temp_frames_array); return err; } //! apeng_load_frames_file_nt //! loads all frames into nullptr-terminated array of buffers //! all buffers and the returned array must be deleted using free() APENG_DLLIMPORT unsigned int APENG_API apeng_load_frames_file_nt( FILE* file, uint8_t*** frames_array, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes) { uint8_t** temp_frames_array; unsigned int frames; unsigned int err = apeng_load_frames_file(file, &temp_frames_array, &frames, width, height, channels, rowbytes); *frames_array = (uint8_t**)malloc((frames + 1) * sizeof(uint8_t*)); memset(*frames_array, 0, frames + 1); memcpy(*frames_array, temp_frames_array, frames); free(temp_frames_array); return err; } //! apeng_load_frames_file //! loads all frames array of buffers //! all buffers and the returned array must be deleted using free() APENG_DLLIMPORT unsigned int APENG_API apeng_load_frames_file(FILE* file, uint8_t*** frames_array, unsigned int* frames, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes) { assert(file); assert(frames_array); assert(frames); assert(width); assert(height); assert(channels); assert(rowbytes); unsigned char sig[8]; if (!(fread(sig, 1, 8, file) == 8 && png_sig_cmp(sig, 0, 8) == 0)) { return (unsigned int)APENG_ERROR::data_invalid; } png_structp png_ptr = png_create_read_struct(PNG_LIBPNG_VER_STRING, nullptr, nullptr, nullptr); assert(png_ptr); png_infop info_ptr = png_create_info_struct(png_ptr); assert(info_ptr); if (png_ptr != nullptr && info_ptr != nullptr && setjmp(png_jmpbuf(png_ptr)) == 0) { png_init_io(png_ptr, file); png_set_sig_bytes(png_ptr, 8); png_read_info(png_ptr, info_ptr); png_set_expand(png_ptr); png_set_strip_16(png_ptr); png_set_gray_to_rgb(png_ptr); png_set_add_alpha(png_ptr, 0xff, PNG_FILLER_AFTER); png_set_bgr(png_ptr); (void)png_set_interlace_handling(png_ptr); png_read_update_info(png_ptr, info_ptr); *width = png_get_image_width(png_ptr, info_ptr); *height = png_get_image_height(png_ptr, info_ptr); *channels = png_get_channels(png_ptr, info_ptr); *rowbytes = png_get_rowbytes(png_ptr, info_ptr); unsigned int framesize = (*height) * (*rowbytes); png_bytepp rows = (png_bytepp)malloc((*height) * sizeof(png_bytep)); assert(rows); *frames = 1; png_uint_32 w0 = *width; png_uint_32 h0 = *height; #ifdef PNG_APNG_SUPPORTED png_uint_32 plays = 0; png_uint_32 x0 = 0; png_uint_32 y0 = 0; unsigned short delay_num = 1; unsigned short delay_den = 10; unsigned char displayOp = 0; unsigned char blendOp = 0; if (png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL)) { png_get_acTL(png_ptr, info_ptr, frames, &plays); } #endif *frames_array = (uint8_t**)malloc(*frames * sizeof(uint8_t*)); for (unsigned int frameIdx = 0; frameIdx < *frames; ++frameIdx) { (*frames_array)[frameIdx] = (uint8_t*)malloc(framesize); for (unsigned rowIdx = 0; rowIdx < *height; ++rowIdx) { rows[rowIdx] = (*frames_array)[frameIdx] + (rowIdx * (*rowbytes)); } #ifdef PNG_APNG_SUPPORTED if (png_get_valid(png_ptr, info_ptr, PNG_INFO_acTL)) { png_read_frame_head(png_ptr, info_ptr); png_get_next_frame_fcTL(png_ptr, info_ptr, &w0, &h0, &x0, &y0, &delay_num, &delay_den, &displayOp, &blendOp); } #endif png_read_image(png_ptr, rows); } png_read_end(png_ptr, info_ptr); free(rows); } png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); return (unsigned int)APENG_ERROR::no_error; } //! apeng_load_frames_blob //! loads all frames into large buffer frame_blob //! frame_blob must be deleted by user using free() APENG_DLLIMPORT unsigned int APENG_API apeng_load_frames_blob(const char* filename, uint8_t** frames_blob, unsigned int* frames_blob_size, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes, unsigned int* frames) { std::shared_ptr<FILE> file(fopen(filename, "rb"), fclose); assert(file); return apeng_load_frames_file_blob(file.get(), frames_blob, frames_blob_size, width, height, channels, rowbytes, frames); } //! apeng_load_frames_nt //! loads all frames into nullptr-terminated array of buffers //! all buffers and the returned array must be deleted using free() APENG_DLLIMPORT unsigned int APENG_API apeng_load_frames_nt( const char* filename, uint8_t*** frames_array, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes) { std::shared_ptr<FILE> file(fopen(filename, "rb"), fclose); assert(file); return apeng_load_frames_file_nt(file.get(), frames_array, width, height, channels, rowbytes); } //! apeng_load_frames //! loads all frames array of buffers //! all buffers and the returned array must be deleted using free() APENG_DLLIMPORT unsigned int APENG_API apeng_load_frames(const char* filename, uint8_t*** frames_array, unsigned int* frames, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes) { std::shared_ptr<FILE> file(fopen(filename, "rb"), fclose); assert(file); return apeng_load_frames_file(file.get(), frames_array, frames, width, height, channels, rowbytes); } /////////////////////////////////////////////////////////////////////////////// /// C++ #ifdef __cplusplus APENG_DLLIMPORT unsigned int APENG_API apeng::load_frames(FILE* file, uint8_t** frames_blob, unsigned int* frames_blob_size, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes, unsigned int* frames) { return ::apeng_load_frames_file_blob(file, frames_blob, frames_blob_size, width, height, channels, rowbytes, frames); } APENG_DLLIMPORT unsigned int APENG_API apeng::load_frames( FILE* file, uint8_t*** frames_array, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes) { return ::apeng_load_frames_file_nt(file, frames_array, width, height, channels, rowbytes); } APENG_DLLIMPORT unsigned int APENG_API apeng::load_frames(FILE* file, uint8_t*** frames_array, unsigned int* frames, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes) { return ::apeng_load_frames_file(file, frames_array, frames, width, height, channels, rowbytes); } APENG_DLLIMPORT unsigned int APENG_API apeng::load_frames(const char* filename, uint8_t** frames_blob, unsigned int* frames_blob_size, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes, unsigned int* frames) { return ::apeng_load_frames_blob(filename, frames_blob, frames_blob_size, width, height, channels, rowbytes, frames); } APENG_DLLIMPORT unsigned int APENG_API apeng::load_frames( const char* filename, uint8_t*** frames_array, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes) { return ::apeng_load_frames_nt(filename, frames_array, width, height, channels, rowbytes); } APENG_DLLIMPORT unsigned int APENG_API apeng::load_frames(const char* filename, uint8_t*** frames_array, unsigned int* frames, unsigned int* width, unsigned int* height, unsigned int* channels, unsigned int* rowbytes) { return ::apeng_load_frames(filename, frames_array, frames, width, height, channels, rowbytes); } APENG_DLLIMPORT unsigned int APENG_API apeng::save_frames(FILE* file, const uint8_t* frames_blob, unsigned int frames_blob_size, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes, unsigned int frames) { return ::apeng_save_frames_file_blob(file, frames_blob, frames_blob_size, width, height, colortype, rowbytes, frames); } APENG_DLLIMPORT unsigned int APENG_API apeng::save_frames( FILE* file, const uint8_t** frames_array, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes) { return ::apeng_save_frames_file_nt(file, frames_array, width, height, colortype, rowbytes); } APENG_DLLIMPORT unsigned int APENG_API apeng::save_frames(FILE* file, const uint8_t** frames_array, unsigned int frames, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes) { return ::apeng_save_frames_file(file, frames_array, frames, width, height, colortype, rowbytes); } APENG_DLLIMPORT unsigned int APENG_API apeng::save_frames(const char* filename, const uint8_t* frames_blob, unsigned int frames_blob_size, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes, unsigned int frames) { return ::apeng_save_frames_blob(filename, frames_blob, frames_blob_size, width, height, colortype, rowbytes, frames); } APENG_DLLIMPORT unsigned int APENG_API apeng::save_frames( const char* filename, const uint8_t** frames_array, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes) { return ::apeng_save_frames_nt(filename, frames_array, width, height, colortype, rowbytes); } APENG_DLLIMPORT unsigned int APENG_API apeng::save_frames(const char* filename, const uint8_t** frames_array, unsigned int frames, unsigned int width, unsigned int height, unsigned int colortype, unsigned int rowbytes) { return ::apeng_save_frames(filename, frames_array, frames, width, height, colortype, rowbytes); } #endif //__cplusplus /////////////////////////////////////////////////////////////////////////////// /// EOF
[ "kagekirin+apeng@gmail.com" ]
kagekirin+apeng@gmail.com
db28222107faf025adb454f4d976e5d2977e509d
24a56616271adb0342b5e4f7a0e0bb5da33746d2
/src/scene.cpp
a2178d4d9bbf4c489bffaf448d9c11f8da076262
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mitsuba-rei/lightmetrica-v3
b7ffb34a9e45742812eed47c6092e75552199206
db5b7d5a9a245fb7c0d25124433c38d09b62813e
refs/heads/master
2020-08-04T04:20:28.070039
2019-09-30T13:59:48
2019-09-30T13:59:48
212,001,950
0
0
NOASSERTION
2019-10-01T02:59:21
2019-10-01T02:59:21
null
UTF-8
C++
false
false
19,651
cpp
/* Lightmetrica - Copyright (c) 2019 Hisanari Otsu Distributed under MIT license. See LICENSE file for details. */ #include <pch.h> #include <lm/core.h> #include <lm/scene.h> #include <lm/assets.h> #include <lm/accel.h> #include <lm/mesh.h> #include <lm/camera.h> #include <lm/material.h> #include <lm/light.h> #include <lm/model.h> #include <lm/medium.h> #include <lm/phase.h> LM_NAMESPACE_BEGIN(LM_NAMESPACE) struct LightPrimitiveIndex { Transform globalTransform; // Global transform matrix int index; // Primitive node index template <typename Archive> void serialize(Archive& ar) { ar(globalTransform, index); } }; class Scene_ final : public Scene { private: std::vector<SceneNode> nodes_; // Scene nodes Ptr<Accel> accel_; // Acceleration structure std::optional<int> camera_; // Camera index std::vector<LightPrimitiveIndex> lights_; // Primitive node indices of lights and global transforms std::unordered_map<int, int> lightIndicesMap_; // Map from node indices to light indices. std::optional<int> envLight_; // Environment light index std::optional<int> medium_; // Medium index public: Scene_() { // Index 0 is fixed to the scene group nodes_.push_back(SceneNode::makeGroup(0, false, {})); } public: LM_SERIALIZE_IMPL(ar) { ar(nodes_, accel_, camera_, lights_, lightIndicesMap_, envLight_); } virtual void foreachUnderlying(const ComponentVisitor& visit) override { comp::visit(visit, accel_); for (auto& node : nodes_) { if (node.type == SceneNodeType::Primitive) { comp::visit(visit, node.primitive.mesh); comp::visit(visit, node.primitive.material); comp::visit(visit, node.primitive.light); comp::visit(visit, node.primitive.camera); } } } virtual Component* underlying(const std::string& name) const override { if (name == "accel") { return accel_.get(); } if (name == "camera") { return nodes_.at(*camera_).primitive.camera; } return nullptr; } public: virtual bool renderable() const override { if (nodes_.size() == 1) { LM_ERROR("Missing primitives. Use lm::primitive() function to add primitives."); return false; } if (!camera_) { LM_ERROR("Missing camera primitive. Use lm::primitive() function to add camera primitive."); return false; } if (!accel_) { LM_ERROR("Missing acceleration structure. Use lm::build() function before rendering."); return false; } return true; } // ------------------------------------------------------------------------ virtual int rootNode() override { return 0; } virtual int createNode(SceneNodeType type, const Json& prop) override { if (type == SceneNodeType::Primitive) { // Find an asset by property name const auto getAssetRefBy = [&](const std::string& propName) -> Component* { const auto it = prop.find(propName); if (it == prop.end()) { return nullptr; } return comp::get<Component>(it.value().get<std::string>()); }; // Node index const int index = int(nodes_.size()); // Get asset references auto* mesh = dynamic_cast<Mesh*>(getAssetRefBy("mesh")); auto* material = dynamic_cast<Material*>(getAssetRefBy("material")); auto* light = dynamic_cast<Light*>(getAssetRefBy("light")); auto* camera = dynamic_cast<Camera*>(getAssetRefBy("camera")); auto* medium = dynamic_cast<Medium*>(getAssetRefBy("medium")); // Check validity if (!mesh && !material && !light && !camera && !medium) { LM_ERROR("Invalid primitive node. Given assets are invalid."); return false; } if (camera && light) { LM_ERROR("Primitive cannot be both camera and light"); return false; } // Camera if (camera) { camera_ = index; } // Envlight if (light && light->isInfinite()) { if (envLight_) { LM_ERROR("Environment light is already registered. " "You can register only one environment light in the scene."); return false; } envLight_ = index; } // Medium if (medium) { // For now, consider the medium as global asset. medium_ = index; } // Create primitive node nodes_.push_back(SceneNode::makePrimitive(index, mesh, material, light, camera, medium)); return index; } // ---------------------------------------------------------------- if (type == SceneNodeType::Group) { const int index = int(nodes_.size()); nodes_.push_back(SceneNode::makeGroup( index, json::value<bool>(prop, "instanced", false), json::valueOrNone<Mat4>(prop, "transform") )); return index; } // ---------------------------------------------------------------- LM_UNREACHABLE_RETURN(); } virtual void addChild(int parent, int child) override { if (parent < 0 || parent >= int(nodes_.size())) { LM_ERROR("Missing parent index [index='{}'", parent); return; } auto& node = nodes_.at(parent); if (node.type != SceneNodeType::Group) { LM_ERROR("Adding child to non-group node [parent='{}', child='{}']", parent, child); return; } node.group.children.push_back(child); } virtual void addChildFromModel(int parent, const std::string& modelLoc) override { if (parent < 0 || parent >= int(nodes_.size())) { LM_ERROR("Missing parent index [index='{}'", parent); return; } auto* model = comp::get<Model>(modelLoc); if (!model) { return; } model->createPrimitives([&](Component* mesh, Component* material, Component* light) { const int index = int(nodes_.size()); nodes_.push_back(SceneNode::makePrimitive( index, dynamic_cast<Mesh*>(mesh), dynamic_cast<Material*>(material), dynamic_cast<Light*>(light), nullptr, nullptr)); addChild(parent, index); }); } // ------------------------------------------------------------------------ virtual void traverseNodes(const NodeTraverseFunc& traverseFunc) const override { std::function<void(int, Mat4)> visit = [&](int index, Mat4 globalTransform) { const auto& node = nodes_.at(index); traverseFunc(node, globalTransform); if (node.type == SceneNodeType::Group) { const auto M = node.group.localTransform ? globalTransform * *node.group.localTransform : globalTransform; for (int child : node.group.children) { visit(child, M); } } }; visit(0, Mat4(1_f)); } virtual void visitNode(int nodeIndex, const VisitNodeFunc& visit) const override { visit(nodes_.at(nodeIndex)); } virtual const SceneNode& nodeAt(int nodeIndex) const override { return nodes_.at(nodeIndex); } // ------------------------------------------------------------------------ virtual void build(const std::string& name, const Json& prop) override { // Update light indices // We keep the global transformation of the light primitive as well as the references. // We need to recompute the indices when an update of the scene happens, // because the global tranformation can only be obtained by traversing the nodes. lightIndicesMap_.clear(); lights_.clear(); traverseNodes([&](const SceneNode& node, Mat4 globalTransform) { if (node.type == SceneNodeType::Primitive && node.primitive.light) { lightIndicesMap_[node.index] = int(lights_.size()); lights_.push_back({ Transform(globalTransform), node.index }); } }); // Build acceleration structure accel_ = comp::create<Accel>(name, makeLoc(loc(), "accel"), prop); if (!accel_) { return; } LM_INFO("Building acceleration structure [name='{}']", name); LM_INDENT(); accel_->build(*this); } virtual std::optional<SceneInteraction> intersect(Ray ray, Float tmin, Float tmax) const override { const auto hit = accel_->intersect(ray, tmin, tmax); if (!hit) { // Use environment light when tmax = Inf if (tmax < Inf) { return {}; } if (!envLight_) { return {}; } return SceneInteraction::makeLightEndpoint( *envLight_, 0, PointGeometry::makeInfinite(-ray.d)); } const auto [t, uv, globalTransform, primitiveIndex, faceIndex] = *hit; const auto& primitive = nodes_.at(primitiveIndex).primitive; const auto p = primitive.mesh->surfacePoint(faceIndex, uv); return SceneInteraction::makeSurfaceInteraction( primitiveIndex, -1, PointGeometry::makeOnSurface( globalTransform.M * Vec4(p.p, 1_f), globalTransform.normalM * p.n, p.t ) ); } // ------------------------------------------------------------------------ virtual bool isLight(const SceneInteraction& sp) const override { const auto& primitive = nodes_.at(sp.primitive).primitive; return sp.medium ? primitive.medium->isEmitter() : primitive.light != nullptr; } virtual bool isSpecular(const SceneInteraction& sp) const override { const auto& primitive = nodes_.at(sp.primitive).primitive; if (sp.medium) { return primitive.medium->phase()->isSpecular(sp.geom); } if (sp.endpoint) { if (primitive.light) { return primitive.light->isSpecular(sp.geom, sp.comp); } else if (primitive.camera) { return primitive.camera->isSpecular(sp.geom); } LM_UNREACHABLE_RETURN(); } return primitive.material->isSpecular(sp.geom, sp.comp); } // ------------------------------------------------------------------------ virtual Ray primaryRay(Vec2 rp, Float aspectRatio) const { return nodes_.at(*camera_).primitive.camera->primaryRay(rp, aspectRatio); } virtual std::optional<RaySample> sampleRay(Rng& rng, const SceneInteraction& sp, Vec3 wi) const override { if (sp.medium) { // Medium interaction const auto& primitive = nodes_.at(sp.primitive).primitive; const auto s = primitive.medium->phase()->sample(rng, sp.geom, wi); if (!s) { return {}; } return RaySample{ sp, s->wo, s->weight }; } else if (sp.terminator && sp.terminator == TerminatorType::Camera) { // Endpoint const auto* camera = nodes_.at(*camera_).primitive.camera; const auto s = camera->samplePrimaryRay(rng, sp.cameraCond.window, sp.cameraCond.aspectRatio); if (!s) { return {}; } return RaySample{ SceneInteraction::makeCameraEndpoint( *camera_, 0, s->geom, sp.cameraCond.window, sp.cameraCond.aspectRatio ), s->wo, s->weight }; } else { // Surface interaction const auto& primitive = nodes_.at(sp.primitive).primitive; if (!primitive.material) { return {}; } const auto s = primitive.material->sample(rng, sp.geom, wi); if (!s) { return {}; } return RaySample{ SceneInteraction::makeSurfaceInteraction( sp.primitive, s->comp, sp.geom ), s->wo, s->weight }; } } virtual Float pdfComp(const SceneInteraction& sp, Vec3 wi) const override { const auto& primitive = nodes_.at(sp.primitive).primitive; if (sp.medium) { return 1_f; } else { if (!primitive.material) { return 1_f; } return primitive.material->pdfComp(sp.geom, sp.comp, wi); } } virtual std::optional<RaySample> samplePrimaryRay(Rng& rng, Vec4 window, Float aspectRatio) const override { const auto s = nodes_.at(*camera_).primitive.camera->samplePrimaryRay(rng, window, aspectRatio); if (!s) { return {}; } return RaySample{ SceneInteraction::makeCameraEndpoint( *camera_, 0, s->geom, window, aspectRatio ), s->wo, s->weight }; } virtual std::optional<Vec2> rasterPosition(Vec3 wo, Float aspectRatio) const override { const auto* camera = nodes_.at(*camera_).primitive.camera; return camera->rasterPosition(wo, aspectRatio); } virtual std::optional<RaySample> sampleLight(Rng& rng, const SceneInteraction& sp) const override { // Sample a light const int n = int(lights_.size()); const int i = glm::clamp(int(rng.u() * n), 0, n-1); const auto pL = 1_f / n; // Sample a position on the light const auto light = lights_.at(i); const auto& primitive = nodes_.at(light.index).primitive; const auto s = primitive.light->sample(rng, sp.geom, light.globalTransform); if (!s) { return {}; } return RaySample{ SceneInteraction::makeLightEndpoint( light.index, s->comp, s->geom ), s->wo, s->weight / pL }; } virtual Float pdf(const SceneInteraction& sp, Vec3 wi, Vec3 wo) const override { const auto& primitive = nodes_.at(sp.primitive).primitive; if (sp.medium) { return primitive.medium->phase()->pdf(sp.geom, wi, wo); } else if (sp.endpoint) { if (primitive.light) { LM_TBA_RUNTIME(); } else if (primitive.camera) { return primitive.camera->pdf(wo, sp.cameraCond.aspectRatio); } LM_UNREACHABLE_RETURN(); } else { return primitive.material->pdf(sp.geom, sp.comp, wi, wo); } } virtual Float pdfLight(const SceneInteraction& sp, const SceneInteraction& spL, Vec3 wo) const override { const auto& primitive = nodes_.at(spL.primitive).primitive; const auto lightTransform = lights_.at(lightIndicesMap_.at(spL.primitive)).globalTransform; const auto pL = 1_f / int(lights_.size()); return primitive.light->pdf(sp.geom, spL.geom, spL.comp, lightTransform, wo) * pL; } // ------------------------------------------------------------------------ virtual std::optional<DistanceSample> sampleDistance(Rng& rng, const SceneInteraction& sp, Vec3 wo) const override { // Intersection to next surface const auto hit = intersect({ sp.geom.p, wo }, Eps, Inf); const auto dist = hit && !hit->geom.infinite ? glm::length(hit->geom.p - sp.geom.p) : Inf; // Sample a distance const auto* medium = nodes_.at(*medium_).primitive.medium; const auto ds = medium->sampleDistance(rng, { sp.geom.p, wo }, 0_f, dist); if (ds && ds->medium) { // Medium interaction return DistanceSample{ SceneInteraction::makeMediumInteraction( *medium_, 0, PointGeometry::makeDegenerated(ds->p) ), ds->weight }; } else { // Surface interaction return DistanceSample{ *hit, ds ? ds->weight : Vec3(1_f) }; } } virtual std::optional<Vec3> evalTransmittance(Rng& rng, const SceneInteraction& sp1, const SceneInteraction& sp2) const override { if (!visible(sp1, sp2)) { return {}; } if (!medium_) { return Vec3(1_f); } // Extended distance between two points assert(!sp1.geom.infinite); const auto dist = !sp2.geom.infinite ? glm::distance(sp1.geom.p, sp2.geom.p) : Inf; const auto wo = !sp2.geom.infinite ? glm::normalize(sp2.geom.p - sp1.geom.p) : -sp2.geom.wo; const auto* medium = nodes_.at(*medium_).primitive.medium; return medium->evalTransmittance(rng, { sp1.geom.p, wo }, 0_f, dist); } // ------------------------------------------------------------------------ virtual Vec3 evalContrb(const SceneInteraction& sp, Vec3 wi, Vec3 wo) const override { const auto& primitive = nodes_.at(sp.primitive).primitive; if (sp.medium) { // Medium interaction return primitive.medium->phase()->eval(sp.geom, wi, wo); } else { // Surface interaction if (sp.endpoint) { if (primitive.camera) { return primitive.camera->eval(wo, sp.cameraCond.aspectRatio); } else if (primitive.light) { return primitive.light->eval(sp.geom, sp.comp, wo); } LM_UNREACHABLE(); } return primitive.material->eval(sp.geom, sp.comp, wi, wo); } } virtual Vec3 evalContrbEndpoint(const SceneInteraction& sp, Vec3 wo) const override { const auto& primitive = nodes_.at(sp.primitive).primitive; if (!primitive.light) { return {}; } return primitive.light->eval(sp.geom, sp.comp, wo); } virtual std::optional<Vec3> reflectance(const SceneInteraction& sp) const override { const auto& primitive = nodes_.at(sp.primitive).primitive; if (!primitive.material) { return {}; } return primitive.material->reflectance(sp.geom, sp.comp); } }; LM_COMP_REG_IMPL(Scene_, "scene::default"); LM_NAMESPACE_END(LM_NAMESPACE)
[ "hi2p.perim@gmail.com" ]
hi2p.perim@gmail.com
5c4ac12b1d0d5b73bf3debeeb626f8f40a4337ef
123f6cbafbad11fe585d3d50b7cfd29461e4977d
/IndirectRelation.cpp
a1f699cd1864af3cbe05524a6c7640c0f458ca27
[]
no_license
chase0213/CNImplementation
b7f5f094a8541e8d8051015d8772fd2f7f893ca8
df19827d171805f8aca5f7dd8e3f90f6fabcbcfa
refs/heads/master
2021-01-01T17:32:12.866910
2014-04-19T17:40:28
2014-04-19T17:40:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
187
cpp
// // IndirectRelation.cpp // CNImplementation // // Created by 長谷川 知里 on 12/04/26. // Copyright (c) 2012年 __MyCompanyName__. All rights reserved. // #include <iostream>
[ "chase0213@gmail.com" ]
chase0213@gmail.com
ce9c522b6adeb5a5d1e5c64879df609eace36906
6814fc732acb956ce438211f88f28a4191b97306
/src/spin_turtle/src/spin_turtle.cpp
cd19c2867833f73940c9bc25e5be0e2ced775f14
[]
no_license
tvhong/catkin_ws
2fe7a58904a8b816ac8b7e50491f9431866fe157
0f6fdd05159a207e22d1d10bdf1c4fb43ad7f36e
refs/heads/master
2021-01-22T02:43:11.616297
2013-12-02T23:31:08
2013-12-02T23:31:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,149
cpp
#include "ros/ros.h" #include <cstdlib> #include "geometry_msgs/Twist.h" void generate_new_msg(geometry_msgs::Twist &msg) { msg.linear.x = (double) rand() / RAND_MAX * 2; msg.linear.y = (double) 0; msg.linear.z = (double) 0; if (rand() < RAND_MAX / 4) msg.linear.x *= -1; msg.angular.x = (double) 0; msg.angular.y = (double) 0; msg.angular.z = (double) rand() / RAND_MAX * 2; if (rand() > RAND_MAX / 2) msg.angular.z *= -1; } int main(int argc, char **argv) { if (argc != 2) { ROS_INFO("Usage: spin_turtle <topic>"); return 1; } ros::init(argc, argv, "spin_turtle"); ros::NodeHandle n; ros::Publisher turtle_commander = n.advertise<geometry_msgs::Twist>(argv[1], 1000); ros::Rate loop_rate(1); int cnt = 0; geometry_msgs::Twist msg; srand(time(NULL)); while (ros::ok()) { if (!cnt) { cnt = rand() % 3 + 1; generate_new_msg(msg); } turtle_commander.publish(msg); ROS_INFO("Move boy"); ros::spinOnce(); loop_rate.sleep(); cnt--; } return 0; }
[ "tvho795@cse.unsw.edu.au" ]
tvho795@cse.unsw.edu.au
01391e2f3d321b8720c25541bcd91e251a41de64
2163bb148d7bae8006eea473fe3de3ebeb0f6879
/modules/core/include/nt2/sdk/meta/tieable_hierarchy.hpp
3ed9ea970c20424ed3ef302424d2da92c0272cf2
[ "BSL-1.0" ]
permissive
pcaruan/nt2
b6226a745e4bf56449aae25d9801a959e04e001b
cc36110fb3db9849156c5ab625b5b44c8c4c3c8f
refs/heads/master
2021-01-18T05:50:28.768185
2012-07-02T12:40:02
2012-07-02T12:51:19
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,147
hpp
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_SDK_META_TIEABLE_HIERARCHY_HPP_INCLUDED #define NT2_SDK_META_TIEABLE_HIERARCHY_HPP_INCLUDED #include <nt2/sdk/simd/category.hpp> #include <nt2/sdk/meta/hierarchy_of.hpp> namespace boost { namespace dispatch { namespace meta { //========================================================================== // Tie-able node hierarchy //========================================================================== template<class Tag> struct tieable_ : unspecified_<Tag> { typedef unspecified_<Tag> parent; }; } } } namespace nt2 { namespace ext { using boost::dispatch::meta::tieable_; } } #endif
[ "joel.falcou@lri.fr" ]
joel.falcou@lri.fr
a56031b80645b1eabbaab72480d8315c383836c1
f88c5eece108dba61d0dabc661327230ada6edf1
/src/nwx/gui/color.hpp
484ad043c48420bdb76dc36c546f5d914a78b38e
[]
no_license
veicu/native-widgets
d948d543da64192c755d356c638195ed1c882271
de4e17395480f3553da2e18c9e2d8056a82738c0
refs/heads/master
2022-01-06T11:28:40.971028
2021-12-22T12:01:22
2021-12-22T12:01:22
226,700,019
0
0
null
null
null
null
UTF-8
C++
false
false
1,233
hpp
/** Declartion of class color. */ #ifndef NWX_GUI_COLOR #define NWX_GUI_COLOR namespace nwx { namespace gui { class color { public: color(); color( unsigned char red, unsigned char green, unsigned char blue ); color( unsigned char alpha, unsigned char red, unsigned char green, unsigned char blue ); ~color(); color( const color& other ); color& operator=( const color& other ); unsigned char red() const; unsigned char green() const; unsigned char blue() const; unsigned char alpha() const; void red( unsigned char red ); void green( unsigned char green ); void blue( unsigned char blue ); void alpha( unsigned char alpha ); void rgb( unsigned char red, unsigned char green, unsigned char blue ); void rgba( unsigned char red, unsigned char green, unsigned char blue, unsigned char alpha ); private: unsigned char m_red; unsigned char m_green; unsigned char m_blue; unsigned char m_alpha; }; } } #endif // NWX_GUI_COLOR
[ "veiuc@outlook.com" ]
veiuc@outlook.com
0a832808568ec18783880d2b7017802031ad5cb8
15a7631b8e055317dfea466a2ed1f2784ca2878d
/Cosas Hechas/PROGRAMACION 2/FICHEROS/lectura.cc
98f66cebb1577a2a0b548a34f85514677eaab423
[]
no_license
Nepre/P1-To-o
d7ebd76cb2031305e343810867c1195915a77615
0406afc3ed10122ce432dd4c8abda327370751ee
refs/heads/master
2020-08-01T23:16:55.340779
2020-04-17T11:54:23
2020-04-17T11:54:23
211,153,316
0
0
null
null
null
null
UTF-8
C++
false
false
1,237
cc
#include <iostream> #include <fstream> #include <string.h> #include <string> using namespace std; int main(int argc, char const *argv[]) { //argc == numero de argumentos que tiene (minimo 1) //argv[1] == "ficheroLeer.txt" // ./lecturatxt ficheroLeer.txt if(argc <= 1){ cout<<"error"; return 1; } /* ficheroLeer.txt ficheroLeer.dat char * ch = argv[1]; for (size_t i = 0; i < count; i++) { if(ch[i] == '.' && ch[i+1] == 't') }*/ ifstream l; ofstream e("leerMayus.txt"); l.open("ficheroLeer.txt", ios::in); if (l.is_open() && e.is_open()) { string smin; string smay; e << "En mayusculas: "<<endl; while(getline(l,smin)){ for (int i = 0; smin[i] != '\0'; i++) { //cout<<smin<<endl; //cout<<smay<<endl; smay += toupper(smin[i]); } e << smay << endl; smay = ""; } e.close(); l.close(); } else { cout<<"Error al abrir el fichero"<<endl; } return 0; }
[ "toni.games2101@gmail.com" ]
toni.games2101@gmail.com
a5d2da4933fd4c82ca32e97a6fe7b0a975f4a791
e3b1a99ff96c50674651236cbb5ad67c6a5332b0
/working-effectively-with-legacycode-cc++/cpp/tests/gtest_lib/googletest/include/gtest/gtest-typed-test.h
52eaeb4a548ffb5a471357aac3aae16714748765
[ "BSD-3-Clause" ]
permissive
unclejet/software-craftsman-ship
6388864bf4acaa0b543b0e26d65dd110a8ebac5b
6310c5b618f32cb84ff193e625b6c38a8469f460
refs/heads/master
2023-03-31T11:36:18.494187
2021-04-05T01:25:34
2021-04-05T01:25:34
292,982,586
0
0
null
null
null
null
UTF-8
C++
false
false
15,991
h
// Copyright 2008 Google Inc. // 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 Google Inc. 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. // GOOGLETEST_CM0001 DO NOT DELETE #ifndef GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ #define GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_ // This header implements typed tests and type-parameterized tests. // Typed (aka type-driven) tests repeat the same test for types in a // list. You must know which types you want to test with when writing // typed tests. Here's how you do it: #if 0 // First, define a fixture class template. It should be parameterized // by a type. Remember to derive it from testing::Test. template <typename T> class FooTest : public testing::Test { public: ... typedef std::list<T> List; static T shared_; T value_; }; // Next, associate a list of types with the test suite, which will be // repeated for each type in the list. The typedef is necessary for // the macro to parse correctly. typedef testing::Types<char, int, unsigned int> MyTypes; TYPED_TEST_SUITE(FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: // TYPED_TEST_SUITE(FooTest, int); // Then, use TYPED_TEST() instead of TEST_F() to define as many typed // tests for this test suite as you want. TYPED_TEST(FooTest, DoesBlah) { // Inside a test, refer to the special name TypeParam to get the type // parameter. Since we are inside a derived class template, C++ requires // us to visit the members of FooTest via 'this'. TypeParam n = this->value_; // To visit static members of the fixture, add the TestFixture:: // prefix. n += TestFixture::shared_; // To refer to typedefs in the fixture, add the "typename // TestFixture::" prefix. typename TestFixture::List values; values.push_back(n); ... } TYPED_TEST(FooTest, HasPropertyA) { ... } // TYPED_TEST_SUITE takes an optional third argument which allows to specify a // class that generates custom test name suffixes based on the type. This should // be a class which has a static template function GetName(int index) returning // a string for each type. The provided integer index equals the index of the // type in the provided type list. In many cases the index can be ignored. // // For example: // class MyTypeNames { // public: // template <typename T> // static std::string GetName(int) { // if (std::is_same<T, char>()) return "char"; // if (std::is_same<T, int>()) return "int"; // if (std::is_same<T, unsigned int>()) return "unsignedInt"; // } // }; // TYPED_TEST_SUITE(FooTest, MyTypes, MyTypeNames); #endif // 0 // Type-parameterized tests are abstract test patterns parameterized // by a type. Compared with typed tests, type-parameterized tests // allow you to define the test pattern without knowing what the type // parameters are. The defined pattern can be instantiated with // different types any number of times, in any number of translation // units. // // If you are designing an interface or concept, you can define a // suite of type-parameterized tests to verify properties that any // valid implementation of the interface/concept should have. Then, // each implementation can easily instantiate the test suite to verify // that it conforms to the requirements, without having to write // similar tests repeatedly. Here's an example: #if 0 // First, define a fixture class template. It should be parameterized // by a type. Remember to derive it from testing::Test. template <typename T> class FooTest : public testing::Test { ... }; // Next, declare that you will define a type-parameterized test suite // (the _P suffix is for "parameterized" or "pattern", whichever you // prefer): TYPED_TEST_SUITE_P(FooTest); // Then, use TYPED_TEST_P() to define as many type-parameterized tests // for this type-parameterized test suite as you want. TYPED_TEST_P(FooTest, DoesBlah) { // Inside a test, refer to TypeParam to get the type parameter. TypeParam n = 0; ... } TYPED_TEST_P(FooTest, HasPropertyA) { ... } // Now the tricky part: you need to register all test patterns before // you can instantiate them. The first argument of the macro is the // test suite name; the rest are the names of the tests in this test // case. REGISTER_TYPED_TEST_SUITE_P(FooTest, DoesBlah, HasPropertyA); // Finally, you are free to instantiate the pattern with the types you // want. If you put the above code in a header file, you can #HelloWorld // it in multiple C++ source files and instantiate it multiple times. // // To distinguish different instances of the pattern, the first // argument to the INSTANTIATE_* macro is a prefix that will be added // to the actual test suite name. Remember to pick unique prefixes for // different instances. typedef testing::Types<char, int, unsigned int> MyTypes; INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes); // If the type list contains only one type, you can write that type // directly without Types<...>: // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, int); // // Similar to the optional argument of TYPED_TEST_SUITE above, // INSTANTIATE_TEST_SUITE_P takes an optional fourth argument which allows to // generate custom names. // INSTANTIATE_TYPED_TEST_SUITE_P(My, FooTest, MyTypes, MyTypeNames); #endif // 0 #include "gtest/internal/gtest-internal.h" #include "gtest/internal/gtest-port.h" #include "gtest/internal/gtest-type-util.h" // Implements typed tests. #if GTEST_HAS_TYPED_TEST // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the typedef for the type parameters of the // given test suite. #define GTEST_TYPE_PARAMS_(TestSuiteName) gtest_type_params_##TestSuiteName##_ // Expands to the name of the typedef for the NameGenerator, responsible for // creating the suffixes of the name. #define GTEST_NAME_GENERATOR_(TestSuiteName) \ gtest_type_params_##TestSuiteName##_NameGenerator #define TYPED_TEST_SUITE(CaseName, Types, ...) \ typedef ::testing::internal::GenerateTypeList<Types>::type \ GTEST_TYPE_PARAMS_(CaseName); \ typedef ::testing::internal::NameGeneratorSelector<__VA_ARGS__>::type \ GTEST_NAME_GENERATOR_(CaseName) #define TYPED_TEST(CaseName, TestName) \ static_assert(sizeof(GTEST_STRINGIFY_(TestName)) > 1, \ "test-name must not be empty"); \ template <typename gtest_TypeParam_> \ class GTEST_TEST_CLASS_NAME_(CaseName, TestName) \ : public CaseName<gtest_TypeParam_> { \ private: \ typedef CaseName<gtest_TypeParam_> TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ void TestBody() override; \ }; \ static bool gtest_##CaseName##_##TestName##_registered_ \ GTEST_ATTRIBUTE_UNUSED_ = ::testing::internal::TypeParameterizedTest< \ CaseName, \ ::testing::internal::TemplateSel<GTEST_TEST_CLASS_NAME_(CaseName, \ TestName)>, \ GTEST_TYPE_PARAMS_( \ CaseName)>::Register("", \ ::testing::internal::CodeLocation( \ __FILE__, __LINE__), \ GTEST_STRINGIFY_(CaseName), \ GTEST_STRINGIFY_(TestName), 0, \ ::testing::internal::GenerateNames< \ GTEST_NAME_GENERATOR_(CaseName), \ GTEST_TYPE_PARAMS_(CaseName)>()); \ template <typename gtest_TypeParam_> \ void GTEST_TEST_CLASS_NAME_(CaseName, \ TestName)<gtest_TypeParam_>::TestBody() // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define TYPED_TEST_CASE \ static_assert(::testing::internal::TypedTestCaseIsDeprecated(), ""); \ TYPED_TEST_SUITE #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_HAS_TYPED_TEST // Implements type-parameterized tests. #if GTEST_HAS_TYPED_TEST_P // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the namespace name that the type-parameterized tests for // the given type-parameterized test suite are defined in. The exact // name of the namespace is subject to change without notice. #define GTEST_SUITE_NAMESPACE_(TestSuiteName) gtest_suite_##TestSuiteName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE. // // Expands to the name of the variable used to remember the names of // the defined tests in the given test suite. #define GTEST_TYPED_TEST_SUITE_P_STATE_(TestSuiteName) \ gtest_typed_test_suite_p_state_##TestSuiteName##_ // INTERNAL IMPLEMENTATION - DO NOT USE IN USER CODE DIRECTLY. // // Expands to the name of the variable used to remember the names of // the registered tests in the given test suite. #define GTEST_REGISTERED_TEST_NAMES_(TestSuiteName) \ gtest_registered_test_names_##TestSuiteName##_ // The variables defined in the type-parameterized test macros are // static as typically these macros are used in a .h file that can be // #included in multiple translation units linked together. #define TYPED_TEST_SUITE_P(SuiteName) \ static ::testing::internal::TypedTestSuitePState \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define TYPED_TEST_CASE_P \ static_assert(::testing::internal::TypedTestCase_P_IsDeprecated(), ""); \ TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define TYPED_TEST_P(SuiteName, TestName) \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ template <typename gtest_TypeParam_> \ class TestName : public SuiteName<gtest_TypeParam_> { \ private: \ typedef SuiteName<gtest_TypeParam_> TestFixture; \ typedef gtest_TypeParam_ TypeParam; \ void TestBody() override; \ }; \ static bool gtest_##TestName##_defined_ GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).AddTestName( \ __FILE__, __LINE__, GTEST_STRINGIFY_(SuiteName), \ GTEST_STRINGIFY_(TestName)); \ } \ template <typename gtest_TypeParam_> \ void GTEST_SUITE_NAMESPACE_( \ SuiteName)::TestName<gtest_TypeParam_>::TestBody() // Note: this won't work correctly if the trailing arguments are macros. #define REGISTER_TYPED_TEST_SUITE_P(SuiteName, ...) \ namespace GTEST_SUITE_NAMESPACE_(SuiteName) { \ typedef ::testing::internal::Templates<__VA_ARGS__> gtest_AllTests_; \ } \ static const char* const GTEST_REGISTERED_TEST_NAMES_( \ SuiteName) GTEST_ATTRIBUTE_UNUSED_ = \ GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName).VerifyRegisteredTestNames( \ GTEST_STRINGIFY_(SuiteName), __FILE__, __LINE__, #__VA_ARGS__) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define REGISTER_TYPED_TEST_CASE_P \ static_assert(::testing::internal::RegisterTypedTestCase_P_IsDeprecated(), \ ""); \ REGISTER_TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define INSTANTIATE_TYPED_TEST_SUITE_P(Prefix, SuiteName, Types, ...) \ static_assert(sizeof(GTEST_STRINGIFY_(Prefix)) > 1, \ "test-suit-prefix must not be empty"); \ static bool gtest_##Prefix##_##SuiteName GTEST_ATTRIBUTE_UNUSED_ = \ ::testing::internal::TypeParameterizedTestSuite< \ SuiteName, GTEST_SUITE_NAMESPACE_(SuiteName)::gtest_AllTests_, \ ::testing::internal::GenerateTypeList<Types>::type>:: \ Register(GTEST_STRINGIFY_(Prefix), \ ::testing::internal::CodeLocation(__FILE__, __LINE__), \ &GTEST_TYPED_TEST_SUITE_P_STATE_(SuiteName), \ GTEST_STRINGIFY_(SuiteName), \ GTEST_REGISTERED_TEST_NAMES_(SuiteName), \ ::testing::internal::GenerateNames< \ ::testing::internal::NameGeneratorSelector< \ __VA_ARGS__>::type, \ ::testing::internal::GenerateTypeList<Types>::type>()) // Legacy API is deprecated but still available #ifndef GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #define INSTANTIATE_TYPED_TEST_CASE_P \ static_assert( \ ::testing::internal::InstantiateTypedTestCase_P_IsDeprecated(), ""); \ INSTANTIATE_TYPED_TEST_SUITE_P #endif // GTEST_REMOVE_LEGACY_TEST_CASEAPI_ #endif // GTEST_HAS_TYPED_TEST_P #endif // GTEST_INCLUDE_GTEST_GTEST_TYPED_TEST_H_
[ "unclejet@126.com" ]
unclejet@126.com
660e85a6eed609fcf3f46893d5ce9780eee043a2
cb6965abb99b51fa366b8bc086d93636e754e432
/src/pawn.cpp
d8842c9b3d5bff7b7161ee03b39d78c3cd651040
[]
no_license
bcm314/TogaII
2f4264c432a83b24548bbad0289e5f305c7aa21d
85bd65d0fd64866de4ebac6c3e5ae1c229b00fd5
refs/heads/master
2022-04-15T00:19:03.015199
2020-04-14T14:15:57
2020-04-14T14:15:57
255,625,424
1
1
null
null
null
null
UTF-8
C++
false
false
14,561
cpp
// pawn.cpp // includes #include <cstring> #include "board.h" #include "colour.h" #include "hash.h" #include "option.h" #include "pawn.h" #include "piece.h" #include "protocol.h" #include "square.h" #include "util.h" #include "search.h" // constants static const bool UseTable = true; static const uint32 TableSize = 16384; // was 16384 256kB tried 65536 // types typedef pawn_info_t entry_t; struct pawn_t { entry_t * table; uint32 size; uint32 mask; uint32 used; sint64 read_nb; sint64 read_hit; sint64 write_nb; sint64 write_collision; }; // constants and variables static /* const */ int PawnStructureWeight = 256; // 100% static const int DoubledOpening = 10; static const int DoubledEndgame = 20; static const int IsolatedOpening = 10; static const int IsolatedOpeningOpen = 20; static const int IsolatedEndgame = 20; static const int BackwardOpening = 8; static const int BackwardOpeningOpen = 16; static const int BackwardEndgame = 10; static const int CandidateOpeningMin = 5; static const int CandidateOpeningMax = 55; static const int CandidateEndgameMin = 10; static const int CandidateEndgameMax = 110; // this was moved to eval.cpp /* static const int PassedOpeningMin = 10; static const int PassedOpeningMax = 70; static const int PassedEndgameMin = 20; static const int PassedEndgameMax = 140; */ static /* const */ int Bonus[RankNb]; static /* const */ int FileBonus[FileNb]; // JD static /* const */ int RankBonus[FileNb]; // variables int BitEQ[16]; int BitLT[16]; int BitLE[16]; int BitGT[16]; int BitGE[16]; int BitFirst[0x100]; int BitLast[0x100]; int BitCount[0x100]; int BitRev[0x100]; static pawn_t Pawn[MaxThreads][1]; static int BitRank1[RankNb]; static int BitRank2[RankNb]; static int BitRank3[RankNb]; // prototypes static void pawn_comp_info (pawn_info_t * info, const board_t * board); // functions // pawn_init_bit() void pawn_init_bit() { int rank; int first, last, count; int b, rev; // rank-indexed Bit*[] for (rank = 0; rank < RankNb; rank++) { BitEQ[rank] = 0; BitLT[rank] = 0; BitLE[rank] = 0; BitGT[rank] = 0; BitGE[rank] = 0; BitRank1[rank] = 0; BitRank2[rank] = 0; BitRank3[rank] = 0; } for (rank = Rank1; rank <= Rank8; rank++) { BitEQ[rank] = 1 << (rank - Rank1); BitLT[rank] = BitEQ[rank] - 1; BitLE[rank] = BitLT[rank] | BitEQ[rank]; BitGT[rank] = BitLE[rank] ^ 0xFF; BitGE[rank] = BitGT[rank] | BitEQ[rank]; } for (rank = Rank1; rank <= Rank8; rank++) { BitRank1[rank] = BitEQ[rank+1]; BitRank2[rank] = BitEQ[rank+1] | BitEQ[rank+2]; BitRank3[rank] = BitEQ[rank+1] | BitEQ[rank+2] | BitEQ[rank+3]; } // bit-indexed Bit*[] for (b = 0; b < 0x100; b++) { first = Rank8; // HACK for pawn shelter last = Rank1; // HACK count = 0; rev = 0; for (rank = Rank1; rank <= Rank8; rank++) { if ((b & BitEQ[rank]) != 0) { if (rank < first) first = rank; if (rank > last) last = rank; count++; rev |= BitEQ[RANK_OPP(rank)]; } } BitFirst[b] = first; BitLast[b] = last; BitCount[b] = count; BitRev[b] = rev; } } // pawn_parameter() void pawn_parameter() { // UCI options PawnStructureWeight = (option_get_int("Pawn Structure") * 256 + 50) / 100; } // pawn_init() void pawn_init() { int rank, file, ThreadId; // UCI options pawn_parameter(); // bonus for (rank = 0; rank < RankNb; rank++) { Bonus[rank] = 0; RankBonus[rank] = 0; } for (file = 0; file < FileNb; file++) FileBonus[file] = 0; Bonus[Rank4] = 26; Bonus[Rank5] = 77; Bonus[Rank6] = 154; Bonus[Rank7] = 256; RankBonus[Rank4] = 2; RankBonus[Rank5] = 4; RankBonus[Rank6] = 8; RankBonus[Rank7] = 20; //FileBonus[FileA] = 0; //FileBonus[FileB] = 0; FileBonus[FileC] = 1; FileBonus[FileD] = 2; FileBonus[FileE] = 2; FileBonus[FileF] = 1; //FileBonus[FileG] = 0; //FileBonus[FileH] = 0; // pawn hash-table for (ThreadId = 0; ThreadId < NumberThreads; ThreadId++){ Pawn[ThreadId]->size = 0; Pawn[ThreadId]->mask = 0; Pawn[ThreadId]->table = NULL; } } // pawn_alloc() void pawn_alloc() { int ThreadId; ASSERT(sizeof(entry_t)==16); if (UseTable) { for (ThreadId = 0; ThreadId < NumberThreads; ThreadId++){ Pawn[ThreadId]->size = TableSize; Pawn[ThreadId]->mask = TableSize - 1; Pawn[ThreadId]->table = (entry_t *) my_malloc(Pawn[ThreadId]->size*sizeof(entry_t)); pawn_clear(ThreadId); } } } // pawn_free() void pawn_free() { int ThreadId; ASSERT(sizeof(entry_t)==16); if (UseTable) { for (ThreadId = 0; ThreadId < NumberThreads; ThreadId++){ my_free(Pawn[ThreadId]->table); } } } // pawn_clear() void pawn_clear(int ThreadId) { if (Pawn[ThreadId]->table != NULL) { memset(Pawn[ThreadId]->table,0,Pawn[ThreadId]->size*sizeof(entry_t)); } Pawn[ThreadId]->used = 0; Pawn[ThreadId]->read_nb = 0; Pawn[ThreadId]->read_hit = 0; Pawn[ThreadId]->write_nb = 0; Pawn[ThreadId]->write_collision = 0; } // pawn_get_info() void pawn_get_info(pawn_info_t * info, const board_t * board, int ThreadId) { uint64 key; entry_t * entry; ASSERT(info!=NULL); ASSERT(board!=NULL); // probe if (UseTable) { Pawn[ThreadId]->read_nb++; key = board->pawn_key; entry = &Pawn[ThreadId]->table[KEY_INDEX(key)&Pawn[ThreadId]->mask]; if (entry->lock == KEY_LOCK(key)) { // found Pawn[ThreadId]->read_hit++; *info = *entry; return; } } // calculation pawn_comp_info(info,board); // store if (UseTable) { Pawn[ThreadId]->write_nb++; if (entry->lock == 0) { // HACK: assume free entry Pawn[ThreadId]->used++; } else { Pawn[ThreadId]->write_collision++; } *entry = *info; entry->lock = KEY_LOCK(key); } } // pawn_comp_info() static void pawn_comp_info(pawn_info_t * info, const board_t * board) { int colour; int file, rank; int me, opp; const sq_t * ptr; int sq; bool backward, candidate, doubled, isolated, open, passed; int t1, t2; int n; int bits; int support; int pawn_support[ColourNb]; int opening[ColourNb], endgame[ColourNb]; int flags[ColourNb]; int file_bits[ColourNb]; int passed_bits[ColourNb]; int single_file[ColourNb]; ASSERT(info!=NULL); ASSERT(board!=NULL); // pawn_file[] #if DEBUG for (colour = 0; colour < ColourNb; colour++) { int pawn_file[FileNb]; me = colour; for (file = 0; file < FileNb; file++) { pawn_file[file] = 0; } for (ptr = &board->pawn[me][0]; (sq=*ptr) != SquareNone; ptr++) { file = SQUARE_FILE(sq); rank = PAWN_RANK(sq,me); ASSERT(file>=FileA&&file<=FileH); ASSERT(rank>=Rank2&&rank<=Rank7); pawn_file[file] |= BIT(rank); } for (file = 0; file < FileNb; file++) { if (board->pawn_file[colour][file] != pawn_file[file]) my_fatal("board->pawn_file[][]\n"); } } #endif // init for (colour = 0; colour < ColourNb; colour++) { opening[colour] = 0; endgame[colour] = 0; pawn_support[colour] = 0; flags[colour] = 0; file_bits[colour] = 0; passed_bits[colour] = 0; single_file[colour] = SquareNone; } // features and scoring for (colour = 0; colour < ColourNb; colour++) { me = colour; opp = COLOUR_OPP(me); for (ptr = &board->pawn[me][0]; (sq=*ptr) != SquareNone; ptr++) { // init file = SQUARE_FILE(sq); rank = PAWN_RANK(sq,me); ASSERT(file>=FileA&&file<=FileH); ASSERT(rank>=Rank2&&rank<=Rank7); // flags file_bits[me] |= BIT(file); if (rank == Rank2) flags[me] |= BackRankFlag; // features // pawn support/duos support = 0; if (me == White){ if (board->square[sq+1] == WP || board->square[sq-1] == WP)support += 2; if (board->square[sq+15] == WP || board->square[sq+17] == WP)support += 1; else if (board->square[sq-15] == WP || board->square[sq-17] == WP)support += 1; } else { if (board->square[sq+1] == BP || board->square[sq-1] == BP)support += 2; if (board->square[sq+15] == BP || board->square[sq+17] == BP)support += 1; else if (board->square[sq-15] == BP || board->square[sq-17] == BP)support += 1; } if (support > 0){ support += FileBonus[file]; support += RankBonus[rank]; pawn_support[me] += support; } backward = false; candidate = false; doubled = false; isolated = false; open = false; passed = false; t1 = board->pawn_file[me][file-1] | board->pawn_file[me][file+1]; t2 = board->pawn_file[me][file] | BitRev[board->pawn_file[opp][file]]; // doubled if ((board->pawn_file[me][file] & BitLT[rank]) != 0) { doubled = true; } // isolated and backward if (t1 == 0) { isolated = true; } else if ((t1 & BitLE[rank]) == 0) { backward = true; // really backward? if ((t1 & BitRank1[rank]) != 0) { ASSERT(rank+2<=Rank8); if (((t2 & BitRank1[rank]) | ((BitRev[board->pawn_file[opp][file-1]] | BitRev[board->pawn_file[opp][file+1]]) & BitRank2[rank])) == 0) { backward = false; } } else if (rank == Rank2 && ((t1 & BitEQ[rank+2]) != 0)) { ASSERT(rank+3<=Rank8); if (((t2 & BitRank2[rank]) | ((BitRev[board->pawn_file[opp][file-1]] | BitRev[board->pawn_file[opp][file+1]]) & BitRank3[rank])) == 0) { backward = false; } } } // open, candidate and passed if ((t2 & BitGT[rank]) == 0) { open = true; if (((BitRev[board->pawn_file[opp][file-1]] | BitRev[board->pawn_file[opp][file+1]]) & BitGT[rank]) == 0) { passed = true; passed_bits[me] |= BIT(file); } else { // candidate? n = 0; n += BIT_COUNT(board->pawn_file[me][file-1]&BitLE[rank]); n += BIT_COUNT(board->pawn_file[me][file+1]&BitLE[rank]); n -= BIT_COUNT(BitRev[board->pawn_file[opp][file-1]]&BitGT[rank]); n -= BIT_COUNT(BitRev[board->pawn_file[opp][file+1]]&BitGT[rank]); if (n >= 0) { // safe? n = 0; n += BIT_COUNT(board->pawn_file[me][file-1]&BitEQ[rank-1]); n += BIT_COUNT(board->pawn_file[me][file+1]&BitEQ[rank-1]); n -= BIT_COUNT(BitRev[board->pawn_file[opp][file-1]]&BitEQ[rank+1]); n -= BIT_COUNT(BitRev[board->pawn_file[opp][file+1]]&BitEQ[rank+1]); if (n >= 0) candidate = true; } } } // score if (doubled) { opening[me] -= DoubledOpening; endgame[me] -= DoubledEndgame; } if (isolated) { if (open) { opening[me] -= IsolatedOpeningOpen; endgame[me] -= IsolatedEndgame; } else { opening[me] -= IsolatedOpening; endgame[me] -= IsolatedEndgame; } } if (backward) { if (open) { opening[me] -= BackwardOpeningOpen; endgame[me] -= BackwardEndgame; } else { opening[me] -= BackwardOpening; endgame[me] -= BackwardEndgame; } } if (candidate) { opening[me] += quad(CandidateOpeningMin,CandidateOpeningMax,rank); endgame[me] += quad(CandidateEndgameMin,CandidateEndgameMax,rank); } // this was moved to the dynamic evaluation /* if (passed) { opening[me] += quad(PassedOpeningMin,PassedOpeningMax,rank); endgame[me] += quad(PassedEndgameMin,PassedEndgameMax,rank); } */ } // pawn duos / support opening[me] += pawn_support[me]/2; endgame[me] += pawn_support[me]/2; } // store info info->opening = ((opening[White] - opening[Black]) * PawnStructureWeight) / 256; info->endgame = ((endgame[White] - endgame[Black]) * PawnStructureWeight) / 256; for (colour = 0; colour < ColourNb; colour++) { me = colour; opp = COLOUR_OPP(me); // draw flags bits = file_bits[me]; if (bits != 0 && (bits & (bits-1)) == 0) { // one set bit file = BIT_FIRST(bits); rank = BIT_FIRST(board->pawn_file[me][file]); ASSERT(rank>=Rank2); if (((BitRev[board->pawn_file[opp][file-1]] | BitRev[board->pawn_file[opp][file+1]]) & BitGT[rank]) == 0) { rank = BIT_LAST(board->pawn_file[me][file]); single_file[me] = SQUARE_MAKE(file,rank); } } info->flags[colour] = flags[colour]; info->passed_bits[colour] = passed_bits[colour]; info->single_file[colour] = single_file[colour]; } } // quad() int quad(int y_min, int y_max, int x) { int y; ASSERT(y_min>=0&&y_min<=y_max&&y_max<=+32767); ASSERT(x>=Rank2&&x<=Rank7); y = y_min + ((y_max - y_min) * Bonus[x] + 128) / 256; ASSERT(y>=y_min&&y<=y_max); return y; } // end of pawn.cpp
[ "bcm314-github@yahoo.de" ]
bcm314-github@yahoo.de
bcd20963c778831d544b50ce4d6d420e35271788
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/curl/gumtree/curl_repos_function_527_last_repos.cpp
1a33ca68ce43afd4c90db86866506235796540cf
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,008
cpp
int test(char *URL) { CURL *c = NULL; CURLM *m = NULL; int res = 0; int running; start_test_timing(); global_init(CURL_GLOBAL_ALL); easy_init(c); easy_setopt(c, CURLOPT_URL, URL); multi_init(m); multi_add_handle(m, c); for(;;) { struct timeval timeout; fd_set fdread, fdwrite, fdexcep; int maxfd = -99; timeout.tv_sec = 0; timeout.tv_usec = 100000L; /* 100 ms */ multi_perform(m, &running); abort_on_test_timeout(); if(!running) break; /* done */ FD_ZERO(&fdread); FD_ZERO(&fdwrite); FD_ZERO(&fdexcep); multi_fdset(m, &fdread, &fdwrite, &fdexcep, &maxfd); /* At this point, maxfd is guaranteed to be greater or equal than -1. */ select_test(maxfd + 1, &fdread, &fdwrite, &fdexcep, &timeout); abort_on_test_timeout(); } test_cleanup: /* proper cleanup sequence - type PA */ curl_multi_remove_handle(m, c); curl_multi_cleanup(m); curl_easy_cleanup(c); curl_global_cleanup(); return res; }
[ "993273596@qq.com" ]
993273596@qq.com
98598bde9926591d646f03e1dadc6ecda30abcc3
46b4fff7a14147354e80662c6b0c9b3f79cc5046
/src/receive_send.ino
085213b810f84598adc29cfe3e88e39fee184564
[]
no_license
perivar/rcswitch-testing
1aabd647abfc09ecb04a6f1676b05251837df459
0a355f0c7f6209c727f15655b1799296152fa092
refs/heads/master
2021-05-09T04:31:05.891171
2018-02-03T14:41:11
2018-02-03T14:41:11
119,277,394
0
0
null
null
null
null
UTF-8
C++
false
false
3,228
ino
/* Example for sending and receiving Modified library to support Nexa and Everflourish https://github.com/perivar/rc-switch https://z4ziggy.wordpress.com/2014/06/27/rf-sniffer-open-gates-cars-and-rf-remote-controlled-devices-with-ease/ If you want to visualize a telegram copy the rawBits data and paste it into http://test.sui.li/oszi/ */ #include <Arduino.h> #include <RCSwitch.h> RCSwitch mySwitch = RCSwitch(); // pins for the 433 Mhz module int rxPin = 2; int txPin = 10; unsigned long previousMillis = 0; const long waitInterval = 15000; void setup() { // print fast to console Serial.begin(115200); // Receiver on interrupt 0 => that is pin #2 mySwitch.enableReceive(digitalPinToInterrupt(rxPin)); // Transmitter is connected to Arduino Pin #10 mySwitch.enableTransmit(txPin); Serial.println("[+] Listening"); } void loop() { if (mySwitch.available()) { Serial.print("Received "); Serial.print(mySwitch.getReceivedValue()); Serial.print(" / "); Serial.print(mySwitch.getReceivedBitlength()); Serial.print("bit "); Serial.print("Protocol: "); Serial.println(mySwitch.getReceivedProtocol()); Serial.print("Raw timing data: "); unsigned int *rawTimings = mySwitch.getReceivedRawdata(); for (unsigned int i = 0; i < mySwitch.getReceivedBitlength() * 2; i++) { Serial.print(rawTimings[i]); Serial.print(","); } Serial.println(); Serial.print("Raw bitdata: "); char *rawBits = mySwitch.getReceivedRawBits(); for (unsigned int i = 0; i < mySwitch.getReceivedBitlength(); i++) { Serial.print(rawBits[i]); } Serial.println(); mySwitch.resetAvailable(); } unsigned long currentMillis = millis(); if (currentMillis - previousMillis > waitInterval) { // save the last time you entered this routine previousMillis = currentMillis; // 8 = Nexa // 9 = Everflourish mySwitch.setProtocol(8); // Nexa repeats 10 times. mySwitch.setRepeatTransmit(10); const char *nexaCode = "1001100101101010100101101010011001011001100110100110010110101010"; Serial.print("Sending Nexa: "); Serial.print(strlen(nexaCode)); Serial.print(" bits."); Serial.println(); mySwitch.send(nexaCode); delay(1000); // 8 = Nexa // 9 = Everflourish mySwitch.setProtocol(9); // Everflourish repeates only 4 times. mySwitch.setRepeatTransmit(4); const char *everflourish4On = "0000011010100110100101100110010110101010100110101010"; Serial.print("Sending 4 ON: "); Serial.print(strlen(everflourish4On)); Serial.print(" bits."); Serial.println(); mySwitch.send(everflourish4On); delay(2000); const char *everflourish4Off = "0000011010100110100101100110010110101010100101010101"; Serial.print("Sending 4 OFF: "); Serial.print(strlen(everflourish4Off)); Serial.print(" bits."); Serial.println(); mySwitch.send(everflourish4Off); } }
[ "perivar@nerseth.com" ]
perivar@nerseth.com
6630c97aa9093a725b240407a01160314a078a99
4a39209fd473b5b4536d558c9787020cadccfd1c
/shortcut/llvm_ch5/Cpu0ISelDAGToDAG.cpp
f065161fa32f38249536a01bd02e9bb36cf51224
[]
no_license
elliott-wen/LLVM_for_cpu0
f6d91b80c31724d6b8b463dc320b8142a1485c56
295d1f9c9fdd298860645c70bc70356d46c0ac2d
refs/heads/main
2023-06-09T06:47:49.425551
2021-06-28T09:42:20
2021-06-28T09:42:20
380,849,425
0
0
null
2021-06-27T22:26:37
2021-06-27T22:26:36
null
UTF-8
C++
false
false
4,591
cpp
//===-- Cpu0ISelDAGToDAG.cpp - A DAG to DAG Inst Selector for Cpu0 -*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an instruction selector for the Cpu0 target. // //===----------------------------------------------------------------------===// #include "Cpu0ISelDAGToDAG.h" #include "Cpu0.h" #include "Cpu0MachineFunctionInfo.h" #include "Cpu0RegisterInfo.h" #include "Cpu0SEISelDAGToDAG.h" #include "Cpu0TargetMachine.h" #include "llvm/CodeGen/MachineConstantPool.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/SelectionDAGISel.h" #include "llvm/CodeGen/SelectionDAGNodes.h" #include "llvm/IR/CFG.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Intrinsics.h" #include "llvm/IR/Type.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Target/TargetMachine.h" using namespace llvm; #define DEBUG_TYPE "cpu0-isel" //===----------------------------------------------------------------------===// // Instruction Selector Implementation //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // CPU0 specific code to select CPU0 machine instructions // for SelectionDAG operations. //===----------------------------------------------------------------------===// bool Cpu0DAGToDAGISel::runOnMachineFunction(MachineFunction &MF) { bool Ret = SelectionDAGISel::runOnMachineFunction(MF); return Ret; } // Complex Pattern used on Cpu0InstrInfo // Used on Cpu0 Load/Store instructions bool Cpu0DAGToDAGISel::SelectAddr(SDNode *Parent, SDValue Addr, SDValue &Base, SDValue &Offset) { EVT ValTy = Addr.getValueType(); SDLoc DL(Addr); // If Parent is an unaligned f32 load or store, select a (base + index) // float point load/store instruction (luxcl or suxcl) const LSBaseSDNode *LS = 0; if (Parent && (LS = dyn_cast<LSBaseSDNode>(Parent))) { EVT VT = LS->getMemoryVT(); if (VT.getSizeInBits() / 8 > LS->getAlignment()) { assert(false && "Unaligned loads/stores not supported for this type."); if (VT == MVT::f32) return false; } } // If address is FI, get the TargetFrameIndex. if (FrameIndexSDNode *FIN = dyn_cast<FrameIndexSDNode>(Addr)) { Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), ValTy); Offset = CurDAG->getTargetConstant(0, DL, ValTy); return true; } // on PIC code Load GA if (Addr.getOpcode() == Cpu0ISD::Wrapper) { Base = Addr.getOperand(0); Offset = Addr.getOperand(1); return true; } // static if (TM.getRelocationModel() != Reloc::PIC_) { if ((Addr.getOpcode() == ISD::TargetExternalSymbol || Addr.getOpcode() == ISD::TargetGlobalAddress)) return false; } Base = Addr; Offset = CurDAG->getTargetConstant(0, DL, ValTy); return true; } // Select instructions not customized! // Used for expended, promoted and normal instructions void Cpu0DAGToDAGISel::Select(SDNode *Node) { unsigned Opcode = Node->getOpcode(); // Dump information about the Node being selected LLVM_DEBUG(errs() << "Selecting: "; Node->dump(CurDAG); errs() << "\n"); // If we have a custom node, we already have selected. if (Node->isMachineOpcode()) { LLVM_DEBUG(errs() << "== "; Node->dump(CurDAG); errs() << "\n"); Node->setNodeId(-1); return; } // See if subclasses (e.g. SEISelDAGToDAG) can handle this node. if (trySelect(Node)) return; switch(Opcode) { default: break; // Get target GOT address. case ISD::GLOBAL_OFFSET_TABLE: ReplaceNode(Node, getGlobalBaseReg()); return; } // Select the default instruction defined in Cpu0GenDAGISel.inc SelectCode(Node); } // Output the instructions required to put the GOT address into a register. SDNode *Cpu0DAGToDAGISel::getGlobalBaseReg() { unsigned GlobalBaseReg = MF->getInfo<Cpu0MachineFunctionInfo>()->getGlobalBaseReg(); return CurDAG->getRegister(GlobalBaseReg, getTargetLowering()->getPointerTy( CurDAG->getDataLayout())) .getNode(); }
[ "dicksonliuming@gmail.com" ]
dicksonliuming@gmail.com
52858353180e9b995eb4a30e08fc76a3351b5fd1
55cf4bf18ed297235d1acf680fb8d23bf0456647
/questions/poj/1469_dfs.cpp
2fdaaec59add318b37a5673024d4cad338c12d0d
[]
no_license
sequix/algorithm
82186891c56bb74182e2849ece00464bb0f85aa4
1b47637e517d9bb49ea63945dd282cd8e9d7b5bf
refs/heads/master
2021-01-12T08:55:11.475288
2017-05-24T13:38:23
2017-05-24T13:38:23
76,718,512
1
0
null
null
null
null
UTF-8
C++
false
false
1,548
cpp
// POJ No.1469 二分图最大匹配 匈牙利DFS算法O(VE) (408K 469MS) // 找左侧点的右侧点进行匹配 // 若右侧点已被匹配,递归地找该右侧点匹配的左侧点下一个右侧点进行匹配 // 来把当前点需要的右侧点让出来为止 #include <cstdio> #include <cstring> using namespace std; int p, n; // 左右集合的大小 bool vis[310]; // vis[i] 右侧i是否被访问过 char G[110][310]; // G[1][1] 代表边 左1->右1,仅保存左到右的边 int cx[110]; // cx[i] 左i与右cx[i]配对,可以省掉 int cy[310]; // cy[i] 右i与左cy[i]配对 int dfs(int u) { for(int i = 1; i <= n; ++i) { if(G[u][i] && !vis[i]) { vis[i] = 1; if(cy[i] == -1 || dfs(cy[i])) { cy[i] = u; cx[u] = i; return 1; } } } return 0; } int maxmatch() { int ans = 0; memset(cx, -1, sizeof(cx)); memset(cy, -1, sizeof(cy)); for(int i = 1; i <= p; ++i) { if(cx[i] == -1) { memset(vis, 0, sizeof(vis)); ans += dfs(i); } } return ans; } int main() { int T, nn, u; for(scanf("%d", &T); T > 0; --T) { memset(G, 0, sizeof(G)); scanf("%d%d", &p, &n); for(int i = 1; i <= p; ++i) { for(scanf("%d", &nn); nn > 0; --nn) { scanf("%d", &u); G[i][u] = 1; } } puts(maxmatch() >= p ? "YES" : "NO"); } }
[ "sequix@163.com" ]
sequix@163.com
e3421cec0c163f31f28f007f9aba431570eea4d7
6784af4571bdd17351869173eb0830941bdbd125
/AppFrame/AppAlgoEnergyVisual.h
65b5510e68d953cdf355baebf776d840dc228878
[]
no_license
helloppt211/MicrographyQRCodes
ffcbaa649eecdeec42df179c418a27cccceadf73
5ca574426f99363de2d0d01b0f8a4e3b50b4f547
refs/heads/master
2022-12-10T12:49:27.522745
2019-04-02T19:04:31
2019-04-02T19:04:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,804
h
#pragma once #include "stdafx.h" #include "AppAlgoEnergyTextSpace.h" public class AppAlgoEnergyVisual { public: AppAlgoEnergyVisual(HKCAppItem^ _appitem) {initial(_appitem); } ~AppAlgoEnergyVisual() {} /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Algorithm Operations */ /*! \{ */ /// Perform visual quality energy evaluate bool initial(HKCAppItem^ _appItem); /*! \} */ /*---------------------------------------------------------------------*/ /*! \name Access Methods */ /*! \{ */ double getEs(){return m_Es;} double getEc(){return m_Ec;} double getEss(){return m_Ess;} double getEt(){return m_Et;} double getEws(){return m_Ews;} double getEls(){return m_Els;} double getEcs(){return m_Ecs;} double getEca(){return m_Eca;} public: double EvaluateVisualEnergy(HKCWordArtData& word_art); double EvaluateLocalVisualEnergy(QRWordArt::QRStringLine& spline,QRWordArt::QRStringLine::QRSample& qr_sample); double EvaluateSplineEnergy(QRWordArt::QRStringLines& spline); double EvaluateLineSpace(QRWordArt::QRStringLines& splines); double EvaluateSingleLineSpace(QRWordArt::QRStringLines& splines,QRWordArt::QRStringLine* spline); double EvaluateFittingEdge(QRWordArt::QRStringLines& splines); double EvaluateFittingEdge(QRWordArt::QRStringLines& splines,int region_id); double EvaluateTextEnergy(QRWordArt::QRStringLines& splines,double _sigma=0.5); double EvaluateTextEnergy(QRWordArt::QRStringLine& spline,double _sigma=0.5); double EvaluateLetterSpace(QRWordArt::QRStringLines& splines); double EvaluateWordSpace(QRWordArt::QRStringLines& splines); double EvaluateCharStructure(QRWordArt::QRStringLines& splines); double EvaluateCharStructure(QRWordArt::QRCharacter::Char* qr_char, HSSSpline::Scale3& size); double EvaluateCharArea(QRWordArt::QRStringLines& splines); double EvaluateCharArea(QRWordArt::QRCharacter::Char* qr_char, HSSSpline::Scale3& size); private: vector<double> findnearest(HSSSpline::PathPoint<2>& ori_p,HSSSpline::PathPoint<2>& normal, cv::Mat& nearlinemap,double step); private: double m_Es; double m_Ec,m_Ess; double m_Et; double m_Ews,m_Els; double m_Ecs; double m_Eca; AppAlgoEnergyTextSpace m_TextEnergy; int img_height; int img_width; QRWordArt::QRStringLines* edge_splines; cv::Mat segment_img_RGB; cv::Mat total_segment; std::vector<cv::Mat> region_segs; std::vector<std::vector<cv::Point2i>> region_points; };
[ "hungsh@oregonstate.edu" ]
hungsh@oregonstate.edu
1c3676516e3b3540a3ed0b97315d7d25f3d1dc20
685a061b13558607e0502c6e1d012578bc1db157
/Learn-CPP/Day-05/array_uses.cpp
e84e7e772e2853c52691d24d2eb606e63f8d336c
[]
no_license
dotQuestionmark/git-github-fundamentals-mukeshgurpude
59119732e929349400fd46be963f5b3c31733f47
544360a650d63d9f6d37c6d6cabb4d8245befd73
refs/heads/main
2023-04-02T04:18:02.990646
2021-04-06T18:12:55
2021-04-06T18:12:55
353,628,427
1
0
null
2021-04-06T18:04:00
2021-04-01T08:25:25
C++
UTF-8
C++
false
false
385
cpp
// sum of array elements #include<iostream> using namespace std; int main(void){ int n; cout<<"What's the size of your array: "; cin>>n; int arr[n]; cout<<"\nDrop in "<<n<<" elements separated by space: "; for(int i=0; i<n; i++){ cin>>arr[i]; } int sum = 0; for(int i=0; i<n; i++) sum+=arr[i]; cout<<"\nSum of your array elements is: "<<sum; return 0; }
[ "mukeshgurpude02@gmail.com" ]
mukeshgurpude02@gmail.com
a880f67659d74cd5b7db7f3f04ea2ca94cb22b8b
2389f5c4960610e8577661d94eb7b82753c70a98
/week-3-bewegendebal/wall.hpp
8a1c71d84e1796ce9282455ed30cb3fd761c1af5
[]
no_license
vincevannoort/opdrachten-cpp
590c0d9324d1f29d564779db4c4cc607f8f0c086
1d5c7a8b4a4e6a45793a3268a2d627dd5ab6ece1
refs/heads/master
2021-01-20T01:46:10.879373
2017-05-31T09:31:45
2017-05-31T09:31:45
89,328,184
2
0
null
null
null
null
UTF-8
C++
false
false
302
hpp
#ifndef WALL_HPP #define WALL_HPP #include "rectangle.hpp" class wall: public rectangle { private: bool filled; int update_interval, update_count; public: wall(window & w, const vector & start, const vector & end, const int & update_interval); void draw(); void update(); }; #endif // WALL_HPP
[ "vince.vannoort@student.hu.nl" ]
vince.vannoort@student.hu.nl
e2b19d303d47a3860d0d8019b4ef6165362a37d4
4130b36e09feb24f16bdbbc1fa3e1d6659c0d439
/congcongclient/Classes/GamePlaza/HomeScene/CreateRoomPanel/GPHomeRoomListPanel_TLJ.h
1729c12b55147d7d6f5728b30038cf80f7b5b3bc
[ "MIT" ]
permissive
cnceo/18_TTL
b48eaf46f93b289047769a89bbdb749c14720a42
c8fc3fe7b7a0acad2b2cb5e80e96219b6257f0e4
refs/heads/master
2020-04-09T04:01:14.354570
2018-12-01T06:44:23
2018-12-01T06:44:23
null
0
0
null
null
null
null
GB18030
C++
false
false
1,188
h
#pragma once #include "cocos2d.h" #include "Game/FV/FvSingleton.h" #include "Game/FV/FvMask.h" #include "Game/Game/GameDefine.h" #include "Game/Widget/WidgetFun.h" #include "Game/Widget/WidgetManager.h" #include "Game/Widget/WidgetScenceXmlParse.h" class GPHomeRoomListPanel_TLJ : public cocos2d::Node , public FvSingleton<GPHomeRoomListPanel_TLJ> { public: GPHomeRoomListPanel_TLJ(); ~GPHomeRoomListPanel_TLJ(); public: bool init(); void initListView(); void initButton(); public: void show(); void hide(); public: void Button_Close(cocos2d::Ref*, WidgetUserInfo*); void Button_Refresh(cocos2d::Ref*, WidgetUserInfo*); void Button_Join(cocos2d::Ref*, WidgetUserInfo*); void Button_CreateRoom(cocos2d::Ref*, WidgetUserInfo*); void onSelectedItemEvent(cocos2d::Ref *pSender, cocos2d::ui::ListView::EventType type); void RefreshListView(void * data, size_t iDataSize); void setGameRuleIdex(int iIdex); void Button_JionRomByIDLeft(cocos2d::Ref*,WidgetUserInfo*); void Button_JionRomByIDRight(cocos2d::Ref*,WidgetUserInfo*); private: int m_CurrentModeIndex; //支付方式 int m_CurrentRuleIndex; //规则 time_t m_lastTime; };
[ "taotingfu819@163.com" ]
taotingfu819@163.com
b19b86d801ba5f2f64947241c224cac3044fa609
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/content/public/test/media_start_stop_observer.h
7594c3f8491a3b6fc5ce409ff9d71b290b0f791e
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
1,254
h
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef CONTENT_PUBLIC_TEST_MEDIA_START_STOP_OBSERVER_H_ #define CONTENT_PUBLIC_TEST_MEDIA_START_STOP_OBSERVER_H_ #include "base/macros.h" #include "base/run_loop.h" #include "content/public/browser/web_contents_observer.h" namespace content { class WebContents; // Used in tests to wait for media in a WebContents to start or stop playing. class MediaStartStopObserver : public WebContentsObserver { public: enum class Type { kStart, kStop }; MediaStartStopObserver(WebContents* web_contents, Type type); ~MediaStartStopObserver() override; // WebContentsObserver implementation. void MediaStartedPlaying(const MediaPlayerInfo& info, const MediaPlayerId& id) override; void MediaStoppedPlaying( const MediaPlayerInfo& info, const MediaPlayerId& id, WebContentsObserver::MediaStoppedReason reason) override; void Wait(); private: base::RunLoop run_loop_; const Type type_; DISALLOW_COPY_AND_ASSIGN(MediaStartStopObserver); }; } // namespace content #endif // CONTENT_PUBLIC_TEST_MEDIA_START_STOP_OBSERVER_H_
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
bcbca262758083d8b088d9066468a35628646c18
76863a6b86f78da9050ed89e6161a94340d3ec38
/RHI/Renderer/GLRenderer.cpp
4495fb2edda03ffc372a8c8649768b1a45984b1f
[]
no_license
Schuket/FrogEngine
49da7d73a9f1656fa86e8519d2ee0107812cce03
277037dd7d88220580ac094debcf0041068371c2
refs/heads/master
2020-04-26T14:59:17.908231
2019-04-05T09:11:43
2019-04-05T09:11:43
173,633,083
1
0
null
null
null
null
UTF-8
C++
false
false
10,493
cpp
#include "GLRenderer.h" #include "../Error/RHIError.h" namespace FrogEngine { namespace OPENGL { int feRenderer::ClearBuffers(Math::Vector4d color) { Error error; glClearColor(color.X(), color.Y(), color.Z(), color.W()); std::vector<GLbitfield> masks; masks.push_back(GL_COLOR_BUFFER_BIT); masks.push_back(GL_DEPTH_BUFFER_BIT); error = RHIGLClear(masks); if (error) return error; return Error::RHI_SUCCESS; } int feRenderer::InitViewport(Math::Vector2d sizeWindow) { Error error; error = RHIGLInitViewport(0, 0, (GLsizei)sizeWindow.X(), (GLsizei)sizeWindow.Y()); if (error) return error; return Error::RHI_SUCCESS; } int feRenderer::InitDepthStencil() { Error error; error = RHIGlewInit(); if (error) return error; error = RHIGLEnable(GL_DEPTH_TEST); if (error) return error; error = RHIGLEnable(GL_FRAMEBUFFER_SRGB); if (error) return error; error = RHIGLDepthFunc(GL_LEQUAL); if (error) return error; glClearDepth(1.f); return Error::RHI_SUCCESS; } int feRenderer::SetPolygonMode(PolygonMode mode) { int error = 0; switch (mode) { case PolygonMode::FILL: error = RHIGLPolygonMode(GL_FRONT_AND_BACK, GL_FILL); if (error) return error; break; case PolygonMode::LINE: error = RHIGLPolygonMode(GL_FRONT_AND_BACK, GL_LINE); if (error) return error; break; case PolygonMode::POINTS: error = RHIGLPolygonMode(GL_FRONT_AND_BACK, GL_POINT); if (error) return error; break; default: return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::SetPolygonMode : Mode is not valid."); } return RHI_SUCCESS; } int feRenderer::SetDepthMode(DepthMode mode) { int error = 0; switch (mode) { case DepthMode::LESS: error = RHIGLDepthFunc(GL_LESS); if (error) return error; break; case DepthMode::LEQUAL: error = RHIGLDepthFunc(GL_LEQUAL); if (error) return error; break; default: return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::SetPolygonMode : Mode is not valid."); } return RHI_SUCCESS; } int feRenderer::Draw(size_t count, TypeDraw typeDraw, TypePolygon typePoly) { Error error; if (typeDraw == TypeDraw::DRAW) { error = RHIGLDrawArrays(ConvertTypePolygon(typePoly), 0, (GLsizei)count); if (error) return error; } else if (typeDraw == TypeDraw::DRAW_ELEMENT) { error = RHIGLDrawElements(ConvertTypePolygon(typePoly), (GLsizei)count, GL_UNSIGNED_SHORT, nullptr); if (error) return error; } else if (typeDraw == TypeDraw::DRAW_INDEXED) { error = RHIGLDrawElementBaseVertex(ConvertTypePolygon(typePoly), (GLsizei)count, GL_UNSIGNED_SHORT, nullptr, 0); if (error) return error; } return Error::RHI_SUCCESS; } //private GLenum feRenderer::ConvertTypePolygon(TypePolygon typePoly) { switch (typePoly) { case TypePolygon::POINTS: return GL_POINTS; case TypePolygon::LINES: return GL_LINES; case TypePolygon::PATCHES: return GL_PATCHES; case TypePolygon::TRIANGLES: return GL_TRIANGLES; default: return GL_NONE; } } Error feRenderer::RHIGlewInit() { glewExperimental = GL_TRUE; GLenum error = glewInit(); if (error != GLEW_OK) return RHIError::CastError(Error::RHI_UNKNOWN_ERROR, WARNING, "feRenderer::RHIGlewInit : glewInit error"); return RHI_SUCCESS; } Error feRenderer::RHIGLInitViewport(GLint x, GLint y, GLsizei width, GLsizei height) { glViewport(x, y, width, height); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_VALUE) return RHIError::CastError(Error::RHI_INVALID_VALUE, WARNING, "feRenderer::RHIGLInitViewport : Either width or height is negative."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLInitViewport");; } Error feRenderer::RHIGLClear(std::vector<GLbitfield> masks) { for (int idx = 0; idx < masks.size(); ++idx) { glClear(masks[idx]); GLenum error = glGetError(); if (error == GL_INVALID_VALUE) return RHIError::CastError(Error::RHI_INVALID_VALUE, RHIPriority::WARNING, "feRenderer::RHIGLClear : Any bit other than the three defined bits is set in mask."); } return Error::RHI_SUCCESS; } Error feRenderer::RHIGLMatrixMode(GLenum mode) { glMatrixMode(mode); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_ENUM) return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::RHIGLMatrixMode : Mode is not an accepted value."); else if (error == GL_INVALID_OPERATION) return RHIError::CastError(Error::RHI_INVALID_OPERATION, WARNING, "feRenderer::RHIGLMatrixMode : glMatrixMode is executed between the execution of glBegin and the corresponding execution of glEnd."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLMatrixMode"); } Error feRenderer::RHIGLFrustum(GLdouble left, GLdouble right, GLdouble bottom, GLdouble top, GLdouble nearVal, GLdouble farVal) { glFrustum(left, right, bottom, top, nearVal, farVal); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_VALUE) return RHIError::CastError(Error::RHI_INVALID_VALUE, WARNING, "feRenderer::RHIGLFrustum : nearVal or farVal is not positive, or if left = right, or bottom = top, or near = far."); else if (error == GL_INVALID_OPERATION) return RHIError::CastError(Error::RHI_INVALID_OPERATION, WARNING, "feRenderer::RHIGLFrustum : glFrustum is executed between the execution of glBegin and the corresponding execution of glEnd."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLFrustum"); } Error feRenderer::RHIGLPolygonMode(GLenum face, GLenum mode) { glPolygonMode(face, mode); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_ENUM) return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::RHIGLPolygonMode : face or mode value are not accepted."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLPolygonMode"); } Error feRenderer::RHIGLEnable(GLenum cap) { glEnable(cap); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_ENUM) return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::RHIGLEnable : cap is not one of the values listed previously."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLEnable"); } Error feRenderer::RHIGLDepthFunc(GLenum func) { glDepthFunc(func); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_ENUM) return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::RHIGLDepthFunc : func is not an accepted value."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLDepthFunc"); } Error feRenderer::RHIGLDrawArrays(GLenum mode, GLint first, GLsizei count) { glDrawArrays(mode, first, count); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_ENUM) return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::RHIGLDrawArrays : mode is not an accepted value."); else if (error == GL_INVALID_VALUE) return RHIError::CastError(Error::RHI_INVALID_VALUE, WARNING, "feRenderer::RHIGLDrawArrays : count is negative."); else if (error == GL_INVALID_OPERATION) return RHIError::CastError(Error::RHI_INVALID_OPERATION, WARNING, "feRenderer::RHIGLDrawArrays : a non-zero buffer object name is bound to an enabled array and the buffer object's _data store is currently mapped or a geometry shader is active and mode is incompatible with the input primitive type of the geometry shader in the currently installed program object."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLDrawArrays"); } Error feRenderer::RHIGLDrawElements(GLenum mode, GLint first, GLsizei count, GLvoid* indices) { //glDrawElements(mode, first, count, indices); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_ENUM) return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::RHIGLDrawElements : mode is not an accepted value."); else if (error == GL_INVALID_VALUE) return RHIError::CastError(Error::RHI_INVALID_VALUE, WARNING, "feRenderer::RHIGLDrawElements : count is negative."); else if (error == GL_INVALID_OPERATION) return RHIError::CastError(Error::RHI_INVALID_OPERATION, WARNING, "feRenderer::RHIGLDrawElements : a non-zero buffer object name is bound to an enabled array and the buffer object's _data store is currently mapped or a geometry shader is active and mode is incompatible with the input primitive type of the geometry shader in the currently installed program object."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLDrawElements"); } Error feRenderer::RHIGLDrawElementBaseVertex(GLenum mode, GLsizei count, GLenum type, GLvoid* indices, GLint baseVertex) { glDrawElementsBaseVertex(mode, count, type, indices, baseVertex); GLenum error = glGetError(); if (!error) return Error::RHI_SUCCESS; else if (error == GL_INVALID_ENUM) return RHIError::CastError(Error::RHI_INVALID_ENUM, WARNING, "feRenderer::RHIGLDrawElementBaseVertex : mode is not an accepted value."); else if (error == GL_INVALID_VALUE) return RHIError::CastError(Error::RHI_INVALID_VALUE, WARNING, "feRenderer::RHIGLDrawElementBaseVertex : count is negative."); else if (error == GL_INVALID_OPERATION) return RHIError::CastError(Error::RHI_INVALID_OPERATION, WARNING, "feRenderer::RHIGLDrawElementBaseVertex : a geometry shader is active and mode is incompatible with the input primitive type of the geometry shader in the currently installed program object or a non-zero buffer object name is bound to an enabled array or the element array and the buffer object's _data store is currently mapped."); return RHIError::CastError(RHI_UNKNOWN_ERROR, CRITICAL, "feRenderer::RHIGLDrawElementBaseVertex"); } } // namespace OPENGL } // namespace FrogEngine
[ "t.aubart@student.isartdigital.com" ]
t.aubart@student.isartdigital.com
6a994b3de333396dc4eb7ca5cb1f17bbdb49cf12
d350c660e32e05e9b65f2ab81b6a91c8cc2f7060
/Features/UnitsApi.cpp
6aec53f281c793600e139fce1620282df0e3c407
[]
no_license
annaliceN/CarpentryCAD
50462e46776dc8d11f989108fb5d00c1f9a2aa11
693613af8a53a28b5e06503798d8c3d158e580da
refs/heads/master
2020-04-16T21:49:11.440041
2019-01-15T16:01:31
2019-01-15T16:01:36
165,941,367
1
0
null
2019-01-15T23:47:57
2019-01-15T23:47:57
null
UTF-8
C++
false
false
6,015
cpp
/*************************************************************************** * Copyright (c) 2009 Juergen Riegel (FreeCAD@juergen-riegel.net) * * * * This file is part of the FreeCAD CAx development system. * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License as published by the Free Software Foundation; either * * version 2 of the License, or (at your option) any later version. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU Library General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this library; see the file COPYING.LIB. If not, * * write to the Free Software Foundation, Inc., 59 Temple Place, * * Suite 330, Boston, MA 02111-1307, USA * * * ***************************************************************************/ #ifdef __GNUC__ # include <unistd.h> #endif #include <QString> #include "Exception.h" #include "UnitsApi.h" #include "UnitsSchemaInternal.h" #include "UnitsSchemaImperial1.h" #include "UnitsSchemaMKS.h" #include "UnitsSchemaCentimeters.h" #include "UnitsSchemaMmMin.h" #ifndef M_PI #define M_PI 3.14159265358979323846 #endif #ifndef M_E #define M_E 2.71828182845904523536 #endif #ifndef DOUBLE_MAX # define DOUBLE_MAX 1.7976931348623157E+308 /* max decimal value of a "double"*/ #endif #ifndef DOUBLE_MIN # define DOUBLE_MIN 2.2250738585072014E-308 /* min decimal value of a "double"*/ #endif using namespace Base; //const QString UnitsApi::getQuantityName(QuantityType t) //{ // // check limits // assert(t<9); // // returns // return QString::fromLatin1(QuantityNames[t]); //} // === static attributes ================================================ double UnitsApi::defaultFactor = 1.0; UnitsSchema *UnitsApi::UserPrefSystem = new UnitsSchemaInternal(); UnitSystem UnitsApi::actSystem = SI1; //double UnitsApi::UserPrefFactor [50]; //QString UnitsApi::UserPrefUnit [50]; int UnitsApi::UserPrefDecimals = 2; UnitsApi::UnitsApi(const char* /*filter*/) { } UnitsApi::UnitsApi(const std::string& /*filter*/) { } UnitsApi::~UnitsApi() { } const char* UnitsApi::getDescription(UnitSystem system) { switch (system) { case SI1: return "Standard (mm/kg/s/degree)"; case SI2: return "MKS (m/kg/s/degree)"; case Imperial1: return "US customary (in/lb)"; case ImperialDecimal: return "Imperial decimal (in/lb)"; case Centimeters: return "Building Euro (cm/m²/m³)"; case ImperialBuilding: return "Building US (ft-in/sqft/cuft)"; case MmMin: return "Metric small parts & CNC(mm, mm/min)"; case ImperialCivil: return "Imperial for Civil Eng (ft, ft/sec)"; default: return "Unknown schema"; } } UnitsSchema* UnitsApi::createSchema(UnitSystem s) { switch (s) { case SI1: return new UnitsSchemaInternal(); case SI2: return new UnitsSchemaMKS(); case Imperial1: return new UnitsSchemaImperial1(); case ImperialDecimal: return new UnitsSchemaImperialDecimal(); case Centimeters: return new UnitsSchemaCentimeters(); case ImperialBuilding: return new UnitsSchemaImperialBuilding(); case MmMin: return new UnitsSchemaMmMin(); case ImperialCivil: return new UnitsSchemaImperialCivil(); default: break; } return 0; } void UnitsApi::setSchema(UnitSystem s) { if (UserPrefSystem) { UserPrefSystem->resetSchemaUnits(); // for schemas changed the Quantity constants delete UserPrefSystem; UserPrefSystem = 0; } UserPrefSystem = createSchema(s); actSystem = s; // for wrong value fall back to standard schema if (!UserPrefSystem) { UserPrefSystem = new UnitsSchemaInternal(); actSystem = SI1; } UserPrefSystem->setSchemaUnits(); // if necessary a unit schema can change the constants in Quantity (e.g. mi=1.8km rather then 1.6km). } //double UnitsApi::translateUnit(const char* str) //{ // bool temp; // return parse(str,temp ); //} // //double UnitsApi::translateUnit(const QString & str) //{ // bool temp; // return parse(str.toUtf8() ,temp); //} // // === static translation methods ========================================== QString UnitsApi::schemaTranslate(const Base::Quantity& quant, double &factor, QString &unitString) { return UserPrefSystem->schemaTranslate(quant,factor,unitString); } //QString UnitsApi::toStrWithUserPrefs(QuantityType t,double Value) //{ // return UserPrefSystem->toStrWithUserPrefs(t,Value); // //double UnitValue = Value/UserPrefFactor[t]; // //return QString::fromLatin1("%1 %2").arg(UnitValue).arg(UserPrefUnit[t]); //} // //void UnitsApi::toStrWithUserPrefs(QuantityType t,double Value,QString &outValue,QString &outUnit) //{ // UserPrefSystem->toStrWithUserPrefs(t,Value,outValue,outUnit); //} // //PyObject *UnitsApi::toPyWithUserPrefs(QuantityType t,double Value) //{ // return PyFloat_FromDouble(Value * UserPrefFactor[t]); //} // void UnitsApi::setDecimals(int prec) { UserPrefDecimals = prec; } int UnitsApi::getDecimals() { return UserPrefDecimals; }
[ "wcm15@mails.tsinghua.edu.cn" ]
wcm15@mails.tsinghua.edu.cn
2d7092ecfdd13ac419c53a5ab128bf8042e2fca0
c0e1302b97c0d4c20f77fb3587b2c78f3ec6cf55
/D-jarvan++/D-Jarvan++.cpp
dc5baa0074dd627bcdff627c6920a028dc02b1f0
[]
no_license
aiRTako/LeagueC-Plus-Plus
f01c5edc2bee4a8e26c68ec7d98da7d21759962d
78df9a0242e2a5b66852fbfc4294cbd7bae03eba
refs/heads/master
2021-01-19T19:38:10.756646
2017-04-16T17:29:30
2017-04-16T17:29:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
26,087
cpp
// D-Jarvan.cpp : Defines the exported functions for the DLL application. // //#include "stdafx.h" #include "PluginSDK.h" #define M_PI 3.14159265358979323846 PluginSetup("D-Jarvan"); IMenu* MainMenu; IMenu* ComboMenu; IMenu* HarassMenu; IMenu* FarmMenu; IMenu* JungleMenu; IMenu* MiscMenu; IMenu* Drawings; IMenu* ItemsMenu; IMenu* PotionMenu; IMenu* SmiteMenu; IMenuOption* Harassitems; IMenuOption* HarassEQ; IMenuOption* HarassHpPercent; IMenuOption* UseIgnitecombo; IMenuOption* ComboQ; IMenuOption* ComboW; IMenuOption* ComboE; IMenuOption* ComboR; IMenuOption* ComboRAOEuse; IMenuOption* HarassQ; IMenuOption* HarassW; IMenuOption* HarassE; IMenuOption* HarassR; IMenuOption* Harassammo; IMenuOption* HarassManaPercent; IMenuOption* FarmQ; IMenuOption* FarmW; IMenuOption* FarmWManaPercent; IMenuOption* FarmE; IMenuOption* FarmR; IMenuOption* Farmitems; IMenuOption* FarmManaPercent; IMenuOption* JungleQ; IMenuOption* JungleE; IMenuOption* JungleW; IMenuOption* JungleWManaPercent; IMenuOption* JungleR; IMenuOption* Jungleitems; IMenuOption* JungleManaPercent; IMenuOption* smitejungle; IMenuOption* usesmitetarget; IMenuOption* usesmitejungle; IMenuOption* UseIgnitekillsteal; IMenuOption* KillstealQ; IMenuOption* KillstealE; IMenuOption* KillstealR; IMenuOption* UseEQ; IMenuOption* UseEQW; IMenuOption* useYoumuu; IMenuOption* Hydra; IMenuOption* RHydra; IMenuOption* _tiamat; IMenuOption* Blade_Cutlass; IMenuOption* MyHpPreBlade; IMenuOption* EnemyHpPreBlade; IMenuOption*hextechuse; IMenuOption*MyHpPrehextech; IMenuOption*EnemyHpPrehextech; IMenuOption* usepotion; IMenuOption* usepotionhpper; IMenuOption* DrawReady; IMenuOption* DrawQ; IMenuOption* DrawW; IMenuOption* DrawE; IMenuOption* DrawR; IUnit* myHero; ISpell2* Q; ISpell2* W; ISpell2* E; ISpell2* R; ISpell* Ignite; ISpell* smite; IInventoryItem* Titanic_Hydra; IInventoryItem* Ravenous_Hydra; IInventoryItem* Tiamat; IInventoryItem* hextech; IInventoryItem* blade; IInventoryItem* Cutlass; IInventoryItem* HealthPot; IInventoryItem* CorruptPot; IInventoryItem* Biscuit; IInventoryItem* RefillPot; IInventoryItem* hunter; IInventoryItem* Youmuu; int lastq; int lastr; int _haveulti; void Menu() { MainMenu = GPluginSDK->AddMenu("D-Jarvan"); ComboMenu = MainMenu->AddMenu("Combo Settings"); UseIgnitecombo = ComboMenu->CheckBox("Use Ignite", true); ComboQ = ComboMenu->CheckBox("Use Q", true); ComboW = ComboMenu->CheckBox("Use W", true); ComboE = ComboMenu->CheckBox("Use E", true); ComboR = ComboMenu->CheckBox("Use R", true); //ComboRAOEuse = ComboMenu->CheckBox("Use R if Hit 3 Enemys", true); HarassMenu = MainMenu->AddMenu("Harass Setting"); Harassitems = HarassMenu->CheckBox("Use Items Jungle", true); HarassQ = HarassMenu->CheckBox("Use Q", true); HarassE = HarassMenu->CheckBox("Use E", true); HarassEQ = HarassMenu->CheckBox("Use EQ", true); HarassHpPercent = HarassMenu->AddInteger("HP Percent to Use EQ > ", 10, 100, 70); HarassManaPercent = HarassMenu->AddInteger("Mana Percent for harass", 10, 100, 70); FarmMenu = MainMenu->AddMenu("LaneClear Setting"); FarmQ = FarmMenu->CheckBox("Use Q Farm", true); FarmE = FarmMenu->CheckBox("Use E Farm", true); FarmManaPercent = FarmMenu->AddInteger("Mana Percent for Farm", 10, 100, 70); Farmitems = FarmMenu->CheckBox("Use Items Farm", true); JungleMenu = MainMenu->AddMenu("Jungle Setting"); JungleQ = JungleMenu->CheckBox("Use Q Jungle", true); JungleW = JungleMenu->CheckBox("Use W Jungle", true); JungleWManaPercent = FarmMenu->AddInteger("Use W if my HP <", 10, 100, 20); JungleE = JungleMenu->CheckBox("Use E Jungle", true); JungleManaPercent = JungleMenu->AddInteger("Mana Percent for Farm", 10, 100, 70); Jungleitems = JungleMenu->CheckBox("Use Items Jungle", true); MiscMenu = MainMenu->AddMenu("Misc Setting"); KillstealQ = MiscMenu->CheckBox("Use Q to killsteal", true); KillstealE = MiscMenu->CheckBox("Use E to killsteal", true); KillstealR = MiscMenu->CheckBox("Use R to killsteal", true); UseEQ = MiscMenu->AddKey("Use EQ to Mouse", 84); UseEQW = MiscMenu->CheckBox("Use W if Enemy in range after the EQ ", true); SmiteMenu = MainMenu->AddMenu("Smite Setting"); usesmitetarget = SmiteMenu->CheckBox("Use Smite on target", true); smitejungle = SmiteMenu->CheckBox("Use Smite in Jungle", true); usesmitejungle = SmiteMenu->AddInteger("0=Smite all Monst, 1=Smite only Epic", 0, 1, 0); ItemsMenu = MainMenu->AddMenu("Items Setting"); useYoumuu = ItemsMenu->CheckBox("Use Youmuu's", true); Hydra = ItemsMenu->CheckBox("Use Titanic_Hydra", true); RHydra = ItemsMenu->CheckBox(" Use Ravenous_Hydras", true); _tiamat = ItemsMenu->CheckBox(" UseTiamat", true); Blade_Cutlass = ItemsMenu->CheckBox("Blade-Cutlass", true); MyHpPreBlade = ItemsMenu->AddInteger("Use Blade-Cutlass if my HP <", 10, 100, 35); EnemyHpPreBlade = ItemsMenu->AddInteger("Use Blade-Cutlass if Enemy HP <", 10, 100, 35); hextechuse = ItemsMenu->CheckBox("hextech", true); MyHpPrehextech = ItemsMenu->AddInteger("Use hextech if my HP <", 10, 100, 35); EnemyHpPrehextech = ItemsMenu->AddInteger("Use hextech if Enemy HP <", 10, 100, 35); PotionMenu = MainMenu->AddMenu("Potion Setting"); usepotion = PotionMenu->CheckBox("Use potions", true); usepotionhpper = PotionMenu->AddInteger("Use potions if HP <", 10, 100, 35); Drawings = MainMenu->AddMenu("Drawings"); DrawReady = Drawings->CheckBox("Draw Only Ready Spells", true); DrawQ = Drawings->CheckBox("Draw Q", true); DrawW = Drawings->CheckBox("Draw W", false); DrawE = Drawings->CheckBox("Draw E", false); DrawR = Drawings->CheckBox("Draw R", false); } void LoadSpells() { Q = GPluginSDK->CreateSpell2(kSlotQ, kLineCast, true, true, static_cast<eCollisionFlags>(kCollidesWithNothing)); Q->SetSkillshot(0.5f, 70.f, FLT_MAX, 770.f); W = GPluginSDK->CreateSpell2(kSlotW, kTargetCast, false, true, static_cast<eCollisionFlags>(kCollidesWithNothing)); W->SetOverrideRange(600); E = GPluginSDK->CreateSpell2(kSlotE, kCircleCast, true, true, static_cast<eCollisionFlags> (kCollidesWithNothing)); E->SetSkillshot(0.50f, 50.f, FLT_MAX, 830.f); R = GPluginSDK->CreateSpell2(kSlotR, kTargetCast, true, true, static_cast<eCollisionFlags>(kCollidesWithNothing)); R->SetOverrideRange(650); auto slot1 = GPluginSDK->GetEntityList()->Player()->GetSpellName(kSummonerSlot1); auto slot2 = GPluginSDK->GetEntityList()->Player()->GetSpellName(kSummonerSlot2); if (strcmp(slot1, "SummonerDot") == 0) { Ignite = GPluginSDK->CreateSpell(kSummonerSlot1, 600); } if (strcmp(slot2, "SummonerDot") == 0) { Ignite = GPluginSDK->CreateSpell(kSummonerSlot2, 600); } else Ignite == nullptr; if (strcmp(slot1, "SummonerSmite") == 0) { smite = GPluginSDK->CreateSpell(kSummonerSlot1, 570); } if (strcmp(slot2, "SummonerSmite") == 0) { smite = GPluginSDK->CreateSpell(kSummonerSlot2, 570); } else smite == nullptr; Youmuu = GPluginSDK->CreateItemForId(3142, 0); Titanic_Hydra = GPluginSDK->CreateItemForId(3748, 385); Ravenous_Hydra = GPluginSDK->CreateItemForId(3074, 385); Tiamat = GPluginSDK->CreateItemForId(3077, 385); hextech = GPluginSDK->CreateItemForId(3146, 700); blade = GPluginSDK->CreateItemForId(3153, 550); Cutlass = GPluginSDK->CreateItemForId(3144, 550); HealthPot = GPluginSDK->CreateItemForId(2003, 0); CorruptPot = GPluginSDK->CreateItemForId(2033, 0); RefillPot = GPluginSDK->CreateItemForId(2031, 0); Biscuit = GPluginSDK->CreateItemForId(2010, 0); hunter = GPluginSDK->CreateItemForId(2032, 0); } void GetBuffName() { std::vector<void*> vecBuffs; GEntityList->Player()->GetAllBuffsData(vecBuffs); for (auto i : vecBuffs) { GBuffData->GetBuffName(i); GGame->PrintChat(GBuffData->GetBuffName(i)); } } bool haveulti() { if (myHero->GetSpellBook()->GetLevel(kSlotR) > 0) { return myHero->HasBuff("JarvanIVCataclysm"); } return false; } static bool InFountain(IUnit *unit) { //TODO: Implement return unit->HasBuff("kappachino"); } int EnemiesInRange(IUnit* Source, float range) { auto Targets = GEntityList->GetAllHeros(false, true); auto enemiesInRange = 0; for (auto target : Targets) { if (target != nullptr) { auto flDistance = (target->GetPosition() - Source->GetPosition()).Length(); if (flDistance < range) { enemiesInRange++; } } } return enemiesInRange; } float GetDistance(IUnit* Player, IUnit* target) { return (Player->GetPosition() - target->GetPosition()).Length2D(); } int CountEnemiesInRange(float range) { int enemies = 0; for (auto enemy : GEntityList->GetAllHeros(false, true)) { if (enemy != nullptr && GetDistance(GEntityList->Player(), enemy) <= range) { enemies++; } } return enemies; } void UseItems() { if (GOrbwalking->GetOrbwalkingMode() == kModeCombo) { for (auto enemy : GEntityList->GetAllHeros(false, true)) { if (useYoumuu->Enabled() && Youmuu->IsReady() && Youmuu->IsOwned()) { if (myHero->IsValidTarget(enemy, 550)) Youmuu->CastOnPlayer(); } if (Blade_Cutlass->Enabled() && myHero->IsValidTarget(enemy, 550)) { if (myHero->HealthPercent() < MyHpPreBlade->GetInteger() || enemy->HealthPercent() < EnemyHpPreBlade->GetInteger()) { if (blade->IsOwned() && blade->IsReady()) blade->CastOnTarget(enemy); if (Cutlass->IsOwned() && Cutlass->IsReady()) Cutlass->CastOnTarget(enemy); } } if (hextechuse->Enabled() && myHero->IsValidTarget(enemy, 700)) { if (myHero->HealthPercent() < MyHpPrehextech->GetInteger() || enemy->HealthPercent() < EnemyHpPrehextech->GetInteger()) { if (hextech->IsOwned() && hextech->IsReady()) hextech->CastOnTarget(enemy); } } if (_tiamat->Enabled() && myHero->IsValidTarget(enemy, 385)) { if (Tiamat->IsOwned() && Tiamat->IsReady()) Tiamat->CastOnPlayer(); } if (Hydra->Enabled() && myHero->IsValidTarget(enemy, 385)) { if (Titanic_Hydra->IsOwned() && Titanic_Hydra->IsReady()) Titanic_Hydra->CastOnPlayer(); } if (RHydra->Enabled() && myHero->IsValidTarget(enemy, 385)) { if (Ravenous_Hydra->IsOwned() && Ravenous_Hydra->IsReady()) Ravenous_Hydra->CastOnPlayer(); } } } } void Smiteuse() { if (smite != nullptr && smite->IsReady()) { auto minions = GEntityList->GetAllMinions(false, false, true); for (IUnit* minion : minions) { auto smitestage = usesmitejungle->GetInteger(); if (smitestage == 0) { if (strstr(minion->GetObjectName(), "Blue") || strstr(minion->GetObjectName(), "Gromp") || strstr(minion->GetObjectName(), "Murkwolf") || strstr(minion->GetObjectName(), "Razorbeak") || strstr(minion->GetObjectName(), "RiftHerald") || strstr(minion->GetObjectName(), "Red") || strstr(minion->GetObjectName(), "Krug") || strstr(minion->GetObjectName(), "Dragon") || strstr(minion->GetObjectName(), "Baron")) { auto Dmg = GDamage->GetSummonerSpellDamage(myHero, minion, kSummonerSpellSmite); if (minion != nullptr && !minion->IsDead() && minion->GetHealth() <= Dmg && myHero->IsValidTarget(minion, 570)) { smite->CastOnUnit(minion); } } } if (smitestage == 1) { if (strstr(minion->GetObjectName(), "RiftHerald") || strstr(minion->GetObjectName(), "Dragon") || strstr(minion->GetObjectName(), "Baron")) { auto Dmg = GDamage->GetSummonerSpellDamage(myHero, minion, kSummonerSpellSmite); if (minion != nullptr && !minion->IsDead() && minion->GetHealth() <= Dmg && myHero->IsValidTarget(minion, 570)) { smite->CastOnUnit(minion); } } } } } } void smitetarget() { if (smite == nullptr) return; if (!usesmitetarget->Enabled() || !smite->IsReady()) return; for (auto enemy : GEntityList->GetAllHeros(false, true)) { if (enemy != nullptr && myHero->IsValidTarget(enemy, 570)) { auto Dmg = GDamage->GetSummonerSpellDamage(myHero, enemy, kSummonerSpellSmite); smite->CastOnUnit(enemy); } } } void Combo() { auto Ecd = myHero->GetSpellRemainingCooldown(kSlotE); auto Qcd = myHero->GetSpellRemainingCooldown(kSlotQ); smitetarget(); if (Ignite != nullptr) { auto Enemy = GTargetSelector->FindTarget(QuickestKill, SpellDamage, Q->Range()); if (UseIgnitecombo->Enabled() && Ignite->IsReady()) { if (Enemy != nullptr && Enemy->IsValidTarget(myHero, 570)) { if (Enemy->HealthPercent() <= 30) { Ignite->CastOnUnit(Enemy); } } } } if (ComboQ->Enabled() && ComboE->Enabled()) { if (Q->IsReady() && E->IsReady() && myHero->GetMana() > Q->ManaCost() + E->ManaCost()) { auto target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, E->Range()); if (myHero->IsValidTarget(target, E->Range()) && target != nullptr) { AdvPredictionOutput prediction_output; E->RunPrediction(target, true, kCollidesWithYasuoWall | kCollidesWithMinions, &prediction_output); if (E->IsReady() && prediction_output.HitChance >= kHitChanceHigh) { Vec3 Enemypos; //auto Rstartcast = target->ServerPosition().Extend(target->ServerPosition(), 50); GPrediction->GetFutureUnitPosition(target, 0.5, true, Enemypos); E->CastOnPosition(Enemypos); Q->CastOnPosition(Enemypos); } } } } if (ComboE->Enabled() && (!Q->IsReady() || Qcd > 3) || !ComboQ->Enabled()) { if (E->IsReady()) { auto target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, E->Range()); if (target != nullptr && myHero->IsValidTarget(target, E->Range())) { auto dmg = GDamage->GetSpellDamage(myHero, target, kSlotE); if (target->GetHealth() < dmg) E->CastOnTarget(target, kHitChanceHigh); } } } if (ComboW->Enabled()) { if (W->IsReady()) { auto target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, W->Range()); if (target != nullptr) { if (myHero->IsValidTarget(target, W->Range())) W->CastOnPlayer(); } } } if (ComboQ->Enabled()) { if (Q->IsReady()) { auto target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, Q->Range()); if (target != nullptr && myHero->IsValidTarget(target, Q->Range())) { if (!E->IsReady() || Ecd > 3) { Q->CastOnTarget(target, kHitChanceHigh); } auto dmg = GDamage->GetSpellDamage(myHero, target, kSlotQ); if (target->GetHealth() < dmg) { Q->CastOnTarget(target, kHitChanceHigh); } } } } if (ComboR->Enabled() && R->IsReady()) { auto Enemy = GTargetSelector->GetFocusedTarget(); if (myHero->IsValidTarget(Enemy, R->Range()) && Enemy != nullptr) { //auto dmg = GDamage->GetSpellDamage(myHero, Enemy, kSlotQ); auto Rlvl = GEntityList->Player()->GetSpellLevel(kSlotR) - 1; auto BaseDamage = std::vector<double>({ 200, 325, 450 }).at(Rlvl); auto ADMultiplier = 1.5 * GEntityList->Player()->TotalPhysicalDamage(); auto dmg = GDamage->GetSpellDamage(myHero, Enemy, kSlotQ); auto TotalD = BaseDamage + ADMultiplier; if (!Enemy->IsInvulnerable() && Enemy->GetHealth() < TotalD+ dmg) { R->CastOnTarget(Enemy); } } } /*if (R->IsReady() && ComboRAOEuse->Enabled()) { for (auto target : GEntityList->GetAllHeros(false, true)) if (target != nullptr && myHero->IsValidTarget(target, R->Range())) { R->CastOnTargetAoE(target, 3, kHitChanceLow); } }*/ } void Forest() { GGame->IssueOrder(myHero, kMoveTo, GGame->CursorPosition()); if (Q->IsReady() && E->IsReady()) { if (Q->ManaCost() + E->ManaCost() < myHero->GetMana()) { E->CastOnPosition(GGame->CursorPosition()); Q->CastOnPosition(GGame->CursorPosition()); } } if (UseEQW->Enabled() && W->IsReady()) { auto Enemy = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, W->Range()); if (myHero->IsValidTarget(Enemy, W->Range()) && Enemy != nullptr) { W->CastOnPlayer(); } } } void laneclear() { for (auto minions : GEntityList->GetAllMinions(false, true, false)) { if (Farmitems->Enabled()) { if (_tiamat->Enabled() && myHero->IsValidTarget(minions, 385)) { if (Tiamat->IsOwned() && Tiamat->IsReady()) Tiamat->CastOnPlayer(); } if (Hydra->Enabled() && myHero->IsValidTarget(minions, 385)) { if (Titanic_Hydra->IsOwned() && Titanic_Hydra->IsReady()) Titanic_Hydra->CastOnPlayer(); } if (RHydra->Enabled() && myHero->IsValidTarget(minions, 385)) { if (Ravenous_Hydra->IsOwned() && Ravenous_Hydra->IsReady()) Ravenous_Hydra->CastOnPlayer(); } } if (myHero->ManaPercent() < FarmManaPercent->GetInteger()) return; if (FarmQ->Enabled() && Q->IsReady()) { if (minions != nullptr && myHero->IsValidTarget(minions, Q->Range())) { auto dmg = GDamage->GetSpellDamage(myHero, minions, kSlotQ); Q->AttackMinions(); if (minions->GetHealth() < dmg && GetDistance(myHero, minions) > myHero->GetRealAutoAttackRange(minions)) { Q->CastOnUnit(minions); return; } } } if (FarmE->Enabled() && E->IsReady()) { if (minions != nullptr && myHero->IsValidTarget(minions, Q->Range())) { auto dmg = GDamage->GetSpellDamage(myHero, minions, kSlotQ); Vec3 pos; int hit; GPrediction->FindBestCastPosition(E->Range(), E->Radius(), true, true, false, pos, hit); if (hit >= 2) { E->CastOnPosition(pos); return; } if (minions->GetHealth() < dmg && GetDistance(myHero, minions) > myHero->GetRealAutoAttackRange(minions)) { E->CastOnUnit(minions); return; } } } } } void jungleclear() { for (auto jMinion : GEntityList->GetAllMinions(false, false, true)) { if (Jungleitems->Enabled()) { if (_tiamat->Enabled() && myHero->IsValidTarget(jMinion, 385)) { if (Tiamat->IsOwned() && Tiamat->IsReady()) Tiamat->CastOnPlayer(); } if (Hydra->Enabled() && myHero->IsValidTarget(jMinion, 385)) { if (Titanic_Hydra->IsOwned() && Titanic_Hydra->IsReady()) Titanic_Hydra->CastOnPlayer(); } if (RHydra->Enabled() && myHero->IsValidTarget(jMinion, 385)) { if (Ravenous_Hydra->IsOwned() && Ravenous_Hydra->IsReady()) Ravenous_Hydra->CastOnPlayer(); } } if (myHero->ManaPercent() < JungleManaPercent->GetInteger()) return; if (strstr(jMinion->GetObjectName(), "mini")) return; if (JungleE->Enabled() && E->IsReady()) { if (jMinion != nullptr && !jMinion->IsDead() && myHero->IsValidTarget(jMinion, E->Range())) { E->CastOnUnit(jMinion); return; } } if (JungleQ->Enabled() && Q->IsReady()) { if (jMinion != nullptr && !jMinion->IsDead() && myHero->IsValidTarget(jMinion, Q->Range())) { Q->CastOnUnit(jMinion); return; } } if (JungleW->Enabled() && W->IsReady()) { if (jMinion != nullptr && !jMinion->IsDead() && myHero->IsValidTarget(jMinion, W->Range())) {if(myHero->GetHealth() <JungleWManaPercent->GetInteger()) W->CastOnPlayer(); return; } } } } void Harass() { if (Harassitems->Enabled()) { auto target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, Q->Range()); if (myHero->IsValidTarget(target, Q->Range()) && target != nullptr) { if (_tiamat->Enabled() && myHero->IsValidTarget(target, 385)) { if (Tiamat->IsOwned() && Tiamat->IsReady()) Tiamat->CastOnPlayer(); } if (Hydra->Enabled() && myHero->IsValidTarget(target, 385)) { if (Titanic_Hydra->IsOwned() && Titanic_Hydra->IsReady()) Titanic_Hydra->CastOnPlayer(); } if (RHydra->Enabled() && myHero->IsValidTarget(target, 385)) { if (Ravenous_Hydra->IsOwned() && Ravenous_Hydra->IsReady()) Ravenous_Hydra->CastOnPlayer(); } } } if (myHero->ManaPercent() < HarassManaPercent->GetInteger()) return; if (HarassQ->Enabled()) { if (Q->IsReady()) { auto target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, Q->Range()); if (myHero->IsValidTarget(target, Q->Range()) && target != nullptr) { Q->CastOnTarget(target, kHitChanceHigh); } } } if (HarassE->Enabled()) { if (E->IsReady()) { auto target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, E->Range()); if (target != nullptr) { if (myHero->IsValidTarget(target, E->Range())) { E->CastOnTarget(target, kHitChanceHigh); } } } } if (HarassEQ->Enabled()) { if (Q->IsReady() && E->IsReady() && myHero->GetMana() > Q->ManaCost() + E->ManaCost()) { auto target = GTargetSelector->FindTarget(QuickestKill, PhysicalDamage, E->Range()); if (myHero->GetHealth() > HarassHpPercent->GetInteger()) { if (myHero->IsValidTarget(target, E->Range()) && target != nullptr) { AdvPredictionOutput prediction_output; E->RunPrediction(target, true, kCollidesWithYasuoWall | kCollidesWithMinions, &prediction_output); if (E->IsReady() && prediction_output.HitChance >= kHitChanceHigh) { Vec3 Enemypos; //auto Rstartcast = target->ServerPosition().Extend(target->ServerPosition(), 50); GPrediction->GetFutureUnitPosition(target, 0.5, true, Enemypos); E->CastOnPosition(Enemypos); Q->CastOnPosition(Enemypos); } } } } } } void killsteal() { if (GGame->IsChatOpen()) return; for (auto Enemy : GEntityList->GetAllHeros(false, true)) { if (Enemy != nullptr && !Enemy->IsDead()) { if (KillstealQ->Enabled() && Q->IsReady()) { auto dmg = GDamage->GetSpellDamage(GEntityList->Player(), Enemy, kSlotQ); if (myHero->IsValidTarget(Enemy, Q->Range()) && !Enemy->IsInvulnerable()) { if (Enemy->GetHealth() <= dmg) { Q->CastOnTarget(Enemy, kHitChanceHigh); } } } if (KillstealE->Enabled() && E->IsReady()) { auto dmg = GDamage->GetSpellDamage(GEntityList->Player(), Enemy, kSlotE); if (myHero->IsValidTarget(Enemy, E->Range()) && !Enemy->IsInvulnerable()) { if (Enemy->GetHealth() <= dmg) { E->CastOnTarget(Enemy, kHitChanceHigh); } } } if (KillstealR->Enabled() && R->IsReady()) { auto dmg = GDamage->GetSpellDamage(myHero, Enemy, kSlotR); if (myHero->IsValidTarget(Enemy, R->Range()) && !Enemy->IsInvulnerable()) { if (Enemy->GetHealth() <= dmg) { R->CastOnTarget(Enemy, kHitChanceHigh); } } } } } } void Usepotion() { if (usepotion->Enabled() && !myHero->IsRecalling() && !myHero->IsDead()) { if (CountEnemiesInRange(2000) > 0) { bool usepotions = myHero->GetHealth() < myHero->GetMaxHealth()* usepotionhpper->GetInteger() / 100; if (usepotions) { if (myHero->GetBuffDataByName("ItemDarkCrystalFlask") || myHero->GetBuffDataByName("ItemMiniRegenPotion") || myHero->GetBuffDataByName("ItemCrystalFlask") || myHero->GetBuffDataByName("RegenerationPotion") || myHero->HasBuff("ItemCrystalFlaskJungle")) return; if (Biscuit->IsOwned() && !InFountain(myHero) && Biscuit->IsReady()) { Biscuit->CastOnPlayer(); } else if (HealthPot->IsOwned() && !InFountain(myHero) && HealthPot->IsReady()) { HealthPot->CastOnPlayer(); } else if (CorruptPot->IsOwned() && CorruptPot->IsReady()) { CorruptPot->CastOnPlayer(); } else if (RefillPot->IsOwned() && RefillPot->IsReady()) { RefillPot->CastOnPlayer(); } else if (hunter->IsOwned() && hunter->IsReady()) { hunter->CastOnPlayer(); } } } } } PLUGIN_EVENT(void) OnRender() { if (DrawReady->Enabled()) { if (Q->IsReady() && DrawQ->Enabled()) { GRender->DrawOutlinedCircle(GEntityList->Player()->GetPosition(), Vec4(255, 255, 0, 255), Q->Range()); } if (W->IsReady() && DrawW->Enabled()) { GRender->DrawOutlinedCircle(GEntityList->Player()->GetPosition(), Vec4(255, 255, 0, 255), W->Range()); } if (E->IsReady() && DrawE->Enabled()) { GRender->DrawOutlinedCircle(GEntityList->Player()->GetPosition(), Vec4(255, 255, 0, 255), E->Range()); } if (R->IsReady() && DrawR->Enabled()) { GRender->DrawOutlinedCircle(GEntityList->Player()->GetPosition(), Vec4(255, 255, 0, 255), R->Range()); } } else { if (DrawQ->Enabled()) { GRender->DrawOutlinedCircle(GEntityList->Player()->GetPosition(), Vec4(255, 255, 0, 255), Q->Range()); } if (DrawW->Enabled()) { GRender->DrawOutlinedCircle(GEntityList->Player()->GetPosition(), Vec4(255, 255, 0, 255), W->Range()); } if (DrawE->Enabled()) { GRender->DrawOutlinedCircle(GEntityList->Player()->GetPosition(), Vec4(255, 255, 0, 255), E->Range()); } if (DrawR->Enabled()) { GRender->DrawOutlinedCircle(GEntityList->Player()->GetPosition(), Vec4(255, 255, 0, 255), R->Range()); } } } PLUGIN_EVENT(void) OnCreateObject(IUnit* obj) { if (strcmp(obj->GetObjectName(), "JarvanIVCataclysm") == 0) { _haveulti = true; GGame->PrintChat("ulti"); } } PLUGIN_EVENT(void) OnDestroyObject(IUnit* obj) { if (strcmp(obj->GetObjectName(), "JarvanCataclysm_tar") == 0) { _haveulti = false; } } PLUGIN_EVENT(void) OnGameUpdate() { if (GOrbwalking->GetOrbwalkingMode() == kModeCombo) { Combo(); } if (GOrbwalking->GetOrbwalkingMode() == kModeMixed) { Harass(); } if (GOrbwalking->GetOrbwalkingMode() == kModeLaneClear) { laneclear(); jungleclear(); } killsteal(); UseItems(); Usepotion(); if (smitejungle->Enabled()) { Smiteuse(); } if (GetAsyncKeyState(UseEQ->GetInteger())) { Forest(); } } PLUGIN_API void OnLoad(IPluginSDK* PluginSDK) { PluginSDKSetup(PluginSDK); Menu(); LoadSpells(); myHero = GEntityList->Player(); GEventManager->AddEventHandler(kEventOnGameUpdate, OnGameUpdate); GEventManager->AddEventHandler(kEventOnRender, OnRender); // GEventManager->AddEventHandler(kEventOnCreateObject, OnCreateObject); //GEventManager->AddEventHandler(kEventOnDestroyObject, OnDestroyObject); if (strcmp(GEntityList->Player()->ChampionName(), "JarvanIV") == 0) { GGame->PrintChat("D-JarvanIV : Loaded"); } else { GGame->PrintChat("You are not playing JarvanIV..."); } } PLUGIN_API void OnUnload() { MainMenu->Remove(); GEventManager->RemoveEventHandler(kEventOnGameUpdate, OnGameUpdate); GEventManager->RemoveEventHandler(kEventOnRender, OnRender); //GEventManager->RemoveEventHandler(kEventOnCreateObject, OnCreateObject); //GEventManager->RemoveEventHandler(kEventOnDestroyObject, OnDestroyObject); }
[ "diabatiis@gmail.com" ]
diabatiis@gmail.com
db097d12fcf4d3b1b9c1f96f57fdb727eefed105
1942a0d16bd48962e72aa21fad8d034fa9521a6c
/aws-cpp-sdk-route53domains/include/aws/route53domains/model/ListOperationsResult.h
596d1c2196b6c273857da995cd7c1b385c0c6352
[ "Apache-2.0", "JSON", "MIT" ]
permissive
yecol/aws-sdk-cpp
1aff09a21cfe618e272c2c06d358cfa0fb07cecf
0b1ea31e593d23b5db49ee39d0a11e5b98ab991e
refs/heads/master
2021-01-20T02:53:53.557861
2018-02-11T11:14:58
2018-02-11T11:14:58
83,822,910
0
1
null
2017-03-03T17:17:00
2017-03-03T17:17:00
null
UTF-8
C++
false
false
7,214
h
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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. */ #pragma once #include <aws/route53domains/Route53Domains_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/route53domains/model/OperationSummary.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace Route53Domains { namespace Model { /** * <p>The ListOperations response includes the following elements.</p><p><h3>See * Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/route53domains-2014-05-15/ListOperationsResponse">AWS * API Reference</a></p> */ class AWS_ROUTE53DOMAINS_API ListOperationsResult { public: ListOperationsResult(); ListOperationsResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); ListOperationsResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); /** * <p>Lists summaries of the operations.</p> <p>Type: Complex type containing a * list of operation summaries</p> <p>Children: <code>OperationId</code>, * <code>Status</code>, <code>SubmittedDate</code>, <code>Type</code></p> */ inline const Aws::Vector<OperationSummary>& GetOperations() const{ return m_operations; } /** * <p>Lists summaries of the operations.</p> <p>Type: Complex type containing a * list of operation summaries</p> <p>Children: <code>OperationId</code>, * <code>Status</code>, <code>SubmittedDate</code>, <code>Type</code></p> */ inline void SetOperations(const Aws::Vector<OperationSummary>& value) { m_operations = value; } /** * <p>Lists summaries of the operations.</p> <p>Type: Complex type containing a * list of operation summaries</p> <p>Children: <code>OperationId</code>, * <code>Status</code>, <code>SubmittedDate</code>, <code>Type</code></p> */ inline void SetOperations(Aws::Vector<OperationSummary>&& value) { m_operations = value; } /** * <p>Lists summaries of the operations.</p> <p>Type: Complex type containing a * list of operation summaries</p> <p>Children: <code>OperationId</code>, * <code>Status</code>, <code>SubmittedDate</code>, <code>Type</code></p> */ inline ListOperationsResult& WithOperations(const Aws::Vector<OperationSummary>& value) { SetOperations(value); return *this;} /** * <p>Lists summaries of the operations.</p> <p>Type: Complex type containing a * list of operation summaries</p> <p>Children: <code>OperationId</code>, * <code>Status</code>, <code>SubmittedDate</code>, <code>Type</code></p> */ inline ListOperationsResult& WithOperations(Aws::Vector<OperationSummary>&& value) { SetOperations(value); return *this;} /** * <p>Lists summaries of the operations.</p> <p>Type: Complex type containing a * list of operation summaries</p> <p>Children: <code>OperationId</code>, * <code>Status</code>, <code>SubmittedDate</code>, <code>Type</code></p> */ inline ListOperationsResult& AddOperations(const OperationSummary& value) { m_operations.push_back(value); return *this; } /** * <p>Lists summaries of the operations.</p> <p>Type: Complex type containing a * list of operation summaries</p> <p>Children: <code>OperationId</code>, * <code>Status</code>, <code>SubmittedDate</code>, <code>Type</code></p> */ inline ListOperationsResult& AddOperations(OperationSummary&& value) { m_operations.push_back(value); return *this; } /** * <p>If there are more operations than you specified for <code>MaxItems</code> in * the request, submit another request and include the value of * <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> <p>Type: * String</p> <p>Parent: <code>Operations</code></p> */ inline const Aws::String& GetNextPageMarker() const{ return m_nextPageMarker; } /** * <p>If there are more operations than you specified for <code>MaxItems</code> in * the request, submit another request and include the value of * <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> <p>Type: * String</p> <p>Parent: <code>Operations</code></p> */ inline void SetNextPageMarker(const Aws::String& value) { m_nextPageMarker = value; } /** * <p>If there are more operations than you specified for <code>MaxItems</code> in * the request, submit another request and include the value of * <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> <p>Type: * String</p> <p>Parent: <code>Operations</code></p> */ inline void SetNextPageMarker(Aws::String&& value) { m_nextPageMarker = value; } /** * <p>If there are more operations than you specified for <code>MaxItems</code> in * the request, submit another request and include the value of * <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> <p>Type: * String</p> <p>Parent: <code>Operations</code></p> */ inline void SetNextPageMarker(const char* value) { m_nextPageMarker.assign(value); } /** * <p>If there are more operations than you specified for <code>MaxItems</code> in * the request, submit another request and include the value of * <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> <p>Type: * String</p> <p>Parent: <code>Operations</code></p> */ inline ListOperationsResult& WithNextPageMarker(const Aws::String& value) { SetNextPageMarker(value); return *this;} /** * <p>If there are more operations than you specified for <code>MaxItems</code> in * the request, submit another request and include the value of * <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> <p>Type: * String</p> <p>Parent: <code>Operations</code></p> */ inline ListOperationsResult& WithNextPageMarker(Aws::String&& value) { SetNextPageMarker(value); return *this;} /** * <p>If there are more operations than you specified for <code>MaxItems</code> in * the request, submit another request and include the value of * <code>NextPageMarker</code> in the value of <code>Marker</code>.</p> <p>Type: * String</p> <p>Parent: <code>Operations</code></p> */ inline ListOperationsResult& WithNextPageMarker(const char* value) { SetNextPageMarker(value); return *this;} private: Aws::Vector<OperationSummary> m_operations; Aws::String m_nextPageMarker; }; } // namespace Model } // namespace Route53Domains } // namespace Aws
[ "henso@amazon.com" ]
henso@amazon.com
0eefc65820830402c9b5c63d75eeaf0cc3296dec
ca7b464d6903abdf904ab197c97194f2fb65a6c5
/common/Report.cpp
07c0686b0635a13a260f5f8532fad574646c6f24
[]
no_license
ddowling/SecurityTools
1e68ce666460f86b81517194f284a8701dcb8c06
0f42b3eecaa2c2fe3cab6e867d6d864ba326c0dd
refs/heads/master
2021-01-22T04:49:39.185429
2015-01-04T09:18:35
2015-01-04T09:18:35
28,761,861
0
1
null
null
null
null
UTF-8
C++
false
false
2,083
cpp
/* $Id$ * * Copyright : (c) 2015 Open Source Solutions Pty Ltd. All Rights Reserved * Project : SecurityTools * File : Report * * Author : Denis Dowling * Created : 8 May 2009 * * Description : classes to implement the Report Composite pattern */ #include "Report.h" #include "Section.h" #include "Assert.h" // ******** // Visitor pattern for the Report class. It will be called when we traverse // the Report composite pattern ReportVisitor::~ReportVisitor() { } void ReportVisitor::enterReport(Report &r) { } void ReportVisitor::exitReport(Report &r) { } void ReportVisitor::enterSection(Section &s) { } void ReportVisitor::exitSection(Section &s) { } void ReportVisitor::enterParagraph(Paragraph &p) { } void ReportVisitor::exitParagraph(Paragraph &p) { } void ReportVisitor::enterTable(Table &t) { } void ReportVisitor::exitTable(Table &t) { } // ******** // Base class for elements of a report ReportElement::ReportElement() : parent(0) { } ReportElement::~ReportElement() { } void ReportElement::appendChild(ReportElementPtr child) { ASSERT(child->parent == 0); child->parent = this; children.push_back(child); } void ReportElement::traverse(ReportVisitor &report_visitor) { ReportElementVector::iterator iter; for(iter = children.begin(); iter != children.end(); ++iter) { ReportElementPtr p = *iter; p->traverse(report_visitor); } } // ******** Report::Report() { } // The title of the report void Report::setTitle(String title_) { title = title_; } String Report::getTitle() const { return title; } // The author of the report void Report::setAuthor(String author_) { author = author_; } String Report::getAuthor() const { return author; } Section & Report::addSection() { Section *s = new Section; ReportElement::ReportElementPtr sp(s); appendChild(sp); return *s; } void Report::traverse(ReportVisitor &report_visitor) { report_visitor.enterReport(*this); ReportElement::traverse(report_visitor); report_visitor.exitReport(*this); }
[ "dpd@cloud02.opsol.com.au" ]
dpd@cloud02.opsol.com.au
fb920d0978bf408df1571c3f695ac94b2d9b7cc2
4fd9c9dc7995d91481c5f9ee3e048aa095c82059
/Examples/01_LMP91200Quickstart/01_LMP91200Quickstart.ino
d80aacd36bd2d23c8c8e195c6883ed4b694759cf
[ "MIT" ]
permissive
HydroSense/LMP91200
695cc099b00c330274c6e1ffcf64246015b3bcc2
13c667695642180d619b37e8a286586c702775d8
refs/heads/master
2021-01-10T17:47:40.833391
2016-03-26T23:39:35
2016-03-26T23:39:35
52,460,381
4
3
null
null
null
null
UTF-8
C++
false
false
1,124
ino
#include <SPI.h> #define CS_LMP91200 A4 void setup() { // put your setup code here, to run once: Serial.begin(9600); SPI.begin(); SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3)); //SPI.beginTransaction(SPISettings(1000000, MSBFIRST, SPI_MODE3)); pinMode(CS_LMP91200, OUTPUT); pinMode(A5, OUTPUT); pinMode(5, OUTPUT); pinMode(11, OUTPUT); digitalWrite(A5, HIGH); digitalWrite(5, HIGH); digitalWrite(11, HIGH); delay(1000); Serial.println("here"); } void loop() { // put your main code here, to run repeatedly: LMP91200_init(A4); delay(500); } bool LMP91200_init(int cs){ uint16_t dataIn = 0xA080; //Check for connection by sending default config and checking that it return corretly digitalWrite(CS_LMP91200, LOW); //digitalWrite(A4, LOW); SPI.transfer16(dataIn); uint16_t recievedVal = SPI.transfer16(dataIn); //digitalWrite(A4, HIGH); digitalWrite(CS_LMP91200, HIGH); Serial.print("Out: "); Serial.println(recievedVal, HEX); Serial.println(); } void LMP91200_setPGA(){ } void LMP91200_setVCM(){ } void LMP91200_setVOCM(){ } void LMP91200_setDIAG(){ }
[ "wardprescott95@gmail.com" ]
wardprescott95@gmail.com
534af82c36ea3ad4a8a1b628e873e447d3058b97
5378ee9b548580898498253d1724ab7031b27ab5
/tesselate/ffd.cpp
f7fe88f70254b82071a10377a0babd39bdfabf6e
[]
no_license
DominicNgoetjana/3D-Graphics-Renderer
e1d3351fb09b18e2458ee37162815cd6860e3e8d
10fcadce681414331ab7a14dabfd2f6a9baa4c9b
refs/heads/master
2020-08-20T18:06:30.824944
2019-10-18T16:14:42
2019-10-18T16:14:42
216,051,903
0
0
null
null
null
null
UTF-8
C++
false
false
7,582
cpp
// // ffd // #include "ffd.h" #include <stdio.h> using namespace std; GLfloat defaultLatCol[] = {0.2f, 0.2f, 0.2f, 1.0f}; GLfloat highlightLatCol[] = {1.0f, 0.176f, 0.176f, 1.0f}; int maxbezorder = 4; void ffd::alloc() { // allocate memory for a 3D array of control points and highlighting switches if(dimx > 1 && dimy > 1 && dimz > 1 && dimx <= maxbezorder && dimy <= maxbezorder && dimz <= maxbezorder) { cp = new cgp::Point **[dimx]; highlight = new bool **[dimx]; for (int i = 0; i < dimx; i++) { cp[i] = new cgp::Point *[dimy]; highlight[i] = new bool *[dimy]; for (int j = 0; j < dimy; j++) { cp[i][j] = new cgp::Point[dimz]; highlight[i][j] = new bool[dimz]; } } deactivateAllCP(); } } void ffd::dealloc() { // deallocate 3D array of control points and boolean highlighting switches for (int i = 0; i < dimx; i++) { for (int j = 0; j < dimy; j++) { delete [] cp[i][j]; delete [] highlight[i][j]; } delete [] cp[i]; delete [] highlight[i]; } delete [] cp; delete [] highlight; cp = NULL; } bool ffd::inCPBounds(int i, int j, int k) { return (i >= 0 && j >= 0 && k >= 0 && i < dimx && j < dimy && k < dimz); } float ffd::basis(float t, int i, int n) { float b = 0.0f; float tinv = 1.0f - t; // this could be made more efficienct by calculating the Bernstein polynomials for all indices at the same time // but I have left it this way for readability switch(n) { case 0: break; // b=0 case 1: switch(i) { case 0: b = tinv; break; case 1: b = t; break; default: break; // b=0 } break; case 2: switch(i) { case 0: b = tinv*tinv; break; case 1: b = 2.0f*tinv*t; break; case 2: b = t*t; break; default: break; // b=0 } break; case 3: switch(i) { case 0: b = tinv*tinv*tinv; break; case 1: b = 3.0f*tinv*tinv*t; break; case 2: b = 3.0f*tinv*t*t; break; case 3: b = t*t*t; break; default: break; // b=0 } break; default: break; // b=0 } return b; } ffd::ffd() { dimx = dimy = dimz = 0; setFrame(cgp::Point(0.0f, 0.0f, 0.0f), cgp::Vector(0.0f, 0.0f, 0.0f)); cp = NULL; highlight = NULL; } ffd::ffd(int xnum, int ynum, int znum, cgp::Point corner, cgp::Vector diag) { dimx = xnum; dimy = ynum; dimz = znum; alloc(); setFrame(corner, diag); } void ffd::reset() { cgp::Vector step; cgp::Point pos; // use linear precision property of bezier curves to lay out ffd control point in a regular pattern // that is equivalent to an identity deformation step.i = diagonal.i / (float) (dimx-1); step.j = diagonal.j / (float) (dimy-1); step.k = diagonal.k / (float) (dimz-1); for(int i = 0; i < dimx; i++) for(int j = 0; j < dimy; j++) for(int k = 0; k < dimz; k++) { pos = origin; pos.x += (float) i * step.i; pos.y += (float) j * step.j; pos.z += (float) k * step.k; cp[i][j][k] = pos; } } void ffd::getDim(int &numx, int &numy, int &numz) { numx = dimx; numy = dimy; numz = dimz; } void ffd::setDim(int numx, int numy, int numz) { dimx = numx; dimy = numy; dimz = numz; alloc(); reset(); } void ffd::getFrame(cgp::Point &corner, cgp::Vector &diag) { corner = origin; diag = diagonal; } void ffd::setFrame(cgp::Point corner, cgp::Vector diag) { origin = corner; diagonal = diag; reset(); } void ffd::activateCP(int i, int j, int k) { if(inCPBounds(i,j,k)) highlight[i][j][k] = true; } void ffd::deactivateCP(int i, int j, int k) { if(inCPBounds(i,j,k)) highlight[i][j][k] = false; } void ffd::deactivateAllCP() { for(int i = 0; i < dimx; i++) for(int j = 0; j < dimy; j++) for(int k = 0; k < dimz; k++) highlight[i][j][k] = false; } bool ffd::bindGeometry(View * view, ShapeDrawData &sdd, bool active) { int i, j, k; glm::mat4 tfm, idt; glm::vec3 trs; cgp::Point pnt; bool draw; if(active) { activegeom.clear(); activegeom.setColour(highlightLatCol); } else { geom.clear(); geom.setColour(defaultLatCol); } idt = glm::mat4(1.0f); // identity matrix // place a sphere at non-active control point positions with appropriate colour for(i = 0; i < dimx; i++) for(j = 0; j < dimy; j++) for(k = 0; k < dimz; k++) { if(active) // only draw those control points that match active flag draw = highlight[i][j][k]; else draw = !highlight[i][j][k]; if(draw) { pnt = cp[i][j][k]; trs = glm::vec3(pnt.x, pnt.y, pnt.z); tfm = glm::translate(idt, trs); if(active) activegeom.genSphere(0.4, 10, 10, tfm); else geom.genSphere(0.4, 10, 10, tfm); } } // bind geometry to buffers and return drawing parameters, if possible if(active) { if(activegeom.bindBuffers(view)) { sdd = activegeom.getDrawParameters(); return true; } else return false; } else { if(geom.bindBuffers(view)) { sdd = geom.getDrawParameters(); return true; } else return false; } } cgp::Point ffd::getCP(int i, int j, int k) { if(inCPBounds(i,j,k)) { return cp[i][j][k]; } else { cerr << "Error ffd::getCP: out of bounds access to lattice" << endl; return cgp::Point(0.0f, 0.0f, 0.0f); } } void ffd::setCP(int i, int j, int k, cgp::Point pnt) { if(inCPBounds(i,j,k)) cp[i][j][k] = pnt; } void ffd::deform(cgp::Point & pnt) { float u, v, w; // coordinates of point within the lattice int i, j, k; // control point indices float b; // basis value // embed in axis-aligned lattice // basically, find the local [0,1]X[0,1]X[0,1] coordinates of the point within the space of the lattice u = (pnt.x - origin.x) / diagonal.i; v = (pnt.y - origin.y) / diagonal.j; w = (pnt.z - origin.z) / diagonal.k; // don't change the point if it lies outside the lattice if(u >= 0.0f && u <= 1.0f && v >= 0.0f && v <= 1.0f && w >= 0.0f && w <= 1.0f) { pnt = cgp::Point(0.0f, 0.0f, 0.0f); // deformation // weighted sum of control points and basis functions that depends on the vertex (u,v,w) coordinates for(i = 0; i < dimx; ++i) for(j = 0; j < dimy; ++j) for(k = 0; k < dimz; ++k) { b = basis(u, i, dimx-1) * basis(v, j, dimy-1) * basis(w, k, dimz-1); pnt.x += b * cp[i][j][k].x; pnt.y += b * cp[i][j][k].y; pnt.z += b * cp[i][j][k].z; } } }
[ "dominicngoetjana@gmail.com" ]
dominicngoetjana@gmail.com
f2832ed9bb1d8fc05b6f5723452fca2705a5cb92
31a9d51fbe30f44ea3a1ebfd52e45af42128058c
/Database.cpp
a1ac7cd33a3830a4cd46dfc40136a4eb580346e6
[]
no_license
menfangwang/Simple-Database
1fbc9c17782ca6aaea64b3415de9fd96cf123330
4286f7d7f11cf12b2dcd00c4380fb72d01214fc6
refs/heads/master
2021-01-10T07:34:24.199261
2016-04-14T22:01:26
2016-04-14T22:01:26
54,804,080
0
0
null
null
null
null
UTF-8
C++
false
false
164
cpp
// // Database.cpp // Simple_Database // // Created by xiaolingtc on 3/16/16. // Copyright © 2016 xiaolingtc. All rights reserved. // #include "Database.hpp"
[ "595957155@qq.com" ]
595957155@qq.com
88f122e3e542cf09b965451861f74514ab1feced
57ec6def4e88141f002fd6c90944b444321d8f96
/examples/displacement/displacement.cpp
2a98a3c17eb31a527ec5e7a2d2bccd937e0ddd98
[ "MIT" ]
permissive
willbetheone/VulkanSample
2be302052750e8ab224de5c83e4f59b68901d052
5f327f8d66b17fdaf9d38328b71f40382cb87b50
refs/heads/master
2022-03-31T06:21:08.447750
2018-05-15T19:53:16
2018-05-15T20:01:23
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,195
cpp
/* * Vulkan Example - Displacement mapping with tessellation shaders * * Copyright (C) 2016 by Sascha Willems - www.saschawillems.de * * This code is licensed under the MIT license (MIT) * (http://opensource.org/licenses/MIT) */ #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <vector> #define GLM_FORCE_RADIANS #define GLM_FORCE_DEPTH_ZERO_TO_ONE #include <gli/gli.hpp> #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include "VulkanBuffer.hpp" #include "VulkanModel.hpp" #include "VulkanTexture.hpp" #include "vulkanexamplebase.h" #include <vulkan/vulkan.h> #define VERTEX_BUFFER_BIND_ID 0 #define ENABLE_VALIDATION false class VulkanExample : public VulkanExampleBase { private: struct { vks::Texture2D colorHeightMap; } textures; public: bool splitScreen = true; bool displacement = true; struct { VkPipelineVertexInputStateCreateInfo inputState; std::vector<VkVertexInputBindingDescription> bindingDescriptions; std::vector<VkVertexInputAttributeDescription> attributeDescriptions; } vertices; // Vertex layout for the models vks::VertexLayout vertexLayout = vks::VertexLayout({ vks::VERTEX_COMPONENT_POSITION, vks::VERTEX_COMPONENT_NORMAL, vks::VERTEX_COMPONENT_UV, }); struct { vks::Model object; } models; struct { vks::Buffer tessControl, tessEval; } uniformBuffers; struct UBOTessControl { float tessLevel = 64.0f; } uboTessControl; struct UBOTessEval { glm::mat4 projection; glm::mat4 model; glm::vec4 lightPos = glm::vec4(0.0f, -1.0f, 0.0f, 0.0f); float tessAlpha = 1.0f; float tessStrength = 0.1f; } uboTessEval; struct Pipelines { VkPipeline solid; VkPipeline wireframe = VK_NULL_HANDLE; } pipelines; VkPipelineLayout pipelineLayout; VkDescriptorSet descriptorSet; VkDescriptorSetLayout descriptorSetLayout; VulkanExample() : VulkanExampleBase(ENABLE_VALIDATION) { zoom = -1.25f; rotation = glm::vec3(-20.0f, 45.0f, 0.0f); title = "Tessellation shader displacement"; settings.overlay = true; } ~VulkanExample() { // Clean up used Vulkan resources // Note : Inherited destructor cleans up resources stored in base class vkDestroyPipeline(device, pipelines.solid, nullptr); if (pipelines.wireframe != VK_NULL_HANDLE) { vkDestroyPipeline(device, pipelines.wireframe, nullptr); }; vkDestroyPipelineLayout(device, pipelineLayout, nullptr); vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr); uniformBuffers.tessControl.destroy(); uniformBuffers.tessEval.destroy(); models.object.destroy(); textures.colorHeightMap.destroy(); } // Enable physical device features required for this example virtual void getEnabledFeatures() { // Tessellation shader support is required for this example if (deviceFeatures.tessellationShader) { enabledFeatures.tessellationShader = VK_TRUE; } else { vks::tools::exitFatal( "Selected GPU does not support tessellation shaders!", VK_ERROR_FEATURE_NOT_PRESENT); } // Fill mode non solid is required for wireframe display if (deviceFeatures.fillModeNonSolid) { enabledFeatures.fillModeNonSolid = VK_TRUE; } else { splitScreen = false; } } void loadAssets() { models.object.loadFromFile(getAssetPath() + "models/plane.obj", vertexLayout, 0.25f, vulkanDevice, queue); // Textures if (vulkanDevice->features.textureCompressionBC) { textures.colorHeightMap.loadFromFile( getAssetPath() + "textures/stonefloor03_color_bc3_unorm.ktx", VK_FORMAT_BC3_UNORM_BLOCK, vulkanDevice, queue); } else if (vulkanDevice->features.textureCompressionASTC_LDR) { textures.colorHeightMap.loadFromFile( getAssetPath() + "textures/stonefloor03_color_astc_8x8_unorm.ktx", VK_FORMAT_ASTC_8x8_UNORM_BLOCK, vulkanDevice, queue); } else if (vulkanDevice->features.textureCompressionETC2) { textures.colorHeightMap.loadFromFile( getAssetPath() + "textures/stonefloor03_color_etc2_unorm.ktx", VK_FORMAT_ETC2_R8G8B8_UNORM_BLOCK, vulkanDevice, queue); } else { vks::tools::exitFatal( "Device does not support any compressed texture format!", VK_ERROR_FEATURE_NOT_PRESENT); } } void buildCommandBuffers() { VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); VkClearValue clearValues[2]; clearValues[0].color = defaultClearColor; clearValues[1].depthStencil = {1.0f, 0}; VkRenderPassBeginInfo renderPassBeginInfo = vks::initializers::renderPassBeginInfo(); renderPassBeginInfo.renderPass = renderPass; renderPassBeginInfo.renderArea.offset.x = 0; renderPassBeginInfo.renderArea.offset.y = 0; renderPassBeginInfo.renderArea.extent.width = width; renderPassBeginInfo.renderArea.extent.height = height; renderPassBeginInfo.clearValueCount = 2; renderPassBeginInfo.pClearValues = clearValues; for (int32_t i = 0; i < drawCmdBuffers.size(); ++i) { // Set target frame buffer renderPassBeginInfo.framebuffer = frameBuffers[i]; VK_CHECK_RESULT(vkBeginCommandBuffer(drawCmdBuffers[i], &cmdBufInfo)); vkCmdBeginRenderPass(drawCmdBuffers[i], &renderPassBeginInfo, VK_SUBPASS_CONTENTS_INLINE); VkViewport viewport = vks::initializers::viewport((float)width, (float)height, 0.0f, 1.0f); vkCmdSetViewport(drawCmdBuffers[i], 0, 1, &viewport); VkRect2D scissor = vks::initializers::rect2D( splitScreen ? width / 2 : width, height, 0, 0); vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); vkCmdSetLineWidth(drawCmdBuffers[i], 1.0f); vkCmdBindDescriptorSets(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, &descriptorSet, 0, NULL); VkDeviceSize offsets[1] = {0}; vkCmdBindVertexBuffers(drawCmdBuffers[i], VERTEX_BUFFER_BIND_ID, 1, &models.object.vertices.buffer, offsets); vkCmdBindIndexBuffer(drawCmdBuffers[i], models.object.indices.buffer, 0, VK_INDEX_TYPE_UINT32); if (splitScreen) { vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.wireframe); vkCmdDrawIndexed(drawCmdBuffers[i], models.object.indexCount, 1, 0, 0, 0); scissor.offset.x = width / 2; vkCmdSetScissor(drawCmdBuffers[i], 0, 1, &scissor); } vkCmdBindPipeline(drawCmdBuffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, pipelines.solid); vkCmdDrawIndexed(drawCmdBuffers[i], models.object.indexCount, 1, 0, 0, 0); vkCmdEndRenderPass(drawCmdBuffers[i]); VK_CHECK_RESULT(vkEndCommandBuffer(drawCmdBuffers[i])); } } void setupVertexDescriptions() { // Binding description vertices.bindingDescriptions.resize(1); vertices.bindingDescriptions[0] = vks::initializers::vertexInputBindingDescription( VERTEX_BUFFER_BIND_ID, vertexLayout.stride(), VK_VERTEX_INPUT_RATE_VERTEX); // Attribute descriptions // Describes memory layout and shader positions vertices.attributeDescriptions.resize(3); // Location 0 : Position vertices.attributeDescriptions[0] = vks::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 0, VK_FORMAT_R32G32B32_SFLOAT, 0); // Location 1 : Normals vertices.attributeDescriptions[1] = vks::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 1, VK_FORMAT_R32G32B32_SFLOAT, sizeof(float) * 3); // Location 2 : Texture coordinates vertices.attributeDescriptions[2] = vks::initializers::vertexInputAttributeDescription( VERTEX_BUFFER_BIND_ID, 2, VK_FORMAT_R32G32_SFLOAT, sizeof(float) * 6); vertices.inputState = vks::initializers::pipelineVertexInputStateCreateInfo(); vertices.inputState.vertexBindingDescriptionCount = static_cast<uint32_t>(vertices.bindingDescriptions.size()); vertices.inputState.pVertexBindingDescriptions = vertices.bindingDescriptions.data(); vertices.inputState.vertexAttributeDescriptionCount = static_cast<uint32_t>(vertices.attributeDescriptions.size()); vertices.inputState.pVertexAttributeDescriptions = vertices.attributeDescriptions.data(); } void setupDescriptorPool() { // Example uses two ubos and two image samplers std::vector<VkDescriptorPoolSize> poolSizes = { vks::initializers::descriptorPoolSize(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2), vks::initializers::descriptorPoolSize( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1)}; VkDescriptorPoolCreateInfo descriptorPoolInfo = vks::initializers::descriptorPoolCreateInfo( static_cast<uint32_t>(poolSizes.size()), poolSizes.data(), 2); VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolInfo, nullptr, &descriptorPool)); } void setupDescriptorSetLayout() { std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0 : Tessellation control shader ubo vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT, 0), // Binding 1 : Tessellation evaluation shader ubo vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT, 1), // Binding 2 : Combined color (rgb) and height (alpha) map vks::initializers::descriptorSetLayoutBinding( VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 2), }; VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo( setLayoutBindings.data(), static_cast<uint32_t>(setLayoutBindings.size())); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &descriptorSetLayout)); VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&descriptorSetLayout, 1); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &pipelineLayout)); } void setupDescriptorSet() { VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &descriptorSetLayout, 1); VK_CHECK_RESULT( vkAllocateDescriptorSets(device, &allocInfo, &descriptorSet)); // Color and height map image descriptor VkDescriptorImageInfo texDescriptor = vks::initializers::descriptorImageInfo(textures.colorHeightMap.sampler, textures.colorHeightMap.view, VK_IMAGE_LAYOUT_GENERAL); std::vector<VkWriteDescriptorSet> writeDescriptorSets = { // Binding 0 : Tessellation control shader ubo vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 0, &uniformBuffers.tessControl.descriptor), // Binding 1 : Tessellation evaluation shader ubo vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, &uniformBuffers.tessEval.descriptor), // Binding 2 : Color and displacement map (alpha channel) vks::initializers::writeDescriptorSet( descriptorSet, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 2, &texDescriptor), }; vkUpdateDescriptorSets(device, static_cast<uint32_t>(writeDescriptorSets.size()), writeDescriptorSets.data(), 0, NULL); } void preparePipelines() { VkPipelineInputAssemblyStateCreateInfo inputAssemblyState = vks::initializers::pipelineInputAssemblyStateCreateInfo( VK_PRIMITIVE_TOPOLOGY_PATCH_LIST, 0, VK_FALSE); VkPipelineRasterizationStateCreateInfo rasterizationState = vks::initializers::pipelineRasterizationStateCreateInfo( VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, 0); VkPipelineColorBlendAttachmentState blendAttachmentState = vks::initializers::pipelineColorBlendAttachmentState(0xf, VK_FALSE); VkPipelineColorBlendStateCreateInfo colorBlendState = vks::initializers::pipelineColorBlendStateCreateInfo( 1, &blendAttachmentState); VkPipelineDepthStencilStateCreateInfo depthStencilState = vks::initializers::pipelineDepthStencilStateCreateInfo( VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS_OR_EQUAL); VkPipelineViewportStateCreateInfo viewportState = vks::initializers::pipelineViewportStateCreateInfo(1, 1, 0); VkPipelineMultisampleStateCreateInfo multisampleState = vks::initializers::pipelineMultisampleStateCreateInfo( VK_SAMPLE_COUNT_1_BIT, 0); std::vector<VkDynamicState> dynamicStateEnables = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR, VK_DYNAMIC_STATE_LINE_WIDTH}; VkPipelineDynamicStateCreateInfo dynamicState = vks::initializers::pipelineDynamicStateCreateInfo( dynamicStateEnables.data(), static_cast<uint32_t>(dynamicStateEnables.size()), 0); VkPipelineTessellationStateCreateInfo tessellationState = vks::initializers::pipelineTessellationStateCreateInfo(3); // Tessellation pipeline // Load shaders std::array<VkPipelineShaderStageCreateInfo, 4> shaderStages; shaderStages[0] = loadShader(getAssetPath() + "shaders/displacement/base.vert.spv", VK_SHADER_STAGE_VERTEX_BIT); shaderStages[1] = loadShader(getAssetPath() + "shaders/displacement/base.frag.spv", VK_SHADER_STAGE_FRAGMENT_BIT); shaderStages[2] = loadShader( getAssetPath() + "shaders/displacement/displacement.tesc.spv", VK_SHADER_STAGE_TESSELLATION_CONTROL_BIT); shaderStages[3] = loadShader( getAssetPath() + "shaders/displacement/displacement.tese.spv", VK_SHADER_STAGE_TESSELLATION_EVALUATION_BIT); VkGraphicsPipelineCreateInfo pipelineCreateInfo = vks::initializers::pipelineCreateInfo(pipelineLayout, renderPass, 0); pipelineCreateInfo.pVertexInputState = &vertices.inputState; pipelineCreateInfo.pInputAssemblyState = &inputAssemblyState; pipelineCreateInfo.pRasterizationState = &rasterizationState; pipelineCreateInfo.pColorBlendState = &colorBlendState; pipelineCreateInfo.pMultisampleState = &multisampleState; pipelineCreateInfo.pViewportState = &viewportState; pipelineCreateInfo.pDepthStencilState = &depthStencilState; pipelineCreateInfo.pDynamicState = &dynamicState; pipelineCreateInfo.pTessellationState = &tessellationState; pipelineCreateInfo.stageCount = static_cast<uint32_t>(shaderStages.size()); pipelineCreateInfo.pStages = shaderStages.data(); pipelineCreateInfo.renderPass = renderPass; // Solid pipeline rasterizationState.cullMode = VK_CULL_MODE_BACK_BIT; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.solid)); if (deviceFeatures.fillModeNonSolid) { // Wireframe pipeline rasterizationState.polygonMode = VK_POLYGON_MODE_LINE; rasterizationState.cullMode = VK_CULL_MODE_NONE; VK_CHECK_RESULT(vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineCreateInfo, nullptr, &pipelines.wireframe)); } } // Prepare and initialize uniform buffer containing shader uniforms void prepareUniformBuffers() { // Tessellation evaluation shader uniform buffer VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffers.tessEval, sizeof(uboTessEval))); // Tessellation control shader uniform buffer VK_CHECK_RESULT(vulkanDevice->createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffers.tessControl, sizeof(uboTessControl))); // Map persistent VK_CHECK_RESULT(uniformBuffers.tessControl.map()); VK_CHECK_RESULT(uniformBuffers.tessEval.map()); updateUniformBuffers(); } void updateUniformBuffers() { // Tessellation eval glm::mat4 viewMatrix = glm::mat4(1.0f); uboTessEval.projection = glm::perspective( glm::radians(45.0f), (float)(width) / (float)height, 0.1f, 256.0f); viewMatrix = glm::translate(viewMatrix, glm::vec3(0.0f, 0.0f, zoom)); uboTessEval.model = glm::mat4(1.0f); uboTessEval.model = viewMatrix * glm::translate(uboTessEval.model, glm::vec3(0, 0, 0)); uboTessEval.model = glm::rotate(uboTessEval.model, glm::radians(rotation.x), glm::vec3(1.0f, 0.0f, 0.0f)); uboTessEval.model = glm::rotate(uboTessEval.model, glm::radians(rotation.y), glm::vec3(0.0f, 1.0f, 0.0f)); uboTessEval.model = glm::rotate(uboTessEval.model, glm::radians(rotation.z), glm::vec3(0.0f, 0.0f, 1.0f)); uboTessEval.lightPos.y = -0.5f - uboTessEval.tessStrength; memcpy(uniformBuffers.tessEval.mapped, &uboTessEval, sizeof(uboTessEval)); // Tessellation control float savedLevel = uboTessControl.tessLevel; if (!displacement) { uboTessControl.tessLevel = 1.0f; } memcpy(uniformBuffers.tessControl.mapped, &uboTessControl, sizeof(uboTessControl)); if (!displacement) { uboTessControl.tessLevel = savedLevel; } } void draw() { VulkanExampleBase::prepareFrame(); // Command buffer to be sumitted to the queue submitInfo.commandBufferCount = 1; submitInfo.pCommandBuffers = &drawCmdBuffers[currentBuffer]; // Submit to queue VK_CHECK_RESULT(vkQueueSubmit(queue, 1, &submitInfo, VK_NULL_HANDLE)); VulkanExampleBase::submitFrame(); } void prepare() { VulkanExampleBase::prepare(); loadAssets(); setupVertexDescriptions(); prepareUniformBuffers(); setupDescriptorSetLayout(); preparePipelines(); setupDescriptorPool(); setupDescriptorSet(); buildCommandBuffers(); prepared = true; } virtual void render() { if (!prepared) return; draw(); } virtual void viewChanged() { updateUniformBuffers(); } virtual void OnUpdateUIOverlay(vks::UIOverlay *overlay) { if (overlay->header("Settings")) { if (overlay->checkBox("Tessellation displacement", &displacement)) { updateUniformBuffers(); } if (overlay->inputFloat("Strength", &uboTessEval.tessStrength, 0.025f, 3)) { updateUniformBuffers(); } if (overlay->inputFloat("Level", &uboTessControl.tessLevel, 0.5f, 2)) { updateUniformBuffers(); } if (deviceFeatures.fillModeNonSolid) { if (overlay->checkBox("Splitscreen", &splitScreen)) { buildCommandBuffers(); updateUniformBuffers(); } } } } }; VULKAN_EXAMPLE_MAIN()
[ "jaebaek@google.com" ]
jaebaek@google.com
5b6027e2fd8516e32f2395a38ba07b9fe8e34265
23c7d101bc49099d5dd4d9185a39f450dd566c32
/src/stack.h
2fb47b31b6d380e918a95f63c82b6f12f5bcec77
[]
no_license
gracerpro/luaob
27c84f9febf754423402125b9de22073bdb34a09
ca18aa9e8270f00cbe81127e3cd86da2dd2b0a47
refs/heads/master
2022-10-03T05:26:20.218369
2014-07-04T19:45:36
2014-07-04T19:45:36
14,826,928
14
6
null
2023-04-06T05:27:29
2013-11-30T19:24:38
C++
UTF-8
C++
false
false
940
h
// stack.h #include <string> struct stObfuscatedName { std::string name; std::string fake_name; }; class LocalVarsStack { public: LocalVarsStack(size_t initCount = STACK_CAPACITY); ~LocalVarsStack(); void push(const stObfuscatedName& obfuscatedName); void push(const char *name, const char *fake_name); void pop(); void pops(size_t elementCount = 1); friend LocalVarsStack& operator+= (LocalVarsStack& stackDest, const LocalVarsStack& stackSource); stObfuscatedName& top() const; size_t getTopIndex() const; stObfuscatedName& items(const size_t index) const; bool find(stObfuscatedName& obfuscatedName) const; bool find(const std::string& name) const; bool find(const char *name) const; size_t count() const; bool empty() const; private: enum { STACK_CAPACITY = 16, INDEX_NULL = -1 }; stObfuscatedName* m_data; size_t m_count; size_t m_reservedCount; };
[ "gracerpro@gmail.com" ]
gracerpro@gmail.com
2bd8942b5bce23ff51a96fb38a9b22bb2d72cb02
764d6e74bccd222454983bcf224129b041db9831
/XIntersect.cpp
83f4817717399c32ab44003e70a6f81f1c4e8708
[ "MIT" ]
permissive
Legacy-LuaSTG-Engine/lstgx_Math
6da4151da96f6003531bc058f726b8cab12eb508
d63939b5b5cd69ffeaa908f2ec38708a62ad3139
refs/heads/master
2023-05-06T02:41:03.444557
2021-05-31T03:21:12
2021-05-31T03:21:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
11,127
cpp
#include "XIntersect.h" #include "XDistance.h" #include "XMath.h" using namespace xmath; using namespace cocos2d; bool intersect::Point_AABB(const Vec2& p0, const Vec2& p1, float halfW, float halfH) { const auto dx = p0.x - p1.x; const auto dy = p0.y - p1.y; return -halfW < dx&&dx < halfW&&-halfH < dy&&dy < halfH; } bool intersect::Point_OBB(const Vec2& p0, const Vec2& p1, float halfW, float halfH, float rot) { auto p = p0; p.rotate(p1, -rot); return Point_AABB(p, p1, halfW, halfH); } bool intersect::Point_Diamond(const Vec2& p0, const Vec2& p1, float a, float b, float rot) { auto p = p0 - p1; p.rotate(Vec2::ZERO, -rot); const auto x_ = p.x / a; const auto y_ = p.y / b; const auto sum = x_ + y_; const auto dif = x_ - y_; return -1 < sum&&sum < 1 && -1 < dif&&dif < 1; } bool intersect::Point_Ellipse(const Vec2& p0, const Vec2& p1, float a, float b, float rot) { if (a == b) return Point_Circle(p0, p1, a); auto p = p0 - p1; p.rotate(Vec2::ZERO, -rot); const auto x = p.x; const auto y = p.y; return x * x / (a * a) + y * y / (b * b) < 1; } bool intersect::Point_Triangle(const Vec2& p, const Vec2& A, const Vec2& B, const Vec2& C) { return Point_Triangle(p - B, A - B, C - B); } bool intersect::Point_Triangle(const Vec2& P, const Vec2& E0, const Vec2& E1) { const auto _den = E0.y*E1.x - E0.x*E1.y; const auto s = (P.y*E1.x - P.x*E1.y) / _den; const auto t = (P.x*E0.y - P.y*E0.x) / _den; return s > 0 && t > 0 && s + t < 1; } bool intersect::Point_Parallelogram(const Vec2& p0, const Vec2& p1, const Vec2& halfDiagA, const Vec2& halfDiagB) { const auto E0 = halfDiagA + halfDiagB; const auto E1 = halfDiagA - halfDiagB; const auto P = p0 - p1 + halfDiagA; const auto _den = E0.y*E1.x - E0.x*E1.y; const auto s = (P.y*E1.x - P.x*E1.y) / _den; const auto t = (P.x*E0.y - P.y*E0.x) / _den; return 0 < s&&s < 1 && 0 < t&&t < 1; } bool intersect::OBB_Circle(const Vec2& p0, float halfW, float halfH, float rot, const Vec2& p1, float r) { float tSin, tCos; SinCos(rot, tSin, tCos); const auto d = p0 - p1; const auto dw = std::max(0.f, std::abs(tCos * d.x + tSin * d.y) - halfW); const auto dh = std::max(0.f, std::abs(-tSin * d.x + tCos * d.y) - halfH); return r * r >= dh * dh + dw * dw; } bool intersect::OBB_OBB(const Vec2& p0, float halfW0, float halfH0, float rot0, const Vec2& p1, float halfW1, float halfH1, float rot1) { float tSin0, tCos0; SinCos(rot0, tSin0, tCos0); float tSin1, tCos1; SinCos(rot1, tSin1, tCos1); Vec2 e[] = { {tCos0, tSin0},//e00 {-tSin0, tCos0},//e01 {tCos1, tSin1},//e10 {-tSin1, tCos1}//e11 }; float projOther[] = { halfW0,halfH0,halfW1,halfH1 }; const auto d = p0 - p1; for (size_t i = 0; i < 4; i++) { const auto ii = 2 - size_t(i / 2) * 2;//2200 const auto v0 = e[ii] * projOther[ii]; const auto v1 = e[ii + 1] * projOther[ii + 1]; const auto ex = e[i].x; const auto ey = e[i].y; const auto projHalfDiag = std::max( std::abs(ex*(v0.x + v1.x) + ey * (v0.y + v1.y)), std::abs(ex*(v0.x - v1.x) + ey * (v0.y - v1.y)) ); if (projHalfDiag + projOther[i] < std::abs(ex * d.x + ey * d.y)) return false; } return true; } bool intersect::OBB_Line(const Vec2& p0, float halfW0, float halfH0, float rot0, const Vec2& p1, float rot1) { float tSin0, tCos0; SinCos(rot0, tSin0, tCos0); float tSin1, tCos1; SinCos(rot1, tSin1, tCos1); const Vec2 e00(tCos0, tSin0); const Vec2 e01(-tSin0, tCos0); const Vec2 halfDiag0 = e00 * halfW0 + e01 * halfH0; const Vec2 halfDiag1 = e00 * halfW0 - e01 * halfH0; Vec2 eProj(-tSin1, tCos1); const auto halfProj = std::max( std::abs(eProj.dot(halfDiag0)), std::abs(eProj.dot(halfDiag1))); const auto d = distance::Point_Line(p0, p1, tCos1, tSin1); return d <= halfProj; } bool intersect::OBB_Triangle( const Vec2& p, float halfW, float halfH, float rot, const Vec2& A, const Vec2& B, const Vec2& C) { float tSin, tCos; SinCos(rot, tSin, tCos); const Vec2 hw(tCos*halfW, tSin*halfW); const Vec2 hh(-tSin * halfH, tCos*halfH); const auto v0 = p + hw + hh; const auto v1 = p + hw - hh; const auto v2 = p - hw - hh; const auto v3 = p - hw + hh; return Triangle_Triangle(A, B, C, v0, v1, v2) || Triangle_Triangle(A, B, C, v0, v3, v2); } bool intersect::OBB_Diamond(const Vec2& p0, float halfW, float halfH, float rot0, const Vec2& p1, float a, float b, float rot1) { float tSin0, tCos0, tSin1, tCos1; SinCos(rot0, tSin0, tCos0); SinCos(rot1, tSin1, tCos1); const Vec2 hw(tCos0*halfW, tSin0*halfW); const Vec2 hh(-tSin0*halfH, tCos0*halfH); return Parallelogram_Parallelogram( p0, hw + hh, hw - hh, p1, Vec2(tCos1*a, tSin1*a), Vec2(-tSin1 * b, tCos1*b)); } bool intersect::OBB_Ellipse(const Vec2& p0, float halfW, float halfH, float rot0, const Vec2& p1, float a, float b, float rot1) { if (a == b) return OBB_Circle(p0, halfW, halfH, rot0, p1, a); float tSin0, tCos0; SinCos(rot0, tSin0, tCos0); float tSin1, tCos1; SinCos(rot1, tSin1, tCos1); const auto e00 = Vec2(tCos0, tSin0); const auto e01 = Vec2(-tSin0, tCos0); const auto e11 = Vec2(-tSin1, tCos1); const auto f = e11 * (a / b - 1); const auto p0_ = p0 + distance::Point_Line_signed(p0, p1, e11) * f; const auto tmp = e00 * halfW + p0; const auto vDiag0 = tmp + e01 * halfH; const auto vDiag1 = tmp - e01 * halfH; const auto vDiag0_ = vDiag0 + distance::Point_Line_signed(vDiag0, p1, e11) * f; const auto vDiag1_ = vDiag1 + distance::Point_Line_signed(vDiag1, p1, e11) * f; const auto halfDiag0_ = vDiag0_ - p0_; const auto halfDiag1_ = vDiag1_ - p0_; const auto d = distance::Point_Parallelogram(p1, p0_, halfDiag0_, halfDiag1_); return d <= a; } bool intersect::Circle_Ellipse(const Vec2& p0, float r, const Vec2& p1, float a, float b, float rot) { return distance::Point_Ellipse2(p0, p1, a, b, rot) <= r; } bool intersect::Circle_Diamond(const Vec2& p0, float r, const Vec2& p1, float a, float b, float rot) { return distance::Point_Diamond(p0, p1, a, b, rot) <= r; } bool intersect::Circle_Triangle(const Vec2& p, float r, const Vec2& A, const Vec2& B, const Vec2& C) { return distance::Point_Triangle(p, A, B, C) <= r; } bool intersect::Ellipse_Ellipse( const Vec2& p0, float a0, float b0, float rot0, const Vec2& p1, float a1, float b1, float rot1) { if (a0 == b0) return Circle_Ellipse(p0, a0, p1, a1, b1, rot1); if (a1 == b1) return Circle_Ellipse(p1, a1, p0, a0, b0, rot0); float s, c; SinCos(rot1 - rot0, s, c); const auto c2 = c * c; const auto s2 = s * s; const auto sc = s * c; const auto a_ = 1 / (a1*a1); const auto b_ = 1 / (b1*b1); const auto m00 = (a_ * c2 + b_ * s2) * (a0*a0); const auto m11 = (b_ * c2 + a_ * s2) * (b0*b0); const auto m01 = (a_ - b_)*sc * (a0*b0); const auto sum = m00 + m11; const auto tmp = m00 - m11; const auto dif = std::sqrt(tmp*tmp + 4 * m01*m01); const auto tanv = 2 * m01 / (dif + m00 - m11); float s0, c0; SinCos(-rot0, s0, c0); const auto d = p1 - p0; auto d_ = Vec2(d.x*c0 - d.y*s0, d.y*c0 + d.x*s0); d_.x /= a0; d_.y /= b0; return distance::Point_Ellipse2( Vec2::ZERO, d_, std::sqrt(2 / (sum + dif)), std::sqrt(2 / (sum - dif)), std::atan(tanv)) <= 1; } bool intersect::Ellipse_Diamond(const Vec2& p0, float a0, float b0, float rot0, const Vec2& p1, float a1, float b1, float rot1) { if (a0 == b0) return Circle_Diamond(p0, a0, p1, a1, b1, rot1); float s, c; SinCos(rot1 - rot0, s, c); const auto fac = a0 / b0; auto p = p1 - p0; p.rotate(Vec2::ZERO, -rot0); p.y *= fac; return distance::Point_Parallelogram( Vec2::ZERO, p, Vec2(c*a1, s*a1*fac), Vec2(-s * b1, c*b1*fac)) <= a0; } bool intersect::Ellipse_Triangle(const Vec2& p, float a, float b, float rot, const Vec2& A, const Vec2& B, const Vec2& C) { if (a == b) return Circle_Triangle(p, a, A, B, C); float s, c; SinCos(-rot, s, c); const auto fac = a / b; const auto PA = A - p; const auto PB = B - p; const auto PC = C - p; const Vec2 A_(PA.x*c - PA.y*s, (PA.y*c + PA.x*s)*fac); const Vec2 B_(PB.x*c - PB.y*s, (PB.y*c + PB.x*s)*fac); const Vec2 C_(PC.x*c - PC.y*s, (PC.y*c + PC.x*s)*fac); return Point_Triangle(Vec2::ZERO, A_, B_, C_); } bool intersect::Segment_Segment(const Vec2& A0, const Vec2& B0, const Vec2& A1, const Vec2& B1) { const auto A0B0 = B0 - A0; const auto A0A1 = A1 - A0; const auto A0B1 = B1 - A0; const auto c1 = A0B0.cross(A0A1); const auto c2 = A0B0.cross(A0B1); if (c1 == 0.f&&c2 == 0.f) { if (A0B0.lengthSquared() == 0.f) return false; const auto t1 = (A0B0.x == 0.f) ? A0A1.y / A0B0.y : A0A1.x / A0B0.x; const auto t2 = (A0B0.x == 0.f) ? A0B1.y / A0B0.y : A0B1.x / A0B0.x; return (0 < t1&&t1 < 1) || (0 < t2&&t2 < 1) || (t1 < 0 && 1 < t2) || (t2 < 0 && 1 < t1); } if (c1*c2 > 0) return false; const auto A1B1 = B1 - A1; //if (A1B1.lengthSquared() == 0.f) // return false; const auto c3 = -A1B1.cross(A0A1); const auto c4 = A1B1.cross(B0 - A1); return c3 * c4 < 0; } bool intersect::Triangle_Triangle(const Vec2& A0, const Vec2& B0, const Vec2& C0, const Vec2& A1, const Vec2& B1, const Vec2& C1) { const auto E00 = A0 - B0; const auto E01 = C0 - B0; for (auto& p : { A1,B1,C1 }) { if (Point_Triangle(p - B0, E00, E01)) return true; } const auto E10 = A1 - B1; const auto E11 = C1 - B1; for (auto& p : { A0,B0,C0 }) { if (Point_Triangle(p - B1, E10, E11)) return true; } for (auto& p0 : { A0,C0 }) { for (auto& p1 : { A1,C1 }) { if (Segment_Segment(B0, p0, B1, p1)) return true; } } return false; } bool intersect::Parallelogram_Parallelogram( const Vec2& p0, const Vec2& halfDiagA0, const Vec2& halfDiagB0, const Vec2& p1, const Vec2& halfDiagA1, const Vec2& halfDiagB1) { const auto d01 = p1 - p0; for (auto& e : { (halfDiagA0 + halfDiagB0), (halfDiagA0 - halfDiagB0), (halfDiagA1 + halfDiagB1), (halfDiagA1 - halfDiagB1)}) { const auto ep = e.getPerp().getNormalized(); const auto proj0 = std::max(std::abs(ep.dot(halfDiagA0)), std::abs(ep.dot(halfDiagB0))); const auto proj1 = std::max(std::abs(ep.dot(halfDiagA1)), std::abs(ep.dot(halfDiagB1))); if (proj0 + proj1 < std::abs(ep.dot(d01))) return false; } return true; } bool intersect::Diamond_Diamond( const Vec2& p0, float a0, float b0, float rot0, const Vec2& p1, float a1, float b1, float rot1) { float tSin0, tCos0, tSin1, tCos1; SinCos(rot0, tSin0, tCos0); SinCos(rot1, tSin1, tCos1); return Parallelogram_Parallelogram( p0, Vec2(tCos0*a0, tSin0*a0), Vec2(-tSin0 * b0, tCos0*b0), p1, Vec2(tCos1*a1, tSin1*a1), Vec2(-tSin1 * b1, tCos1*b1)); } bool intersect::Diamond_Triangle(const Vec2& p, float a, float b, float rot, const Vec2& A, const Vec2& B, const Vec2& C) { float tSin, tCos; SinCos(rot, tSin, tCos); const Vec2 hd0(tCos*a, tSin*a); const Vec2 hd1(-tSin*b, tCos*b); const auto v0 = p + hd0; const auto v1 = p + hd1; const auto v2 = p - hd0; const auto v3 = p - hd1; return Triangle_Triangle(A, B, C, v0, v1, v2) || Triangle_Triangle(A, B, C, v0, v3, v2); } bool intersect::Line_Circle(const Vec2& p0, float r, const Vec2& p1, float rot) { float tSin0, tCos0; SinCos(rot, tSin0, tCos0); return distance::Point_Line(p0, p1, tCos0, tSin0) <= r; }
[ "xrysnow@outlook.com" ]
xrysnow@outlook.com
f15a10894e92bde744b8cc5598602bbb694e39e8
66373475210367b11fb872f4b14c9ce6c5a59add
/BasePrimitive/BasePrimitive/Vertices.hpp
c2be8cb3c96637caa8d5ab2684796af17245b38a
[ "MIT" ]
permissive
roastduckcd/OpenGL
3d7452f9dbe5d0776448e8ebfe29b54e81ab919e
a90e377668d5be806706bb037e9042eb3423dc55
refs/heads/master
2020-05-26T10:24:21.513378
2019-07-17T01:25:56
2019-07-17T01:25:56
188,202,414
0
0
null
null
null
null
UTF-8
C++
false
false
493
hpp
// // Vertices.hpp // BasePrimitive // // Created by yang song on 2019/6/2. // Copyright © 2019 yangsong. All rights reserved. // #ifndef Vertices_hpp #define Vertices_hpp #include <stdio.h> #ifdef __APPLE__ #include "TargetConditionals.h" #endif #include "GLTools.h" #ifdef __APPLE__ #include <glut/glut.h> #else #define FREEGLUT_STATIC #include <GL/glut.h> #endif GLfloat *getVertices(int *count); void setupVertexData(GLBatch *batch, GLenum primitive); #endif /* Vertices_hpp */
[ "roart_duck@163.com" ]
roart_duck@163.com
ac762fe8a3eb802e3c855a1b75a41115bc609e07
f5e0fbe7cd268e54e68a5d43bd97d90c25d9a895
/Source/npsflibScripts/InputStuff.cpp
dafcf52232fab9707c135793a3f4e36c8f3ed75e
[]
no_license
HxCory/delayFitting
a0e97ace0ab97a3c05a80025ac6b19e1e8308543
f2f4862da7d6edf0ab8d759df71413035cd81422
refs/heads/master
2020-05-22T03:59:11.922006
2016-09-12T23:09:33
2016-09-12T23:09:33
65,320,990
3
0
null
null
null
null
UTF-8
C++
false
false
4,508
cpp
#include <string.h> #include <stdlib.h> #include "InputStuff.h" extern Parameter<string> outputFolder; // it's defined outside ConfigFileParser cfg; // global //void create_dir(std::string & name){ inline std::string create_dir(std::string name){ /** * name - name of the directory to be created * (for instance a global parameter) * In case directory name exists the function * tries name__1, name__2, ... etc. * * If it was succesfull returns the new directory name * ( and also used to append it to the file "_jobnames" ) * * Exits the program in case of failure. * * possible simple modifications: * - change cerr to other stream, like log file * (now both success and different failures are reported), change format of logs * - change the rule for choosing names * - change exit to other action * - change permissions of created directory * - set if you want to respect umask or not (set const bool parameter) * - maximal nr of names it tries is 10000 now */ using namespace std; int i=0; mode_t mask; FILE *jobnames; const bool respect_umask=false; stringstream tmp; tmp.str(""); // set string to empty tmp<<name; if(!respect_umask) mask=umask(007); //optionally skip system-wide umask while(i<10000){ // here permissions, see sys/stat.h for names (may be google) if(mkdir( tmp.str().c_str(),S_IRWXU|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)==0){ //after successful creation of directory do the following stuff //and exit from this function returning the new name /* jobnames=fopen("_jobnames","a"); if(jobnames==NULL){ cerr<<__FILE__<<":"<<__LINE__<<": "<<strerror(errno)<<"; _jobnames not updated"<<endl; } else{ fprintf(jobnames,"%s\n",tmp.str().c_str()); fclose(jobnames); } */ //here cerr cout<<__FILE__<<":"<<__LINE__<<": created directory \""<<tmp.str()<<"\""<<endl; //if(!respect_umask) umask(mask); // reset umask at the return return tmp.str(); } if(errno!=EEXIST) break; i++; tmp.str(""); //reset the string // here creation of suffixes tmp<<name<<"__"<<i; } //the following is in case of failure cerr<<__FILE__<<":"<<__LINE__<<": "<<strerror(errno)<<". Were not able to create directory "<< name<<endl; cerr<<"exit"<<endl; //if(!respect_umask) umask(mask); // reset umask at the return exit(1); } void touchdir(std::string name){ /** * name - name of the directory to be created * (for instance a global parameter) * * Exits the program in case of failure. * */ using namespace std; mode_t mask; const bool respect_umask=false; // check exsistence of dir struct stat st; stat(name.c_str(), &st); if(S_ISDIR(st.st_mode)) return; // directory already there if(!respect_umask) mask=umask(0); //optionally skip system-wide umask // here permissions, see sys/stat.h for names (may be google) if(mkdir( name.c_str(),S_IRWXU|S_IWGRP|S_IRGRP|S_IXGRP|S_IROTH|S_IXOTH)==0){ //here cerr cout<<__FILE__<<":"<<__LINE__<<": created directory \""<<name<<"\""<<endl; if(!respect_umask) umask(mask); // reset umask at the return } else { cerr<<__FILE__<<":"<<__LINE__<<": "<<strerror(errno)<<". Were not able to create directory "<< name<<endl; if(!respect_umask) umask(mask); // reset umask at the return exit(1); } } void parseInput(int argc, char *argv[]){ string cfgName("example.cfg"); if( argc == 2 ) { cfgName=argv[1]; } else { cerr<<"usage: "<<argv[0]<<" configfile"<<endl; cerr<<"trying default: "<<cfgName<<endl; } /***************************************/ // read configuration file, name may be obtained from command line cfg.read( cfgName.c_str() ); // the next line gets a pointer to the ParameterMap object: //ParameterMap& parameters = ParameterMap::instance(); ParameterMap parameters; // initialize all Paramter<T> type objects from the config file parameters.init( cfg ); // | could also simply become global::paramters.init( cfg ) | // | instead of the two lines above | // create the output directory (after reading the name of the job from cfg) string job = parameters["jobname"]->getValueString(); outputFolder.set(create_dir( job )+"/"); // with slash at the end! cout<<parameters; cout<<"Press Ctrl-C to stop"<<endl; //sleep(3); /****************************************/ }
[ "coryscottgoldsmith@gmail.com" ]
coryscottgoldsmith@gmail.com
8ce3faab1ec7d5be3b58324f2d2118a5daec9cf6
eb4d50fe7f5dc9ec8dcf786e3d6b1321ae2a443e
/lab5/Time/Time/Time/main.cpp
940f128eafe948048eaf086e570068c3e0a67ae3
[]
no_license
EvgeniyGlazirin/oop
196d9ad5ef4802cd4573e53f3192dddc6895dbed
82a964151c6eda8bd308293c4014d0519f3945bc
refs/heads/master
2021-04-29T13:26:15.450641
2018-06-29T20:02:58
2018-06-29T20:02:58
121,751,696
0
0
null
null
null
null
UTF-8
C++
false
false
64
cpp
#include "stdafx.h" #include "Time.h" int main() { return 0; }
[ "technoglazirin@gmail.com" ]
technoglazirin@gmail.com
dce10d5a1ab20480c5396a84cfd753cfc9b2557b
bec6ce9163fa330c166cf54e5e5976a6ad21368a
/i_PIRsensor.ino
ee89cccb5d1042e5ac66fa2fb7c042a86e5fa615
[ "MIT" ]
permissive
B3ND3R/MewPro
d37287dd40f31a5be0555cec1a4f6e6efcc70f78
895ded6efb8b8d02bbf503c57b890259e586a641
refs/heads/master
2020-12-24T19:45:35.297565
2016-02-07T23:35:01
2016-02-07T23:35:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,464
ino
/* * ////////////////////////////////////////////////// * //making sense of the Parallax PIR sensor's output * ////////////////////////////////////////////////// * * Switches video recording according to the state of the sensors output pin. * Determines the beginning and end of continuous motion sequences. * * Original code is located at * http://playground.arduino.cc/Code/PIRsense * @author: Kristian Gohlke / krigoo (_) gmail (_) com / http://krx.at * @date: 3. September 2006 * * kr1 (cleft) 2006 * released under a creative commons "Attribution-NonCommercial-ShareAlike 2.0" license * http://creativecommons.org/licenses/by-nc-sa/2.0/de/ * * Modified by orangkucing for MewPro (c) 2014 * * The Parallax PIR Sensor is an easy to use digital infrared motion sensor module. * ( http://www.parallax.com/product/555-28027 ) * * The sensor's output pin goes to HIGH if motion is present. * However, even if motion is present it goes to LOW from time to time, * which might give the impression no motion is present. * This program deals with this issue by ignoring LOW-phases shorter than a given time, * assuming continuous motion is present during these phases. * */ #ifdef USE_PIR_SENSOR void setupPIRSensor() { pinMode(PIR_PIN, INPUT); __debug(F("PIR sensor calibration start (10 seconds)")); } void checkPIRSensor() { //the time when the sensor outputs a low impulse static unsigned long lowIn; //the amount of seconds the sensor has to be low //before we assume all motion has stopped const unsigned long pause = 5; static boolean lockLow = true; static boolean takeLowTime; if (millis() < 10000) { // Still calibrating... return; } if (digitalRead(PIR_PIN) == HIGH) { if (lockLow){ //makes sure we wait for a transition to LOW before any further output is made: lockLow = false; __debug(F("---")); __debug(F("motion detected at ")); #ifdef USE_TIME_ALARMS if (debug) { time_t t = now(); char s[20]; sprintf(s, "%04d-%02d-%02d %02d:%02d:%02d", year(t), month(t), day(t), hour(t), minute(t), second(t)); Serial.println(s); } #else if (debug) { Serial.print(millis() / 1000); } __debug(F(" sec")); #endif startRecording(); } takeLowTime = true; } if (digitalRead(PIR_PIN) == LOW) { if (takeLowTime) { lowIn = millis(); //save the time of the transition from high to LOW takeLowTime = false; //make sure this is only done at the start of a LOW phase } //if the sensor is low for more than the given pause, //we assume that no more motion is going to happen if (!lockLow && millis() - lowIn > pause * 1000) { //makes sure this block of code is only executed again after //a new motion sequence has been detected lockLow = true; __debug(F("motion finished at ")); //output #ifdef USE_TIME_ALARMS if (debug) { time_t t = now() - pause; char s[20]; sprintf(s, "%04d-%02d-%02d %02d:%02d:%02d", year(t), month(t), day(t), hour(t), minute(t), second(t)); Serial.println(s); } #else if (debug) { Serial.print(millis() / 1000 - pause); } __debug(F(" sec")); #endif stopRecording(); } } } #else void setupPIRSensor() { } void checkPIRSensor() { } #endif
[ "orangkucing@mac.com" ]
orangkucing@mac.com
ee23e934e6b2d2b667c893b8bc83a8d06fd3217d
eb0a0014ca44f231e67d002fccc3682fded80116
/01-Win32/09-Multithreading/window.cpp
6a186258f1eecc6e9146a5bfb0c855874b873cbb
[]
no_license
devgroupJava/Win32SDK_2021
e8fc7451f10ff55475844785db57b58e4be55759
32cb6dba8242f88365b46a365b1958350643e9cd
refs/heads/master
2023-06-23T12:32:35.831016
2021-07-22T13:25:21
2021-07-22T13:25:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,804
cpp
#include <windows.h> #include "Window.h" #include<tchar.h> //global function decalration LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); DWORD WINAPI ThreadProcOne(LPVOID); DWORD WINAPI ThreadProcTwo(LPVOID); //global variable decalaration //Entry point function int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdLine, int iCmdShow) { //local variable declaration WNDCLASSEX wndClass; HWND hwnd; MSG msg; TCHAR szAppName[] = TEXT("MyWindow"); //code wndClass.cbSize = sizeof(WNDCLASSEX); wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = WndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = hInstance; wndClass.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(MYICON)); wndClass.hCursor = LoadCursor(NULL,IDC_ARROW); wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndClass.lpszClassName = szAppName; wndClass.lpszMenuName = NULL; wndClass.hIconSm = LoadIcon(hInstance, MAKEINTRESOURCE(MYICON)); RegisterClassEx(&wndClass); //create window in memory hwnd = CreateWindow(szAppName, TEXT("DRG:Multi Threading"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInstance, NULL); ShowWindow(hwnd, iCmdShow); UpdateWindow(hwnd); //Message Loop while (GetMessage(&msg,NULL,0,0)) { TranslateMessage(&msg); DispatchMessage(&msg); } return((int)msg.wParam); } LRESULT CALLBACK WndProc(HWND hwnd,UINT iMsg,WPARAM wParam, LPARAM lParam) { static HANDLE hThread1 = NULL; static HANDLE hThread2 = NULL; //code switch (iMsg) { case WM_CREATE: hThread1 = CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)ThreadProcOne,(LPVOID)hwnd,0,NULL); //to create thread ani returns handle // para1 : security parameter NULL means default // para2 : size of stack because every thread has own stack..0 means mala size tharvata yet nai aahe os tu main thread la jo detes to mala de Os tu tharav // para3 : Every thread has its associated function.Ya thread cha callback function LPTHREAD_START_ROUTINE ya pointer la typecast kara.. // para4 : 4th parameter 4th para n manta to 3rd para madhe lihilelya function cha parameter mana // para5 : Tumhala thread kasa pahije hawa..0 mhnje lgech suru ho // para6 : Thread cha id till win97 /***here should be error checking for hThread1***/ hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProcTwo, (LPVOID)hwnd, 0, NULL); /***here should be error checking for hThread2***/ break; case WM_LBUTTONDOWN: MessageBox(hwnd, TEXT("I am thread4"), TEXT("Message"),MB_OK); break; case WM_DESTROY: //CloseHandle(hThread1); //to close thread CloseHandle(hThread2); PostQuitMessage(0); break; default : break; } return(DefWindowProc(hwnd,iMsg,wParam,lParam)); } DWORD WINAPI ThreadProcOne(LPVOID param) { //Variable Declaration HDC hdc = NULL; TCHAR str[255]; long i; //code hdc = GetDC((HWND)param); SetBkColor(hdc, RGB(0, 0, 0)); SetTextColor(hdc, RGB(0,255,0)); for ( i = 0; i < 2147483648; i++) { wsprintf(str,TEXT("Incrementing Order : %ld"),i); TextOut(hdc,5,5,str,(int)_tcslen(str)); //special para,x,y,string,tchar valya string chi length kadhnyasathi } ReleaseDC((HWND)param, hdc); return(0); } DWORD WINAPI ThreadProcTwo(LPVOID param) { //Variable Declaration HDC hdc = NULL; TCHAR str[255]; long i; //code hdc = GetDC((HWND)param); SetBkColor(hdc, RGB(0, 0, 0)); SetTextColor(hdc, RGB(255, 0, 0)); for (i = 2147483647; i >= 0; i--) { wsprintf(str, TEXT("Decrementing Order : %ld"), i); TextOut(hdc, 5, 25, str, (int)_tcslen(str)); //special para,x,y,string,tchar valya string chi length kadhnyasathi } ReleaseDC((HWND)param, hdc); return(0); }
[ "devenghadge13@gmail.com" ]
devenghadge13@gmail.com
910a34f2a7c4e1eec12902ee87ca434708743019
e4f5424ec408fe27a23396483af15fb131f1267f
/output/bMod.cpp
9dcd61416c0545ad6b284cc72f83d7aeca51d286
[]
no_license
mwegner/chaotica-apophysis-plugins-from-jwildfire
4053b32f83c055d9a5f032b70f5588ab1f1be3a9
717b452d3e6f6c690bd4c0ecd7057390d4f92337
refs/heads/master
2020-04-16T12:42:48.686683
2019-04-01T01:03:30
2019-04-01T01:03:30
165,593,324
7
2
null
null
null
null
UTF-8
C++
false
false
5,379
cpp
#define PLUGIN_WARNING "NOTE_modded_for_jwildfire_workflow" /* Apophysis Plugin: bMod Port of: https://github.com/thargor6/JWildfire/blob/master/src/org/jwildfire/create/tina/variation/BModFunc.java This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "datahelpers.h" typedef struct { double radius; double distance; } Variables; #define APO_VARIABLE_PREFIX "bMod_" #include "plugin.h" APO_PLUGIN("bMod"); APO_VARIABLES( VAR_REAL(radius, 1.0), VAR_REAL(distance, 0.0) ); int PluginVarPrepare(Variation* vp) { return TRUE; } int PluginVarCalc(Variation* vp) { // bMod by Michael Faber, http://michaelfaber.deviantart.com/art/bSeries-320574477 double tau, sigma; double temp; double cosht, sinht; double sins, coss; tau = 0.5 * (log(sqr(FTx + 1.0) + sqr(FTy)) - log(sqr(FTx - 1.0) + sqr(FTy))); sigma = M_PI - atan2(FTy, FTx + 1.0) - atan2(FTy, 1.0 - FTx); if (tau < VAR(radius) && -tau < VAR(radius)) { tau = fmod(tau + VAR(radius) + VAR(distance) * VAR(radius), 2.0 * VAR(radius)) - VAR(radius); } sinht = sinh(tau); cosht = cosh(tau); sins = sin(sigma); coss = cos(sigma); temp = cosht - coss; if (temp == 0) { return TRUE; } FPx += VVAR * sinht / temp; FPy += VVAR * sins / temp; if (true /* pContext\.isPreserveZCoordinate() */) { FPz += VVAR * FTz; } return TRUE; } // original java file embedded here: // // /* // JWildfire - an image and animation processor written in Java // Copyright (C) 1995-2011 Andreas Maschke // // This is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser // General Public License as published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This software is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without // even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License along with this software; // if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA // 02110-1301 USA, or see the FSF site: http://www.fsf.org. // */ // package org.jwildfire.create.tina.variation; // // import org.jwildfire.create.tina.base.XForm; // import org.jwildfire.create.tina.base.XYZPoint; // // import static org.jwildfire.base.mathlib.MathLib.*; // // public class BModFunc extends VariationFunc { // private static final long serialVersionUID = 1L; // // private static final String PARAM_RADIUS = "radius"; // private static final String PARAM_DISTANCE = "distance"; // // private static final String[] paramNames = {PARAM_RADIUS, PARAM_DISTANCE}; // // private double radius = 1.0; // private double distance = 0.0; // // @Override // public void transform(FlameTransformationContext pContext, XForm pXForm, XYZPoint pAffineTP, XYZPoint pVarTP, double pAmount) { // // bMod by Michael Faber, http://michaelfaber.deviantart.com/art/bSeries-320574477 // double tau, sigma; // double temp; // double cosht, sinht; // double sins, coss; // // tau = 0.5 * (log(sqr(pAffineTP.x + 1.0) + sqr(pAffineTP.y)) - log(sqr(pAffineTP.x - 1.0) + sqr(pAffineTP.y))); // sigma = M_PI - atan2(pAffineTP.y, pAffineTP.x + 1.0) - atan2(pAffineTP.y, 1.0 - pAffineTP.x); // // if (tau < radius && -tau < radius) { // tau = fmod(tau + radius + distance * radius, 2.0 * radius) - radius; // } // // sinht = sinh(tau); // cosht = cosh(tau); // sins = sin(sigma); // coss = cos(sigma); // temp = cosht - coss; // if (temp == 0) { // return; // } // pVarTP.x += pAmount * sinht / temp; // pVarTP.y += pAmount * sins / temp; // if (pContext.isPreserveZCoordinate()) { // pVarTP.z += pAmount * pAffineTP.z; // } // } // // @Override // public String[] getParameterNames() { // return paramNames; // } // // @Override // public Object[] getParameterValues() { // return new Object[]{radius, distance}; // } // // @Override // public void setParameter(String pName, double pValue) { // if (PARAM_RADIUS.equalsIgnoreCase(pName)) // radius = limitVal(pValue, 0.0, Double.MAX_VALUE); // else if (PARAM_DISTANCE.equalsIgnoreCase(pName)) // distance = limitVal(pValue, 0.0, 2.0); // else // throw new IllegalArgumentException(pName); // } // // @Override // public String getName() { // return "bMod"; // } // // } //
[ "mwegner@gmail.com" ]
mwegner@gmail.com
8e664d1b2e7314544d3944d46f8e89b49510f393
0660b69c36ceaa9832fe1ac6415df3495cab92f6
/Minesweeper/common.h
8d62d3f3f31bc3dc265ca2a03ebb5b5b77ef723a
[]
no_license
shmily21/Minesweeper
81e47c1ccc8c1a58aba918f45ced5f82c9b33af0
fce3ec04cf4bddc5a37a974b9cbbc5af93a5f471
refs/heads/master
2016-09-06T18:12:27.182262
2015-07-23T07:31:28
2015-07-23T07:31:28
39,061,916
0
0
null
null
null
null
GB18030
C++
false
false
2,090
h
/* *************************************************************************************************** * 名称 :common.h * * 作者 :王斌 * * 描述 : * * 版权 :perturbed@sina.com * *************************************************************************************************** */ #ifndef __WANGBIN_MINESWEEPER_COMMON_H__ #define __WANGBIN_MINESWEEPER_COMMON_H__ /* * For Microsoft Compiler */ #if defined(_MSC_VER) && _MSC_VER > 1000 # pragma once #endif /* defined(_MSC_VER) && _MSC_VER > 1000 */ #include <Windows.h> #include <atlimage.h> #include <cassert> template<class T> __forceinline void CheckDelete(T* tp) { typedef char complete_type[sizeof(T)?1:-1]; (void)sizeof(complete_type); try { delete tp; tp=0; } catch(...) { assert(false); } } template<class T> __forceinline void CheckDeleteArray(T* tp) { typedef char complete_type[sizeof(T)?1:-1]; (void)sizeof(complete_type); try { delete [] tp; tp=0; } catch(...) { assert(false); } } class CImageEx:public CImage { public: CImageEx(VOID); virtual ~CImageEx(VOID) throw(); public: BOOL LoadImageFromResource( __in HINSTANCE hInstance, __in LPCTSTR pszResoureName, __in LPCTSTR pszResourceType); }; struct MINESWEEPER_RUNTIME { CImageEx hImageBack; CImageEx hImageNum[12]; CImageEx hImageClock; CImageEx hImageClockItem; CImageEx hImageFlag; INT nRowCount; INT nColCount; INT nMineCount; INT nCurMineCount; INT nCurRowCount; INT nCurColCount; BOOL bIsOver; INT nTimer; }; struct CELL { INT nCount; BOOL bShow; BOOL bFlag; BOOL bWhyFlag; }; HWND GetMainWindow(); CELL** GetCellMap(); #endif /* __WANGBIN_MINESWEEPER_COMMON_H__ */
[ "perturbed@sina.com" ]
perturbed@sina.com
e2816f889e4190bbfb7eb4a4bbd41e358eaff1dc
88a0321864636f79e4674a6bca5d8848c375ed4d
/src/core/GLSLProgram.cpp
faccdfd24d477be307bfdb5d36e4619564516ff4
[]
no_license
limdor/quoniam
e60b04835e437f7178e3668f60fc4bb23b660c34
affe179231f969f449c40657f8a106d2fc990a43
refs/heads/master
2021-12-10T03:07:07.067351
2021-08-24T04:12:02
2021-08-24T04:12:02
24,506,914
11
1
null
2021-08-24T04:12:03
2014-09-26T16:32:51
C++
UTF-8
C++
false
false
4,582
cpp
#include "GLSLProgram.h" #include "Debug.h" #include "glm/gtc/type_ptr.hpp" GLSLProgram::GLSLProgram(const std::string& pName): mName(pName), mId(glCreateProgram()) { CHECK_GL_ERROR(); } GLSLProgram::~GLSLProgram() { glDeleteProgram(mId); } const std::string& GLSLProgram::GetName() const { return mName; } void GLSLProgram::AttachShader(const GLSLShader& pShader) { glAttachShader(mId, pShader.GetId()); CHECK_GL_ERROR(); } void GLSLProgram::LinkProgram() { glLinkProgram(mId); CHECK_GL_ERROR(); // Get the location of every uniform mUniforms.clear(); GLint nUniforms, maxLen; glGetProgramiv( mId, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxLen); glGetProgramiv( mId, GL_ACTIVE_UNIFORMS, &nUniforms); std::vector<GLchar> name; name.reserve(maxLen); for( GLint i = 0; i < nUniforms; ++i ) { GLint size; GLenum type; glGetActiveUniform( mId, i, maxLen, nullptr, &size, &type, name.data() ); GLint location = glGetUniformLocation(mId, name.data()); mUniforms[std::string(name.data())] = location; } // Get the location of every attribute mAttributes.clear(); glGetProgramiv( mId, GL_ACTIVE_ATTRIBUTE_MAX_LENGTH, &maxLen); GLint nAttributes; glGetProgramiv( mId, GL_ACTIVE_ATTRIBUTES, &nAttributes); name.reserve(maxLen); for( GLint i = 0; i < nAttributes; ++i ) { GLint size; GLenum type; glGetActiveAttrib( mId, i, maxLen, nullptr, &size, &type, name.data() ); GLint location = glGetAttribLocation(mId, name.data()); mAttributes[std::string(name.data())] = location; } } void GLSLProgram::UseProgram() const { glUseProgram(mId); } void GLSLProgram::ShowInformation() const { // Show program name Debug::Log( "Program name: " + mName ); // Show uniforms information Debug::Log("Uniforms:"); Debug::Log(" Name | Location"); Debug::Log("------------------------------------------------");; for( auto it = mUniforms.cbegin(); it != mUniforms.cend(); ++it ) { Debug::Log( " " + it->first + " | " + std::to_string(it->second)); } // Show attributes information Debug::Log("Attributes:"); Debug::Log(" Name | Location"); Debug::Log("------------------------------------------------"); for( auto it = mAttributes.cbegin(); it != mAttributes.cend(); ++it ) { Debug::Log( " " + it->first + " | " + std::to_string(it->second)); } } GLint GLSLProgram::GetUniformLocation(const std::string& pName) const { const auto it = mUniforms.find(pName); if( it == mUniforms.end() ) { Debug::Warning( "Invalid uniform: " + pName); return -1; } else { return it->second; } } void GLSLProgram::SetUniform(const std::string &pName, const glm::mat4 &pValue) const { glUniformMatrix4fv( GetUniformLocation(pName), 1, GL_FALSE, glm::value_ptr(pValue)); } void GLSLProgram::SetUniform(const std::string& pName, const glm::vec4& pValue) const { glUniform4fv( GetUniformLocation(pName), 1, glm::value_ptr(pValue) ); } void GLSLProgram::SetUniform(const std::string& pName, const glm::vec3& pValue) const { glUniform3fv( GetUniformLocation(pName), 1, glm::value_ptr(pValue) ); } void GLSLProgram::SetUniform(const std::string& pName, float pValue) const { glUniform1f( GetUniformLocation(pName), pValue ); } void GLSLProgram::SetUniform(const std::string& pName, int pValue) const { glUniform1i( GetUniformLocation(pName), pValue ); } void GLSLProgram::SetUniform(const std::string& pName, bool pValue) const { glUniform1i( GetUniformLocation(pName), pValue ); } GLint GLSLProgram::GetAttribLocation(const std::string& pName) const { const auto it = mAttributes.find(pName); if( it == mAttributes.end() ) { Debug::Warning( "Invalid attribute: " + pName ); return -1; } else { return it->second; } } void GLSLProgram::BindFragDataLocation(GLuint pLocation, const std::string& pName) { const char *constName = pName.c_str(); glBindFragDataLocation( mId, pLocation, constName ); CHECK_GL_ERROR(); } void GLSLProgram::BindTexture(GLenum pTarget, const std::string& pTextureName, GLuint pTextureId, int pTextureUnit) { glActiveTexture(GL_TEXTURE0 + pTextureUnit); glBindTexture(pTarget, pTextureId); GLint id = GetUniformLocation( pTextureName ); if( id == -1 ) { Debug::Warning( "Invalid texture: " + pTextureName ); } glUniform1i(id, pTextureUnit); }
[ "xavibonaventura@gmail.com" ]
xavibonaventura@gmail.com
7416ed94961cd200de1eddb7ad66a7009ae428ba
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/httpd/gumtree/httpd_repos_function_1894_httpd-2.0.43.cpp
9ecb192c6ae47cb19669d2a1f0ee0d62326f43b1
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
183
cpp
static int core_post_config(apr_pool_t *pconf, apr_pool_t *plog, apr_pool_t *ptemp, server_rec *s) { ap_set_version(pconf); ap_setup_make_content_type(pconf); return OK; }
[ "993273596@qq.com" ]
993273596@qq.com
ed35b4bf9006771e7f59757e6f2d339cbeae9970
04b4a578b1eb2243b7ba369e289812ca80cb1ab8
/gameSource/game.cpp
601c55428ff858da2944bf683a2153858e7a753e
[ "LicenseRef-scancode-public-domain" ]
permissive
yy3243/OneLife
a403b7e7bdb10007d1bb96969093828b9d39d713
ad297b089c933b4caba44148a48088fce7c7e2ca
refs/heads/master
2020-05-19T14:07:34.245670
2019-05-04T17:11:31
2019-05-04T17:11:31
null
0
0
null
null
null
null
UTF-8
C++
false
false
66,170
cpp
int versionNumber = 221; int dataVersionNumber = 0; int binVersionNumber = versionNumber; // NOTE that OneLife doesn't use account hmacs // retain an older version number here if server is compatible // with older client versions. // Change this number (and number on server) if server has changed // in a way that breaks old clients. int accountHmacVersionNumber = 0; #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <math.h> //#define USE_MALLINFO #ifdef USE_MALLINFO #include <malloc.h> #endif #include "minorGems/graphics/Color.h" #include "minorGems/util/SimpleVector.h" #include "minorGems/util/stringUtils.h" #include "minorGems/util/SettingsManager.h" #include "minorGems/util/random/CustomRandomSource.h" #include "minorGems/io/file/File.h" #include "minorGems/system/Time.h" #include "minorGems/crypto/hashes/sha1.h" // static seed CustomRandomSource randSource( 34957197 ); #include "minorGems/util/log/AppLog.h" #include "minorGems/game/game.h" #include "minorGems/game/gameGraphics.h" #include "minorGems/game/Font.h" #include "minorGems/game/drawUtils.h" #include "minorGems/game/diffBundle/client/diffBundleClient.h" #include "spriteBank.h" #include "objectBank.h" #include "categoryBank.h" #include "transitionBank.h" #include "soundBank.h" #include "liveObjectSet.h" #include "groundSprites.h" #include "emotion.h" #include "photos.h" #include "FinalMessagePage.h" #include "LoadingPage.h" #include "AutoUpdatePage.h" #include "LivingLifePage.h" #include "ExistingAccountPage.h" #include "ExtendedMessagePage.h" #include "RebirthChoicePage.h" #include "SettingsPage.h" #include "ReviewPage.h" #include "TwinPage.h" //#include "TestPage.h" #include "ServerActionPage.h" #include "ageControl.h" #include "musicPlayer.h" #include "whiteSprites.h" // should we pull the map static char mapPullMode = 0; static char autoLogIn = 0; char loginEditOverride = false; // start at reflector URL char *reflectorURL = NULL; char usingCustomServer = false; char *serverIP = NULL; int serverPort = 0; char *userEmail = NULL; char *accountKey = NULL; char *userTwinCode = NULL; int userTwinCount = 0; char userReconnect = false; // these are needed by ServerActionPage, but we don't use them int userID = -1; int serverSequenceNumber = 0; FinalMessagePage *finalMessagePage; ServerActionPage *getServerAddressPage; LoadingPage *loadingPage; AutoUpdatePage *autoUpdatePage; LivingLifePage *livingLifePage; ExistingAccountPage *existingAccountPage; ExtendedMessagePage *extendedMessagePage; RebirthChoicePage *rebirthChoicePage; SettingsPage *settingsPage; ReviewPage *reviewPage; TwinPage *twinPage; //TestPage *testPage = NULL; GamePage *currentGamePage = NULL; int loadingPhase = 0; int loadingStepBatchSize = 1; double loadingPhaseStartTime; int numLoadingSteps = 20; SpriteHandle instructionsSprite; // position of view in world doublePair lastScreenViewCenter = {0, 0 }; // world width of one view double viewWidth = 1280; double viewHeight = 720; // this is the desired visible width // if our screen is wider than this (wider than 16:9 aspect ratio) // then we will put letterbox bars on the sides // Usually, if screen is not 16:9, it will be taller, not wider, // and we will put letterbox bars on the top and bottom double visibleViewWidth = viewWidth; // fraction of viewWidth visible vertically (aspect ratio) double viewHeightFraction; int screenW, screenH; char initDone = false; float mouseSpeed; int maxSimultaneousExpectedSoundEffects = 10; // fraction of full volume devoted to music // Note that musicLoudness and soundEffectLoudness settings still // effect absolute loudness of each, beyond this setting // this setting is used to trim music volume relative to sound effects // if both are at full volume // 1.0 makes it as loud as the sound effect mix // on the other hand, it's stereo, compressed, full-frequency etc. // so it's subjectively louder double musicHeadroom = 1.0; int musicOff = 0; float musicLoudness; int webRetrySeconds; double frameRateFactor = 1; int baseFramesPerSecond = 60; int targetFramesPerSecond = baseFramesPerSecond; char firstDrawFrameCalled = false; int firstServerMessagesReceived = 0; char upKey = 'w'; char leftKey = 'a'; char downKey = 's'; char rightKey = 'd'; char doesOverrideGameImageSize() { return true; } void getGameImageSize( int *outWidth, int *outHeight ) { *outWidth = (int)viewWidth; *outHeight = (int)viewHeight; } char shouldNativeScreenResolutionBeUsed() { return true; } char isNonIntegerScalingAllowed() { return true; } const char *getWindowTitle() { return "OneLife"; } const char *getAppName() { return "OneLife"; } int getAppVersion() { return versionNumber; } const char *getLinuxAppName() { // no dir-name conflict here because we're using all caps for app name return "OneLifeApp"; } const char *getFontTGAFileName() { return "font_32_64.tga"; } char isDemoMode() { return false; } const char *getDemoCodeSharedSecret() { return "fundamental_right"; } const char *getDemoCodeServerURL() { return "http://FIXME/demoServer/server.php"; } char gamePlayingBack = false; Font *mainFont; Font *mainFontFixed; // closer spacing Font *mainFontReview; Font *numbersFontFixed; Font *handwritingFont; Font *pencilFont; Font *pencilErasedFont; Font *smallFont; char *shutdownMessage = NULL; static float pauseScreenFade = 0; static char *currentUserTypedMessage = NULL; // for delete key repeat during message typing static int holdDeleteKeySteps = -1; static int stepsBetweenDeleteRepeat; static void updateDataVersionNumber() { File file( NULL, "dataVersionNumber.txt" ); if( file.exists() ) { char *contents = file.readFileContents(); if( contents != NULL ) { sscanf( contents, "%d", &dataVersionNumber ); delete [] contents; if( dataVersionNumber > versionNumber ) { versionNumber = dataVersionNumber; } } } } #define SETTINGS_HASH_SALT "another_loss" static const char *customDataFormatWriteString = "version%d_mouseSpeed%f_musicOff%d_musicLoudness%f" "_webRetrySeconds%d"; static const char *customDataFormatReadString = "version%d_mouseSpeed%f_musicOff%d_musicLoudness%f" "_webRetrySeconds%d"; char *getCustomRecordedGameData() { updateDataVersionNumber(); float mouseSpeedSetting = SettingsManager::getFloatSetting( "mouseSpeed", 1.0f ); int musicOffSetting = SettingsManager::getIntSetting( "musicOff", 0 ); float musicLoudnessSetting = SettingsManager::getFloatSetting( "musicLoudness", 1.0f ); int webRetrySecondsSetting = SettingsManager::getIntSetting( "webRetrySeconds", 10 ); char * result = autoSprintf( customDataFormatWriteString, versionNumber, mouseSpeedSetting, musicOffSetting, musicLoudnessSetting, webRetrySecondsSetting ); return result; } char showMouseDuringPlayback() { // since we rely on the system mouse pointer during the game (and don't // draw our own pointer), we need to see the recorded pointer position // to make sense of game playback return true; } char *getHashSalt() { return stringDuplicate( SETTINGS_HASH_SALT ); } void initDrawString( int inWidth, int inHeight ) { toggleLinearMagFilter( true ); toggleMipMapGeneration( true ); toggleMipMapMinFilter( true ); toggleTransparentCropping( true ); mainFont = new Font( getFontTGAFileName(), 6, 16, false, 16 ); mainFont->setMinimumPositionPrecision( 1 ); setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); viewHeightFraction = inHeight / (double)inWidth; if( viewHeightFraction < 9.0 / 16.0 ) { // weird, wider than 16:9 aspect ratio viewWidth = viewHeight / viewHeightFraction; } setViewSize( viewWidth ); setLetterbox( visibleViewWidth, viewHeight ); } void freeDrawString() { delete mainFont; } void initFrameDrawer( int inWidth, int inHeight, int inTargetFrameRate, const char *inCustomRecordedGameData, char inPlayingBack ) { // it's always safe to call this, just in case we're launching post-update postUpdate(); instructionsSprite = loadWhiteSprite( "instructions.tga" ); initAgeControl(); updateDataVersionNumber(); AppLog::printOutNextMessage(); AppLog::infoF( "OneLife client v%d (binV=%d, dataV=%d) starting up", versionNumber, binVersionNumber, dataVersionNumber ); toggleLinearMagFilter( true ); toggleMipMapGeneration( true ); toggleMipMapMinFilter( true ); toggleTransparentCropping( true ); gamePlayingBack = inPlayingBack; screenW = inWidth; screenH = inHeight; if( inTargetFrameRate != baseFramesPerSecond ) { frameRateFactor = (double)baseFramesPerSecond / (double)inTargetFrameRate; numLoadingSteps /= frameRateFactor; } targetFramesPerSecond = inTargetFrameRate; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); viewHeightFraction = inHeight / (double)inWidth; if( viewHeightFraction < 9.0 / 16.0 ) { // weird, wider than 16:9 aspect ratio viewWidth = viewHeight / viewHeightFraction; } setViewSize( viewWidth ); setLetterbox( visibleViewWidth, viewHeight ); setCursorVisible( true ); grabInput( false ); // world coordinates setMouseReportingMode( true ); mainFontReview = new Font( getFontTGAFileName(), 4, 8, false, 16 ); mainFontReview->setMinimumPositionPrecision( 1 ); mainFontFixed = new Font( getFontTGAFileName(), 6, 16, true, 16 ); numbersFontFixed = new Font( getFontTGAFileName(), 6, 16, true, 16, 16 ); mainFontFixed->setMinimumPositionPrecision( 1 ); numbersFontFixed->setMinimumPositionPrecision( 1 ); smallFont = new Font( getFontTGAFileName(), 3, 8, false, 8 ); handwritingFont = new Font( "font_handwriting_32_32.tga", 3, 6, false, 16 ); handwritingFont->setMinimumPositionPrecision( 1 ); pencilFont = new Font( "font_pencil_32_32.tga", 3, 6, false, 16 ); pencilFont->setMinimumPositionPrecision( 1 ); pencilErasedFont = new Font( "font_pencil_erased_32_32.tga", 3, 6, false, 16 ); pencilErasedFont->setMinimumPositionPrecision( 1 ); pencilErasedFont->copySpacing( pencilFont ); float mouseSpeedSetting = 1.0f; int musicOffSetting = 0; float musicLoudnessSetting = 1.0f; int webRetrySecondsSetting = 10; int readVersionNumber; int numRead = sscanf( inCustomRecordedGameData, customDataFormatReadString, &readVersionNumber, &mouseSpeedSetting, &musicOffSetting, &musicLoudnessSetting, &webRetrySecondsSetting ); if( numRead != 6 ) { // no recorded game? } else { if( readVersionNumber != versionNumber ) { AppLog::printOutNextMessage(); AppLog::warningF( "WARNING: version number in playback file is %d " "but game version is %d...", readVersionNumber, versionNumber ); } } userEmail = SettingsManager::getStringSetting( "email" ); accountKey = SettingsManager::getStringSetting( "accountKey" ); double mouseParam = 0.000976562; mouseParam *= mouseSpeedSetting; mouseSpeed = mouseParam * inWidth / viewWidth; musicOff = musicOffSetting; musicLoudness = musicLoudnessSetting; webRetrySeconds = webRetrySecondsSetting; reflectorURL = SettingsManager::getStringSetting( "reflectorURL" ); if( reflectorURL == NULL ) { reflectorURL = stringDuplicate( "http://localhost/jcr13/oneLifeReflector/server.php" ); } setSoundLoudness( 1.0 ); setSoundPlaying( true ); const char *resultNamesA[4] = { "serverIP", "serverPort", "requiredVersionNumber", "autoUpdateURL" }; getServerAddressPage = new ServerActionPage( reflectorURL, "reflect", 4, resultNamesA, false ); finalMessagePage = new FinalMessagePage; loadingPage = new LoadingPage; autoUpdatePage = new AutoUpdatePage; livingLifePage = NULL; existingAccountPage = new ExistingAccountPage; extendedMessagePage = new ExtendedMessagePage; rebirthChoicePage = new RebirthChoicePage; settingsPage = new SettingsPage; char *reviewURL = SettingsManager::getStringSetting( "reviewServerURL", "" ); if( strcmp( reviewURL, "" ) == 0 ) { existingAccountPage->showReviewButton( false ); rebirthChoicePage->showReviewButton( false ); } reviewPage = new ReviewPage( reviewURL ); delete [] reviewURL; twinPage = new TwinPage(); // 0 music headroom needed, because we fade sounds before playing music setVolumeScaling( 10, 0 ); //setSoundSpriteRateRange( 0.95, 1.05 ); setSoundSpriteVolumeRange( 0.60, 1.0 ); char rebuilding; int numSprites = initSpriteBankStart( &rebuilding ); if( rebuilding ) { loadingPage->setCurrentPhase( translate( "spritesRebuild" ) ); } else { loadingPage->setCurrentPhase( translate( "sprites" ) ); } loadingPage->setCurrentProgress( 0 ); loadingStepBatchSize = numSprites / numLoadingSteps; if( loadingStepBatchSize < 1 ) { loadingStepBatchSize = 1; } // for filter support in LivingLifePage enableObjectSearch( true ); currentGamePage = loadingPage; //testPage = new TestPage; //currentGamePage = testPage; currentGamePage->base_makeActive( true ); initDone = true; } void freeFrameDrawer() { freeSprite( instructionsSprite ); delete mainFontReview; delete mainFontFixed; delete numbersFontFixed; delete handwritingFont; delete pencilFont; delete pencilErasedFont; delete smallFont; if( currentUserTypedMessage != NULL ) { delete [] currentUserTypedMessage; currentUserTypedMessage = NULL; } if( shutdownMessage != NULL ) { delete [] shutdownMessage; shutdownMessage = NULL; } delete getServerAddressPage; delete finalMessagePage; delete loadingPage; delete autoUpdatePage; if( livingLifePage != NULL ) { delete livingLifePage; livingLifePage = NULL; } delete existingAccountPage; delete extendedMessagePage; delete rebirthChoicePage; delete settingsPage; delete reviewPage; delete twinPage; //if( testPage != NULL ) { // delete testPage; // testPage = NULL; // } freeGroundSprites(); freeAnimationBank(); freeObjectBank(); freeSpriteBank(); freeTransBank(); freeCategoryBank(); freeLiveObjectSet(); freeSoundBank(); freeMusicPlayer(); freeEmotion(); freePhotos(); if( reflectorURL != NULL ) { delete [] reflectorURL; reflectorURL = NULL; } if( serverIP != NULL ) { delete [] serverIP; serverIP = NULL; } if( userEmail != NULL ) { delete [] userEmail; } if( accountKey != NULL ) { delete [] accountKey; } if( userTwinCode != NULL ) { delete [] userTwinCode; } } // draw code separated from updates // some updates are still embedded in draw code, so pass a switch to // turn them off static void drawFrameNoUpdate( char inUpdate ); static void drawPauseScreen() { double viewHeight = viewHeightFraction * viewWidth; setDrawColor( 1, 1, 1, 0.5 * pauseScreenFade ); drawSquare( lastScreenViewCenter, 1.05 * ( viewHeight / 3 ) ); setDrawColor( 0.2, 0.2, 0.2, 0.85 * pauseScreenFade ); drawSquare( lastScreenViewCenter, viewHeight / 3 ); setDrawColor( 1, 1, 1, pauseScreenFade ); doublePair messagePos = lastScreenViewCenter; messagePos.y += 4.5 * (viewHeight / 15); mainFont->drawString( translate( "pauseMessage1" ), messagePos, alignCenter ); messagePos.y -= 1.25 * (viewHeight / 15); mainFont->drawString( translate( "pauseMessage2" ), messagePos, alignCenter ); if( currentGamePage == livingLifePage ) { doublePair drawPos = { -9, 0 }; drawPos = add( drawPos, lastScreenViewCenter ); drawSprite( instructionsSprite, drawPos ); } if( currentUserTypedMessage != NULL ) { messagePos.y -= 1.25 * (viewHeight / 15); double maxWidth = 0.95 * ( viewHeight / 1.5 ); int maxLines = 9; SimpleVector<char *> *tokens = tokenizeString( currentUserTypedMessage ); // collect all lines before drawing them SimpleVector<char *> lines; while( tokens->size() > 0 ) { // build up a a line // always take at least first token, even if it is too long char *currentLineString = stringDuplicate( *( tokens->getElement( 0 ) ) ); delete [] *( tokens->getElement( 0 ) ); tokens->deleteElement( 0 ); char nextTokenIsFileSeparator = false; char *nextLongerString = NULL; if( tokens->size() > 0 ) { char *nextToken = *( tokens->getElement( 0 ) ); if( nextToken[0] == 28 ) { nextTokenIsFileSeparator = true; } else { nextLongerString = autoSprintf( "%s %s ", currentLineString, *( tokens->getElement( 0 ) ) ); } } while( !nextTokenIsFileSeparator && nextLongerString != NULL && mainFont->measureString( nextLongerString ) < maxWidth && tokens->size() > 0 ) { delete [] currentLineString; currentLineString = nextLongerString; nextLongerString = NULL; // token consumed delete [] *( tokens->getElement( 0 ) ); tokens->deleteElement( 0 ); if( tokens->size() > 0 ) { char *nextToken = *( tokens->getElement( 0 ) ); if( nextToken[0] == 28 ) { nextTokenIsFileSeparator = true; } else { nextLongerString = autoSprintf( "%s%s ", currentLineString, *( tokens->getElement( 0 ) ) ); } } } if( nextLongerString != NULL ) { delete [] nextLongerString; } while( mainFont->measureString( currentLineString ) > maxWidth ) { // single token that is too long by itself // simply trim it and discard part of it // (user typing nonsense anyway) currentLineString[ strlen( currentLineString ) - 1 ] = '\0'; } if( currentLineString[ strlen( currentLineString ) - 1 ] == ' ' ) { // trim last bit of whitespace currentLineString[ strlen( currentLineString ) - 1 ] = '\0'; } lines.push_back( currentLineString ); if( nextTokenIsFileSeparator ) { // file separator // put a paragraph separator in lines.push_back( stringDuplicate( "---" ) ); // token consumed delete [] *( tokens->getElement( 0 ) ); tokens->deleteElement( 0 ); } } // all tokens deleted above delete tokens; double messageLineSpacing = 0.625 * (viewHeight / 15); int numLinesToSkip = lines.size() - maxLines; if( numLinesToSkip < 0 ) { numLinesToSkip = 0; } for( int i=0; i<numLinesToSkip-1; i++ ) { char *currentLineString = *( lines.getElement( i ) ); delete [] currentLineString; } int lastSkipLine = numLinesToSkip - 1; if( lastSkipLine >= 0 ) { char *currentLineString = *( lines.getElement( lastSkipLine ) ); // draw above and faded out somewhat doublePair lastSkipLinePos = messagePos; lastSkipLinePos.y += messageLineSpacing; setDrawColor( 1, 1, 0.5, 0.125 * pauseScreenFade ); mainFont->drawString( currentLineString, lastSkipLinePos, alignCenter ); delete [] currentLineString; } setDrawColor( 1, 1, 0.5, pauseScreenFade ); for( int i=numLinesToSkip; i<lines.size(); i++ ) { char *currentLineString = *( lines.getElement( i ) ); if( false && lastSkipLine >= 0 ) { if( i == numLinesToSkip ) { // next to last setDrawColor( 1, 1, 0.5, 0.25 * pauseScreenFade ); } else if( i == numLinesToSkip + 1 ) { // next after that setDrawColor( 1, 1, 0.5, 0.5 * pauseScreenFade ); } else if( i == numLinesToSkip + 2 ) { // rest are full fade setDrawColor( 1, 1, 0.5, pauseScreenFade ); } } mainFont->drawString( currentLineString, messagePos, alignCenter ); delete [] currentLineString; messagePos.y -= messageLineSpacing; } } setDrawColor( 1, 1, 1, pauseScreenFade ); messagePos = lastScreenViewCenter; messagePos.y -= 3.75 * ( viewHeight / 15 ); //mainFont->drawString( translate( "pauseMessage3" ), // messagePos, alignCenter ); messagePos.y -= 0.625 * (viewHeight / 15); const char* quitMessageKey = "pauseMessage3"; if( isQuittingBlocked() ) { quitMessageKey = "pauseMessage3b"; } mainFont->drawString( translate( quitMessageKey ), messagePos, alignCenter ); } void deleteCharFromUserTypedMessage() { if( currentUserTypedMessage != NULL ) { int length = strlen( currentUserTypedMessage ); char fileSeparatorDeleted = false; if( length > 2 ) { if( currentUserTypedMessage[ length - 2 ] == 28 ) { // file separator with spaces around it // delete whole thing with one keypress currentUserTypedMessage[ length - 3 ] = '\0'; fileSeparatorDeleted = true; } } if( !fileSeparatorDeleted && length > 0 ) { currentUserTypedMessage[ length - 1 ] = '\0'; } } } static void startConnecting() { userReconnect = false; if( SettingsManager::getIntSetting( "useCustomServer", 0 ) ) { usingCustomServer = true; if( serverIP != NULL ) { delete [] serverIP; serverIP = NULL; } serverIP = SettingsManager::getStringSetting( "customServerAddress" ); if( serverIP == NULL ) { serverIP = stringDuplicate( "127.0.0.1" ); } serverPort = SettingsManager::getIntSetting( "customServerPort", 8005 ); printf( "Using custom server address: %s:%d\n", serverIP, serverPort ); currentGamePage = livingLifePage; currentGamePage->base_makeActive( true ); } else { usingCustomServer = false; printf( "Starting fetching server URL from reflector %s\n", reflectorURL ); getServerAddressPage->clearActionParameters(); getServerAddressPage->setActionParameter( "email", userEmail ); if( userTwinCode != NULL ) { char *codeHash = computeSHA1Digest( userTwinCode ); getServerAddressPage->setActionParameter( "twin_code", codeHash ); delete [] codeHash; } currentGamePage = getServerAddressPage; currentGamePage->base_makeActive( true ); } } void showDiedPage() { userReconnect = false; lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = extendedMessagePage; extendedMessagePage->setMessageKey( "youDied" ); char *reason = livingLifePage->getDeathReason(); if( reason == NULL ) { extendedMessagePage->setSubMessage( "" ); } else { extendedMessagePage->setSubMessage( reason ); delete [] reason; } currentGamePage->base_makeActive( true ); } void showReconnectPage() { lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = extendedMessagePage; extendedMessagePage->setMessageKey( "connectionLost" ); extendedMessagePage->setSubMessage( translate( "willTryReconnect" ) ); userReconnect = true; // don't reconnect as twin // that will cause them to wait for their party again. if( userTwinCode != NULL ) { delete [] userTwinCode; userTwinCode = NULL; } currentGamePage->base_makeActive( true ); } void drawFrame( char inUpdate ) { if( !inUpdate ) { // because this is a networked game, we can't actually pause stepSpriteBank(); stepSoundBank(); stepMusicPlayer(); if( currentGamePage != NULL ) { currentGamePage->base_step(); } wakeUpPauseFrameRate(); drawFrameNoUpdate( true ); drawPauseScreen(); // handle delete key repeat if( holdDeleteKeySteps > -1 ) { holdDeleteKeySteps ++; if( holdDeleteKeySteps > stepsBetweenDeleteRepeat ) { // delete repeat // platform layer doesn't receive event for key held down // tell it we are still active so that it doesn't // reduce the framerate during long, held deletes wakeUpPauseFrameRate(); // subtract from messsage deleteCharFromUserTypedMessage(); // shorter delay for subsequent repeats stepsBetweenDeleteRepeat = (int)( 2/ frameRateFactor ); holdDeleteKeySteps = 0; } } // fade in pause screen if( pauseScreenFade < 1 ) { pauseScreenFade += ( 1.0 / 30 ) * frameRateFactor; if( pauseScreenFade > 1 ) { pauseScreenFade = 1; } } // keep checking for this signal even if paused if( currentGamePage == livingLifePage && livingLifePage->checkSignal( "died" ) ) { showDiedPage(); } if( currentGamePage == livingLifePage && livingLifePage->checkSignal( "disconnect" ) ) { showReconnectPage(); } return; } // not paused // fade pause screen out if( pauseScreenFade > 0 ) { pauseScreenFade -= ( 1.0 / 30 ) * frameRateFactor; if( pauseScreenFade < 0 ) { pauseScreenFade = 0; if( currentUserTypedMessage != NULL ) { // make sure it doesn't already end with a file separator // (never insert two in a row, even when player closes // pause screen without typing anything) int lengthCurrent = strlen( currentUserTypedMessage ); if( lengthCurrent < 2 || currentUserTypedMessage[ lengthCurrent - 2 ] != 28 ) { // insert at file separator (ascii 28) char *oldMessage = currentUserTypedMessage; currentUserTypedMessage = autoSprintf( "%s %c ", oldMessage, 28 ); delete [] oldMessage; } } } } if( !firstDrawFrameCalled ) { // do final init step... stuff that shouldn't be done until // we have control of screen char *moveKeyMapping = SettingsManager::getStringSetting( "upLeftDownRightKeys" ); if( moveKeyMapping != NULL ) { char *temp = stringToLowerCase( moveKeyMapping ); delete [] moveKeyMapping; moveKeyMapping = temp; if( strlen( moveKeyMapping ) == 4 && strcmp( moveKeyMapping, "wasd" ) != 0 ) { // different assignment upKey = moveKeyMapping[0]; leftKey = moveKeyMapping[1]; downKey = moveKeyMapping[2]; rightKey = moveKeyMapping[3]; } delete [] moveKeyMapping; } firstDrawFrameCalled = true; } // updates here stepSpriteBank(); stepSoundBank(); stepMusicPlayer(); stepPhotos(); if( currentGamePage != NULL ) { currentGamePage->base_step(); if( currentGamePage == loadingPage ) { switch( loadingPhase ) { case 0: { float progress; for( int i=0; i<loadingStepBatchSize; i++ ) { progress = initSpriteBankStep(); loadingPage->setCurrentProgress( progress ); } if( progress == 1.0 ) { initSpriteBankFinish(); loadingPhaseStartTime = Time::getCurrentTime(); char rebuilding; int numSounds = initSoundBankStart( &rebuilding ); if( rebuilding ) { loadingPage->setCurrentPhase( translate( "soundsRebuild" ) ); } else { loadingPage->setCurrentPhase( translate( "sounds" ) ); } loadingPage->setCurrentProgress( 0 ); loadingStepBatchSize = numSounds / numLoadingSteps; if( loadingStepBatchSize < 1 ) { loadingStepBatchSize = 1; } loadingPhase ++; } break; } case 1: { float progress; for( int i=0; i<loadingStepBatchSize; i++ ) { progress = initSoundBankStep(); loadingPage->setCurrentProgress( progress ); } if( progress == 1.0 ) { initSoundBankFinish(); loadingPhaseStartTime = Time::getCurrentTime(); char rebuilding; int numAnimations = initAnimationBankStart( &rebuilding ); if( rebuilding ) { loadingPage->setCurrentPhase( translate( "animationsRebuild" ) ); } else { loadingPage->setCurrentPhase( translate( "animations" ) ); } loadingPage->setCurrentProgress( 0 ); loadingStepBatchSize = numAnimations / numLoadingSteps; if( loadingStepBatchSize < 1 ) { loadingStepBatchSize = 1; } loadingPhase ++; } break; } case 2: { float progress; for( int i=0; i<loadingStepBatchSize; i++ ) { progress = initAnimationBankStep(); loadingPage->setCurrentProgress( progress ); } if( progress == 1.0 ) { initAnimationBankFinish(); printf( "Finished loading animation bank in %f sec\n", Time::getCurrentTime() - loadingPhaseStartTime ); loadingPhaseStartTime = Time::getCurrentTime(); char rebuilding; int numObjects = initObjectBankStart( &rebuilding, true, true ); if( rebuilding ) { loadingPage->setCurrentPhase( translate( "objectsRebuild" ) ); } else { loadingPage->setCurrentPhase( translate( "objects" ) ); } loadingPage->setCurrentProgress( 0 ); loadingStepBatchSize = numObjects / numLoadingSteps; if( loadingStepBatchSize < 1 ) { loadingStepBatchSize = 1; } loadingPhase ++; } break; } case 3: { float progress; for( int i=0; i<loadingStepBatchSize; i++ ) { progress = initObjectBankStep(); loadingPage->setCurrentProgress( progress ); } if( progress == 1.0 ) { initObjectBankFinish(); printf( "Finished loading object bank in %f sec\n", Time::getCurrentTime() - loadingPhaseStartTime ); loadingPhaseStartTime = Time::getCurrentTime(); char rebuilding; int numCats = initCategoryBankStart( &rebuilding ); if( rebuilding ) { loadingPage->setCurrentPhase( translate( "categoriesRebuild" ) ); } else { loadingPage->setCurrentPhase( translate( "categories" ) ); } loadingPage->setCurrentProgress( 0 ); loadingStepBatchSize = numCats / numLoadingSteps; if( loadingStepBatchSize < 1 ) { loadingStepBatchSize = 1; } loadingPhase ++; } break; } case 4: { float progress; for( int i=0; i<loadingStepBatchSize; i++ ) { progress = initCategoryBankStep(); loadingPage->setCurrentProgress( progress ); } if( progress == 1.0 ) { initCategoryBankFinish(); printf( "Finished loading category bank in %f sec\n", Time::getCurrentTime() - loadingPhaseStartTime ); loadingPhaseStartTime = Time::getCurrentTime(); char rebuilding; // true to auto-generate concrete transitions // for all abstract category transitions int numTrans = initTransBankStart( &rebuilding, true, true, true, true ); if( rebuilding ) { loadingPage->setCurrentPhase( translate( "transitionsRebuild" ) ); } else { loadingPage->setCurrentPhase( translate( "transitions" ) ); } loadingPage->setCurrentProgress( 0 ); loadingStepBatchSize = numTrans / numLoadingSteps; if( loadingStepBatchSize < 1 ) { loadingStepBatchSize = 1; } loadingPhase ++; } break; } case 5: { float progress; for( int i=0; i<loadingStepBatchSize; i++ ) { progress = initTransBankStep(); loadingPage->setCurrentProgress( progress ); } if( progress == 1.0 ) { initTransBankFinish(); printf( "Finished loading transition bank in %f sec\n", Time::getCurrentTime() - loadingPhaseStartTime ); loadingPhaseStartTime = Time::getCurrentTime(); loadingPage->setCurrentPhase( translate( "groundTextures" ) ); loadingPage->setCurrentProgress( 0 ); initGroundSpritesStart(); loadingStepBatchSize = 1; loadingPhase ++; } break; } case 6: { float progress; for( int i=0; i<loadingStepBatchSize; i++ ) { progress = initGroundSpritesStep(); loadingPage->setCurrentProgress( progress ); } if( progress == 1.0 ) { initGroundSpritesFinish(); printf( "Finished loading ground sprites in %f sec\n", Time::getCurrentTime() - loadingPhaseStartTime ); loadingPhaseStartTime = Time::getCurrentTime(); initLiveObjectSet(); loadingPhaseStartTime = Time::getCurrentTime(); livingLifePage = new LivingLifePage(); loadingPhase ++; } break; } default: // NOW game engine can start measuring frame rate loadingComplete(); initEmotion(); initPhotos(); initMusicPlayer(); setMusicLoudness( musicLoudness ); mapPullMode = SettingsManager::getIntSetting( "mapPullMode", 0 ); autoLogIn = SettingsManager::getIntSetting( "autoLogIn", 0 ); if( userEmail == NULL || accountKey == NULL ) { autoLogIn = false; } currentGamePage = existingAccountPage; currentGamePage->base_makeActive( true ); } } else if( currentGamePage == settingsPage ) { if( settingsPage->checkSignal( "back" ) ) { existingAccountPage->setStatus( NULL, false ); currentGamePage = existingAccountPage; currentGamePage->base_makeActive( true ); } else if( settingsPage->checkSignal( "editAccount" ) ) { loginEditOverride = true; existingAccountPage->setStatus( "editAccountWarning", false ); existingAccountPage->setStatusPositiion( true ); currentGamePage = existingAccountPage; currentGamePage->base_makeActive( true ); } else if( settingsPage->checkSignal( "relaunchFailed" ) ) { currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "manualRestartMessage" ); currentGamePage->base_makeActive( true ); } } else if( currentGamePage == reviewPage ) { if( reviewPage->checkSignal( "back" ) ) { existingAccountPage->setStatus( NULL, false ); currentGamePage = existingAccountPage; currentGamePage->base_makeActive( true ); } } else if( currentGamePage == twinPage ) { if( twinPage->checkSignal( "cancel" ) ) { existingAccountPage->setStatus( NULL, false ); currentGamePage = existingAccountPage; currentGamePage->base_makeActive( true ); } else if( twinPage->checkSignal( "done" ) ) { startConnecting(); } } else if( currentGamePage == existingAccountPage ) { if( existingAccountPage->checkSignal( "quit" ) ) { quitGame(); } else if( existingAccountPage->checkSignal( "settings" ) ) { currentGamePage = settingsPage; currentGamePage->base_makeActive( true ); } else if( existingAccountPage->checkSignal( "review" ) ) { currentGamePage = reviewPage; currentGamePage->base_makeActive( true ); } else if( existingAccountPage->checkSignal( "friends" ) ) { currentGamePage = twinPage; currentGamePage->base_makeActive( true ); } else if( existingAccountPage->checkSignal( "done" ) || mapPullMode || autoLogIn ) { // auto-log-in one time for map pull // or one time for autoLogInMode mapPullMode = false; autoLogIn = false; // login button clears twin status // they have to login from twin page to play as twin if( userTwinCode != NULL ) { delete [] userTwinCode; userTwinCode = NULL; } startConnecting(); } else if( existingAccountPage->checkSignal( "tutorial" ) ) { livingLifePage->runTutorial(); // tutorial button clears twin status // they have to login from twin page to play as twin if( userTwinCode != NULL ) { delete [] userTwinCode; userTwinCode = NULL; } startConnecting(); } else if( autoUpdatePage->checkSignal( "relaunchFailed" ) ) { currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "manualRestartMessage" ); currentGamePage->base_makeActive( true ); } } else if( currentGamePage == getServerAddressPage ) { if( getServerAddressPage->isResponseReady() ) { if( serverIP != NULL ) { delete [] serverIP; } serverIP = getServerAddressPage->getResponse( "serverIP" ); serverPort = getServerAddressPage->getResponseInt( "serverPort" ); if( strstr( serverIP, "NONE_FOUND" ) != NULL ) { currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "serverShutdownMessage" ); currentGamePage->base_makeActive( true ); } else { printf( "Got server address: %s:%d\n", serverIP, serverPort ); int requiredVersion = getServerAddressPage->getResponseInt( "requiredVersionNumber" ); if( versionNumber < requiredVersion ) { if( SettingsManager::getIntSetting( "useSteamUpdate", 0 ) ) { // flag SteamGate that app needs update FILE *f = fopen( "steamGateForceUpdate.txt", "w" ); if( f != NULL ) { fprintf( f, "1" ); fclose( f ); } // launch steamGateClient in parallel // it will tell Steam that the app is dirty // and needs to be updated. runSteamGateClient(); currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "upgradeMessageSteam" ); currentGamePage->base_makeActive( true ); } else { char *autoUpdateURL = getServerAddressPage->getResponse( "autoUpdateURL" ); char updateStarted = startUpdate( autoUpdateURL, versionNumber ); delete [] autoUpdateURL; if( ! updateStarted ) { currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "upgradeMessage" ); currentGamePage->base_makeActive( true ); } else { currentGamePage = autoUpdatePage; currentGamePage->base_makeActive( true ); } } } else { // up to date, okay to connect currentGamePage = livingLifePage; currentGamePage->base_makeActive( true ); } } } } else if( currentGamePage == autoUpdatePage ) { if( autoUpdatePage->checkSignal( "failed" ) ) { currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "upgradeMessage" ); currentGamePage->base_makeActive( true ); } else if( autoUpdatePage->checkSignal( "writeError" ) ) { currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "updateWritePermissionMessage" ); currentGamePage->base_makeActive( true ); } else if( autoUpdatePage->checkSignal( "relaunchFailed" ) ) { currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "manualRestartMessage" ); currentGamePage->base_makeActive( true ); } } else if( currentGamePage == livingLifePage ) { if( livingLifePage->checkSignal( "loginFailed" ) ) { lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = existingAccountPage; existingAccountPage->setStatus( "loginFailed", true ); existingAccountPage->setStatusPositiion( true ); currentGamePage->base_makeActive( true ); } else if( livingLifePage->checkSignal( "connectionFailed" ) ) { lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = existingAccountPage; existingAccountPage->setStatus( "connectionFailed", true ); existingAccountPage->setStatusPositiion( true ); currentGamePage->base_makeActive( true ); } else if( livingLifePage->checkSignal( "versionMismatch" ) ) { lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = existingAccountPage; char *message = autoSprintf( translate( "versionMismatch" ), versionNumber, livingLifePage-> getRequiredVersion() ); if( SettingsManager::getIntSetting( "useCustomServer", 0 ) ) { existingAccountPage->showDisableCustomServerButton( true ); } existingAccountPage->setStatusDirect( message, true ); delete [] message; existingAccountPage->setStatusPositiion( true ); currentGamePage->base_makeActive( true ); } else if( livingLifePage->checkSignal( "twinCancel" ) ) { existingAccountPage->setStatus( NULL, false ); lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = existingAccountPage; currentGamePage->base_makeActive( true ); } else if( livingLifePage->checkSignal( "serverShutdown" ) ) { lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = existingAccountPage; existingAccountPage->setStatus( "serverShutdown", true ); existingAccountPage->setStatusPositiion( true ); currentGamePage->base_makeActive( true ); } else if( livingLifePage->checkSignal( "serverUpdate" ) ) { lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = existingAccountPage; existingAccountPage->setStatus( "serverUpdate", true ); existingAccountPage->setStatusPositiion( true ); currentGamePage->base_makeActive( true ); } else if( livingLifePage->checkSignal( "serverFull" ) ) { lastScreenViewCenter.x = 0; lastScreenViewCenter.y = 0; setViewCenterPosition( lastScreenViewCenter.x, lastScreenViewCenter.y ); currentGamePage = existingAccountPage; existingAccountPage->setStatus( "serverFull", true ); existingAccountPage->setStatusPositiion( true ); currentGamePage->base_makeActive( true ); } else if( livingLifePage->checkSignal( "died" ) ) { showDiedPage(); } else if( livingLifePage->checkSignal( "disconnect" ) ) { showReconnectPage(); } else if( livingLifePage->checkSignal( "loadFailure" ) ) { currentGamePage = finalMessagePage; finalMessagePage->setMessageKey( "loadingMapFailedMessage" ); char *failedFileName = getSpriteBankLoadFailure(); if( failedFileName == NULL ) { failedFileName = getSoundBankLoadFailure(); } if( failedFileName != NULL ) { char *detailMessage = autoSprintf( translate( "loadingMapFailedSubMessage" ), failedFileName ); finalMessagePage->setSubMessage( detailMessage ); delete [] detailMessage; } currentGamePage->base_makeActive( true ); } } else if( currentGamePage == extendedMessagePage ) { if( extendedMessagePage->checkSignal( "done" ) ) { extendedMessagePage->setSubMessage( "" ); if( userReconnect ) { currentGamePage = livingLifePage; } else { currentGamePage = rebirthChoicePage; } currentGamePage->base_makeActive( true ); } } else if( currentGamePage == rebirthChoicePage ) { if( rebirthChoicePage->checkSignal( "reborn" ) ) { // get server address again from scratch, in case // the server we were on just crashed // but keep twin status, if set startConnecting(); } else if( rebirthChoicePage->checkSignal( "tutorial" ) ) { livingLifePage->runTutorial(); // heck, allow twins in tutorial too, for now, it's funny startConnecting(); } else if( rebirthChoicePage->checkSignal( "review" ) ) { currentGamePage = reviewPage; currentGamePage->base_makeActive( true ); } else if( rebirthChoicePage->checkSignal( "menu" ) ) { currentGamePage = existingAccountPage; currentGamePage->base_makeActive( true ); } else if( rebirthChoicePage->checkSignal( "quit" ) ) { quitGame(); } } else if( currentGamePage == finalMessagePage ) { if( finalMessagePage->checkSignal( "quit" ) ) { quitGame(); } } } // now draw stuff AFTER all updates drawFrameNoUpdate( true ); // draw tail end of pause screen, if it is still visible if( pauseScreenFade > 0 ) { drawPauseScreen(); } } void drawFrameNoUpdate( char inUpdate ) { if( currentGamePage != NULL ) { currentGamePage->base_draw( lastScreenViewCenter, viewWidth ); } } // store mouse data for use as unguessable randomizing data // for key generation, etc. #define MOUSE_DATA_BUFFER_SIZE 20 int mouseDataBufferSize = MOUSE_DATA_BUFFER_SIZE; int nextMouseDataIndex = 0; // ensure that stationary mouse data (same value over and over) // doesn't overwrite data from actual motion float lastBufferedMouseValue = 0; float mouseDataBuffer[ MOUSE_DATA_BUFFER_SIZE ]; void pointerMove( float inX, float inY ) { // save all mouse movement data for key generation float bufferValue = inX + inY; // ignore mouse positions that are the same as the last one // only save data when mouse actually moving if( bufferValue != lastBufferedMouseValue ) { mouseDataBuffer[ nextMouseDataIndex ] = bufferValue; lastBufferedMouseValue = bufferValue; nextMouseDataIndex ++; if( nextMouseDataIndex >= mouseDataBufferSize ) { nextMouseDataIndex = 0; } } if( isPaused() ) { return; } if( currentGamePage != NULL ) { currentGamePage->base_pointerMove( inX, inY ); } } void pointerDown( float inX, float inY ) { if( isPaused() ) { return; } if( currentGamePage != NULL ) { currentGamePage->base_pointerDown( inX, inY ); } } void pointerDrag( float inX, float inY ) { if( isPaused() ) { return; } if( currentGamePage != NULL ) { currentGamePage->base_pointerDrag( inX, inY ); } } void pointerUp( float inX, float inY ) { if( isPaused() ) { return; } if( currentGamePage != NULL ) { currentGamePage->base_pointerUp( inX, inY ); } } void keyDown( unsigned char inASCII ) { // taking screen shot is ALWAYS possible if( inASCII == '=' ) { saveScreenShot( "screen" ); } /* if( inASCII == 'N' ) { toggleMipMapMinFilter( true ); } if( inASCII == 'n' ) { toggleMipMapMinFilter( false ); } */ if( isPaused() ) { // block general keyboard control during pause switch( inASCII ) { case 13: // enter // unpause pauseGame(); break; } // don't let user type on pause screen anymore return; if( inASCII == 127 || inASCII == 8 ) { // subtract from it deleteCharFromUserTypedMessage(); holdDeleteKeySteps = 0; // start with long delay until first repeat stepsBetweenDeleteRepeat = (int)( 30 / frameRateFactor ); } else if( inASCII >= 32 ) { // add to it if( currentUserTypedMessage != NULL ) { char *oldMessage = currentUserTypedMessage; currentUserTypedMessage = autoSprintf( "%s%c", oldMessage, inASCII ); delete [] oldMessage; } else { currentUserTypedMessage = autoSprintf( "%c", inASCII ); } } return; } if( currentGamePage != NULL ) { currentGamePage->base_keyDown( inASCII ); } switch( inASCII ) { case 'm': case 'M': { #ifdef USE_MALLINFO struct mallinfo meminfo = mallinfo(); printf( "Mem alloc: %d\n", meminfo.uordblks / 1024 ); #endif } break; } } void keyUp( unsigned char inASCII ) { if( inASCII == 127 || inASCII == 8 ) { // delete no longer held // even if pause screen no longer up, pay attention to this holdDeleteKeySteps = -1; } if( ! isPaused() ) { if( currentGamePage != NULL ) { currentGamePage->base_keyUp( inASCII ); } } } void specialKeyDown( int inKey ) { if( isPaused() ) { return; } if( currentGamePage != NULL ) { currentGamePage->base_specialKeyDown( inKey ); } } void specialKeyUp( int inKey ) { if( isPaused() ) { return; } if( currentGamePage != NULL ) { currentGamePage->base_specialKeyUp( inKey ); } } char getUsesSound() { return ! musicOff; } void drawString( const char *inString, char inForceCenter ) { setDrawColor( 1, 1, 1, 0.75 ); doublePair messagePos = lastScreenViewCenter; TextAlignment align = alignCenter; if( initDone && !inForceCenter ) { // transparent message setDrawColor( 1, 1, 1, 0.75 ); // stick messages in corner messagePos.x -= viewWidth / 2; messagePos.x += 20; messagePos.y += (viewWidth * viewHeightFraction) / 2; messagePos.y -= 32; align = alignLeft; } else { // fully opaque message setDrawColor( 1, 1, 1, 1 ); // leave centered } int numLines; char **lines = split( inString, "\n", &numLines ); for( int i=0; i<numLines; i++ ) { mainFont->drawString( lines[i], messagePos, align ); messagePos.y -= 32; delete [] lines[i]; } delete [] lines; }
[ "jasonrohrer@fastmail.fm" ]
jasonrohrer@fastmail.fm
05f21bc7b7d43a334e8f459ab1fb440e7ca72782
df4c6ec178bdc708cf1e269bf9f5a83f5854eb25
/src/lib/GuiRequest.h
aedb24889fba8fb3df5644e747c42e0bd249085c
[ "BSD-3-Clause" ]
permissive
romoadri21/boi
a43eb9dd258d6aa0eda7226404ac85735c25eb85
deef8e7148b50fbb36886ba4ff491a6c0e18ad67
refs/heads/master
2021-01-10T04:26:55.476114
2011-03-10T20:29:27
2011-03-10T20:29:27
51,186,522
0
0
null
null
null
null
UTF-8
C++
false
false
2,234
h
/* Copyright (c) 2010, Piet Hein Schouten. All rights reserved. * This code is licensed under a BSD-style license that can be * found in the LICENSE file. The license can also be found at: * http://www.boi-project.org/license */ #ifndef __BOI_GUIREQUEST_H #define __BOI_GUIREQUEST_H #include <QtGlobal> #include "ViewLayerId.h" #include "CRef.h" namespace BOI { class ComponentData; class GuiRequest { public: enum { RequestType_MoveToLayer = 0, RequestType_DestroyComponent, RequestType_SetBoundingRect, RequestType_CenterComponentOn, RequestType_SetTransformOrigin, RequestType_SetRotation, RequestType_SetPosition, RequestType_StackOnTop, RequestType_SetVisible, RequestType_SetOpacity, RequestType_SetParent, RequestType_UpdateRect, RequestType_Update, RequestType_Emit, RequestType_Rotate, RequestType_SetFlag, NumRequests }; public: int type; CRef cref; CRef cref2; union { ViewLayerId viewLayerId; ComponentData* pComponentData; qreal opacity; qreal rotation; bool boolean; struct { qreal x; qreal y; } point; struct { qreal x; qreal y; qreal width; qreal height; } rect; struct { int flag; bool enabled; } flagData; struct { int emitter; bool newOnly; } emitData; struct { bool relativeToScene; qreal x; qreal y; } centerComponentData; } data; GuiRequest* pNext; public: GuiRequest(); GuiRequest(const GuiRequest& request); GuiRequest& operator=(const GuiRequest& request); }; } // namespace BOI #endif //__BOI_GUIREQUEST_H
[ "piet.hein.schouten@localhost" ]
piet.hein.schouten@localhost
539066acfb7a55f80777ab295ca8b1993a435841
9030ce2789a58888904d0c50c21591632eddffd7
/SDK/ARKSurvivalEvolved_OnlineSubsystemEOS_classes.hpp
79f9a8b269e3cd4768900ce70283b4334e435ed3
[ "MIT" ]
permissive
2bite/ARK-SDK
8ce93f504b2e3bd4f8e7ced184980b13f127b7bf
ce1f4906ccf82ed38518558c0163c4f92f5f7b14
refs/heads/master
2022-09-19T06:28:20.076298
2022-09-03T17:21:00
2022-09-03T17:21:00
232,411,353
14
5
null
null
null
null
UTF-8
C++
false
false
647
hpp
#pragma once // ARKSurvivalEvolved (332.8) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_OnlineSubsystemEOS_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // Class OnlineSubsystemEOS.EOSNetDriver // 0x0000 (0x03C0 - 0x03C0) class UEOSNetDriver : public UIpNetDriver { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("Class OnlineSubsystemEOS.EOSNetDriver"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
ae11525765620673b8af1dddb14478d2c1c3f105
e7f7fbf4c029a35cf2f84b25b239b0c57d66c514
/26_11_2019/Source.cpp
e93cf1ab50b43e59531c76fa149f194bdecf2d8e
[ "MIT" ]
permissive
fdiniello/interview_problems
9d45986ad10094335c48abad46a3fb8f2fbf01ab
b9a3466f617e733414211f7b57f0e7bdef80f6c8
refs/heads/master
2022-12-29T01:34:52.457024
2020-10-05T23:36:26
2020-10-05T23:36:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,345
cpp
/* This problem was asked by Facebook. Implement regular expression matching with the following special characters: . (period) which matches any single character * (asterisk) which matches zero or more of the preceding element That is, implement a function that takes in a string and a valid regular expression and returns whether or not the string matches the regular expression. For example, given the regular expression "ra." and the string "ray", your function should return true. The same regular expression on the string "raymond" should return false. Given the regular expression ".*at" and the string "chat", your function should return true. The same regular expression on the string "chats" should return false. */ #include <iostream> #include <string> #include <vector> struct RegExpRule { RegExpRule( const bool _uniqueValue, const bool _multiple, const char _value ) : uniqueValue( _uniqueValue ), multiple( _multiple ), value( _value ) {} bool uniqueValue; bool multiple; char value; }; struct RegExp { RegExp( const std::string& expression ) : m_expression( expression ) { createRules(); } void createRules() { for ( const auto& c : m_expression ) { if ( c == '.' ) { auto rule = RegExpRule( false, false, 'a' ); m_rules.push_back( rule ); } else if ( c == '*' && !m_rules.empty() ) { m_rules.back().multiple = true; } else { auto rule = RegExpRule( true, false, c ); m_rules.push_back( rule ); } } } void helper( const std::string& word, bool& found, int indexWord, int indexRule ) { if ( found ) { return; } if ( indexRule == m_rules.size() && indexWord == word.size() ) { found = true; return; } if ( indexRule == m_rules.size() || indexWord == word.size() ) { return; } const auto& rule = m_rules[indexRule]; if ( rule.multiple ) { if ( !rule.uniqueValue ) { for ( int i = indexWord; i <= word.size(); i++ ) { helper( word, found, i, indexRule + 1 ); } } else if ( rule.value == word[indexWord] ) { helper( word, found, indexWord, indexRule + 1 ); for ( int i = indexWord + 1; i <= word.size(); i++ ) { auto findStr = std::string( i - indexWord, rule.value ); if ( word.find( findStr, indexWord ) == indexWord ) { helper( word, found, i, indexRule + 1 ); } } } } else { if ( !rule.uniqueValue ) { helper( word, found, indexWord + 1, indexRule + 1 ); } else if ( rule.value == word[indexWord] ) { helper( word, found, indexWord + 1, indexRule + 1 ); } } } bool matches( const std::string& word ) { bool found = false; helper( word, found, 0, 0 ); return found; } std::string m_expression; std::vector< RegExpRule > m_rules; }; int main() { std::cout << RegExp( "ra." ).matches( "ray" ) << std::endl; std::cout << RegExp( "ra." ).matches( "raymond" ) << std::endl; std::cout << RegExp( "ra.*" ).matches( "raymond" ) << std::endl; std::cout << RegExp( ".*at" ).matches( "chat" ) << std::endl; std::cout << RegExp( ".*at" ).matches( "cheaeaat" ) << std::endl; std::cout << RegExp( "..a*t" ).matches( "chaabaat" ) << std::endl; std::cout << RegExp( "..a*t" ).matches( "chaaaaat" ) << std::endl; std::cout << RegExp( ".*at" ).matches( "chats" ) << std::endl; std::cin.get(); return 0; }
[ "aduranddiaz@gmail.com" ]
aduranddiaz@gmail.com
981e4ce3fd6f5570f8a5ec83fdcd48cc41ce4254
dcc514c9e9dba73b43152e7911ff286d46f6ab77
/src/ch13/ch13_ex.cpp
a8c80e08b11c86bf45d50c68ec042364dc932907
[]
no_license
peterschussheim/programming_principals_practice
dba73e3a7ed808b0cff422142fcdb79ead6cc222
f3e23f9d38e7b3bc7ab2dd1d653db68bbac28558
refs/heads/master
2023-02-26T00:27:53.090974
2021-01-31T22:26:41
2021-01-31T22:26:41
234,388,882
1
0
null
2020-10-13T20:11:50
2020-01-16T18:51:31
C++
UTF-8
C++
false
false
5,657
cpp
/* Peter Schussheim 02/11/20 Programming Principles and Practice */ #include "std_lib_facilities.h" #include "Simple_window.h" #include "Graph.h" /* Exercise 2: Draw a box with rounded corners. Define a class Box , consisting of four lines and four arcs. */ int main() { try { Point tl{100, 100}; Simple_window win{tl, 800, 800, "Arcs"}; /*Graph_lib::Arc a1{Point{150, 100}, 100, 50, 45, 175}; a1.set_color(Color::blue); Graph_lib::Arc a2{Point{150, 150}, 50, 90, 10, 170}; a2.set_color(Color::dark_yellow); Graph_lib::Arc a3{Point{150, 200}, 100, 50, 45, 175}; a3.set_color(Color::red); win.attach(a1); win.attach(a2); win.attach(a3);*/ Box sharp_box{Point{300, 50}, 100, 80}; // regular box with sharp edges sharp_box.set_color(Color::blue); Box rounded_box{Point{400, 150}, 200, 200, 25}; rounded_box.set_color(Color::red); rounded_box.set_fill_color(Color::blue); /*win.attach(sharp_box); win.attach(rounded_box);*/ // Arrow arrow1{Point{100, 500}, Point{400, 450}}; // arrow1.set_color(Color::dark_green); // win.attach(arrow1); // Graph_lib::Rectangle rect1(Point(200, 200), 150, 150); // rect1.set_color(Color::blue); // win.attach(rect1); // Arrow nwr(nw(rect1), Point(nw(rect1).x - 30, nw(rect1).y - 30)); // win.attach(nwr); // Arrow nr(n(rect1), Point(n(rect1).x, n(rect1).y - 30)); // win.attach(nr); // Arrow ner(ne(rect1), Point(ne(rect1).x + 30, ne(rect1).y - 30)); // win.attach(ner); // Arrow er(e(rect1), Point(e(rect1).x + 30, e(rect1).y)); // win.attach(er); // Arrow ser(se(rect1), Point(se(rect1).x + 30, se(rect1).y + 30)); // win.attach(ser); // Arrow sr(s(rect1), Point(s(rect1).x, s(rect1).y + 30)); // win.attach(sr); // Arrow swr(sw(rect1), Point(sw(rect1).x - 30, sw(rect1).y + 30)); // win.attach(swr); // Arrow wr(w(rect1), Point(w(rect1).x - 30, w(rect1).y)); // win.attach(wr); // Arrow cr(center(rect1), Point(center(rect1).x + 15, center(rect1).y + // 15)); win.attach(cr); nwr.set_color(Color::blue); // nr.set_color(Color::red); // ner.set_color(Color::yellow); // er.set_color(Color::green); // ser.set_color(Color::cyan); // sr.set_color(Color::black); // swr.set_color(Color::blue); // wr.set_color(Color::dark_yellow); // cr.set_color(Color::dark_cyan); Textbox tb_win{Point{100, 50}, 70, "Window"}; tb_win.set_fill_color(Color::dark_green); win.attach(tb_win); Textbox tb_s_win{Point{70, 135}, 130, "Simple_window"}; tb_s_win.set_fill_color(Color::dark_green); tb_s_win.label.set_font(Font::helvetica_bold); win.attach(tb_s_win); Arrow a1(Graph_lib::n(tb_s_win), Graph_lib::s(tb_win)); win.attach(a1); Textbox tb_ls(Point(200, 50), 85, "Line_style"); tb_ls.set_fill_color(Color::dark_green); tb_ls.label.set_font(Font::helvetica_bold); win.attach(tb_ls); Textbox tb_col(Point(315, 50), 55, "Color"); tb_col.set_fill_color(Color::dark_green); tb_col.label.set_font(Font::helvetica_bold); win.attach(tb_col); Textbox tb_pt(Point(340, 135), 52, "Point"); tb_pt.set_fill_color(Color::dark_green); tb_pt.label.set_font(Font::helvetica_bold); win.attach(tb_pt); Textbox tb_shp(Point(240, 120), 58, "Shape"); tb_shp.set_fill_color(Color::dark_green); tb_shp.label.set_font(Font::helvetica_bold); win.attach(tb_shp); Textbox tb_ln(Point(50, 210), 50, "Line"); tb_ln.set_fill_color(Color::dark_green); tb_ln.label.set_font(Font::helvetica_bold); win.attach(tb_ln); Textbox tb_lns(Point(110, 210), 50, "Lines"); tb_lns.set_fill_color(Color::dark_green); tb_lns.label.set_font(Font::helvetica_bold); win.attach(tb_lns); Textbox tb_plg(Point(170, 210), 70, "Polygon"); tb_plg.set_fill_color(Color::dark_green); tb_plg.label.set_font(Font::helvetica_bold); win.attach(tb_plg); Textbox tb_ax(Point(250, 210), 40, "Axis"); tb_ax.set_fill_color(Color::dark_green); tb_ax.label.set_font(Font::helvetica_bold); win.attach(tb_ax); Textbox tb_rect(Point(300, 210), 85, "Rectangle"); tb_rect.set_fill_color(Color::dark_green); tb_rect.label.set_font(Font::helvetica_bold); win.attach(tb_rect); Textbox tb_txt(Point(395, 210), 45, "Text"); tb_txt.set_fill_color(Color::dark_green); tb_txt.label.set_font(Font::helvetica_bold); win.attach(tb_txt); Textbox tb_img(Point(450, 210), 55, "Image"); tb_img.set_fill_color(Color::dark_green); tb_img.label.set_font(Font::helvetica_bold); win.attach(tb_img); Arrow a_ln(n(tb_ln), sw(tb_shp)); win.attach(a_ln); Arrow a_lns(n(tb_lns), Point(sw(tb_shp).x + 10, sw(tb_shp).y)); win.attach(a_lns); Arrow a_plg(n(tb_plg), Point(sw(tb_shp).x + 20, sw(tb_shp).y)); win.attach(a_plg); Arrow a_ax(n(tb_ax), s(tb_shp)); win.attach(a_ax); Arrow a_rect(n(tb_rect), Point(se(tb_shp).x - 20, se(tb_shp).y)); win.attach(a_rect); Arrow a_txt(n(tb_txt), Point(se(tb_shp).x - 10, se(tb_shp).y)); win.attach(a_txt); Arrow a_img(n(tb_img), se(tb_shp)); win.attach(a_img); win.wait_for_button(); keep_window_open("~"); return 0; } catch (exception& e) { cerr << e.what(); keep_window_open("~"); return 1; } catch (...) { cerr << "unhandled exeption\n"; keep_window_open("~"); return 2; } }
[ "peter@schussheim.com" ]
peter@schussheim.com
ccce708f640e6c954a58a388bd8cf3677979fc67
7f62f204ffde7fed9c1cb69e2bd44de9203f14c8
/DboClient/Tool/NaviTool/NaviToolDoc.h
f164567c788bed54dab63eed237d528a9fbc8834
[]
no_license
4l3dx/DBOGLOBAL
9853c49f19882d3de10b5ca849ba53b44ab81a0c
c5828b24e99c649ae6a2953471ae57a653395ca2
refs/heads/master
2022-05-28T08:57:10.293378
2020-05-01T00:41:08
2020-05-01T00:41:08
259,094,679
3
3
null
2020-04-29T17:06:22
2020-04-26T17:43:08
null
UHC
C++
false
false
797
h
// NaviToolDoc.h : CNaviToolDoc 클래스의 인터페이스 // #pragma once class CNaviToolDoc : public CDocument { protected: // serialization에서만 만들어집니다. CNaviToolDoc(); DECLARE_DYNCREATE(CNaviToolDoc) // 특성입니다. public: CString m_strPath; // 작업입니다. public: // 재정의입니다. public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); // 구현입니다. public: virtual ~CNaviToolDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // 생성된 메시지 맵 함수 protected: DECLARE_MESSAGE_MAP() public: afx_msg void OnLoadWorldData(); afx_msg void OnSavePathData(); afx_msg void OnLoadPathData(); afx_msg void OnProjectViewTotalMemory(); };
[ "64261665+dboguser@users.noreply.github.com" ]
64261665+dboguser@users.noreply.github.com
53f004875590281651244b4a69035354edae4ad9
d938c544c610571caf3913948ec7be87db7f3cac
/design_pattern/factory-method/concrete_factory.h
a17c36d84f2ceef425dc9868b78c6e8133b37d5b
[]
no_license
yutakakinjyo/proc-cpp
9a307da8fdabfb94cd8a3a8fa18e67cb929ee741
70a0a5e3665cac7fd7290b55468bb554e93577b4
refs/heads/master
2021-01-10T01:10:11.478369
2016-01-15T10:38:26
2016-01-15T10:38:26
45,298,737
0
0
null
2016-01-15T10:38:26
2015-10-31T11:13:18
C++
UTF-8
C++
false
false
197
h
#ifndef CONCRETE_FACTORY_H #define CONCRETE_FACTORY_H #include "factory.h" #include "concrete_product.h" class ConcreteFactory : public Factory { public: Product* create_product(); }; #endif
[ "yutakakinjyo@gmail.com" ]
yutakakinjyo@gmail.com
cfd2e4f42073b087b10afba4439040a6afe9400e
536656cd89e4fa3a92b5dcab28657d60d1d244bd
/gpu/angle_end2end_tests_main.cc
02997fdc6d1c65c8ae41ac4dd9ac96b8a39c44fc
[ "BSD-3-Clause" ]
permissive
ECS-251-W2020/chromium
79caebf50443f297557d9510620bf8d44a68399a
ac814e85cb870a6b569e184c7a60a70ff3cb19f9
refs/heads/master
2022-08-19T17:42:46.887573
2020-03-18T06:08:44
2020-03-18T06:08:44
248,141,336
7
8
BSD-3-Clause
2022-07-06T20:32:48
2020-03-18T04:52:18
null
UTF-8
C++
false
false
1,182
cc
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/bind.h" #include "base/command_line.h" #include "base/task/single_thread_task_executor.h" #include "base/test/launcher/unit_test_launcher.h" #include "base/test/test_suite.h" #include "testing/gmock/include/gmock/gmock.h" namespace { int RunHelper(base::TestSuite* test_suite) { base::SingleThreadTaskExecutor task_executor; return test_suite->Run(); } } // namespace // Located in third_party/angle/src/tests/test_utils/ANGLETest.cpp. // Defined here so we can avoid depending on the ANGLE headers. void ANGLEProcessTestArgs(int *argc, char *argv[]); int main(int argc, char** argv) { base::CommandLine::Init(argc, argv); ANGLEProcessTestArgs(&argc, argv); testing::InitGoogleMock(&argc, argv); base::TestSuite test_suite(argc, argv); int rt = base::LaunchUnitTestsWithOptions( argc, argv, 1, // Run tests serially. 0, // Disable batching. true, // Use job objects. base::BindOnce(&RunHelper, base::Unretained(&test_suite))); return rt; }
[ "pcding@ucdavis.edu" ]
pcding@ucdavis.edu
794ac9e86b71bb76e0ec0df2b18f5e1d596939e9
bf6341fb7636fe3e666bc509c175f8b147976c9a
/cpp/beginner_contest_157/a.cpp
1539e7cbc0358b296c1a5abd270ea03d90fc1260
[ "MIT" ]
permissive
kitoko552/atcoder
c2877566426efe7bcb198eae004505602e8369a0
a1e18b6d855baefb90ae6df010bcf1ffa8ff5562
refs/heads/master
2022-12-26T03:43:52.347654
2020-10-14T12:24:55
2020-10-14T12:24:55
236,449,143
1
0
null
null
null
null
UTF-8
C++
false
false
427
cpp
#include<iostream> #include<algorithm> #include<cmath> #include<vector> #include<map> #include<queue> #define rep(i, n) for (int i = 0; i < (n); ++i) #define rep1(i, n) for (int i = 1; i < (n); ++i) using namespace std; using ll = long long; using P = pair<int, int>; const int INF = 1001001001; int main() { int N; cin >> N; int ans; if (N%2 == 0) ans = N/2; else ans = N/2+1; cout << ans << endl; return 0; }
[ "blueberryjam09@gmail.com" ]
blueberryjam09@gmail.com
f8f8556a07d6c4b312fa13624a41ff9e6cd9269d
1f787c5ae598e17610d33be4d2cb29c64dc5c497
/onnx/avs_onnx.cpp
5608fa919200af8e4527ee2cdbbd8ec65ab83bc2
[]
no_license
applefishsky009/pointpillars
d57cafa8733295a05552bfaae5fa18f5478303db
9b6bb935ad2c2aba16f5e837b714389462fa88a7
refs/heads/master
2023-04-08T22:06:20.241690
2021-04-14T01:03:41
2021-04-14T01:03:41
357,082,894
2
0
null
null
null
null
GB18030
C++
false
false
8,026
cpp
#include "avs_onnx.h" #include "avs_onnx_lib.h" #include "avs_onnx_common_lib.h" #include "avs_dnn.h" #include "avs_onnxruntime.h" unsigned int AVS_Onnx_GetMemSize( AVS_ONNX_INFO *input, AVS_MEM_TAB mem_tab[AVS_ONNX_MEM_TAB]) { unsigned int mem_size = 0; // pre.onnx输入内存, 完整的lib应该在pointpillars接口中 mem_size += AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // pillar_x mem_size += AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // pillar_y mem_size += AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // pillar_z mem_size += AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // pillar_i mem_size += AVS_PREONNX_MAX_IN_C * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // num_voxels mem_size += AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // x_sub_shaped mem_size += AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // y_sub_shaped mem_size += AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // mask // pre.onnx输出内存, 完整的lib应该在pointpillars接口中 mem_size += AVS_PREONNX_OUT_C * AVS_PREONNX_MAX_IN_C * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // pillars feature // rpn.onnx输入内存 mem_size += AVS_RPNONNX_IN_C * AVS_RPNONNX_IN_H * AVS_RPNONNX_IN_W * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // rpn.onnx输出内存 mem_size += AVS_RPNONNX_IN_H * AVS_RPNONNX_IN_W * AVS_RPNONNX_OUT_1 * sizeof(float) + AVS_MEM_ALIGN_128BYTE; mem_size += AVS_RPNONNX_IN_H * AVS_RPNONNX_IN_W * AVS_RPNONNX_OUT_2 * sizeof(float) + AVS_MEM_ALIGN_128BYTE; mem_size += AVS_RPNONNX_IN_H * AVS_RPNONNX_IN_W * AVS_RPNONNX_OUT_2 * sizeof(float) + AVS_MEM_ALIGN_128BYTE; // 算法库句柄内存 mem_size += sizeof(AVS_ONNX_FILTER) + AVS_MEM_ALIGN_128BYTE; mem_tab[0].size = mem_size; mem_tab[0].base = NULL; mem_tab[0].alignment = AVS_MEM_ALIGN_128BYTE; return 0; } unsigned int AVS_Onnx_CreatMemSize( AVS_ONNX_INFO *input, AVS_MEM_TAB mem_tab[AVS_ONNX_MEM_TAB], void **handle) { int k = 0; AVS_ONNX_FILTER *filter = NULL; AVS_ONNX_BUF mem_buf; mem_buf.start = mem_tab[0].base; mem_buf.cur_pos = mem_tab[0].base; mem_buf.end = (void *)((QWORD)mem_buf.cur_pos + (QWORD)mem_tab[0].size); // pre.onnx输入内存, 完整的lib应该在pointpillars接口中 input->onnx_pre_input.pillar_x = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float)); // pillar_x AVS_CHECK_ERROR(input->onnx_pre_input.pillar_x == NULL, AVS_LIB_PTR_NULL); input->onnx_pre_input.pillar_y = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float)); // pillar_y AVS_CHECK_ERROR(input->onnx_pre_input.pillar_y == NULL, AVS_LIB_PTR_NULL); input->onnx_pre_input.pillar_z = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float)); // pillar_z AVS_CHECK_ERROR(input->onnx_pre_input.pillar_z == NULL, AVS_LIB_PTR_NULL); input->onnx_pre_input.pillar_i = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float)); // pillar_i AVS_CHECK_ERROR(input->onnx_pre_input.pillar_i == NULL, AVS_LIB_PTR_NULL); input->onnx_pre_input.num_voxels = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_MAX_IN_C * sizeof(float)); // num_voxels AVS_CHECK_ERROR(input->onnx_pre_input.num_voxels == NULL, AVS_LIB_PTR_NULL); input->onnx_pre_input.x_sub_shaped = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float)); // x_sub_shaped AVS_CHECK_ERROR(input->onnx_pre_input.x_sub_shaped == NULL, AVS_LIB_PTR_NULL); input->onnx_pre_input.y_sub_shaped = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float)); // y_sub_shaped AVS_CHECK_ERROR(input->onnx_pre_input.y_sub_shaped == NULL, AVS_LIB_PTR_NULL); input->onnx_pre_input.mask = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_MAX_IN_C * AVS_PREONNX_MAX_DIM * sizeof(float)); // mask AVS_CHECK_ERROR(input->onnx_pre_input.mask == NULL, AVS_LIB_PTR_NULL); // pre.onnx输出内存, 完整的lib应该在pointpillars接口中 input->onnx_scatter_in.pillar_feature = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_PREONNX_OUT_C * AVS_PREONNX_MAX_IN_C * sizeof(float)); // pillars feature AVS_CHECK_ERROR(input->onnx_scatter_in.pillar_feature == NULL, AVS_LIB_PTR_NULL); // rpn.onnx输入内存 input->onnx_rpn_in.spatial_features= (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_RPNONNX_IN_C * AVS_RPNONNX_IN_H * AVS_RPNONNX_IN_W * sizeof(float)); // spatial_features AVS_CHECK_ERROR(input->onnx_rpn_in.spatial_features == NULL, AVS_LIB_PTR_NULL); // rpn.onnx输出内存 input->onnx_rpn_out.out_184 = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_RPNONNX_IN_H * AVS_RPNONNX_IN_W * AVS_RPNONNX_OUT_1 * sizeof(float)); // 184 AVS_CHECK_ERROR(input->onnx_rpn_out.out_184 == NULL, AVS_LIB_PTR_NULL); input->onnx_rpn_out.out_185 = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_RPNONNX_IN_H * AVS_RPNONNX_IN_W * AVS_RPNONNX_OUT_2 * sizeof(float)); // 185 AVS_CHECK_ERROR(input->onnx_rpn_out.out_185 == NULL, AVS_LIB_PTR_NULL); input->onnx_rpn_out.out_187 = (float *)AVS_ONNX_COM_alloc_buffer(&mem_buf, AVS_RPNONNX_IN_H * AVS_RPNONNX_IN_W * AVS_RPNONNX_OUT_2 * sizeof(float)); // 187 AVS_CHECK_ERROR(input->onnx_rpn_out.out_187 == NULL, AVS_LIB_PTR_NULL); // 算法库句柄内存 filter = (AVS_ONNX_FILTER *)AVS_ONNX_COM_alloc_buffer(&mem_buf, sizeof(AVS_ONNX_FILTER)); AVS_CHECK_ERROR(filter == NULL, AVS_LIB_PTR_NULL); *handle = (void *)filter; return 0; } unsigned int AVS_Onnx_Init( void *handle, AVS_ONNX_INFO *inbuf, int in_buf_size) { AVS_ONNX_FILTER *filter = (AVS_ONNX_FILTER *)handle; // 下列初始化二选一即可 opencv dnn库支持性不太好 // opencv dnn onnx初始化 // dnn_onnx_init(filter->net, inbuf->onnx); // onnxruntime pre初始化 onnxruntime_init(filter, inbuf->onnx); // onnxruntime rpn初始化 onnxruntime_rpn_init(filter, inbuf->rpn_onnx); printf("onnx init done!"); return 0; } // https://www.pianshen.com/article/3342263430/ // https://blog.csdn.net/wanggao_1990/article/details/86713653 dnn函数介绍 // https://docs.opencv.org/3.4/db/d30/classcv_1_1dnn_1_1Net.html#abf96c5e92de4f6cd3013a6fb900934b4 unsigned int AVS_Onnx_Forward( void *handle, AVS_ONNX_INFO *inbuf, int in_buf_size, AVS_ONNX_INFO *outbuf, int out_buf_size) { AVS_ONNX_FILTER *filter = (AVS_ONNX_FILTER *)handle; // opencv dnn 显示接口 // dnn_onnx_show(filter->net); // opencv dnn 根据图像进行前向 // dnn_onnx_image_forward(filter, inbuf->image); // opencv dnn 根据向量进行前向 // dnn_onnx_vector_forward(filter->net, &inbuf->onnx_pre_input); // printf("opencv dnn done!\n"); // onnxruntime 接口 onnxruntime_show(filter->session); // onnxruntime 输入生成 float *ort_outputs = onnxruntime_foward(filter->session, inbuf->onnx_pre_input); // onnxruntime 结果输出 onnxruntime_output(ort_outputs, inbuf->onnx_scatter_in); printf("onnxruntime pre done!\n"); return 0; } unsigned int AVS_Onnx_Rpn_Forward( void *handle, AVS_ONNX_INFO *inbuf, int in_buf_size, AVS_ONNX_INFO *outbuf, int out_buf_size) { AVS_ONNX_FILTER *filter = (AVS_ONNX_FILTER *)handle; // onnxruntime 接口 onnxruntime_show(filter->rpn_session); // onnxruntime 输入生成 vector<float *> ort_outputs = onnxruntime_rpn_foward(filter->rpn_session, inbuf->onnx_rpn_in); // onnxruntime 结果输出 onnxruntime_rpn_output(ort_outputs, outbuf->onnx_rpn_out); printf("onnxruntime rpn done!\n"); return 0; }
[ "ryl_public@163.com" ]
ryl_public@163.com
a49ac44ebb3493ebdcda056651254364c75b90d7
dc4da3e0a143303761df274d34519a54532d6bc9
/include/core/Timer.hpp
0a762984fb9307512565913d5966fdbbf237aa1d
[ "MIT" ]
permissive
Amirhosein-GPR/checkers
ab41828ae1e940c5a4c594d80f2eff552eb56934
4e4eb1ec23e2f34a663b8b59b07babd03c7354ad
refs/heads/main
2023-02-15T14:31:01.555818
2021-01-15T13:50:01
2021-01-15T13:50:01
326,674,729
0
0
null
null
null
null
UTF-8
C++
false
false
392
hpp
#ifndef TIMER_HPP #define TIMER_HPP #include <SDL2/SDL.h> class Timer { public: Timer(); void start(); void stop(); void pause(); void resume(); Uint32 getTicks(); bool isStarted(); bool isPaused(); private: Uint32 startTicks; Uint32 pausedTicks; bool started; bool paused; }; #endif
[ "a.asgari1999@gmail.com" ]
a.asgari1999@gmail.com
f60162f1f92ef917f77a03e14835a2ae9f1ce1ee
284b1751555df210b39bed480a4a81bce7e356c6
/common/include/Skeleton2D.h
c3bd1eee8a2e8991d89bbcb8f19f130db9b3a569
[]
no_license
Ykauji/Platformer2d
007cb66dade4a6c0e896a8aa95eb497459a4f3d8
60d2209b09540a3dd9b0c92ec96efb251da5fa80
refs/heads/master
2018-11-17T14:39:58.016901
2018-11-14T00:08:36
2018-11-14T00:08:42
116,098,996
1
0
null
null
null
null
UTF-8
C++
false
false
11,305
h
#ifndef _H_SKELETON2D #define _H_SKELETON2D #define AGK_BONE_ANIMATE 0x0001 #define AGK_BONE_INHERIT_ROTATION 0x0002 #define AGK_BONE_INHERIT_SCALE 0x0004 #define AGK_BONE_ROOT 0x0008 #define AGK_BONE_PRE_SCALE 0x0010 #define AGK_SKELETON_PLAYING 0x0001 #define AGK_SKELETON_LOOPING 0x0002 #define AGK_SKELETON_FLIPH 0x0004 #define AGK_SKELETON_FLIPV 0x0008 #define AGK_SKELETON_VISIBLE 0x0010 #define AGK_SLOT_ANIMATE 0x00000001 namespace AGK { class cSprite; class Bone2D; // attachment key frames class Anim2DKeyFrameAttachment { public: float m_fTime; uString m_sSpriteName; cSprite *m_pSprite; }; // color key frames class Anim2DKeyFrameColor { public: float m_fTime; unsigned char m_iRed; unsigned char m_iGreen; unsigned char m_iBlue; unsigned char m_iAlpha; Anim2DKeyFrameColor() {} virtual ~Anim2DKeyFrameColor() {} virtual void Interpolate( Anim2DKeyFrameColor* pNext, float t, unsigned char &red, unsigned char &green, unsigned char &blue, unsigned char &alpha ); }; class Anim2DKeyFrameColorStepped : public Anim2DKeyFrameColor { public: Anim2DKeyFrameColorStepped() {} virtual ~Anim2DKeyFrameColorStepped() {} virtual void Interpolate( Anim2DKeyFrameColor* pNext, float t, unsigned char &red, unsigned char &green, unsigned char &blue, unsigned char &alpha ) { red = m_iRed; green = m_iGreen; blue = m_iBlue; alpha = m_iAlpha; } }; class Anim2DKeyFrameColorCurved : public Anim2DKeyFrameColor { public: float c1, c2, c3, c4; Anim2DKeyFrameColorCurved() {} virtual ~Anim2DKeyFrameColorCurved() {} virtual void Interpolate( Anim2DKeyFrameColor* pNext, float t, unsigned char &red, unsigned char &green, unsigned char &blue, unsigned char &alpha ); }; class Anim2DSlot { public: uString m_sSlotName; int m_iSlotIndex; UINT m_iNumColors; Anim2DKeyFrameColor **m_pColors; UINT m_iNumAttachments; Anim2DKeyFrameAttachment **m_pAttachments; Anim2DSlot(); ~Anim2DSlot(); }; class Slot2D { public: uString m_sName; Bone2D *m_pParent; UINT m_bFlags; cSprite *m_pSprite; UINT m_iColor; cSprite *m_pOrigSprite; UINT m_iOrigColor; Anim2DSlot *m_pPrevAnim; Anim2DSlot *m_pAnim; UINT m_iPrevFrameColor; UINT m_iPrevFrameAttachment; UINT m_iCurrFrameColor; UINT m_iCurrFrameAttachment; Slot2D(); ~Slot2D(); void Tween( float prevtime, float currtime, float s ); void Interpolate( float currtime ); }; // rotation keyframes class Anim2DKeyFrameRotation { public: float m_fTime; float m_fRotation; Anim2DKeyFrameRotation() {} virtual ~Anim2DKeyFrameRotation() {} virtual void Interpolate( Anim2DKeyFrameRotation* pNext, float t, float &r ) { if ( !pNext ) { r = m_fRotation; return; } float oldR = m_fRotation; float newR = pNext->m_fRotation; if ( oldR < newR ) { while ( newR - oldR > 180 ) oldR += 360; } else { while ( oldR - newR > 180 ) newR += 360; } r = oldR + t*(newR - oldR); } }; class Anim2DKeyFrameRotationStepped : public Anim2DKeyFrameRotation { public: Anim2DKeyFrameRotationStepped() {} virtual ~Anim2DKeyFrameRotationStepped() {} virtual void Interpolate( Anim2DKeyFrameRotation* pNext, float t, float &r ) { r = m_fRotation; } }; class Anim2DKeyFrameRotationCurved : public Anim2DKeyFrameRotation { public: float c1, c2, c3, c4; Anim2DKeyFrameRotationCurved() {} virtual ~Anim2DKeyFrameRotationCurved() {} virtual void Interpolate( Anim2DKeyFrameRotation* pNext, float t, float &r ) { float guess = 0.5f; float newGuess = t; int iter = 0; // use newton raphson to find s for t (t=beizer x axis) do { guess = newGuess; newGuess = guess - ( (EvaluateBezier(c1, c3, guess) - t) / EvaluateBezierDt(c1, c3, guess) ); iter++; } while ( fabs(newGuess-guess) > 0.0001f && iter < 10 ); // get new t (from bezier y axis) for this s t = EvaluateBezier(c2, c4, newGuess); float oldR = m_fRotation; float newR = pNext->m_fRotation; if ( oldR < newR ) { while ( newR - oldR > 180 ) oldR += 360; } else { while ( oldR - newR > 180 ) newR += 360; } r = oldR + t*(newR - oldR); } }; // position keyframes class Anim2DKeyFramePosition { public: float m_fTime; float m_fX; float m_fY; Anim2DKeyFramePosition() {} virtual ~Anim2DKeyFramePosition() {} virtual void Interpolate( Anim2DKeyFramePosition* pNext, float t, float &x, float &y ) { if ( !pNext ) { x = m_fX; y = m_fY; return; } x = m_fX + t*(pNext->m_fX - m_fX); y = m_fY + t*(pNext->m_fY - m_fY); } }; class Anim2DKeyFramePositionStepped : public Anim2DKeyFramePosition { public: Anim2DKeyFramePositionStepped() {} virtual ~Anim2DKeyFramePositionStepped() {} virtual void Interpolate( Anim2DKeyFramePosition* pNext, float t, float &x, float &y ) { x = m_fX; y = m_fY; } }; class Anim2DKeyFramePositionCurved : public Anim2DKeyFramePosition { public: float c1, c2, c3, c4; Anim2DKeyFramePositionCurved() {} virtual ~Anim2DKeyFramePositionCurved() {} virtual void Interpolate( Anim2DKeyFramePosition* pNext, float t, float &x, float &y ) { float guess = 0.5f; float newGuess = t; int iter = 0; // use newton raphson to find s for t (t=beizer x axis) do { guess = newGuess; newGuess = guess - ( (EvaluateBezier(c1, c3, guess) - t) / EvaluateBezierDt(c1, c3, guess) ); iter++; } while ( fabs(newGuess-guess) > 0.00001f && iter < 10 ); // get new t (from bezier y axis) for this s t = EvaluateBezier(c2, c4, newGuess); x = m_fX + t*(pNext->m_fX - m_fX); y = m_fY + t*(pNext->m_fY - m_fY); } }; // scale keyframes class Anim2DKeyFrameScale { public: float m_fTime; float m_fScaleX; float m_fScaleY; Anim2DKeyFrameScale() {} virtual ~Anim2DKeyFrameScale() {} virtual void Interpolate( Anim2DKeyFrameScale* pNext, float t, float &x, float &y ) { if ( !pNext ) { x = m_fScaleX; y = m_fScaleY; return; } x = m_fScaleX + t*(pNext->m_fScaleX - m_fScaleX); y = m_fScaleY + t*(pNext->m_fScaleY - m_fScaleY); } }; class Anim2DKeyFrameScaleStepped : public Anim2DKeyFrameScale { public: Anim2DKeyFrameScaleStepped() {} virtual ~Anim2DKeyFrameScaleStepped() {} virtual void Interpolate( Anim2DKeyFrameScale* pNext, float t, float &x, float &y ) { x = m_fScaleX; y = m_fScaleY; } }; class Anim2DKeyFrameScaleCurved : public Anim2DKeyFrameScale { public: float c1, c2, c3, c4; Anim2DKeyFrameScaleCurved() {} virtual ~Anim2DKeyFrameScaleCurved() {} virtual void Interpolate( Anim2DKeyFrameScale* pNext, float t, float &x, float &y ) { float guess = 0.5f; float newGuess = t; int iter = 0; // use newton raphson to find s for t (t=beizer x axis) do { guess = newGuess; newGuess = guess - ( (EvaluateBezier(c1, c3, guess) - t) / EvaluateBezierDt(c1, c3, guess) ); iter++; } while ( fabs(newGuess-guess) > 0.00001f && iter < 10 ); // get new t (from bezier y axis) for this s t = EvaluateBezier(c2, c4, newGuess); x = m_fScaleX + t*(pNext->m_fScaleX - m_fScaleX); y = m_fScaleY + t*(pNext->m_fScaleY - m_fScaleY); } }; // animation for 1 bone class Anim2DBone { public: uString m_sBoneName; int m_iBoneIndex; UINT m_iNumRotations; Anim2DKeyFrameRotation **m_pRotations; UINT m_iNumPositions; Anim2DKeyFramePosition **m_pPositions; UINT m_iNumScales; Anim2DKeyFrameScale **m_pScales; Anim2DBone(); ~Anim2DBone(); }; class Bone2D { public: uString m_sName; float length; float origX, origY, origAngle, origSX, origSY; float x, y, angle, sX, sY; float worldX, worldY, worldAngle, worldSX, worldSY; UINT m_bFlags; Bone2D *m_pParent; float m00, m01, m10, m11; Anim2DBone *m_pPrevAnim; Anim2DBone *m_pAnim; UINT m_iPrevFrameRotation; UINT m_iPrevFramePosition; UINT m_iPrevFrameScale; UINT m_iCurrFrameRotation; UINT m_iCurrFramePosition; UINT m_iCurrFrameScale; Bone2D(); ~Bone2D(); void Tween( float prevtime, float currtime, float s ); void Interpolate( float currtime ); void UpdateWorldMatrix( int flipH, int flipV ); void ResetToOrig(); }; // single animation for a set of bones, e.g. "walk" class Animation2D { public: uString m_sName; float m_fTime; UINT m_iNumBones; Anim2DBone *m_pBoneAnims; UINT m_iNumSlots; Anim2DSlot *m_pSlotAnims; Animation2D(); ~Animation2D(); Anim2DBone* GetAnimForBone( const char* name ); Anim2DSlot* GetAnimForSlot( const char* name ); }; class Skeleton2D { friend class agk; protected: UINT m_iNumBones; Bone2D *m_pBones; UINT m_iNumSprites; cSprite *m_pSprites; UINT m_iNumAnimations; Animation2D *m_pAnimations; UINT m_iNumSlots; Slot2D *m_pSlots; UINT m_iID; UINT m_bFlags; float m_fCurrTime; float m_fPrevTime; float m_fTweenTime; float m_fTotalTweenTime; float m_fSpeed; int m_iCurrAnimation; int m_iLoopCount; int m_iLoopTotal; float m_fX; float m_fY; float m_fAngle; int m_iDepth; public: Skeleton2D(); ~Skeleton2D(); void LoadFromSpine( const char* filename, float scale, cImage *pAtlas, int loadAnim ); void LoadFromSpriter( const char* filename, float scale, cImage *pAtlas ); Bone2D* GetBone( const char* name ); Bone2D* GetBone( UINT index ); int GetBoneIndex( const char* name ); Slot2D* GetSlot( const char* name ); int GetSlotIndex( const char* name ); cSprite* GetSprite( const char* name ); int GetAnimation( const char* name ); void SetPosition( float x, float y ); void SetAngle( float angle ); void SetDepth( int depth ); int GetDepth() { return m_iDepth; } void FixToScreen( int mode ); void SetVisible( int mode ); float GetX() { return m_fX; } float GetY() { return m_fY; } float GetAngle() { return m_fAngle; } void SetAnimationSpeed( float speed ); void PlayAnimation( const char* anim, float starttime, int loop, float tweentime ); void SetAnimationFrame( const char* anim, float time, float tweentime ); void StopAnimation(); int GetIsAnimating(); int GetIsTweening(); float GetCurrentTime(); float GetAnimationTime( const char* anim ); void SetFlipH( int flip ); void SetFlipV( int flip ); void Update( float time ); void Draw(); void DrawBones(); void DrawBoneNames(); }; } #endif
[ "ykauji@gmail.com" ]
ykauji@gmail.com
82619c2166bbc956132946108eb2849b9401e2cc
b664d7e43687fa77d82f1bd8f3cab81dc2f88625
/001-3DS/3DSLoader.cpp
98a2bbaf6449f934fcd710e64692e8c700588ed0
[]
no_license
YessicaSD/opengl-code
cd60ff4bc5de6a1f80a9d49b55172ad99bb90afe
31fd411815d26c0333a74c197c5ef6af457acb75
refs/heads/master
2020-08-05T19:05:04.275416
2017-01-14T16:58:34
2017-01-14T16:58:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
9,190
cpp
#include <iostream> #include <fstream> #include <string> #include <vector> #include <memory> #include <glad\glad.h> #include <glfw\glfw3.h> #include <glm\glm.hpp> #include <glm\gtc\type_ptr.hpp> #include <glm\gtc\matrix_transform.hpp> GLuint init_shader(); void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); } void readChunck(std::ifstream &file, int CHUNCK_ID) { uint16_t chunck = 0; uint32_t lenght = 0; do { file.read(reinterpret_cast<char*>(&chunck), 2); file.read(reinterpret_cast<char*>(&lenght), 4); if (chunck != CHUNCK_ID) file.seekg(lenght - 6, std::ios_base::cur); } while (chunck != CHUNCK_ID); } void readChunckChar(std::ifstream& file) { char c = ' '; while (c != '\0') { file.get(c); std::cout << c; } } void readChunckVertices(std::ifstream& file, std::vector<glm::vec3>& vertices) { uint16_t num_vertices = 0; file.read(reinterpret_cast<char*>(&num_vertices), 2); vertices.resize(num_vertices); file.read(reinterpret_cast<char*>(&vertices[0].x), num_vertices * sizeof(glm::vec3)); } void readChunckFaces(std::ifstream& file, std::vector<GLuint>& faces) { uint16_t num_faces = 0; file.read(reinterpret_cast<char*>(&num_faces), 2); faces.reserve(num_faces * 3); for (uint16_t i = 0; i < num_faces; i++) { uint16_t temp_faces[4]; file.read(reinterpret_cast<char*>(&temp_faces), sizeof(short) * 4); faces.push_back(temp_faces[0]); faces.push_back(temp_faces[1]); faces.push_back(temp_faces[2]); } } GLuint load3DS(const std::string& filename, GLuint& count) { std::ifstream file{ filename, std::ios_base::binary }; if (!file) { std::cerr << "No se puede abrir el archivo: " << filename << std::endl; return 0; } std::vector<glm::vec3> vertices, normals; std::vector<GLuint> faces; readChunck(file, 0x4D4D); readChunck(file, 0x3D3D); readChunck(file, 0x4000); readChunckChar(file); readChunck(file, 0x4100); readChunck(file, 0x4110); readChunckVertices(file, vertices); readChunck(file, 0x4120); readChunckFaces(file, faces); file.close(); normals.resize(vertices.size()); count = faces.size(); for (size_t f = 0; f < faces.size(); f += 3) { GLuint f0 = faces[f + 0]; GLuint f1 = faces[f + 1]; GLuint f2 = faces[f + 2]; glm::vec3 v0 = vertices[f0]; glm::vec3 v1 = vertices[f1]; glm::vec3 v2 = vertices[f2]; glm::vec3 e1 = v1 - v0; glm::vec3 e2 = v2 - v0; glm::vec3 N = glm::cross(e1, e2); normals[f0] += N; normals[f1] += N; normals[f2] += N; } for (size_t i = 0; i < normals.size(); i++) { normals[i] = glm::normalize(normals[i]); } GLuint buffer[3], vao; glGenVertexArrays(1, &vao); glBindVertexArray(vao); glGenBuffers(3, buffer); glBindBuffer(GL_ARRAY_BUFFER, buffer[0]); glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), vertices.data(), GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(0); glBindBuffer(GL_ARRAY_BUFFER, buffer[1]); glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), normals.data(), GL_STATIC_DRAW); glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, NULL); glEnableVertexAttribArray(1); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, buffer[2]); glBufferData(GL_ELEMENT_ARRAY_BUFFER, faces.size() * sizeof(GLuint), faces.data(), GL_STATIC_DRAW); glBindVertexArray(0); return vao; } int main() { glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); glfwWindowHint(GLFW_SAMPLES, 4); GLFWwindow* window = glfwCreateWindow(1280, 768, "3DS :: OpenGL Moderno", NULL, NULL); if (!window) { glfwTerminate(); return -1; } glfwSetKeyCallback(window, key_callback); glfwMakeContextCurrent(window); glfwSwapInterval(0); if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { return -1; } GLuint shader = init_shader(); GLuint u_proj = glGetUniformLocation(shader, "proj"); GLuint u_view = glGetUniformLocation(shader, "view"); GLuint u_modl = glGetUniformLocation(shader, "model"); double start = glfwGetTime(); GLuint count = 0; GLuint vao = load3DS(PROJECT_SOURCE_DIR "../resources/model/duck.3ds", count); std::cout << "loaded in " << glfwGetTime() - start << " segundos" << std::endl; glEnable(GL_DEPTH_TEST); glClearColor(0.45f, 0.75f, 0.90f, 1.0f); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glm::mat4 proj = glm::perspective(45.0f, 1280.0f / 768.0f, 0.1f, 100.0f); glm::mat4 view = glm::lookAt(glm::vec3(4, 5, 3), glm::vec3(0), glm::vec3(0, 1, 0)); glm::mat4 modl; glUseProgram(shader); glUniformMatrix4fv(u_proj, 1, GL_FALSE, glm::value_ptr(proj)); glUniformMatrix4fv(u_view, 1, GL_FALSE, glm::value_ptr(view)); glUniformMatrix4fv(u_modl, 1, GL_FALSE, glm::value_ptr(modl)); glBindVertexArray(vao); glDrawElements(GL_TRIANGLES, count, GL_UNSIGNED_INT, NULL); glfwSwapBuffers(window); glfwPollEvents(); } glfwDestroyWindow(window); glfwTerminate(); return 0; } GLuint init_shader() { const GLchar* vertex_shader_source = R"( #version 330 core in vec3 position; in vec3 normal; uniform mat4 proj; uniform mat4 view; uniform mat4 model; uniform vec3 lightPosition = vec3(0.0, 3.0, 3.0); out VS_OUT { vec3 N; vec3 L; vec3 V; } vs_out; void main(void) { gl_Position = proj * view * model * vec4(position, 1.0); mat4 mv_matrix = view * model; vec3 light_pos = vec3(view * vec4(lightPosition, 1.0)); vec4 view_pos = mv_matrix * vec4(position, 1.0); vs_out.N = mat3(transpose(inverse(mv_matrix))) * normal; vs_out.L = light_pos - view_pos.xyz; vs_out.V = -view_pos.xyz; } )"; const GLchar* fragment_shader_source = R"( #version 330 core out vec4 final_color; uniform vec3 lightColor = vec3(0.75, 0.75, 0.75); uniform vec3 objectColor = vec3(0.75, 0.75, 0.75); in VS_OUT { vec3 N; vec3 L; vec3 V; } fs_in; const float k0 = 1.000; const float k1 = 0.090; const float k2 = 0.032; void main(void) { float d = length(fs_in.L); vec3 N = normalize(fs_in.N); vec3 L = normalize(fs_in.L); vec3 V = normalize(fs_in.V); vec3 H = normalize(L + V); float intensity = 0.80; float diffuse = clamp(dot(N, L), 0, 1); float specular = pow(clamp(dot(N, H), 0, 1), 32); float attenuation = 1.0 / (k0 + (k1 * d) + (k2 * d * d)); diffuse *= attenuation * intensity; specular *= attenuation * intensity; vec3 ambientColor = vec3(0.1); vec3 diffuseColor = objectColor * lightColor * diffuse; vec3 specularColor = objectColor * lightColor * specular; final_color = vec4(ambientColor + diffuseColor + specularColor, 1.0); } )"; GLuint vertex_shader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL); glCompileShader(vertex_shader); GLuint fragment_shader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL); glCompileShader(fragment_shader); GLuint shader_program = glCreateProgram(); glAttachShader(shader_program, vertex_shader); glAttachShader(shader_program, fragment_shader); glLinkProgram(shader_program); GLint link_status = 0; GLint log_length = 0; glGetProgramiv(shader_program, GL_LINK_STATUS, &link_status); glGetProgramiv(shader_program, GL_INFO_LOG_LENGTH, &log_length); if (link_status == GL_FALSE) { auto logger = std::make_unique<GLchar[]>(log_length); glGetProgramInfoLog(shader_program, log_length, NULL, logger.get()); std::cerr << logger.get() << std::endl; } glDeleteShader(vertex_shader); glDeleteShader(fragment_shader); return shader_program; }
[ "marin.carmelo.abrego@gmail.com" ]
marin.carmelo.abrego@gmail.com
589bbd033f05df450318e43202ce455ea56b9384
a65f12e7039ddc3a915c1237b876df82ca17537e
/aws-cpp-sdk-lex-models/source/model/BuiltinSlotTypeMetadata.cpp
49a80c0933a3df1b84f2ae71f29f79bdf3456996
[ "Apache-2.0", "MIT", "JSON" ]
permissive
chiaming0914/awe-cpp-sdk
1a09da8ce36f8a60b9bb47c47fc576c822ccf398
5cd54671ea48151f33f0ddbadc3d68ffacbc160b
refs/heads/master
2021-06-16T18:25:10.864269
2017-06-08T07:02:09
2017-06-08T07:02:09
93,716,067
0
0
null
2017-06-08T08:06:39
2017-06-08T06:42:24
C++
UTF-8
C++
false
false
2,589
cpp
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/lex-models/model/BuiltinSlotTypeMetadata.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace LexModelBuildingService { namespace Model { BuiltinSlotTypeMetadata::BuiltinSlotTypeMetadata() : m_signatureHasBeenSet(false), m_supportedLocalesHasBeenSet(false) { } BuiltinSlotTypeMetadata::BuiltinSlotTypeMetadata(const JsonValue& jsonValue) : m_signatureHasBeenSet(false), m_supportedLocalesHasBeenSet(false) { *this = jsonValue; } BuiltinSlotTypeMetadata& BuiltinSlotTypeMetadata::operator =(const JsonValue& jsonValue) { if(jsonValue.ValueExists("signature")) { m_signature = jsonValue.GetString("signature"); m_signatureHasBeenSet = true; } if(jsonValue.ValueExists("supportedLocales")) { Array<JsonValue> supportedLocalesJsonList = jsonValue.GetArray("supportedLocales"); for(unsigned supportedLocalesIndex = 0; supportedLocalesIndex < supportedLocalesJsonList.GetLength(); ++supportedLocalesIndex) { m_supportedLocales.push_back(LocaleMapper::GetLocaleForName(supportedLocalesJsonList[supportedLocalesIndex].AsString())); } m_supportedLocalesHasBeenSet = true; } return *this; } JsonValue BuiltinSlotTypeMetadata::Jsonize() const { JsonValue payload; if(m_signatureHasBeenSet) { payload.WithString("signature", m_signature); } if(m_supportedLocalesHasBeenSet) { Array<JsonValue> supportedLocalesJsonList(m_supportedLocales.size()); for(unsigned supportedLocalesIndex = 0; supportedLocalesIndex < supportedLocalesJsonList.GetLength(); ++supportedLocalesIndex) { supportedLocalesJsonList[supportedLocalesIndex].AsString(LocaleMapper::GetNameForLocale(m_supportedLocales[supportedLocalesIndex])); } payload.WithArray("supportedLocales", std::move(supportedLocalesJsonList)); } return payload; } } // namespace Model } // namespace LexModelBuildingService } // namespace Aws
[ "Kent_Chiang@trend.com.tw" ]
Kent_Chiang@trend.com.tw
37a347c429f7c0627bc71d9286bc98348d66d36c
2fcfd593db09fdcc5b51a576deb8c7ec274daaff
/src/test/cachemultimap_tests.cpp
d3c4bad7c47166ff64064f039d35d3ca2dfb5586
[ "MIT" ]
permissive
FXBitLab-Etp/etp3
a35791d428135bbe321b3119b9e260fa8b9a27e4
829791221484a9c5275ac938412980e1b94adeee
refs/heads/master
2021-01-19T22:34:32.418454
2017-08-24T05:36:45
2017-08-24T05:36:45
101,256,579
0
1
null
2017-09-02T21:07:56
2017-08-24T05:16:08
C++
UTF-8
C++
false
false
4,940
cpp
// Copyright (c) 2014-2017 The Etp Core developers #include "cachemultimap.h" #include "test/test_etp.h" #include <algorithm> #include <iostream> #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(cachemultimap_tests, BasicTestingSetup) void DumpMap(const CacheMultiMap<int,int>& map) { const CacheMultiMap<int,int>::list_t& listItems = map.GetItemList(); for(CacheMultiMap<int,int>::list_cit it = listItems.begin(); it != listItems.end(); ++it) { const CacheItem<int,int>& item = *it; std::cout << item.key << " : " << item.value << std::endl; } } bool Compare(const CacheMultiMap<int,int>& map1, const CacheMultiMap<int,int>& map2 ) { if(map1.GetMaxSize() != map2.GetMaxSize()) { std::cout << "Compare returning false: max size mismatch" << std::endl; return false; } if(map1.GetSize() != map2.GetSize()) { std::cout << "Compare returning false: size mismatch" << std::endl; return false; } const CacheMultiMap<int,int>::list_t& items1 = map1.GetItemList(); const CacheMultiMap<int,int>::list_t& items2 = map2.GetItemList(); CacheMultiMap<int,int>::list_cit it2 = items2.begin(); for(CacheMultiMap<int,int>::list_cit it1 = items1.begin(); it1 != items1.end(); ++it1) { const CacheItem<int,int>& item1 = *it1; const CacheItem<int,int>& item2 = *it2; if(item1.key != item2.key) { return false; } if(item1.value != item2.value) { return false; } ++it2; } return true; } bool CheckExpected(const CacheMultiMap<int,int>& map, int* expected, CacheMultiMap<int,int>::size_type nSize) { if(map.GetSize() != nSize) { return false; } for(CacheMultiMap<int,int>::size_type i = 0; i < nSize; ++i) { int nVal = 0; int eVal = expected[i]; if(!map.Get(eVal, nVal)) { return false; } if(nVal != eVal) { return false; } } return true; } BOOST_AUTO_TEST_CASE(cachemultimap_test) { // create a CacheMultiMap limited to 10 items CacheMultiMap<int,int> mapTest1(10); // check that the max size is 10 BOOST_CHECK(mapTest1.GetMaxSize() == 10); // check that the size is 0 BOOST_CHECK(mapTest1.GetSize() == 0); // insert (-1, -1) mapTest1.Insert(-1, -1); // make sure that the size is updated BOOST_CHECK(mapTest1.GetSize() == 1); // make sure the map contains the key BOOST_CHECK(mapTest1.HasKey(-1) == true); // add 10 items for(int i = 0; i < 10; ++i) { mapTest1.Insert(i, i); } // check that the size is 10 BOOST_CHECK(mapTest1.GetSize() == 10); // check that the map contains the expected items for(int i = 0; i < 10; ++i) { int nVal = 0; BOOST_CHECK(mapTest1.Get(i, nVal) == true); BOOST_CHECK(nVal == i); } // check that the map no longer contains the first item BOOST_CHECK(mapTest1.HasKey(-1) == false); // erase an item mapTest1.Erase(5); // check the size BOOST_CHECK(mapTest1.GetSize() == 9); // check that the map no longer contains the item BOOST_CHECK(mapTest1.HasKey(5) == false); // check that the map contains the expected items int expected[] = { 0, 1, 2, 3, 4, 6, 7, 8, 9 }; BOOST_CHECK(CheckExpected(mapTest1, expected, 9 ) == true); // add multiple items for the same key mapTest1.Insert(5, 2); mapTest1.Insert(5, 1); mapTest1.Insert(5, 4); // check the size BOOST_CHECK(mapTest1.GetSize() == 10); // check that 2 keys have been removed BOOST_CHECK(mapTest1.HasKey(0) == false); BOOST_CHECK(mapTest1.HasKey(1) == false); BOOST_CHECK(mapTest1.HasKey(2) == true); // check multiple values std::vector<int> vecVals; BOOST_CHECK(mapTest1.GetAll(5, vecVals) == true); BOOST_CHECK(vecVals.size() == 3); BOOST_CHECK(vecVals[0] == 1); BOOST_CHECK(vecVals[1] == 2); BOOST_CHECK(vecVals[2] == 4); // std::cout << "mapTest1 dump:" << std::endl; // DumpMap(mapTest1); // test serialization CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss << mapTest1; CacheMultiMap<int,int> mapTest2; ss >> mapTest2; // std::cout << "mapTest2 dump:" << std::endl; // DumpMap(mapTest2); // check multiple values std::vector<int> vecVals2; BOOST_CHECK(mapTest2.GetAll(5, vecVals2) == true); BOOST_CHECK(vecVals2.size() == 3); BOOST_CHECK(vecVals2[0] == 1); BOOST_CHECK(vecVals2[1] == 2); BOOST_CHECK(vecVals2[2] == 4); BOOST_CHECK(Compare(mapTest1, mapTest2)); // test copy constructor CacheMultiMap<int,int> mapTest3(mapTest1); BOOST_CHECK(Compare(mapTest1, mapTest3)); // test assignment operator CacheMultiMap<int,int> mapTest4; mapTest4 = mapTest1; BOOST_CHECK(Compare(mapTest1, mapTest4)); } BOOST_AUTO_TEST_SUITE_END()
[ "etptoken@etpnode02.fxbitlab.com" ]
etptoken@etpnode02.fxbitlab.com
d66f7f9746d81eaacf4dccbe28c2327cad888bc4
1d213c0ac5960a3b86d7cf4abc0fcd1638b8a5c4
/src/common/DebugRenderer_DX9.h
3fefd4c51759ce292ef64410ead0d80218d5f62f
[]
no_license
jamesmintram/foosics
791de1245ff70a9f96a364dd8e81fce4bd55279e
d255162b409f36844de1dae52fdba364f5d80deb
refs/heads/master
2020-04-12T20:31:50.122034
2019-03-25T10:53:45
2019-03-25T10:53:45
162,739,023
0
0
null
null
null
null
UTF-8
C++
false
false
8,628
h
#pragma once #include "../../foosics/debug/DebugRenderer.h" #include "../../foosics/common/ph_assert.h" #include "../third_party/imgui/imgui.h" #include "../third_party/imgui/imgui_impl_dx9.h" #include <d3d9.h> #include <vector> struct CUSTOMVERTEX { float x, y, z; DWORD color; }; struct RenderedCube { float pos[3]; float rot[3]; float scale; uint32_t color; }; struct RenderedLine { float start[3]; float end[3]; uint32_t color; }; struct RenderedPoint { float pos[3]; uint32_t color; }; const uint32_t kBufferSize = 1024 * 65 * sizeof(CUSTOMVERTEX); const uint32_t kTriCount = kBufferSize / 3; const uint32_t kLineCount = kBufferSize / 2; const uint32_t kPointCount = kBufferSize; const float kIdentity[] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, }; const DirectX::FXMVECTOR cube[] = { { -0.5f, -0.5f, 0.5f, 1 }, { 0.5f, -0.5f, 0.5f, 1 }, { 0.5f, 0.5f, 0.5f, 1 }, { -0.5f, 0.5f, 0.5f, 1 }, { -0.5f, -0.5f, -0.5f, 1 }, { 0.5f, -0.5f, -0.5f, 1 }, { 0.5f, 0.5f, -0.5f, 1 }, { -0.5f, 0.5f, -0.5f, 1 }, }; const uint16_t cubeIndices[] = { // front 0, 2, 1, 2, 0, 3, // right 1, 6, 5, 6, 1, 2, // back 7, 5, 6, 5, 7, 4, // left 4, 3, 0, 3, 4, 7, // bottom 4, 1, 5, 1, 4, 0, // top 3, 6, 2, 6, 3, 7 }; #define CUSTOMFVF (D3DFVF_XYZ | D3DFVF_DIFFUSE ) #define COUNT_OF(x) ((sizeof(x)/sizeof(0[x])) / ((size_t)(!(sizeof(x) % sizeof(0[x]))))) class DebugRenderer : public IDebugRenderer { private: LPDIRECT3D9 d3d; LPDIRECT3DDEVICE9 d3ddev; LPDIRECT3DVERTEXBUFFER9 triBuffer; LPDIRECT3DVERTEXBUFFER9 lineBuffer; LPDIRECT3DVERTEXBUFFER9 pointBuffer; LPDIRECT3DINDEXBUFFER9 triIndices; D3DMATRIX projectionMatrix; D3DMATRIX viewMatrix; D3DVIEWPORT9 viewPort; float penPos[3]; uint32_t penColor; std::vector<RenderedCube> m_cubes; std::vector<RenderedLine> m_lines; std::vector<RenderedPoint> m_points; public: DebugRenderer() : d3d(nullptr) , d3ddev(nullptr) { penPos[0] = penPos[1] = penPos[2] = 0; penColor = 0xFFFFFFFF; SetViewProj(kIdentity, kIdentity); } void SetViewProj(float const *view, float const *projection) { memcpy(&viewMatrix, view, sizeof(viewMatrix)); memcpy(&projectionMatrix, projection, sizeof(projectionMatrix)); } void SetViewport(int x, int y, int w, int h) { viewPort.X = x; viewPort.Y = y; viewPort.Width = w; viewPort.Height = h; } void initDX(HWND hWnd) { d3d = Direct3DCreate9(D3D_SDK_VERSION); D3DPRESENT_PARAMETERS d3dpp; ZeroMemory(&d3dpp, sizeof(D3DPRESENT_PARAMETERS)); d3dpp.Windowed = true; d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; d3dpp.EnableAutoDepthStencil = TRUE; d3dpp.AutoDepthStencilFormat = D3DFMT_D16; d3dpp.hDeviceWindow = hWnd; d3dpp.BackBufferFormat = D3DFMT_UNKNOWN; d3dpp.BackBufferWidth = 1024; d3dpp.BackBufferHeight = 768; d3d->CreateDevice( D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &d3ddev); d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE); //Create buffers d3ddev->CreateVertexBuffer( kBufferSize, 0, CUSTOMFVF, D3DPOOL_MANAGED, &triBuffer, NULL); d3ddev->CreateVertexBuffer( kBufferSize, 0, CUSTOMFVF, D3DPOOL_MANAGED, &lineBuffer, NULL); d3ddev->CreateVertexBuffer( kBufferSize, 0, CUSTOMFVF, D3DPOOL_MANAGED, &pointBuffer, NULL); d3ddev->CreateIndexBuffer( kTriCount * 3, 0, D3DFMT_INDEX16, D3DPOOL_MANAGED, &triIndices, NULL); ImGui_ImplDX9_Init(d3ddev); ImGui_ImplDX9_CreateDeviceObjects(); } void Render() { Begin(); Clear(0x6495ED); //ARGB d3ddev->SetViewport(&viewPort); d3ddev->SetTransform(D3DTS_PROJECTION, &projectionMatrix); d3ddev->SetTransform(D3DTS_VIEW, &viewMatrix); d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE); d3ddev->SetRenderState(D3DRS_ZENABLE, D3DZB_TRUE); d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE); d3ddev->SetRenderState(D3DRS_ZWRITEENABLE, TRUE); d3ddev->SetRenderState(D3DRS_ZFUNC, D3DCMP_LESSEQUAL); RenderTriangles(); RenderLines(); RenderPoints(); //Imgui d3ddev->SetRenderState(D3DRS_ZENABLE, false); d3ddev->SetRenderState(D3DRS_ALPHABLENDENABLE, false); d3ddev->SetRenderState(D3DRS_SCISSORTESTENABLE, false); static int lastFrameCount = 0; if (ImGui::GetFrameCount() > lastFrameCount) { lastFrameCount = ImGui::GetFrameCount(); ImGui::Render(); ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData()); } End(); Flip(); } void SetPenColor(uint32_t newColor) { penColor = newColor; } void SetPen(float *newPenPos) { memcpy(penPos, newPenPos, sizeof(*newPenPos) * 3); } void DrawPoint() { } void DrawLine(float *endPoint) { RenderedLine line; memcpy(&line.start, penPos, sizeof(*penPos) * 3); memcpy(&line.end, endPoint, sizeof(*endPoint) * 3); line.color = penColor; m_lines.push_back(line); memcpy(penPos, endPoint, sizeof(*endPoint) * 3); } void DrawCube(float const *pos, float const *rot, float const scale) { //Transform verts and append to buffer RenderedCube cube; memcpy(&cube.pos, pos, sizeof(*pos) * 3); memcpy(&cube.rot, rot, sizeof(*rot) * 3); cube.color = penColor; cube.scale = scale; m_cubes.push_back(cube); } private: void RenderTriangles() { uint16_t * indices = nullptr; triIndices->Lock(0, 0, (void**)&indices, 0); CUSTOMVERTEX * triBufferData = nullptr; triBuffer->Lock(0, 0, (void**)&triBufferData, 0); uint16_t *currentIndex = indices; CUSTOMVERTEX *currentVertex = triBufferData; // Cubes first const size_t cubeCount = m_cubes.size(); for (size_t idx = 0; idx < cubeCount; idx++) { float const *pos = m_cubes[idx].pos; float const *rot = m_cubes[idx].rot; float const scale = m_cubes[idx].scale; uint32_t const col = m_cubes[idx].color; DirectX::XMMATRIX rotM = DirectX::XMMatrixRotationRollPitchYaw(rot[0], rot[1], rot[2]); DirectX::XMMATRIX trnM = DirectX::XMMatrixTranslation(pos[0], pos[1], pos[2]); DirectX::XMMATRIX sclM = DirectX::XMMatrixScaling(scale, scale, scale); DirectX::XMMATRIX cubeM = DirectX::XMMatrixMultiply(rotM, trnM); cubeM = DirectX::XMMatrixMultiply(sclM, cubeM); size_t startVert = currentVertex - triBufferData; //TODO: Push transformed verts into the buffer for (int idx = 0; idx < COUNT_OF(cube); idx++) { DirectX::XMVECTOR vertPos = DirectX::XMVector4Transform(cube[idx], cubeM); currentVertex->x = vertPos.m128_f32[0]; currentVertex->y = vertPos.m128_f32[1]; currentVertex->z = vertPos.m128_f32[2]; currentVertex->color = col + idx * 10000; currentVertex++; } for (size_t idx = 0; idx < COUNT_OF(cubeIndices); idx++) { size_t index = cubeIndices[idx] + startVert; PH_ASSERT(index < 0xFFFF); *currentIndex = (uint16_t)index; currentIndex++; } } triBuffer->Unlock(); triIndices->Unlock(); m_cubes.clear(); uint32_t const triCount = (uint32_t)((currentIndex - indices) / 3); uint32_t const vertCount = (uint32_t)(currentVertex - triBufferData); if (triCount == 0) return; d3ddev->SetFVF(CUSTOMFVF); d3ddev->SetStreamSource(0, triBuffer, 0, sizeof(CUSTOMVERTEX)); d3ddev->SetIndices(triIndices); d3ddev->DrawIndexedPrimitive(D3DPT_TRIANGLELIST, 0, 0, vertCount, 0, triCount); } void RenderLines() { const uint32_t lineCount = (uint32_t)m_lines.size(); if (lineCount == 0) return; CUSTOMVERTEX* lineBufferData = nullptr; lineBuffer->Lock(0, 0, (void**)&lineBufferData, 0); for (uint32_t idx = 0; idx < lineCount; idx++) { RenderedLine const& line = m_lines[idx]; lineBufferData->x = line.start[0]; lineBufferData->y = line.start[1]; lineBufferData->z = line.start[2]; lineBufferData->color = line.color; lineBufferData++; lineBufferData->x = line.end[0]; lineBufferData->y = line.end[1]; lineBufferData->z = line.end[2]; lineBufferData->color = line.color; lineBufferData++; } lineBuffer->Unlock(); m_lines.clear(); d3ddev->SetStreamSource(0, lineBuffer, 0, sizeof(CUSTOMVERTEX)); d3ddev->SetFVF(CUSTOMFVF); d3ddev->DrawPrimitive(D3DPT_LINELIST, 0, lineCount); } void RenderPoints() { } void Clear(uint32_t col) { d3ddev->Clear( 0, NULL, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, col, 1.0f, 0); } void Flip() { d3ddev->Present(NULL, NULL, NULL, NULL); } void Begin() { d3ddev->BeginScene(); } void End() { d3ddev->EndScene(); } };
[ "jamesmintram@gmail.com" ]
jamesmintram@gmail.com
57b13df114546d203e30590fa608d0c0b0645fe0
9ab38fd440f9fee94f12cc031c216878dac87d32
/engine/core/engine_base.h
18f18729e8a5c324ba9ac54561fd307ae108af3a
[ "MIT" ]
permissive
lp249839965/VCTRenderer
5c01661bfac3ac84c32fd3461756bf1994f8c23f
64afcc68b0fb19f1a00ec876b2d0531fb3498a6d
refs/heads/master
2022-11-05T07:55:39.362805
2020-06-19T04:51:21
2020-06-19T04:51:21
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,512
h
#pragma once #include <memory> class RenderWindow; class GIDeferredRenderer; class AssetsManager; /// <summary> /// This is the entry point of the rendering engine /// where the main rendering loop resides and the /// rendering context is properly set up. /// </summary> class EngineBase { protected: /// <summary> /// The rendering window. /// </summary> std::unique_ptr<RenderWindow> renderWindow; /// <summary> /// Setups all the engine components, imports assets /// and initializes libraries. /// </summary> void Initialize() const; EngineBase(); public: virtual ~EngineBase(); /// <summary> /// Main rendering loop /// </summary> void MainLoop() const; /// <summary> /// The active context window. /// </summary> /// <returns></returns> RenderWindow &Window() const; /// <summary> /// Returns the EngineBase singleton instance. /// </summary> /// <returns></returns> static std::unique_ptr<EngineBase> &Instance(); /// <summary> /// Terminates this instance. /// </summary> static void Terminate(); // No copying, copy, move assignment allowed of this class // or any derived class EngineBase(EngineBase const &r) = delete; EngineBase(EngineBase const &&r) = delete; EngineBase &operator=(EngineBase const &r) = delete; };
[ "polonoise@gmail.com" ]
polonoise@gmail.com
a628307672083fac410dfc0ea54048668e34c8f3
237bf7433d7d213f5cef08049a4278ee4a04fded
/[EDD]Practica1_201504444/Practica1/mainwindow.h
264d1ee5d5f89e6adccd70d03694c7b2815d1b49
[]
no_license
ChristianR007/EDD_201504444
c1b3eac2bae474fe3b57779933fe35889efcaaaa
101ea484de6e3ada8ffc405f344715551c6744dd
refs/heads/master
2021-09-03T15:30:46.028908
2018-01-10T06:02:47
2018-01-10T06:02:47
113,397,544
0
0
null
null
null
null
UTF-8
C++
false
false
756
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include "colapasajeros.h" #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); private slots: void on_pushButton_clicked(); void on_pushButton_3_clicked(); void on_pushButton_2_clicked(); void crearGraficaAviones(); void crearGraficaPasajeros(); void crearGraficaEscritorios(); void crearGraficaMaletas(); void crearPasajeros(colaPasajero *colaP, int numPasajeros); void on_pushButton_4_clicked(); void on_pushButton_5_clicked(); void on_pushButton_6_clicked(); private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
[ "Christian7.gt@gmail.com" ]
Christian7.gt@gmail.com
77356659486ee8afde1e266b9d422ae0304de2eb
a83d26a62954fe2f5f911515ac962976829f0695
/corrFinder.cxx
0096e3a7b32aa6685d7eaadeb796a1c0991511b7
[]
no_license
cdxing/EpdAna
574ff908fe283d016bbbaba0d27c03d55c592dd5
bf479fd813b4aee04753ee9065ae6785b63e649b
refs/heads/master
2022-10-14T01:20:24.547399
2021-06-16T18:40:32
2021-06-16T18:40:32
243,299,183
0
0
null
2021-01-05T06:37:06
2020-02-26T15:40:01
C
UTF-8
C++
false
false
16,713
cxx
#include <iostream> #include <fstream> #include <cmath> #include "TFile.h" #include "TH1.h" #include "TH2.h" #include "TH1D.h" #include "TH2D.h" #include "TH3D.h" #include "TMath.h" #include "TProfile.h" #include "TProfile2D.h" #include "TProfile3D.h" Double_t resoErr(Double_t corrAB, Double_t corrAC, Double_t corrBC, Double_t errAB, Double_t errAC, Double_t errBC); Double_t resoVal(Double_t corrAB, Double_t corrAC, Double_t corrBC); const int _Ncentralities = 10; int corrFinder(){ TFile* inFile = new TFile("corrINPUT_26p5_2ndEp.root","READ"); TProfile *profile_correlation_epd_east[6], *profile_correlation_epd_tpc[4]; Double_t binContentEpd[6][_Ncentralities]; Double_t binErrorEpd[6][_Ncentralities]; Double_t binContentTpc[4][_Ncentralities]; Double_t binErrorTpc[4][_Ncentralities]; for(int i=0;i<6;i++){ profile_correlation_epd_east[i] = (TProfile*)inFile->Get(Form("profile_correlation_epd_east%d",i)); } for(int i=0;i<4;i++){ profile_correlation_epd_tpc[i] = (TProfile*)inFile->Get(Form("profile_correlation_epd%d_tpc",i+1)); } for(int i=0;i<6;i++){ for(int j=0;j<_Ncentralities;j++){ binContentEpd[i][j]=profile_correlation_epd_east[i]->GetBinContent(j+1); std::cout<<Form("profile_correlation_epd_east%d binNumber%d binContent: ",i,j+1) << binContentEpd[i][j]; binErrorEpd[i][j]=profile_correlation_epd_east[i]->GetBinError(j+1); std::cout<<Form("; binError: ") << binErrorEpd[i][j]<<std::endl; } } for(int i=0;i<4;i++){ for(int j=0;j<_Ncentralities;j++){ binContentTpc[i][j]=profile_correlation_epd_tpc[i]->GetBinContent(j+1); std::cout<<Form("profile_correlation_epd%d_tpc binNumber%d binContent: ",i+1,j+1) << binContentTpc[i][j]; binErrorTpc[i][j]=profile_correlation_epd_tpc[i]->GetBinError(j+1); std::cout<<Form("; binError: ") << binErrorTpc[i][j]<<std::endl; } } // --------------------- sqrt bin Contents --------------------------------- for(int i=0;i<6;i++){ for(int j=0;j<_Ncentralities;j++){ if(binContentEpd[i][j]>=0){ // make sure bin content is not negative to sqrt binErrorEpd[i][j] *=1./(2.*sqrt(binContentEpd[i][j])); // Error proagation; std::cout<<Form("profile_correlation_epd_east%d binNumber%d sqrt binError: ",i,j+1) << binErrorEpd[i][j]; binContentEpd[i][j]= sqrt(binContentEpd[i][j]); std::cout<<Form("; sqrt binContent: ") << binContentEpd[i][j]<<std::endl; } else{ binErrorEpd[i][j] =0; // Error proagation; std::cout<<Form("profile_correlation_epd_east%d binNumber%d sqrt binError: ",i,j+1) << binErrorEpd[i][j]; binContentEpd[i][j]=0; std::cout<<Form("; sqrt binContent: ") << binContentEpd[i][j]<<std::endl; } } } for(int i=0;i<4;i++){ for(int j=0;j<_Ncentralities;j++){ if(binContentTpc[i][j]>0){ // make sure bin content is not negative to sqrt binErrorTpc[i][j] *=1./(2.*sqrt(binContentTpc[i][j])); // Error proagation; std::cout<<Form("profile_correlation_epd%d_tpc binNumber%d sqrt binError: ",i+1,j+1) << binErrorTpc[i][j]; binContentTpc[i][j]=sqrt(binContentTpc[i][j]); std::cout<<Form("; sqrt binContent: ") << binContentTpc[i][j]<<std::endl; } else{ binErrorTpc[i][j] =0; // Error proagation; std::cout<<Form("profile_correlation_epd%d_tpc binNumber%d sqrt binError: ",i+1,j+1) << binErrorTpc[i][j]; binContentTpc[i][j]=0; std::cout<<Form("; sqrt binContent: ") << binContentTpc[i][j]<<std::endl; } } } // ------------------ Fill into historgrams ---------------------------------- TFile* outFile = new TFile("corrResult_26p5_2ndEp.root","RECREATE"); TH1D *hist_correlation_epd_east[6], *hist_correlation_epd_tpc[4]; TCanvas* c1[5]; TLegend *legend[5]; for(int i=0;i<5;i++){ c1[i] = new TCanvas(Form("c1_%d",i),Form("Event Plane Resolutions %d",i+1),200,10,700,500); c1[i]->GetFrame()->SetFillColor(21); c1[i]->GetFrame()->SetBorderSize(12); c1[i]->DrawFrame(0., 0.01, 100., 0.6); legend[i] = new TLegend(0.1,0.7,0.48,0.9); } const Int_t n = _Ncentralities; Double_t x[n] = {5,15,25,35,45,55,65,75,85,95}; Double_t ex[n] = {5,5,5,5,5,5,5,5,5,5}; Double_t y1_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y1_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y1_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey1_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey1_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey1_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y2_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y2_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y2_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey2_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey2_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey2_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y3_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y3_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y3_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey3_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey3_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey3_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y4_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y4_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y4_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey4_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey4_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey4_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y5_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y5_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t y5_3[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey5_1[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey5_2[n] = {0,0,0,0,0,0,0,0,0,0}; Double_t ey5_3[n] = {0,0,0,0,0,0,0,0,0,0}; TGraphErrors *gr1[3],*gr2[3],*gr3[3],*gr4[3],*gr5[4]; for(int i=0;i<6;i++){ hist_correlation_epd_east[i] = new TH1D(Form("hist_correlation_epd_east%d",i),Form("hist_correlation_epd_east%d",i),_Ncentralities,0.5,_Ncentralities+.5); } for(int i=0;i<4;i++){ hist_correlation_epd_tpc[i] = new TH1D(Form("hist_correlation_epd_tpc%d",i),Form("hist_correlation_epd_tpc%d",i),_Ncentralities,0.5,_Ncentralities+.5); } hist_correlation_epd_east[0]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-1} #minus #psi_{1}^{EPD-2})>}"); hist_correlation_epd_east[1]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-1} #minus #psi_{1}^{EPD-3})>}"); hist_correlation_epd_east[2]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-1} #minus #psi_{1}^{EPD-4})>}"); hist_correlation_epd_east[3]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-2} #minus #psi_{1}^{EPD-3})>}"); hist_correlation_epd_east[4]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-2} #minus #psi_{1}^{EPD-4})>}"); hist_correlation_epd_east[5]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-3} #minus #psi_{1}^{EPD-4})>}"); hist_correlation_epd_tpc[0]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-1} #minus #psi_{1}^{TPC})>}"); hist_correlation_epd_tpc[1]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-2} #minus #psi_{1}^{TPC})>}"); hist_correlation_epd_tpc[2]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-3} #minus #psi_{1}^{TPC})>}"); hist_correlation_epd_tpc[3]->SetTitle("#sqrt{<cos(#psi_{1}^{EPD-4} #minus #psi_{1}^{TPC})>}"); for(int i=0;i<6;i++){ for(int j=0;j<_Ncentralities;j++){ if(binErrorEpd[i][j]!=0){ hist_correlation_epd_east[i]->SetBinContent(j+1,binContentEpd[i][j]); hist_correlation_epd_east[i]->SetBinError(j+1,binErrorEpd[i][j]); } } } for(int i=0;i<4;i++){ for(int j=0;j<_Ncentralities;j++){ if(binErrorTpc[i][j]!=0){ hist_correlation_epd_tpc[i]->SetBinContent(j+1,binContentTpc[i][j]); hist_correlation_epd_tpc[i]->SetBinError(j+1,binErrorTpc[i][j]); } } } // EPD ep resolutions //binContentEpd[0,1,2,3,4,5] corresponds to correlations of epd subs {1 2,1 3,1 4,2 3,2 4,3 4} //binContentTpc[0,1,2,3] corresponds to correlations of epd subs & tpc {1 t, 2 t, 3 t, 4 t} Double_t ep1Reso[3][n]; // binContentEpd[0,1,2][j] * binContentTpc[0][j] / binContentTpc[1,2,3][j] Double_t ep1Err[3][n]; // binErrorEpd[0,1,2][j] * binErrorTpc[0][j] / binErrorTpc[1,2,3][j] Double_t ep2Reso[3][n]; // binContentEpd[0,3,4][j] * binContentTpc[1][j] / binContentTpc[0,2,3][j] Double_t ep2Err[3][n]; // binErrorEpd[0,3,4][j] * binErrorTpc[1][j] / binErrorTpc[0,2,3][j] Double_t ep3Reso[3][n]; // binContentEpd[1,3,5][j] * binContentTpc[2][j] / binContentTpc[0,1,3][j] Double_t ep3Err[3][n]; // binErrorEpd[1,3,5][j] * binErrorTpc[2][j] / binErrorTpc[0,1,3][j] Double_t ep4Reso[3][n]; // binContentEpd[2,4,5][j] * binContentTpc[3][j] / binContentTpc[0,1,2][j] Double_t ep4Err[3][n]; // binErrorEpd[2,4,5][j] * binErrorTpc[3][j] / binErrorTpc[0,1,2][j] Double_t ep5Reso[3][n]; // binContentTpc[0,1,2][j] * binContentTpc[1,2,3][j] / binContentEpd[0,3,5][j] Double_t ep5Err[3][n]; // binErrorTpc[0,1,2][j] * binErrorTpc[1,2,3][j] / binErrorEpd[0,3,5][j] for(int j=0;j<_Ncentralities;j++){ for(int i=0;i<3;i++){ int order2_1 = 0; // EPD 2 reso int order2_2 = 0; // EPD 2 reso int order3_1 = 2 * i + 1; // 1, 3, 5 // EPD 3 reso int order3_2 = 0; // EPD 3 reso int order4_1 = 2; // EPD 4 reso int order4_2 = i; // EPD 4 reso // 0, 1, 2 int order5_1 = i; // TPC reso // 0, 1, 2 int order5_2 = i+1; // TPC reso // 1, 2, 3 int order5_3 = 0; // TPC reso if(i>0){ order2_1 = i+2; // 0, 3, 4 order2_2 = i+1; // 0, 2, 3 order3_2 = 2*i-1; // 0, 1, 3 order4_1 += i+1; // 2, 4, 5 order5_3 = 2*i+1; // 0, 3, 5 } if(binErrorEpd[i][j]!=0&&binErrorTpc[0][j]!=0&&binErrorTpc[i+1][j]!=0){ // EPD 1 VS EPD {2,3,4} & TPC ep1Reso[i][j] = resoVal(binContentEpd[i][j],binContentTpc[0][j],binContentTpc[i+1][j]); ep1Err[i][j]= resoErr(binContentEpd[i][j],binContentTpc[0][j],binContentTpc[i+1][j], binErrorEpd[i][j],binErrorTpc[0][j],binErrorTpc[i+1][j]); } if(binErrorEpd[order2_1][j]!=0&&binErrorTpc[1][j]!=0&&binErrorTpc[order2_2][j]!=0){ // EPD 2 VS EPD {1,3,4} & TPC ep2Reso[i][j] = resoVal(binContentEpd[order2_1][j],binContentTpc[1][j],binContentTpc[order2_2][j]); ep2Err[i][j]= resoErr(binContentEpd[order2_1][j],binContentTpc[1][j],binContentTpc[order2_2][j], binErrorEpd[order2_1][j],binErrorTpc[1][j],binErrorTpc[order2_2][j]); } if(binErrorEpd[order3_1][j]!=0&&binErrorTpc[2][j]!=0&&binErrorTpc[order2_2][j]!=0){ // EPD 3 VS EPD {1,2,4} & TPC ep3Reso[i][j] = resoVal(binContentEpd[order3_1][j],binContentTpc[2][j],binContentTpc[order2_2][j]); ep3Err[i][j]= resoErr(binContentEpd[order3_1][j],binContentTpc[2][j],binContentTpc[order2_2][j], binErrorEpd[order3_1][j],binErrorTpc[2][j],binErrorTpc[order2_2][j]); } if(binErrorEpd[order4_1][j]!=0&&binErrorTpc[3][j]!=0&&binErrorTpc[order4_2][j]!=0){ // EPD 4 VS EPD {1, 2, 3} & TPC ep4Reso[i][j] = resoVal(binContentEpd[order4_1][j],binContentTpc[3][j],binContentTpc[order4_2][j]); ep4Err[i][j]= resoErr(binContentEpd[order4_1][j],binContentTpc[3][j],binContentTpc[order4_2][j], binErrorEpd[order4_1][j],binErrorTpc[3][j],binErrorTpc[order4_2][j]); } if(binErrorTpc[order5_1][j]!=0&&binErrorTpc[order5_2][j]!=0&&binErrorEpd[order5_3][j]!=0){ // TPC VS EPD {1, 2, 3} & EPD {2, 3, 4} ep5Reso[i][j] = resoVal(binContentTpc[order5_1][j],binContentTpc[order5_2][j],binContentEpd[order5_3][j]); ep5Err[i][j]= resoErr(binContentTpc[order5_1][j],binContentTpc[order5_2][j],binContentEpd[order5_3][j], binErrorTpc[order5_1][j],binErrorTpc[order5_2][j],binErrorEpd[order5_3][j]); } } } for(int j=0;j<_Ncentralities;j++){ y1_1[j]=ep1Reso[0][j]; ey1_1[j]=ep1Err[0][j]; y2_1[j]=ep2Reso[0][j]; ey2_1[j]=ep2Err[0][j]; y3_1[j]=ep3Reso[0][j]; ey3_1[j]=ep3Err[0][j]; y4_1[j]=ep4Reso[0][j]; ey4_1[j]=ep4Err[0][j]; y5_1[j]=ep5Reso[0][j]; ey5_1[j]=ep5Err[0][j]; y1_2[j]=ep1Reso[1][j]; ey1_2[j]=ep1Err[1][j]; y2_2[j]=ep2Reso[1][j]; ey2_2[j]=ep2Err[1][j]; y3_2[j]=ep3Reso[1][j]; ey3_2[j]=ep3Err[1][j]; y4_2[j]=ep4Reso[1][j]; ey4_2[j]=ep4Err[1][j]; y5_2[j]=ep5Reso[1][j]; ey5_2[j]=ep5Err[1][j]; y1_3[j]=ep1Reso[2][j]; ey1_3[j]=ep1Err[2][j]; y2_3[j]=ep2Reso[2][j]; ey2_3[j]=ep2Err[2][j]; y3_3[j]=ep3Reso[2][j]; ey3_3[j]=ep3Err[2][j]; y4_3[j]=ep4Reso[2][j]; ey4_3[j]=ep4Err[2][j]; y5_3[j]=ep5Reso[2][j]; ey5_3[j]=ep5Err[2][j]; } // ey3_1[5]=0; gr1[0] = new TGraphErrors(n,x,y1_1,ex,ey1_1); gr1[0]->SetTitle("EPD sub1 event plane "); gr1[0]->SetMarkerColor(1); gr1[0]->SetMarkerStyle(21); gr1[1] = new TGraphErrors(n,x,y1_2,ex,ey1_2); gr1[1]->SetTitle("EPD sub1 event plane "); gr1[1]->SetMarkerColor(2); gr1[1]->SetMarkerStyle(22); gr1[2] = new TGraphErrors(n,x,y1_3,ex,ey1_3); gr1[2]->SetTitle("EPD sub1 event plane "); gr1[2]->SetMarkerColor(3); gr1[2]->SetMarkerStyle(23); legend[0]->AddEntry(gr1[0],"EPD-1 VS EPD-2 & TPC","p"); legend[0]->AddEntry(gr1[1],"EPD-1 VS EPD-3 & TPC","p"); legend[0]->AddEntry(gr1[2],"EPD-1 VS EPD-4 & TPC","p"); gr2[0] = new TGraphErrors(n,x,y2_1,ex,ey2_1); gr2[0]->SetTitle("EPD sub2 event plane "); gr2[0]->SetMarkerColor(1); gr2[0]->SetMarkerStyle(21); gr2[1] = new TGraphErrors(n,x,y2_2,ex,ey2_2); gr2[1]->SetTitle("EPD sub2 event plane "); gr2[1]->SetMarkerColor(2); gr2[1]->SetMarkerStyle(22); gr2[2] = new TGraphErrors(n,x,y2_3,ex,ey2_3); gr2[2]->SetTitle("EPD sub2 event plane "); gr2[2]->SetMarkerColor(3); gr2[2]->SetMarkerStyle(23); legend[1]->AddEntry(gr2[0],"EPD-2 VS EPD-1 & TPC","p"); legend[1]->AddEntry(gr2[1],"EPD-2 VS EPD-3 & TPC","p"); legend[1]->AddEntry(gr2[2],"EPD-2 VS EPD-4 & TPC","p"); gr3[0] = new TGraphErrors(n,x,y3_1,ex,ey3_1); gr3[0]->SetTitle("EPD sub3 event plane "); gr3[0]->SetMarkerColor(1); gr3[0]->SetMarkerStyle(21); gr3[1] = new TGraphErrors(n,x,y3_2,ex,ey3_2); gr3[1]->SetTitle("EPD sub3 event plane "); gr3[1]->SetMarkerColor(2); gr3[1]->SetMarkerStyle(22); gr3[2] = new TGraphErrors(n,x,y3_3,ex,ey3_3); gr3[2]->SetTitle("EPD sub3 event plane "); gr3[2]->SetMarkerColor(3); gr3[2]->SetMarkerStyle(23); legend[2]->AddEntry(gr3[0],"EPD-3 VS EPD-1 & TPC","p"); legend[2]->AddEntry(gr3[1],"EPD-3 VS EPD-2 & TPC","p"); legend[2]->AddEntry(gr3[2],"EPD-3 VS EPD-4 & TPC","p"); gr4[0] = new TGraphErrors(n,x,y4_1,ex,ey4_1); gr4[0]->SetTitle("EPD sub4 event plane "); gr4[0]->SetMarkerColor(1); gr4[0]->SetMarkerStyle(21); gr4[1] = new TGraphErrors(n,x,y4_2,ex,ey4_2); gr4[1]->SetTitle("EPD sub4 event plane "); gr4[1]->SetMarkerColor(2); gr4[1]->SetMarkerStyle(22); gr4[2] = new TGraphErrors(n,x,y4_3,ex,ey4_3); gr4[2]->SetTitle("EPD sub4 event plane "); gr4[2]->SetMarkerColor(3); gr4[2]->SetMarkerStyle(23); legend[3]->AddEntry(gr4[0],"EPD-4 VS EPD-1 & TPC","p"); legend[3]->AddEntry(gr4[1],"EPD-4 VS EPD-2 & TPC","p"); legend[3]->AddEntry(gr4[2],"EPD-4 VS EPD-3 & TPC","p"); gr5[0] = new TGraphErrors(n,x,y5_1,ex,ey5_1); gr5[0]->SetTitle("TPC event plane "); gr5[0]->SetMarkerColor(1); gr5[0]->SetMarkerStyle(21); gr5[1] = new TGraphErrors(n,x,y5_2,ex,ey5_2); gr5[1]->SetTitle("TPC event plane "); gr5[1]->SetMarkerColor(2); gr5[1]->SetMarkerStyle(22); gr5[2] = new TGraphErrors(n,x,y5_3,ex,ey5_3); gr5[2]->SetTitle("TPC event plane "); gr5[2]->SetMarkerColor(3); gr5[2]->SetMarkerStyle(23); legend[4]->AddEntry(gr5[0],"TPC VS EPD-1 & EPD-2","p"); legend[4]->AddEntry(gr5[1],"TPC VS EPD-2 & EPD-3","p"); legend[4]->AddEntry(gr5[2],"TPC VS EPD-3 & EPD-4","p"); c1[0]->cd(); gr1[0]->Draw("P"); gr1[1]->Draw("P"); gr1[2]->Draw("P"); legend[0]->Draw(); c1[1]->cd(); gr2[0]->Draw("P"); gr2[1]->Draw("P"); gr2[2]->Draw("P"); legend[1]->Draw(); c1[2]->cd(); gr3[0]->Draw("P"); gr3[1]->Draw("P"); gr3[2]->Draw("P"); legend[2]->Draw(); c1[3]->cd(); gr4[0]->Draw("P"); gr4[1]->Draw("P"); gr4[2]->Draw("P"); legend[3]->Draw(); c1[4]->cd(); gr5[0]->Draw("P"); gr5[1]->Draw("P"); gr5[2]->Draw("P"); legend[4]->Draw(); for(int i=0;i<5;i++){ c1[i]->Write(); } outFile->Write(); return 0; } Double_t resoErr(Double_t corrAB, Double_t corrAC, Double_t corrBC, Double_t errAB, Double_t errAC, Double_t errBC){ Double_t error = -999.; if(corrBC!=0){ error = corrAC / corrBC * errAB + corrAB / corrBC * errAC - corrAB * corrAC / (corrBC * corrBC) * errBC; } return error; } Double_t resoVal(Double_t corrAB, Double_t corrAC, Double_t corrBC){ Double_t resolution = -999.; if(corrBC!=0){ resolution = corrAB * corrAC / corrBC; } return resolution; }
[ "danielxchenx@gmail.com" ]
danielxchenx@gmail.com
e3c11c8cec4bb7194e5c54e700265a8e167777d4
b227d23f889f5dc04b7eef4bc3eb514732ccef55
/PTA/PAT_A/Cpp11/A1082_AC.cc
0339109e091dbba1983ad5b6183675449efe274f
[ "MIT" ]
permissive
StrayDragon/OJ-Solutions
e5dd953781237197b98fa83711a818cd705c3fdc
b31b11c01507544aded2302923da080b39cf2ba8
refs/heads/master
2020-04-26T17:17:04.605568
2019-12-24T08:03:18
2019-12-24T08:03:18
173,708,012
1
0
null
null
null
null
UTF-8
C++
false
false
1,246
cc
// --- // id : 1082 // title : Read Number in Chinese // difficulty : Medium // score : 25 // tag : Simple Simulation // keyword : string; lexical analysis; two pointer // status : AC // from : PAT (Advanced Level) Practice // --- #include <iostream> #include <string> using namespace std; const string d2hans[] = { "ling", "yi", "er", "san", "si", "wu", "liu", "qi", "ba", "jiu", }; const string unit[] = { "Shi", "Bai", "Qian", "Wan", "Yi", }; int main() { string digits; cin >> digits; int it = 0, rit = digits.length() - 1, len = digits.length(); if (digits[it] == '-') { cout << "Fu"; it++; } for (; it + 4 <= rit; rit -= 4) { } for (; it < len; rit += 4) { bool zeroes = false, printed = false; for (; it <= rit; it++) { if (it > 0 && digits[it] == '0') { zeroes = true; } else { if (zeroes) { cout << " ling"; zeroes = false; } if (it > 0) cout << " "; cout << d2hans[digits[it] - '0']; printed = true; if (it != rit) cout << " " << unit[rit - it - 1]; } } if (printed && rit != len - 1) cout << " " << unit[(len - 1 - rit) / 4 + 2]; } return 0; }
[ "straydragonl@foxmail.com" ]
straydragonl@foxmail.com
a00f7797c812695db656ab752720bccb159352f0
6968d632ba84a48f27c682691b06ef07e1c72308
/AirLib/include/vehicles/MultiRotor.hpp
b967c3671950eabf774339ea033845f53a668ac9
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
Jinxinshao/AirSimMulti
e148cdc1dfb9542b9636c94f601ec02d9561f7a8
cfc1fc7eb2f7b6e67c7cb59047e9b3273da4691b
refs/heads/master
2020-09-03T16:54:02.557013
2017-09-06T01:30:45
2017-09-06T01:30:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,799
hpp
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #ifndef msr_airlib_multirotor_hpp #define msr_airlib_multirotor_hpp #include "common/Common.hpp" #include "common/CommonStructs.hpp" #include "Rotor.hpp" #include "controllers/ControllerBase.hpp" #include "MultiRotorParams.hpp" #include <vector> #include "physics/PhysicsBody.hpp" namespace msr { namespace airlib { class MultiRotor : public PhysicsBody { public: MultiRotor() { //allow default constructor with later call for initialize } MultiRotor(MultiRotorParams* params, const Kinematics::State& initial_kinematic_state, Environment* environment) { initialize(params, initial_kinematic_state, environment); } void initialize(MultiRotorParams* params, const Kinematics::State& initial_kinematic_state, Environment* environment) { params_ = params; PhysicsBody::initialize(params_->getParams().mass, params_->getParams().inertia, initial_kinematic_state, environment); createRotors(*params_, rotors_, environment); createDragVertices(); initSensors(*params_, getKinematics(), getEnvironment()); } DroneControllerBase* getController() { return params_->getController(); } //*** Start: UpdatableState implementation ***// virtual void reset() override { //reset rotors, kinematics and environment PhysicsBody::reset(); //reset inputs if (getController()) getController()->reset(); //reset sensors last after their ground truth has been reset resetSensors(); } virtual void update() override { //update forces and environment as a result of last dt PhysicsBody::update(); //Note that controller gets updated after kinematics gets updated in kinematicsUpdated } virtual void reportState(StateReporter& reporter) override { //call base PhysicsBody::reportState(reporter); reportSensors(*params_, reporter); //report rotors for (uint rotor_index = 0; rotor_index < rotors_.size(); ++rotor_index) { reporter.startHeading("", 1); reporter.writeValue("Rotor", rotor_index); reporter.endHeading(false, 1); rotors_.at(rotor_index).reportState(reporter); } } //*** End: UpdatableState implementation ***// //implement abstract methods from PhysicsBody virtual void kinematicsUpdated() override { updateSensors(*params_, getKinematics(), getEnvironment()); getController()->update(); //transfer new input values from controller to rotors for (uint rotor_index = 0; rotor_index < rotors_.size(); ++rotor_index) { rotors_.at(rotor_index).setControlSignal( getController()->getVertexControlSignal(rotor_index)); } } //sensor getter const SensorCollection& getSensors() const { return params_->getSensors(); } //physics body interface virtual uint wrenchVertexCount() const override { return params_->getParams().rotor_count; } virtual PhysicsBodyVertex& getWrenchVertex(uint index) override { return rotors_.at(index); } virtual const PhysicsBodyVertex& getWrenchVertex(uint index) const override { return rotors_.at(index); } virtual uint dragVertexCount() const override { return static_cast<uint>(drag_vertices_.size()); } virtual PhysicsBodyVertex& getDragVertex(uint index) override { return drag_vertices_.at(index); } virtual const PhysicsBodyVertex& getDragVertex(uint index) const override { return drag_vertices_.at(index); } virtual real_T getRestitution() const override { return params_->getParams().restitution; } virtual real_T getFriction() const override { return params_->getParams().friction; } Rotor::Output getRotorOutput(uint rotor_index) const { return rotors_.at(rotor_index).getOutput(); } virtual void setCollisionInfo(const CollisionInfo& collison_info) override { PhysicsBody::setCollisionInfo(collison_info); getController()->setCollisionInfo(collison_info); } virtual ~MultiRotor() = default; private: //methods static void createRotors(const MultiRotorParams& params, vector<Rotor>& rotors, const Environment* environment) { rotors.clear(); //for each rotor pose for (uint rotor_index = 0; rotor_index < params.getParams().rotor_poses.size(); ++rotor_index) { const MultiRotorParams::RotorPose& rotor_pose = params.getParams().rotor_poses.at(rotor_index); rotors.emplace_back(rotor_pose.position, rotor_pose.normal, rotor_pose.direction, params.getParams().rotor_params, environment, rotor_index); } } void reportSensors(MultiRotorParams& params, StateReporter& reporter) { params.getSensors().reportState(reporter); } void updateSensors(MultiRotorParams& params, const Kinematics::State& state, const Environment& environment) { unused(state); unused(environment); params.getSensors().update(); } void initSensors(MultiRotorParams& params, const Kinematics::State& state, const Environment& environment) { params.getSensors().initialize(&state, &environment); } void resetSensors() { params_->getSensors().reset(); } void createDragVertices() { const auto& params = params_->getParams(); //Drone is seen as central body that is connected to propellers via arm. We approximate central body as box of size x, y, z. //The drag depends on area exposed so we also add area of propellers to approximate drag they may introduce due to their area. //while moving along any axis, we find area that will be exposed in that direction real_T propeller_area = M_PIf * params.rotor_params.propeller_diameter * params.rotor_params.propeller_diameter; real_T propeller_xsection = M_PIf * params.rotor_params.propeller_diameter * params.rotor_params.propeller_height; real_T top_bottom_area = params.body_box.x() * params.body_box.y(); real_T left_right_area = params.body_box.x() * params.body_box.z(); real_T front_back_area = params.body_box.y() * params.body_box.z(); Vector3r drag_factor_unit = Vector3r( front_back_area + rotors_.size() * propeller_xsection, left_right_area + rotors_.size() * propeller_xsection, top_bottom_area + rotors_.size() * propeller_area) * params.linear_drag_coefficient / 2; //add six drag vertices representing 6 sides drag_vertices_.clear(); drag_vertices_.emplace_back(Vector3r(0, 0, -params.body_box.z()), Vector3r(0, 0, -1), drag_factor_unit.z()); drag_vertices_.emplace_back(Vector3r(0, 0, params.body_box.z()), Vector3r(0, 0, 1), drag_factor_unit.z()); drag_vertices_.emplace_back(Vector3r(0, -params.body_box.y(), 0), Vector3r(0, -1, 0), drag_factor_unit.y()); drag_vertices_.emplace_back(Vector3r(0, params.body_box.y(), 0), Vector3r(0, 1, 0), drag_factor_unit.y()); drag_vertices_.emplace_back(Vector3r(-params.body_box.x(), 0, 0), Vector3r(-1, 0, 0), drag_factor_unit.x()); drag_vertices_.emplace_back(Vector3r( params.body_box.x(), 0, 0), Vector3r( 1, 0, 0), drag_factor_unit.x()); } private: //fields MultiRotorParams* params_; //let us be the owner of rotors object vector<Rotor> rotors_; vector<PhysicsBodyVertex> drag_vertices_; }; }} //namespace #endif
[ "saihemachandra.v@gmail.com" ]
saihemachandra.v@gmail.com
a8f1327a7d4638d33a8ac702d726e0158232ebc4
acdc1fb58b78a487ff39908cae0dbf1e37dc24d0
/N_Body_Simulation/N_Body_Simulation/TaskCollisionCheckNode.h
b45dce196c61d49d430f72374bd51921a0904dd5
[]
no_license
gyroid42/N_Body_Simulation_Final
f16990253b777ad7696437158fd947a9bb4d9d0c
51d8ffccd60f5d09a60be4cd553001c836e7a297
refs/heads/master
2020-04-19T11:18:02.761486
2019-04-29T14:38:14
2019-04-29T14:38:14
168,163,168
0
0
null
null
null
null
UTF-8
C++
false
false
941
h
#pragma once // include parent class #include "Task.h" // include my classes #include "SETTINGS.h" #include "Channel.h" // forward decleration class Body; class OctreeNode; struct CollisionEvent; class TaskCollisionCheckNode : public Task { public: TaskCollisionCheckNode(); ~TaskCollisionCheckNode(); #if BENCHMARKING void Init(OctreeNode* newNode, Channel<int>* newCheckCountChannel, Channel<CollisionEvent*>* newCollisionEventsChannel, Body* newAncestorList[MAX_COLLISION_DEPTH]); #else void Init(OctreeNode* newNode, Channel<CollisionEvent*>* newCollisionEventsChannel, Body* newAncestorList[MAX_COLLISION_DEPTH]); #endif void Run(); private: // node being checked OctreeNode* node_; // list of ancestors to this node Body* ancestorList_[MAX_COLLISION_DEPTH]; // channel to output collisions found Channel<CollisionEvent*>* collisionEventsChannel_; #if BENCHMARKING Channel<int>* checkCountChannel_; #endif };
[ "1501651@abertay.ac.uk" ]
1501651@abertay.ac.uk
ad06d0712e809e6705ed6cd9b8a9791b1f07aeab
90479726ed480dfe1a75166bf0075694cdcb9e51
/DP/xxjs105-硬币问题.cpp
6b3b2b5a68f78fec1faa5cc50c79507d98e96f26
[]
no_license
Edison-Ba/Li2OJ
b2c744676a4cb933dd0a2e1c4e0b9a27018618e1
5a67707080f44f9f3f3c68422431d4edc50458e0
refs/heads/master
2023-08-03T03:15:32.186073
2023-07-29T08:46:11
2023-07-29T08:46:11
378,881,973
1
0
null
null
null
null
UTF-8
C++
false
false
1,510
cpp
/*--------------------------------- *Title number: ybt-dp *Creation date: 2021.2.19 *Author: EdisonBa *-------------------------------*/ #include <algorithm> #include <iostream> #include <cstring> #include <cstdlib> #include <cstdio> #include <vector> #include <stack> #include <cmath> #include <queue> #include <map> using namespace std; typedef long long ll; inline ll read() { ll x = 0, f = 0; char ch = getchar(); while (!isdigit(ch)) f |= (ch == '-'), ch = getchar(); while (isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^= 48), ch = getchar(); return f ? -x : x; } const int maxn = 10003; const int maxm = 100002; ll n, w[maxn], f[maxm], c[maxn], m; int main() { while (cin >> n >> m) { if (n == 0 && m == 0) break; memset(f, 0, sizeof f); f[0] = 1; for (int i = 1; i <= n; ++i) w[i] = read(); for (int i = 1; i <= n; ++i) c[i] = read(); ll ans = 0; for (int mm = 1; mm <= m; ++mm) { memset(f, 0, sizeof f); f[0] = 1; for (int i = 1; i <= n; ++i) { for (int k = 1; k <= c[i]; ++k) { for (int j = mm; j >= w[i]; --j) { f[j] += f[j - w[i]]; } } } //printf("%lld\n",f[mm]); if(f[mm]) ans++; } printf("%lld\n", ans); } }
[ "1325539609@qq.com" ]
1325539609@qq.com
f232279e6b06ed76d7d6e47dadf44558d8c2d4be
be216eddacb8ff9182ca9cb53594eeae88379cf0
/Kinematics/src/Kinematics/Framework/Managers/EnviromentManager.cpp
82198448acfd604b4a3d79baa561b66b8da4fcd8
[]
no_license
vinijabes/MTE
e2550ba408798b4b66138aae72b5c75a2a2ce245
6881a8be0b84808915db7c2b858da59e5282fbde
refs/heads/master
2022-04-18T18:14:55.899453
2020-03-02T16:56:32
2020-03-02T16:56:32
225,663,578
0
1
null
null
null
null
UTF-8
C++
false
false
134
cpp
#include "mtepch.h" #include "EnviromentManager.h" namespace Kinematics { EnviromentManager* EnviromentManager::m_Instance = NULL; }
[ "vinijabes@gmail.com" ]
vinijabes@gmail.com
0985d98170b0824ee37b40cc9fd278788f823287
3a17afa016552480c59f377721164faa3b3c166e
/distro/Skyline2e/src/Globals.hpp
2437523540c07579525ecc1cd6026f0b100bb313
[]
no_license
EdgarReynaldo/Skyline2
6018211459decea8550808aee2e190a3890473c9
9996a35b0edac5f3427e6f813d657e9fc249c2ed
refs/heads/master
2021-05-26T04:47:08.225100
2020-09-24T19:47:43
2020-09-24T19:47:43
127,452,840
0
0
null
null
null
null
UTF-8
C++
false
false
361
hpp
#ifndef Globals_HPP #define Globals_HPP extern int sw; extern int sh; extern int FPS; class EagleSystem; class EagleGraphicsContext; class EagleEventHandler; class EagleTimer; class EagleFont; extern EagleSystem* sys; extern EagleGraphicsContext* win; extern EagleEventHandler* q; extern EagleTimer* t; extern EagleFont* f; #endif // Globals_HPP
[ "edgarreynaldo@members.allegro.cc" ]
edgarreynaldo@members.allegro.cc
57e1e94323c241eba6955e4888b8cb1ed134d39e
3f35f1cc4dacbcaa223a398471950a94102f9d59
/_ongoing_StockAnalysis/stockAnaylsis/mainHeader.h
b77fa81d343a0ab9d4e164c1fbbfd0fd66d44101
[]
no_license
codeAligned/random-projects
0dccfc0bf52c80f0018e3d8e84ad0547a40cc64e
f019ae476ff1aae49ac1f7d135f14924b3219f6e
refs/heads/master
2020-06-13T08:28:38.578175
2016-07-04T13:23:09
2016-07-04T13:23:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,264
h
// Created by Steve Yoo // 9/11/2014 // Header file to link all our files together #ifndef MAINHEADER_H_INCLUDED #define MAINHEADER_H_INCLUDED #include <string> #include <stack> #include "userClass.h" using namespace std; /// Program-Wide Variables // Keeps track of last visited index throughout the entire program extern stack<int> lastVisited; // This is the name of the database used to store all our information extern string userDatabase; // Call on a menu screen (using the proper index provided in "displayMenu.cpp"!) int displayMenu(int a); // a = index!! // Clear the console screen void clearScreen(); // Call on a menu screen for user account control (using index provided in "userAccCtrl.cpp"!) void usrAccCtrl(int index); // Check whether or not a file opened successfully /** filename specifies the name of the file *** type specifies what kind of operation you are performing on the file *** FILE OPERATION NUBMER (TO PUT IN TYPE) *** Writing to a File 0 *** Reading from a File 1 *** Reading and Writing 2 ***/ int checkFile(string filename, int type); // Used to read in the CSV files that are downloaded from Google void csvReader(); #endif // MAINHEADER_H_INCLUDED
[ "shstyoo@gmail.com" ]
shstyoo@gmail.com
00f2b4b901d0122a934df266e6028f56e545c07c
3bffe897d890bbac09cbfa8302f82620f156d7b7
/tools/textmidi.cpp
1b6c2b3920f86955d045db4932644b66465a9e9f
[]
no_license
10000turtles/MusicAndTech2Project
2e14e3b3ba53b0e410028c03407d219d260eb614
aec80a57a53d8e405f556e72532d91f4baa2008f
refs/heads/main
2023-04-21T13:08:35.059232
2021-05-07T17:14:36
2021-05-07T17:14:36
333,765,345
1
0
null
null
null
null
UTF-8
C++
false
false
4,094
cpp
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Sat Nov 27 11:43:31 PST 1999 // Last Modified: Mon Nov 29 14:01:34 PST 1999 // Last Modified: Mon Feb 9 21:26:32 PST 2015 Updated for C++11. // Filename: ...sig/doc/examples/all/textmidi/textmidi.cpp // Syntax: C++ // // Description: Reads a MIDI file and converts data to/from ASCII text. // #include "../src/inc/Options.h" #include "../src/inc/MidiFile.h" #include <iostream> using namespace std; using namespace smf; #define STYLE_TIME_DELTA 'd' #define STYLE_TIME_ABSOLUTE 'a' // global variables: int timestyle = STYLE_TIME_DELTA; // command-line style options (-a | -d) // function declarations: void checkOptions (Options& opts); void example (void); void usage (const char* command); /////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { MidiFile inputfile; Options options(argc, argv); checkOptions(options); for (int i=1; i<=options.getArgCount(); i++) { bool status = inputfile.read(options.getArg(i)); if (options.getArgCount() > 1) { cout << "\n\n\n+++ FILE " << i << "++++++++++++++++++++++++++++\n\n"; } if (status == true) { switch (timestyle) { case 'd': inputfile.deltaTicks(); break; case 'a': inputfile.absoluteTicks(); break; } cout << inputfile; } else { cout << "Syntax error in file: " << options.getArg(i) << "\n"; } } return 0; } /////////////////////////////////////////////////////////////////////////// ////////////////////////////// // // checkOptions -- handle command-line options. // void checkOptions(Options& opts) { opts.define("a|abs|absolute=b"); opts.define("d|delta=b"); opts.define("author=b"); opts.define("version=b"); opts.define("example=b"); opts.define("help=b"); opts.process(); if (opts.getBoolean("author")) { cout << "Written by Craig Stuart Sapp, " << "craig@ccrma.stanford.edu, Nov 1999" << endl; exit(0); } if (opts.getBoolean("version")) { cout << "textmidi version 1.0" << endl; cout << "compiled: " << __DATE__ << endl; } if (opts.getBoolean("help")) { usage(opts.getCommand().c_str()); exit(0); } if (opts.getBoolean("example")) { example(); exit(0); } // can only have one output filename if (opts.getArgCount() == 0) { cout << "Error: need one input MIDI file." << endl; usage(opts.getCommand().c_str()); exit(1); } if (opts.getBoolean("absolute")) { timestyle = STYLE_TIME_ABSOLUTE; } } ////////////////////////////// // // example -- gives example calls to the textmidi program. // void example(void) { cout << "# textmidi examples: \n" " textmidi -a midifile.mid | more \n" << endl; } ////////////////////////////// // // usage -- how to run the textmidi program on the command line. // void usage(const char* command) { cout << " \n" "Creates a printable form of the data in a MIDI File. \n" " \n" "Usage: " << command << " [-d|-a] midifile[s] \n" " \n" "Options: \n" " -a = set time values to absolute time \n" " -d = set time values to delta time \n" " --options = list of all options, aliases and default values. \n" " \n" " \n" << endl; }
[ "10000turtles@gmail.com" ]
10000turtles@gmail.com
51946cea8fc247d9ca771d4b03ad20975ad81c9a
da3215baf37d257d5814f165e98b4b19dee9cb05
/SDK/FN_TextStyle-Base-M-B-Yellow_classes.hpp
ef44ecaccf63590175605a9a13b7ff9f325026ec
[]
no_license
Griizz/Fortnite-Hack
d37a6eea3502bf1b7c78be26a2206c8bc70f6fa5
5b80d585065372a4fb57839b8022dc522fe4110b
refs/heads/Griizz_Version
2022-04-01T22:10:36.081573
2019-05-21T19:28:30
2019-05-21T19:28:30
106,034,464
115
85
null
2020-02-06T04:00:07
2017-10-06T17:55:47
C++
UTF-8
C++
false
false
671
hpp
#pragma once // Fortnite SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass TextStyle-Base-M-B-Yellow.TextStyle-Base-M-B-Yellow_C // 0x0000 (0x00D0 - 0x00D0) class UTextStyle_Base_M_B_Yellow_C : public UTextStyle_Base_M_B_C { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass TextStyle-Base-M-B-Yellow.TextStyle-Base-M-B-Yellow_C"); return ptr; } }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sinbadhacks@gmail.com" ]
sinbadhacks@gmail.com
9d4b972cddf1e8910a974d3646378fa93f9c0261
55dc77e0d9a0d76390f09fc97e25261a77ba82ba
/2) CS163 Data Structures/Graphs/main.cpp
e9cf9b4357e48847f089d69682598facdbb3fd8b
[]
no_license
SourabhJam/ComputerScienceProjects
18f9a97d70ad06c9ab76cd5dc2b90fb8cae8e767
4a9051aa2773ca8969d92b8aae61eb54d4e2d406
refs/heads/master
2020-12-03T10:11:09.376556
2020-06-30T21:42:13
2020-06-30T21:42:13
229,887,186
0
0
null
null
null
null
UTF-8
C++
false
false
1,629
cpp
//Sourabh Jamalapuram, CS163 Data Structures, main.cpp //The main program is the program that interacts with the user by prompting them if they want to add classes, add pre req's, display pre reqs, and display course pathway, and quit. #include "graph.h" int main(){ table graph; //graph char vertex[50]; // used to add a vertex char preReq[50]; // used to add a pre req/edge int userInput; //for user input to see what they want to do do{ cout<<"\n(1)Add Class"<<endl; cout<<"(2)Add Pre Req"<<endl; cout<<"(3)Display Pre Req's"<<endl; cout<<"(4)Display ALL Pre Req's(BFS)"<<endl; cout<<"(5)Quit"<<endl; cout<<"Select One Of The Following: "<<endl; cin>>userInput; cin.ignore(100,'\n'); if(userInput == 1){ cout<<"\nEnter Class Name: "<<endl; cin.get(vertex,100,'\n'); cin.ignore(100,'\n'); graph.insertVertex(vertex); }else if(userInput == 2){ cout<<"\nEnter Class You Wish To Add Pre Req Too: "<<endl; cin.get(vertex,100,'\n'); cin.ignore(100,'\n'); cout<<"\nEnter Pre Req For Class: "<<endl; cin.get(preReq,100,'\n'); cin.ignore(100,'\n'); graph.insertEdge(vertex,preReq); }else if(userInput == 3){ cout<<"\nEnter Class You Want To Take: "<<endl; cin.get(vertex,100,'\n'); cin.ignore(100,'\n'); graph.display(vertex); }else if(userInput == 4){ cout<<"Enter Class You Want To Take: "<<endl; cin.get(vertex,100,'\n'); cin.ignore(100,'\n'); graph.BFS(vertex); }else if(userInput == 5){ }else{ cout<<"\nEnter Valid Input!!!"<<endl; } }while(userInput !=5); return 0; }
[ "sourabh.jamalapuram@gmail.com" ]
sourabh.jamalapuram@gmail.com
241393d6cc8f77ccf5c552a9269ac006f1cd1389
fa9b071fff72371149471851f490a0c6114f8db2
/src/rpplugins/rpstat/src/anim_control_window.cpp
97ed23c4aeaf9712cd692eae92bc90fb3477127f
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
chic-yukim/render_pipeline_cpp
7b94d655918035575d84b58c57dccc53718cf5d9
b6f29c4b5d51734658009405d217bf846f10c8af
refs/heads/master
2020-03-19T19:34:44.062443
2019-03-14T02:22:07
2019-03-14T02:22:07
136,863,921
1
0
null
2018-06-11T02:21:06
2018-06-11T02:21:06
null
UTF-8
C++
false
false
4,251
cpp
/** * MIT License * * Copyright (c) 2018 Younguk Kim (bluekyu) * * 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 "anim_control_window.hpp" #include <animControl.h> #include <fmt/ostream.h> #include <render_pipeline/rppanda/showbase/showbase.hpp> #include <render_pipeline/rpcore/globals.hpp> #include <render_pipeline/rpcore/render_pipeline.hpp> #include "rpplugins/rpstat/plugin.hpp" namespace rpplugins { size_t AnimControlWindow::global_id_ = 0; std::unordered_map<AnimControl*, AnimControlWindow*> AnimControlWindow::holder_; std::pair<AnimControlWindow*, bool> AnimControlWindow::create_window(RPStatPlugin& plugin, rpcore::RenderPipeline& pipeline, AnimControl* control) { auto found = holder_.find(control); if (found != holder_.end()) { return { found->second, false }; } else { auto window = std::unique_ptr<AnimControlWindow>(new AnimControlWindow(plugin, pipeline, control)); auto window_raw = window.get(); plugin.add_window(std::move(window)); return { holder_.emplace(control, window_raw).first->second, true }; } } void AnimControlWindow::remove_window(AnimControlWindow* window) { holder_.erase(window->control_); window->plugin_.remove_window(window); } AnimControlWindow::AnimControlWindow(RPStatPlugin& plugin, rpcore::RenderPipeline& pipeline, AnimControl* control) : WindowInterface(plugin, pipeline, "Anim Control Window", "###AnimControl" + std::to_string(global_id_++)), control_(control) { reset(); } AnimControlWindow::~AnimControlWindow() = default; void AnimControlWindow::draw() { is_open_ = true; title_ = fmt::format("Anim Control Window: {}", control_->get_name()); if (!ImGui::Begin(fmt::format("{}{}", title_, unique_id_).c_str(), &is_open_, window_flags_)) { // Early out if the window is collapsed, as an optimization. ImGui::End(); return; } draw_contents(); ImGui::End(); // auto destruct when closed if (!is_open_) remove_window(this); } void AnimControlWindow::draw_contents() { float frame = static_cast<float>(control_->get_full_fframe()); if (ImGui::DragFloat("Frame", &frame, 0.125f)) control_->pose(frame); ImGui::InputFloat("From", &from_frame_); ImGui::InputFloat("To", &to_frame_); float play_rate = static_cast<float>(control_->get_play_rate()); if (ImGui::InputFloat("Play Rate", &play_rate)) control_->set_play_rate(play_rate); ImGui::Checkbox("Restart", &restart_); if (ImGui::Button("Play")) control_->play(from_frame_, to_frame_); ImGui::SameLine(); if (ImGui::Button("Loop")) control_->loop(restart_, from_frame_, to_frame_); ImGui::SameLine(); if (ImGui::Button("Pingpong")) control_->pingpong(restart_, from_frame_, to_frame_); ImGui::SameLine(); if (ImGui::Button("Stop")) control_->stop(); if (ImGui::Button("Reset")) { control_->pose(0); control_->set_play_rate(1); reset(); } } void AnimControlWindow::reset() { from_frame_ = 0; to_frame_ = static_cast<float>(control_->get_num_frames() - 1); restart_ = false; } }
[ "bluekyu.dev@gmail.com" ]
bluekyu.dev@gmail.com
4e268d497a0c582207751aa794e4651aa2763563
8447ae564fe108850a1b201b2cec7ad9972e42e4
/743.network-delay-time.cpp
67aa2931fd35faf4a6ac070532a17277d4d107bf
[ "MIT" ]
permissive
bsmsnd/LeetCode-CharlieChen
cb7d193da97dcaf7a3fc4cbf4369bcc661869e0d
ddd8f09beabd08e0e7348938604eab69928d9bfe
refs/heads/master
2022-07-06T16:46:27.075115
2020-08-22T06:30:50
2022-07-03T15:12:24
185,423,399
0
0
null
null
null
null
UTF-8
C++
false
false
1,529
cpp
/* * @lc app=leetcode id=743 lang=cpp * * [743] Network Delay Time */ #include <vector> #include <queue> using namespace std; class Solution { public: queue<int> q; vector<vector<int>> G; vector<vector<int>> G_time; int networkDelayTime(vector<vector<int>>& times, int N, int K) { const int E = times.size(); G.resize(N); G_time.resize(N); int ans[N]; for (int i = 0;i < N;i++)ans[i] = -1; // for (int i = 0; i < N;i++)cout<<ans[i]<<endl; for (int i = 0; i < E;++i) { G[times[i][0] - 1].push_back(times[i][1] - 1); G_time[times[i][0] - 1].push_back(times[i][2]); } ans[K-1] = 0; q.push(K-1); int cur_node; while(!q.empty()) { cur_node = q.front(); q.pop(); for (int i = 0;i < G[cur_node].size();++i) { if (ans[G[cur_node][i]] == -1 || ans[G[cur_node][i]] > ans[cur_node] + G_time[cur_node][i]) { ans[G[cur_node][i]] = ans[cur_node] + G_time[cur_node][i]; q.push(G[cur_node][i]); } } } int sol = 0; for (int i = 0; i < N;i++) { if (ans[i] == -1) return -1; else { sol = sol < ans[i] ? ans[i] : sol; // cout<<ans[i]<<endl; } } return sol; } };
[ "chendongcharlie@hotmail.com" ]
chendongcharlie@hotmail.com
e7fe35fb63d5cf22b9fbd3e5096a9596fcbf6c2c
c88d094001300aae6e098bacfc5ea362a8362e07
/A. Vladik and Courtesy.cpp
4781287f696abba0119f414f93839e063fd4bee9
[]
no_license
Mahbub20/Codeforces-Coding-Solutions
d25dfa1933546b805dcef7bbb51146a37f18f09c
e823306607dcad58b96d653a5148609ea52e8044
refs/heads/master
2020-04-26T11:45:07.591117
2019-03-03T04:56:04
2019-03-03T04:56:04
173,527,195
0
0
null
null
null
null
UTF-8
C++
false
false
284
cpp
#include<bits/stdc++.h> using namespace std; int main() { long long a,b,i,j; cin >> a >> b; i = 1; while(1) { if(i%2==1) { a-=i; } else{ b-=i; } i++; if(a<0 || b<0)break; } if(a<0)cout << "Vladik\n"; else cout << "Valera\n"; }
[ "mmahbub569@gmail.com" ]
mmahbub569@gmail.com
330816a5080369174c8729bc30f9e1b3bb3245c2
6c692d65828b7bb3ccd0c53c1054108e09ba5d32
/CCInclusive_validation_Sep2018/CCInclusive_stuff/CCInclusive_validation_22/localProducts_larsoft_v06_26_01_14_e10_prof/uboonecode/v06_26_01_22/source/test/SparseRawDigits/SparseRawDigitTest_module.cc
2a833530292453ba8eed401bc170f527d498a6ce
[]
no_license
ssfehlberg/MCC9_Validation_Codes
da4912b01f6dea84716214adc81e63866fc2225a
d1facebf62f8bdae40f0bf4e489789712f0cb8df
refs/heads/master
2021-09-26T11:13:44.824434
2018-10-25T17:22:57
2018-10-25T17:22:57
150,471,735
0
0
null
null
null
null
UTF-8
C++
false
false
5,373
cc
//====================================================================== // // Name: SparseRawDigitTest_module.cc // // Purpose: Analyzer module to test SparseRawDigit data product. // This module accepts a single fcl parameter, which is the // label of a Wire collection data product. This module // fetches the Wire collection and then uses associations // to fetch associated SparseRawDigits and regular RawDigits. // It performs the following checks. // // 1. Checks that ROIs are the same between Wire and // SparseRawdigit. // // 2. Checks that the SparseRawDigit waveform is the same // as the RawDigit waveform. // // FCL parameters: // // CalDataModuleLabel - CalData module label. // // Created: 19-Nov-2017 H. Greenlee // //====================================================================== #include <iostream> #include <cassert> #include <string> #include "art/Framework/Core/ModuleMacros.h" #include "art/Framework/Core/EDAnalyzer.h" #include "canvas/Persistency/Common/FindOneP.h" #include "cetlib/exception.h" #include "lardataobj/RecoBase/Wire.h" #include "lardataobj/RawData/RawDigit.h" #include "ubooneobj/SparseRawDigit.h" namespace raw{ class SparseRawDigitTest : public art::EDAnalyzer { public: // Constructor, destructor. SparseRawDigitTest(fhicl::ParameterSet const& pset); ~SparseRawDigitTest(); // Overrides. void analyze(const art::Event& evt); private: // Data members. std::string fCalDataModuleLabel; }; DEFINE_ART_MODULE(SparseRawDigitTest) // Constructor. SparseRawDigitTest::SparseRawDigitTest(fhicl::ParameterSet const& pset) : art::EDAnalyzer(pset), fCalDataModuleLabel(pset.get<std::string>("CalDataModuleLabel")) { std::cout << "Constructed SparseRawDigitTest.\n" << "CalDataModuleLabel: " << fCalDataModuleLabel << std::endl; } // Destructor. SparseRawDigitTest::~SparseRawDigitTest() {} // Analyze event. void SparseRawDigitTest::analyze(const art::Event& evt) { // Fetch Wire data product. art::Handle< std::vector<recob::Wire> > wireh; evt.getByLabel(fCalDataModuleLabel, wireh); if(!wireh.isValid()) { throw cet::exception("SparseRawDigitTest") << "Wire data product not found."; } std::cout << "Number of wires: " << wireh->size() << std::endl; // Construct FindOneP objects for RawDigit and SparseRawDigit. art::FindOneP<raw::RawDigit> find_raw_digit(wireh, evt, fCalDataModuleLabel); art::FindOneP<raw::SparseRawDigit> find_sparse_raw_digit(wireh, evt, fCalDataModuleLabel); // Loop over wires. unsigned int iwire = 0; for(auto const& wire : *wireh) { unsigned int channel = wire.Channel(); std::cout << "Wire Channel " << channel << std::endl; // Get associated RawDigit. const art::Ptr<raw::RawDigit>& digit_ptr = find_raw_digit.at(iwire); if(digit_ptr.isNull()) { throw cet::exception("SparseRawDigitTest") << "Associated RawDigit not found."; } if(digit_ptr->Channel() != channel) { throw cet::exception("SparseRawDigitTest") << "RawDigit channel does not match Wire."; } // Get associated SparseRawDigit. const art::Ptr<raw::SparseRawDigit>& sparse_ptr = find_sparse_raw_digit.at(iwire); if(sparse_ptr.isNull()) { throw cet::exception("SparseRawDigitTest") << "Associated SparseRawDigit not found."; } if(sparse_ptr->Channel() != channel) { throw cet::exception("SparseRawDigitTest") << "SparseRawDigit channel does not match Wire."; } // Check ROIs. auto const& wire_ranges = wire.SignalROI().get_ranges(); auto const& sparse_ranges = sparse_ptr->ADCs().get_ranges(); std::cout << "Number of Wire ROIs = " << wire_ranges.size() << std::endl; std::cout << "Number of SparseRawDigit ROIs = " << sparse_ranges.size() << std::endl; if(wire_ranges.size() != sparse_ranges.size()) { throw cet::exception("SparseRawDigitTest") << "Mismatch number of ROIs"; } // Loop over ROIs. unsigned int irange = 0; for(auto const& wire_range : wire_ranges) { auto const& sparse_range = sparse_ranges[irange]; std::cout << "Range " << irange << std::endl; std::cout << " Wire begin index = " << wire_range.begin_index() << std::endl; std::cout << " Wire end index = " << wire_range.end_index() << std::endl; std::cout << " SparseRawDigit begin index = " << sparse_range.begin_index() << std::endl; std::cout << " SparseRawDigit end index = " << sparse_range.end_index() << std::endl; if(wire_range.begin_index() != sparse_range.begin_index()) { throw cet::exception("SparseRawDigitTest") << "Mismatch begin index"; } if(wire_range.end_index() != sparse_range.end_index()) { throw cet::exception("SparseRawDigitTest") << "Mismatch end index"; } // Compare waveforms in this ROI. for(unsigned int i = sparse_range.begin_index(); i < sparse_range.end_index(); ++i) { std::cout << "SparseRawDigit adc = " << sparse_ptr->ADC(i) << std::endl; std::cout << "RawDigit adc = " << digit_ptr->ADC(i) << std::endl; if(sparse_ptr->ADC(i) != digit_ptr->ADC(i)) { throw cet::exception("SparseRawDigitTest") << "Mismatch waveform"; } } ++irange; } ++iwire; } } } // namespace raw
[ "ssfehlberg@gmail.com" ]
ssfehlberg@gmail.com
c92a767e54ff2b64fa7fa6ce56e30209c26262d4
5064a6bb6f6be38400404d5ea2cbce2d961296c1
/Algorithm/Source/List/SLList/Malloc_SL.cpp
64e85da8fef5c6cd9b58cbde90f3676975db7097
[]
no_license
YinHanbing/DataStructure-1
2d6cded2c97d7d766f3b8e8e3220864ec78c54f3
bd104dcc6d4a2af642a5e358211ef2eb5e43b39e
refs/heads/master
2020-03-08T07:33:12.526122
2018-03-27T07:09:37
2018-03-27T07:09:37
null
0
0
null
null
null
null
GB18030
C++
false
false
260
cpp
#include "../../../Header/List/SLList.h" // 若备用空间链表非空,则返回分配的结点下标,否则返回0 int Malloc_SL(SLinkList &space) { int i = space[0].cur; if (space[0].cur) { space[0].cur = space[i].cur; } return i; } // Malloc_SL
[ "hlm52pk@163.com" ]
hlm52pk@163.com
d0dde94a3d72afc4631b06a79ad574a6be0bad3c
33bc3f7ff83d21fa8b12f7a94744b6d57cd7090a
/src/utility/buffer.h
00bbe7f7a5853cc8997748349eeb0bad0f9b8c38
[]
no_license
Evil-crow/levelnet
6d8dcc42c63658f51a857ef90f823a4450966879
2720b7018d52a24bf9015d3738b00c954dacb9c2
refs/heads/master
2020-04-19T20:22:53.342285
2019-03-12T14:51:32
2019-03-12T14:51:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
841
h
/** * Created by Crow on 3/7/19. * Copyright (c) 2019 Crow All rights reserved. * @author Crow */ #ifndef LEVELNET_NET_BUFFER_H #define LEVELNET_NET_BUFFER_H #include <vector> namespace levelnet { class Buffer { public: using const_iter = std::vector<unsigned char>::const_iterator; Buffer(); ~Buffer() = default; size_t ReadFd(int fd); void Reprepare(long size); const_iter BufferBegin() const; const_iter BufferEnd() const; private: void FillData(void *data, size_t length); void MoveData(); size_t Readable() { return write_index_ - read_index_; } size_t Writeable() { return buffer_.capacity() - write_index_; } size_t FrontSpace() { return read_index_ - 0; } std::vector<unsigned char> buffer_; size_t read_index_; size_t write_index_; }; } #endif //LEVELNET_NET_BUFFER_H
[ "Evilcrow486@gmail.com" ]
Evilcrow486@gmail.com
d5836e186890848020e8f2f6d0dc22e717bc19cb
36844405003ffadf1d2fe7ed5d27d3fca4963049
/KeyboardHandlers.h
64cd90f0dde24e3b644ce4fd5341998c530f6b56
[]
no_license
rstratton/cs184-final-project
636360a2335134214988908497a91bd9f126beeb
b92d474d2519c33a1f9aa130ee6139744289d93d
refs/heads/master
2020-05-18T17:12:20.883062
2013-12-17T19:18:50
2013-12-17T19:18:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
444
h
#ifndef KEYBOARD_HANDLERS_H #define KEYBOARD_HANDLERS_H #include "Camera.h" #include "Renderer.h" #include "algebra3.h" class KeyboardHandlers { public: KeyboardHandlers(Camera* c, vec3* pos, Renderer* r); void basicKeyHandler(unsigned char key, int x, int y); void specialKeyHandler(int key, int x, int y); private: Camera* camera; vec3* objectPosition; Renderer* renderer; }; #endif
[ "r.a.stratton88@gmail.com" ]
r.a.stratton88@gmail.com
e0e10e59bcd2ecd100323e29f19526726d1c0c34
420a0250f3466c93957b82a3c559af7fff1a4113
/SAT_Telemetry/SAT_Telemetry.cpp
7ba10fa433b962254464199a450d28e6522a5cb7
[]
no_license
mlbelem/ArduSatSDK
69a994e45f20b3d12a5f432b9fa6535c42d9b3f3
2d737bf816efaeff95f1a45544827dc304b8ece1
refs/heads/master
2021-01-20T22:02:45.520160
2013-05-16T23:02:28
2013-05-16T23:02:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,777
cpp
/* SAT_Telemetry.cpp - Library to write arduino application data from arduino->supervisor. Copyright (C) 2013 Jorge Ortiz for NanoSatisfi Copyright 2013 NanoSatisfi, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /****************************************************************************** * Includes ******************************************************************************/ #include <stdio.h> #include <string.h> #include "SAT_Telemetry.h" /****************************************************************************** * Definitions ******************************************************************************/ extern boolean SAT_Telemetry::_valFetchDone = true; /****************************************************************************** * Constructors ******************************************************************************/ SAT_Telemetry::SAT_Telemetry(uint8_t id){ _local_address = id; _commLayer = new OnboardCommLayer(MULTIMASTER, _local_address); _valFetchDone = true; _commLayer->onReceive(_onTelemetryFetchDone, _buff, sizeof(uint32_t)*2, ADD_SUPERVISOR_TELEMETRY); } /****************************************************************************** * Private functions ******************************************************************************/ void SAT_Telemetry::_onTelemetryFetchDone(size_t bytesRxd, boolean done){ _valFetchDone = true; } /****************************************************************************** * User API ******************************************************************************/ void SAT_Telemetry::set(){ int cycleTime = 100; memset(_send_buffer, 0, SIZE); nanosat_message_t* msg = (nanosat_message_t*)&_send_buffer[0]; msg->prefix=NODE_COMM_MESSAGE_PREFIX; msg->type = TELEMETRY; msg->node_addr = _local_address; msg->len = 0; _valFetchDone = false; _commLayer->send(msg, (uint8_t)ADD_SUPERVISOR_TELEMETRY); while(!SAT_Telemetry::_valFetchDone) delay(cycleTime); _5V_current = _buff[0]; _3_3V_current = _buff[1]; } uint32_t SAT_Telemetry::get3_3V_Current(){ return _3_3V_current; } uint32_t SAT_Telemetry::get5V_Current(){ return _5V_current; }
[ "nick.allain@gmail.com" ]
nick.allain@gmail.com
76c04f14285dff9fc2093568c3eb362ceb858617
575c265b54bbb7f20b74701753174678b1d5ce2c
/lottery/Classes/lottery/BRNN/BRNNPokerCard.cpp
8e984e27fa0c67cb065195cdce0fd81162b18fb6
[]
no_license
larryzen/Project3.x
c8c8a0be1874647909fcb1a0eb453c46d6d674f1
cdc2bf42ea737c317fe747255d2ff955f80dbdae
refs/heads/master
2020-12-04T21:27:46.777239
2019-03-02T06:30:26
2019-03-02T06:30:26
null
0
0
null
null
null
null
GB18030
C++
false
false
5,273
cpp
#include "BRNNPokerCard.h" #include "BRNNRes.h" #include "ToolKit.h" /****************************BRNNPokerCard begin********************************************/ BRNNPokerCard::BRNNPokerCard() { } BRNNPokerCard::~BRNNPokerCard() { } void BRNNPokerCard::initCard(const int nCardIdx) { string sObverseFileName = getCardFileName(nCardIdx); string sReverseFileName = getCardFileName(0); loadCardObverse(sObverseFileName); loadCardReverse(sReverseFileName); m_pCardObverse->setScale(BRNN_CARD_SCALE_BIG); m_pCardReverse->setScale(BRNN_CARD_SCALE_BIG); } bool BRNNPokerCard::init() { bool bRet = false; do { CC_BREAK_IF(!Card::init()); bRet = true; } while (0); return bRet; } string BRNNPokerCard::getCardFileName(const int nCardIdx) { if (nCardIdx < 0 && nCardIdx > BRNN_POKER_CARD_COUNT) { return ""; } char cBuf[128]; sprintf(cBuf, BRNN_POKER_CARD_FORMAT, nCardIdx); return cBuf; } /****************************BRNNPokerCard end********************************************/ /****************************BRNNHandsCard begin********************************************/ BRNNHandsCard::BRNNHandsCard(): m_eCardType(E_BRNN_CardType_Error) { memset(m_cbCardData, 0, sizeof(m_cbCardData)); } BRNNHandsCard::~BRNNHandsCard() { } void BRNNHandsCard::resetHandsCard() { for (int i = 0; i < BRNN_HANDS_CARD_COUNT; i++) { m_pPokerCard[i]->reset(); m_pPokerCard[i]->setVisible(false); } m_pCardTypeFloor->setVisible(false); m_pPokerCard[0]->setPositionY(0); m_pPokerCard[1]->setPositionY(0); memset(m_cbCardData, 0, sizeof(m_cbCardData)); m_eCardType = E_BRNN_CardType_Error; } // 初始化单张手牌 void BRNNHandsCard::initHandsCard(int nIdx, const BYTE sCardData) { m_pPokerCard[nIdx]->initCard(sCardData); m_cbCardData[nIdx] = sCardData; } // 初始化整副手牌 void BRNNHandsCard::initHandsCard(const BYTE sCardData[]) { for (int i = 0; i < BRNN_HANDS_CARD_COUNT; i++) { m_pPokerCard[i]->initCard(sCardData[i]); } memcpy(m_cbCardData, sCardData, sizeof(sCardData)); } // 展现手牌类型 void BRNNHandsCard::showCardType(E_BRNN_CardType eCardType) { switch (eCardType) { case E_BRNN_CardType_Error: return; case E_BRNN_CardType_Point: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_meiniu); break; case E_BRNN_CardType_Niu1: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu1); break; case E_BRNN_CardType_Niu2: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu2); break; case E_BRNN_CardType_Niu3: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu3); break; case E_BRNN_CardType_Niu4: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu4); break; case E_BRNN_CardType_Niu5: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu5); break; case E_BRNN_CardType_Niu6: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu6); break; case E_BRNN_CardType_Niu7: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu7); break; case E_BRNN_CardType_Niu8: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu8); break; case E_BRNN_CardType_Niu9: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niu9); break; case E_BRNN_CardType_NiuNiu: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niuniu); break; case E_BRNN_CardType_SmallNiu: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niuniu); break; case E_BRNN_CardType_BigNiu: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niuniu); break; case E_BRNN_CardType_SilverNiu: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_niuniu); break; case E_BRNN_CardType_GoldNiu: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_goldniu); break; case E_BRNN_CardType_Bomb: m_pCardType->initWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_bomb); break; default: return; } m_pCardTypeFloor->setVisible(true); } // 醒目展示手牌 void BRNNHandsCard::showCardMarkedness() { m_pPokerCard[0]->setPositionY(40); m_pPokerCard[1]->setPositionY(40); } bool BRNNHandsCard::init() { bool bRet = false; do { CC_BREAK_IF(!Node::init()); initUI(); bRet = true; } while (0); return bRet; } void BRNNHandsCard::initUI() { for (int i = 0, j = 2; i < BRNN_HANDS_CARD_COUNT; i++) { m_pPokerCard[i] = BRNNPokerCard::create(); addChild(m_pPokerCard[i]); m_pPokerCard[i]->initCard(0); m_pPokerCard[i]->setPosition(Vec2(- (j-- * 40), 0)); m_pPokerCard[i]->setVisible(false); } setContentSize(m_pPokerCard[0]->getContentSize()); m_pCardTypeFloor = Sprite::createWithSpriteFrameName(BRNNTextureName::s_brnn_card_type_floor); addChild(m_pCardTypeFloor); m_pCardTypeFloor->setPosition(Vec2(0, m_pPokerCard[0]->getContentSize().height * -0.35f)); m_pCardTypeFloor->setVisible(false); m_pCardType = Sprite::create(); m_pCardTypeFloor->addChild(m_pCardType); m_pCardType->setPosition(Vec2(m_pCardTypeFloor->getContentSize() / 2)); } /****************************BRNNHandsCard end********************************************/
[ "hanshouqing85@163.com" ]
hanshouqing85@163.com
cced2266f86e0fa7f6787ee2c2395d439ceb3a04
828913caa1ff1ef94ed1f3686ffa5b81fa090f4d
/src/tradelayer/dbfees.cpp
c92414e3156ded14cf134b6f7f1fbba1a978a69f
[ "MIT" ]
permissive
santos177/TradeLayer
7508c169f331aaa4ff7005ccc2574871428aad21
9ac9c2d47d92a9a7a0849234c3f7f8ebf7997e59
refs/heads/master
2023-02-04T00:43:26.012639
2020-12-17T22:58:42
2020-12-17T22:58:42
221,568,582
0
0
null
2020-12-17T22:58:43
2019-11-13T23:07:45
C++
UTF-8
C++
false
false
21,983
cpp
/** * @file dbfees.cpp * * This file contains code for handling Trade Layer fees. */ #include <tradelayer/dbfees.h> #include <tradelayer/log.h> #include <tradelayer/rules.h> #include <tradelayer/sp.h> #include <tradelayer/sto.h> #include <validation.h> #include <leveldb/db.h> #include <boost/algorithm/string.hpp> #include <boost/lexical_cast.hpp> #include <stdint.h> #include <limits> #include <map> #include <string> #include <vector> using namespace mastercore; std::map<uint32_t, int64_t> distributionThresholds; CTLFeeCache::CTLFeeCache(const fs::path& path, bool fWipe) { leveldb::Status status = Open(path, fWipe); PrintToConsole("Loading fee cache database: %s\n", status.ToString()); } CTLFeeCache::~CTLFeeCache() { if (msc_debug_fees) PrintToLog("CTLFeeCache closed\n"); } // Returns the distribution threshold for a property int64_t CTLFeeCache::GetDistributionThreshold(const uint32_t &propertyId) { return distributionThresholds[propertyId]; } // Sets the distribution thresholds to total tokens for a property / TL_FEE_THRESHOLD void CTLFeeCache::UpdateDistributionThresholds(uint32_t propertyId) { int64_t distributionThreshold = getTotalTokens(propertyId) / TL_FEE_THRESHOLD; if (distributionThreshold <= 0) { // protect against zero valued thresholds for low token count properties distributionThreshold = 1; } distributionThresholds[propertyId] = distributionThreshold; } // Gets the current amount of the fee cache for a property int64_t CTLFeeCache::GetCachedAmount(const uint32_t &propertyId) { assert(pdb); // Get the fee history, set is sorted by block so last entry is most recent std::set<feeCacheItem> sCacheHistoryItems = GetCacheHistory(propertyId); if (!sCacheHistoryItems.empty()) { std::set<feeCacheItem>::iterator endIt = sCacheHistoryItems.end(); --endIt; feeCacheItem mostRecentItem = *endIt; return mostRecentItem.second; } else { return 0; // property has never generated a fee } } // Zeros a property in the fee cache void CTLFeeCache::ClearCache(const uint32_t &propertyId, int block) { if (msc_debug_fees) PrintToLog("ClearCache starting (block %d, property ID %d)...\n", block, propertyId); const std::string key = strprintf("%010d", propertyId); std::set<feeCacheItem> sCacheHistoryItems = GetCacheHistory(propertyId); if (msc_debug_fees) PrintToLog(" Iterating cache history (%d items)...\n",sCacheHistoryItems.size()); std::string newValue; if (!sCacheHistoryItems.empty()) { for (std::set<feeCacheItem>::iterator it = sCacheHistoryItems.begin(); it != sCacheHistoryItems.end(); it++) { feeCacheItem tempItem = *it; if (tempItem.first == block) continue; if (!newValue.empty()) newValue += ","; newValue += strprintf("%d:%d", tempItem.first, tempItem.second); if (msc_debug_fees) PrintToLog(" Readding entry: block %d amount %d\n", tempItem.first, tempItem.second); } if (!newValue.empty()) newValue += ","; } if (msc_debug_fees) PrintToLog(" Adding zero valued entry: block %d\n", block); newValue += strprintf("%d:%d", block, 0); leveldb::Status status = pdb->Put(writeoptions, key, newValue); assert(status.ok()); ++nWritten; PruneCache(propertyId, block); if (msc_debug_fees) PrintToLog("Cleared cache for property %d block %d [%s]\n", propertyId, block, status.ToString()); } // Adds a fee to the cache (eg on a completed trade) void CTLFeeCache::AddFee(const uint32_t &propertyId, int block, const int64_t &amount) { if (msc_debug_fees) PrintToLog("Starting AddFee for prop %d (block %d amount %d)...\n", propertyId, block, amount); // Get current cached fee int64_t currentCachedAmount = GetCachedAmount(propertyId); if (msc_debug_fees) PrintToLog(" Current cached amount %d\n", currentCachedAmount); // Add new fee and rewrite record if ((currentCachedAmount > 0) && (amount > std::numeric_limits<int64_t>::max() - currentCachedAmount)) { // overflow - there is no way the fee cache should exceed the maximum possible number of tokens, not safe to continue const std::string& msg = strprintf("Shutting down due to fee cache overflow (block %d property %d current %d amount %d)\n", block, propertyId, currentCachedAmount, amount); PrintToLog(msg); if (!gArgs.GetBoolArg("-overrideforcedshutdown", false)) { fs::path persistPath = GetDataDir() / "MP_persist"; if (fs::exists(persistPath)) fs::remove_all(persistPath); // prevent the node being restarted without a reparse after forced shutdown DoAbortNode(msg, msg); } } int64_t newCachedAmount = currentCachedAmount + amount; if (msc_debug_fees) PrintToLog(" New cached amount %d\n", newCachedAmount); const std::string key = strprintf("%010d", propertyId); std::set<feeCacheItem> sCacheHistoryItems = GetCacheHistory(propertyId); if (msc_debug_fees) PrintToLog(" Iterating cache history (%d items)...\n",sCacheHistoryItems.size()); std::string newValue; if (!sCacheHistoryItems.empty()) { for (std::set<feeCacheItem>::iterator it = sCacheHistoryItems.begin(); it != sCacheHistoryItems.end(); it++) { feeCacheItem tempItem = *it; if (tempItem.first == block) continue; // this is an older entry for the same block, discard it if (!newValue.empty()) newValue += ","; newValue += strprintf("%d:%d", tempItem.first, tempItem.second); if (msc_debug_fees) PrintToLog(" Readding entry: block %d amount %d\n", tempItem.first, tempItem.second); } if (!newValue.empty()) newValue += ","; } if (msc_debug_fees) PrintToLog(" Adding requested entry: block %d new amount %d\n", block, newCachedAmount); newValue += strprintf("%d:%d", block, newCachedAmount); leveldb::Status status = pdb->Put(writeoptions, key, newValue); assert(status.ok()); ++nWritten; if (msc_debug_fees) PrintToLog("AddFee completed for property %d (new=%s [%s])\n", propertyId, newValue, status.ToString()); // Call for pruning (we only prune when we update a record) PruneCache(propertyId, block); // Call for cache evaluation (we only need to do this each time a fee cache is increased) EvalCache(propertyId, block); return; } // Rolls back the cache to an earlier state (eg in event of a reorg) - block is *inclusive* (ie entries=block will get deleted) void CTLFeeCache::RollBackCache(int block) { assert(pdb); for (uint8_t ecosystem = 1; ecosystem <= 2; ecosystem++) { uint32_t startPropertyId = (ecosystem == 1) ? 1 : TEST_ECO_PROPERTY_1; for (uint32_t propertyId = startPropertyId; propertyId < mastercore::pDbSpInfo->peekNextSPID(ecosystem); propertyId++) { const std::string key = strprintf("%010d", propertyId); std::set<feeCacheItem> sCacheHistoryItems = GetCacheHistory(propertyId); if (!sCacheHistoryItems.empty()) { std::set<feeCacheItem>::iterator mostRecentIt = sCacheHistoryItems.end(); std::string newValue; --mostRecentIt; feeCacheItem mostRecentItem = *mostRecentIt; if (mostRecentItem.first < block) continue; // all entries are unaffected by this rollback, nothing to do for (std::set<feeCacheItem>::iterator it = sCacheHistoryItems.begin(); it != sCacheHistoryItems.end(); it++) { feeCacheItem tempItem = *it; if (tempItem.first >= block) continue; // discard this entry if (!newValue.empty()) newValue += ","; newValue += strprintf("%d:%d", tempItem.first, tempItem.second); } leveldb::Status status = pdb->Put(writeoptions, key, newValue); assert(status.ok()); PrintToLog("Rolling back fee cache for property %d, new=%s [%s])\n", propertyId, newValue, status.ToString()); } } } } // Evaluates fee caches for the property against threshold and executes distribution if threshold met void CTLFeeCache::EvalCache(const uint32_t &propertyId, int block) { if (GetCachedAmount(propertyId) >= distributionThresholds[propertyId]) { DistributeCache(propertyId, block); } } // Performs distribution of fees void CTLFeeCache::DistributeCache(const uint32_t &propertyId, int block) { LOCK(cs_tally); int64_t cachedAmount = GetCachedAmount(propertyId); if (cachedAmount == 0) { PrintToLog("Aborting fee distribution for property %d, the fee cache is empty!\n", propertyId); } OwnerAddrType receiversSet; if (isTestEcosystemProperty(propertyId)) { receiversSet = STO_GetReceivers("FEEDISTRIBUTION", TL_PROPERTY_TMSC, cachedAmount); } else { receiversSet = STO_GetReceivers("FEEDISTRIBUTION", TL_PROPERTY_MSC, cachedAmount); } uint64_t numberOfReceivers = receiversSet.size(); // there will always be addresses holding TL, so no need to check size>0 PrintToLog("Starting fee distribution for property %d to %d recipients...\n", propertyId, numberOfReceivers); int64_t sent_so_far = 0; std::set<feeHistoryItem> historyItems; for (OwnerAddrType::reverse_iterator it = receiversSet.rbegin(); it != receiversSet.rend(); ++it) { const std::string& address = it->second; int64_t will_really_receive = it->first; sent_so_far += will_really_receive; if (msc_debug_fees) PrintToLog(" %s receives %d (running total %d of %d)\n", address, will_really_receive, sent_so_far, cachedAmount); assert(update_tally_map(address, propertyId, will_really_receive, BALANCE)); feeHistoryItem recipient(address, will_really_receive); historyItems.insert(recipient); } PrintToLog("Fee distribution completed, distributed %d out of %d\n", sent_so_far, cachedAmount); // store the fee distribution pDbFeeHistory->RecordFeeDistribution(propertyId, block, sent_so_far, historyItems); // final check to ensure the entire fee cache was distributed, then empty the cache assert(sent_so_far == cachedAmount); ClearCache(propertyId, block); } // Prunes entries over MAX_STATE_HISTORY blocks old from the entry for a property void CTLFeeCache::PruneCache(const uint32_t &propertyId, int block) { if (msc_debug_fees) PrintToLog("Starting PruneCache for prop %d block %d...\n", propertyId, block); assert(pdb); int pruneBlock = block - MAX_STATE_HISTORY; if (msc_debug_fees) PrintToLog("Removing entries prior to block %d...\n", pruneBlock); const std::string key = strprintf("%010d", propertyId); std::set<feeCacheItem> sCacheHistoryItems = GetCacheHistory(propertyId); if (msc_debug_fees) PrintToLog(" Iterating cache history (%d items)...\n",sCacheHistoryItems.size()); if (!sCacheHistoryItems.empty()) { std::set<feeCacheItem>::iterator startIt = sCacheHistoryItems.begin(); feeCacheItem firstItem = *startIt; if (firstItem.first >= pruneBlock) { if (msc_debug_fees) PrintToLog("Endingg PruneCache - no matured entries found.\n"); return; // all entries are above supplied block value, nothing to do } std::string newValue; for (std::set<feeCacheItem>::iterator it = sCacheHistoryItems.begin(); it != sCacheHistoryItems.end(); it++) { feeCacheItem tempItem = *it; if (tempItem.first < pruneBlock) { if (msc_debug_fees) { PrintToLog(" Skipping matured entry: block %d amount %d\n", tempItem.first, tempItem.second); continue; // discard this entry } } if (!newValue.empty()) newValue += ","; newValue += strprintf("%d:%d", tempItem.first, tempItem.second); if (msc_debug_fees) PrintToLog(" Readding immature entry: block %d amount %d\n", tempItem.first, tempItem.second); } // make sure the pruned cache isn't completely empty, if it is, prune down to just the most recent entry if (newValue.empty()) { std::set<feeCacheItem>::iterator mostRecentIt = sCacheHistoryItems.end(); --mostRecentIt; feeCacheItem mostRecentItem = *mostRecentIt; newValue = strprintf("%d:%d", mostRecentItem.first, mostRecentItem.second); if (msc_debug_fees) PrintToLog(" All entries matured and pruned - readding most recent entry: block %d amount %d\n", mostRecentItem.first, mostRecentItem.second); } leveldb::Status status = pdb->Put(writeoptions, key, newValue); assert(status.ok()); if (msc_debug_fees) PrintToLog("PruneCache completed for property %d (new=%s [%s])\n", propertyId, newValue, status.ToString()); } else { return; // nothing to do } } // Show Fee Cache DB statistics void CTLFeeCache::printStats() { PrintToConsole("CTLFeeCache stats: nWritten= %d , nRead= %d\n", nWritten, nRead); } // Show Fee Cache DB records void CTLFeeCache::printAll() { int count = 0; leveldb::Iterator* it = NewIterator(); for(it->SeekToFirst(); it->Valid(); it->Next()) { ++count; PrintToConsole("entry #%8d= %s:%s\n", count, it->key().ToString(), it->value().ToString()); } delete it; } // Return a set containing fee cache history items std::set<feeCacheItem> CTLFeeCache::GetCacheHistory(const uint32_t &propertyId) { assert(pdb); const std::string key = strprintf("%010d", propertyId); std::set<feeCacheItem> sCacheHistoryItems; std::string strValue; leveldb::Status status = pdb->Get(readoptions, key, &strValue); if (status.IsNotFound()) { return sCacheHistoryItems; // no cache, return empty set } assert(status.ok()); std::vector<std::string> vCacheHistoryItems; boost::split(vCacheHistoryItems, strValue, boost::is_any_of(","), boost::token_compress_on); for (std::vector<std::string>::iterator it = vCacheHistoryItems.begin(); it != vCacheHistoryItems.end(); ++it) { std::vector<std::string> vCacheHistoryItem; boost::split(vCacheHistoryItem, *it, boost::is_any_of(":"), boost::token_compress_on); if (2 != vCacheHistoryItem.size()) { PrintToConsole("ERROR: vCacheHistoryItem has unexpected number of elements: %d (raw %s)!\n", vCacheHistoryItem.size(), *it); printAll(); continue; } int64_t cacheItemBlock = boost::lexical_cast<int64_t>(vCacheHistoryItem[0]); int64_t cacheItemAmount = boost::lexical_cast<int64_t>(vCacheHistoryItem[1]); sCacheHistoryItems.insert(std::make_pair(cacheItemBlock, cacheItemAmount)); } return sCacheHistoryItems; } CTLFeeHistory::CTLFeeHistory(const fs::path& path, bool fWipe) { leveldb::Status status = Open(path, fWipe); PrintToConsole("Loading fee history database: %s\n", status.ToString()); } CTLFeeHistory::~CTLFeeHistory() { if (msc_debug_fees) PrintToLog("CTLFeeHistory closed\n"); } // Show Fee History DB statistics void CTLFeeHistory::printStats() { PrintToConsole("CTLFeeHistory stats: nWritten= %d , nRead= %d\n", nWritten, nRead); } // Show Fee History DB records void CTLFeeHistory::printAll() { int count = 0; leveldb::Iterator* it = NewIterator(); for(it->SeekToFirst(); it->Valid(); it->Next()) { ++count; PrintToConsole("entry #%8d= %s-%s\n", count, it->key().ToString(), it->value().ToString()); PrintToLog("entry #%8d= %s-%s\n", count, it->key().ToString(), it->value().ToString()); } delete it; } // Count Fee History DB records int CTLFeeHistory::CountRecords() { // No faster way to count than to iterate - "There is no way to implement Count more efficiently inside leveldb than outside." int count = 0; leveldb::Iterator* it = NewIterator(); for(it->SeekToFirst(); it->Valid(); it->Next()) { ++count; } delete it; return count; } // Roll back history in event of reorg, block is inclusive void CTLFeeHistory::RollBackHistory(int block) { assert(pdb); std::set<int> sDistributions; leveldb::Iterator* it = NewIterator(); for (it->SeekToFirst(); it->Valid(); it->Next()) { std::string strValue = it->value().ToString(); std::string strKey = it->key().ToString(); std::vector<std::string> vFeeHistoryDetail; boost::split(vFeeHistoryDetail, strValue, boost::is_any_of(":"), boost::token_compress_on); if (4 != vFeeHistoryDetail.size()) { PrintToLog("ERROR: vFeeHistoryDetail has unexpected number of elements: %d !\n", vFeeHistoryDetail.size()); continue; // bad data } int feeBlock = boost::lexical_cast<int>(vFeeHistoryDetail[0]); if (feeBlock >= block) { PrintToLog("%s() deleting from fee history DB: %s %s\n", __FUNCTION__, strKey, strValue); pdb->Delete(writeoptions, strKey); } } delete it; } // Retrieve fee distributions for a property std::set<int> CTLFeeHistory::GetDistributionsForProperty(const uint32_t &propertyId) { assert(pdb); std::set<int> sDistributions; leveldb::Iterator* it = NewIterator(); for (it->SeekToFirst(); it->Valid(); it->Next()) { std::string strValue = it->value().ToString(); std::vector<std::string> vFeeHistoryDetail; boost::split(vFeeHistoryDetail, strValue, boost::is_any_of(":"), boost::token_compress_on); if (4 != vFeeHistoryDetail.size()) { PrintToConsole("ERROR: vFeeHistoryDetail has unexpected number of elements: %d !\n", vFeeHistoryDetail.size()); printAll(); continue; // bad data } uint32_t prop = boost::lexical_cast<uint32_t>(vFeeHistoryDetail[1]); if (prop == propertyId) { std::string key = it->key().ToString(); int id = boost::lexical_cast<int>(key); sDistributions.insert(id); } } delete it; return sDistributions; } // Populate data about a fee distribution bool CTLFeeHistory::GetDistributionData(int id, uint32_t *propertyId, int *block, int64_t *total) { assert(pdb); const std::string key = strprintf("%d", id); std::string strValue; leveldb::Status status = pdb->Get(readoptions, key, &strValue); if (status.IsNotFound()) { return false; // fee distribution not found } assert(status.ok()); std::vector<std::string> vFeeHistoryDetail; boost::split(vFeeHistoryDetail, strValue, boost::is_any_of(":"), boost::token_compress_on); if (4 != vFeeHistoryDetail.size()) { PrintToConsole("ERROR: vFeeHistoryDetail has unexpected number of elements: %d !\n", vFeeHistoryDetail.size()); printAll(); return false; // bad data } *block = boost::lexical_cast<int>(vFeeHistoryDetail[0]); *propertyId = boost::lexical_cast<uint32_t>(vFeeHistoryDetail[1]); *total = boost::lexical_cast<int64_t>(vFeeHistoryDetail[2]); return true; } // Retrieve the recipients for a fee distribution std::set<feeHistoryItem> CTLFeeHistory::GetFeeDistribution(int id) { assert(pdb); const std::string key = strprintf("%d", id); std::set<feeHistoryItem> sFeeHistoryItems; std::string strValue; leveldb::Status status = pdb->Get(readoptions, key, &strValue); if (status.IsNotFound()) { return sFeeHistoryItems; // fee distribution not found, return empty set } assert(status.ok()); std::vector<std::string> vFeeHistoryDetail; boost::split(vFeeHistoryDetail, strValue, boost::is_any_of(":"), boost::token_compress_on); if (4 != vFeeHistoryDetail.size()) { PrintToConsole("ERROR: vFeeHistoryDetail has unexpected number of elements: %d !\n", vFeeHistoryDetail.size()); printAll(); return sFeeHistoryItems; // bad data, return empty set } std::vector<std::string> vFeeHistoryItems; boost::split(vFeeHistoryItems, vFeeHistoryDetail[3], boost::is_any_of(","), boost::token_compress_on); for (std::vector<std::string>::iterator it = vFeeHistoryItems.begin(); it != vFeeHistoryItems.end(); ++it) { std::vector<std::string> vFeeHistoryItem; boost::split(vFeeHistoryItem, *it, boost::is_any_of("="), boost::token_compress_on); if (2 != vFeeHistoryItem.size()) { PrintToConsole("ERROR: vFeeHistoryItem has unexpected number of elements: %d (raw %s)!\n", vFeeHistoryItem.size(), *it); printAll(); continue; } int64_t feeHistoryItemAmount = boost::lexical_cast<int64_t>(vFeeHistoryItem[1]); sFeeHistoryItems.insert(std::make_pair(vFeeHistoryItem[0], feeHistoryItemAmount)); } return sFeeHistoryItems; } // Record a fee distribution void CTLFeeHistory::RecordFeeDistribution(const uint32_t &propertyId, int block, int64_t total, std::set<feeHistoryItem> feeRecipients) { assert(pdb); int count = CountRecords() + 1; std::string key = strprintf("%d", count); std::string feeRecipientsStr; if (!feeRecipients.empty()) { for (std::set<feeHistoryItem>::iterator it = feeRecipients.begin(); it != feeRecipients.end(); it++) { feeHistoryItem tempRecipient = *it; feeRecipientsStr += strprintf("%s=%d,", tempRecipient.first, tempRecipient.second); } if (feeRecipientsStr.size() > 0) { feeRecipientsStr.resize(feeRecipientsStr.size() - 1); } } std::string value = strprintf("%d:%d:%d:%s", block, propertyId, total, feeRecipientsStr); leveldb::Status status = pdb->Put(writeoptions, key, value); if (msc_debug_fees) PrintToLog("Added fee distribution to feeCacheHistory - key=%s value=%s [%s]\n", key, value, status.ToString()); }
[ "santos177@gmail.com" ]
santos177@gmail.com
91915e542cde6cfbbf4ade387300f68bf8ac160d
8f66f52d8644b277c98c19a29558bbd05da12807
/arrayMaximalAdjacentDifference/main.cpp
7ffef6e68eab04461a594d4d8f18de9a230e6581
[]
no_license
agrochal/CodeSignal-solutions
e8b9c7c70b523aaff621aad96a7a9b718a99da6d
decbc6d77e063ccd6f6eff257226c238b43258df
refs/heads/master
2022-11-11T16:51:33.678405
2020-06-24T10:39:31
2020-06-24T10:39:31
272,770,676
0
0
null
null
null
null
UTF-8
C++
false
false
226
cpp
int arrayMaximalAdjacentDifference(std::vector<int> inputArray) { int res = -10000000; for(int i=1;i<inputArray.size();i++){ res = max(res, abs(inputArray[i] - inputArray[i-1])); } return res; }
[ "artur@procer.pl" ]
artur@procer.pl
97527b369847ba01ea67958eafe385a189f8b5a8
d22799f4ee746cc5dde14d1055981206c14c1e2c
/libs/libride/data/compileutils.h
25f27457d597b96fd41437ba4758e922467b7e4f
[ "MIT" ]
permissive
standardgalactic/ride
eb6489eceb3bf406f84dd17d9204572827e9f4dc
040f78ce2a03ffe3da5772b76b4dd500d1e7187f
refs/heads/master
2023-08-29T06:06:40.983810
2021-10-12T22:09:27
2021-10-12T22:09:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
322
h
// Copyright (2015) Gustav #ifndef RIDE_COMPILEUTILS_H_ #define RIDE_COMPILEUTILS_H_ #include <ride/wx.h> #include "ride/settings.h" class MainWindow; void CompileProtoFile(const ride::MachineSettings& machine, const wxString& filename, MainWindow* main_window); #endif // RIDE_COMPILEUTILS_H_
[ "sir.gustav.the.coder@gmail.com" ]
sir.gustav.the.coder@gmail.com
ac3661bbcd3b25277eb3a75f0352e6f8741dec3f
9467e2502183e843a67736800199e31674b1d8f6
/HybridCLRData/LocalIl2CppData-OSXEditor/il2cpp/libil2cpp/os/Win32/MarshalAlloc.cpp
46995d62feae5792613adaec1d3662e1dcabd576
[ "Apache-2.0" ]
permissive
yimengfan/BDFramework.Core
3a046fcd755a84ba55d648dd3ad52c37a1cc1a04
81380fce8e84367f912777717665b53f074ab617
refs/heads/master
2023-09-04T10:08:47.644992
2023-07-05T16:22:11
2023-07-05T16:22:11
85,928,537
2,421
497
Apache-2.0
2023-03-21T06:56:21
2017-03-23T09:03:48
C#
UTF-8
C++
false
false
901
cpp
#include "il2cpp-config.h" #if IL2CPP_TARGET_WINDOWS && !(IL2CPP_TARGET_WINRT || IL2CPP_TARGET_XBOXONE) #include "os/MarshalAlloc.h" #include "WindowsHeaders.h" #include "Objbase.h" namespace il2cpp { namespace os { void* MarshalAlloc::Allocate(size_t size) { return ::CoTaskMemAlloc(size); } void* MarshalAlloc::ReAlloc(void* ptr, size_t size) { return ::CoTaskMemRealloc(ptr, size); } void MarshalAlloc::Free(void* ptr) { ::CoTaskMemFree(ptr); } void* MarshalAlloc::AllocateHGlobal(size_t size) { return ::GlobalAlloc(GMEM_FIXED, size); } void* MarshalAlloc::ReAllocHGlobal(void* ptr, size_t size) { return ::GlobalReAlloc(ptr, size, GMEM_MOVEABLE); } void MarshalAlloc::FreeHGlobal(void* ptr) { ::GlobalFree(ptr); } } /* namespace os */ } /* namespace il2cpp*/ #endif
[ "y755737878@gmail.com" ]
y755737878@gmail.com
6debd47f1eeb8d51378925e4145672f43264bcbf
a318a144db0b0b22407efd07f91085e33eab7e2b
/mono_inertial_mbot.cc
3f02268e99a5b74a6810a81d4091984912a46691
[]
no_license
youngbend/eecs467-a3
3bcf08ad931b358fd357b78d959b392736877e90
780f079ec63d677ade98aa59ee17d1ef25599030
refs/heads/master
2022-12-28T12:32:39.701175
2020-10-19T17:37:43
2020-10-19T17:37:43
304,698,607
0
1
null
null
null
null
UTF-8
C++
false
false
2,746
cc
/** * This file is part of ORB-SLAM3 * * Copyright (C) 2017-2020 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza. * Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza. * * ORB-SLAM3 is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ORB-SLAM3 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with ORB-SLAM3. * If not, see <http://www.gnu.org/licenses/>. */ #include<iostream> #include<algorithm> #include<fstream> #include<chrono> #include<opencv2/core/core.hpp> #include<System.h> #include <lcm/lcm-cpp.hpp> #include "lcmtypes/image_t.hpp" #include "lcmtypes/mbot_imu_t.hpp" using namespace std; vector<ORB_SLAM3::IMU::Point> IMU_Data; double start_time; class Image_Handler { private: ORB_SLAM3::System SLAM; public: Image_Handler(const char* vocab_path, const char* settings_path) : SLAM(vocab_path, settings_path, ORB_SLAM3::System::MONOCULAR, true) {} void handleMessage(const lcm::ReceiveBuffer* rbuf, const std::string &chan, const image_t* msg) { if (start_time == -1) start_time = (double)msg->utime / 1.0e9; cv::Mat data_mat(msg->data, true); cv::Mat im(cv::imdecode(data_mat,0)); SLAM.TrackMonocular(im, (double)msg->utime / 1.0e9 - start_time, IMU_Data); IMU_Data.clear(); } ~Image_Handler() { SLAM.Shutdown(); } }; class IMU_Handler { public: ~IMU_Handler() {} void handleMessage(const lcm::ReceiveBuffer* rbuf, const std::string &chan, const mbot_imu_t* msg) { if (start_time == -1) start_time = (double)msg->utime / 1.0e9; IMU_Data.push_back(ORB_SLAM3::IMU::Point(msg->accel[0], msg->accel[1], msg->accel[2], msg->gyro[0], msg->gyro[1], msg->gyro[2], (double)msg->utime / 1.0e9 - start_time)); } }; int main(int argc, char **argv) { if(argc < 3) { cerr << endl << "Usage: ./mono_mbot_stream path_to_vocabulary path_to_settings" << endl; return 1; } lcm::LCM lcm; if (!lcm.good()) { return 1; } start_time = -1; Image_Handler imhandle(argv[1],argv[2]); IMU_Handler imuhandle; lcm.subscribe("MBOT_IMAGE_STREAM", &Image_Handler::handleMessage, &imhandle); lcm.subscribe("MBOT_IMU", &IMU_Handler::handleMessage, &imuhandle); while(lcm.handle() == 0); return 0; }
[ "youngben@umich.edu" ]
youngben@umich.edu