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
8073d7e2f397de324a4bb679bb075c9581fdb16c
c84bf73d4181b66ce1a2a714b64150c922d3f835
/TacticsEngine/ECS/System/PhysicsSystem.cpp
f2e1f7328983a678f39595cd04b9b87cd7abf768
[]
no_license
curtiscovington/TacticsEngine
803f736f7cb6732ad1578d98f3b45a1cf295eeb4
0d03a9b55d0da16d9eb689cf9b43a3829e211841
refs/heads/master
2021-01-17T16:22:55.529402
2016-07-07T18:54:59
2016-07-07T18:54:59
62,830,803
0
0
null
null
null
null
UTF-8
C++
false
false
8,911
cpp
// // PhysicsSystem.cpp // TacticsEngine // // Created by Curtis Covington on 2/2/16. // Copyright © 2016 Curtis Covington. All rights reserved. // #include "PhysicsSystem.h" #include <algorithm> #include "Entity.h" #include "Component.h" #include <glm/vec2.hpp> #include <memory> namespace TacticsEngine { void PhysicsSystem::init() { } void PhysicsSystem::update(float dt) { // Implement a fixed timestep float total = 0.0f; while (total < dt) { float ts = std::min(dt-total, TIME_STEP); step(ts); total += ts; } } void PhysicsSystem::step(float ts) { for (int i = 0; i < m_entities.size(); i++) { PhysicsComponent* phys = m_entities[i]->getComponent<PhysicsComponent>(); PositionComponent* pos = m_entities[i]->getComponent<PositionComponent>(); applyForce(m_entities[i], 5.0f * glm::vec2(0, -1.0f) * ts); // phys->velocity += glm::vec2(0, -0.1f) * ts; if (!phys->isStatic) { if (m_entities[i]->hasComponent(Component::getComponentBitmask<CollisionComponent>())) { glm::vec2 newPos = pos->pos + phys->velocity; handleCollisions(getCollisions(newPos, m_entities[i])); } else { pos->pos += phys->velocity * ts; } } } } void PhysicsSystem::applyForce(Entity* e, const glm::vec2& force) { if (!e->getComponent<PhysicsComponent>()->isStatic) { e->getComponent<PhysicsComponent>()->velocity += force; } } void PhysicsSystem::handleCollisions(const CollisionList& list) { if (list.hasCollisions()) { for (int i = 0; i < list.collisions.size(); i++) { handleCollision(list.e, list.pos, list.collisions[i]); } } else { list.e->getComponent<PositionComponent>()->pos = list.pos; } } void PhysicsSystem::handleCollision(Entity* e, const glm::vec2& pos, const Collision& collision) { switch (collision.type) { case CollisionType::WORLD_BORDER: //e->getComponent<PositionComponent>()->pos = pos - collision.pos; //e->getComponent<PhysicsComponent>()->velocity -= e->getComponent<PhysicsComponent>()->velocity * 0.04f; //e->getComponent<PhysicsComponent>()->velocity = -0.9f * e->getComponent<PhysicsComponent>()->velocity; break; case CollisionType::ENTITY: e->getComponent<PositionComponent>()->pos -= collision.pos; e->getComponent<PhysicsComponent>()->velocity = glm::vec2(0,0); // e->getComponent<PhysicsComponent>()->velocity = e->getComponent<PhysicsComponent>()->velocity * 0.5f; // e->getComponent<PhysicsComponent>()->velocity = -0.5f * e->getComponent<PhysicsComponent>()->velocity; //collision.e->getComponent<PositionComponent>()->pos = pos - collision.pos; //e->getComponent<PhysicsComponent>()->velocity -= e->getComponent<PhysicsComponent>()->velocity * 0.04f; //collision.e->getComponent<PhysicsComponent>()->velocity = -0.5f * e->getComponent<PhysicsComponent>()->velocity; break; default: break; } } // This needs to be refactored out into a collision system CollisionList PhysicsSystem::getCollisions(const glm::vec2& pos, Entity* e) { CollisionList list; list.e = e; list.pos = pos; CollisionComponent* c = e->getComponent<CollisionComponent>(); // if (c->isRect()) { // float x = 0; // float y = 0; // // if (pos.x - c->rect.width/2 < -1.0) { // x = (pos.x - c->rect.width/2) + 1; // list.collisions.emplace_back(CollisionType::WORLD_BORDER, glm::vec2(x, y) ); // } else if (pos.x + c->rect.width/2 > 1.0) { // x = (pos.x + c->rect.width/2) - 1; // list.collisions.emplace_back(CollisionType::WORLD_BORDER, glm::vec2(x, y) ); // } // if (pos.y - c->rect.height/2 < -1.0) { // y = (pos.y - c->rect.height/2) + 1; // list.collisions.emplace_back(CollisionType::WORLD_BORDER, glm::vec2(x, y) ); // } else if (pos.y + c->rect.width/2 > 1.0) { // y = (pos.y + c->rect.height/2) - 1; // list.collisions.emplace_back(CollisionType::WORLD_BORDER, glm::vec2(x, y) ); // } // // if (x > 0 || y > 0) { // // } // // } else { // // } for (int i = 0; i < m_entities.size(); i++) { if (e->getID() != m_entities[i]->getID()) { float left = pos.x - e->getComponent<CollisionComponent>()->rect.width/2; // Right float right = pos.x + e->getComponent<CollisionComponent>()->rect.width/2; if (isColliding(right, m_entities[i]->getComponent<PositionComponent>()->pos.x - m_entities[i]->getComponent<CollisionComponent>()->rect.width/2 , right, m_entities[i]->getComponent<PositionComponent>()->pos.x +m_entities[i]->getComponent<CollisionComponent>()->rect.width/2 )) { if (isColliding(pos.y - e->getComponent<CollisionComponent>()->rect.height/2, m_entities[i]->getComponent<PositionComponent>()->pos.y - m_entities[i]->getComponent<CollisionComponent>()->rect.height/2 , pos.y - e->getComponent<CollisionComponent>()->rect.height/2, m_entities[i]->getComponent<PositionComponent>()->pos.y + m_entities[i]->getComponent<CollisionComponent>()->rect.height/2 )) { list.collisions.emplace_back(CollisionType::ENTITY,e); } else if (isColliding(pos.y + e->getComponent<CollisionComponent>()->rect.height/2, m_entities[i]->getComponent<PositionComponent>()->pos.y - m_entities[i]->getComponent<CollisionComponent>()->rect.height/2 , pos.y + e->getComponent<CollisionComponent>()->rect.height/2, m_entities[i]->getComponent<PositionComponent>()->pos.y + m_entities[i]->getComponent<CollisionComponent>()->rect.height/2 )) { list.collisions.emplace_back(CollisionType::ENTITY,e); } } else if (isColliding(left, m_entities[i]->getComponent<PositionComponent>()->pos.x - m_entities[i]->getComponent<CollisionComponent>()->rect.width/2 , left, m_entities[i]->getComponent<PositionComponent>()->pos.x +m_entities[i]->getComponent<CollisionComponent>()->rect.width/2 )) { if (isColliding(pos.y - e->getComponent<CollisionComponent>()->rect.height/2, m_entities[i]->getComponent<PositionComponent>()->pos.y - m_entities[i]->getComponent<CollisionComponent>()->rect.height/2 , pos.y - e->getComponent<CollisionComponent>()->rect.height/2, m_entities[i]->getComponent<PositionComponent>()->pos.y + m_entities[i]->getComponent<CollisionComponent>()->rect.height/2 )) { list.collisions.emplace_back(CollisionType::ENTITY,e); } else if (isColliding(pos.y + e->getComponent<CollisionComponent>()->rect.height/2, m_entities[i]->getComponent<PositionComponent>()->pos.y - m_entities[i]->getComponent<CollisionComponent>()->rect.height/2 , pos.y + e->getComponent<CollisionComponent>()->rect.height/2, m_entities[i]->getComponent<PositionComponent>()->pos.y + m_entities[i]->getComponent<CollisionComponent>()->rect.height/2 )) { list.collisions.emplace_back(CollisionType::ENTITY,e); } } } } return list; } bool PhysicsSystem::isColliding(const float a1, const float b1, const float a2, const float b2) const { return (a1 >= b1 && a2 <= b2); } }
[ "curtis.covington@gmail.com" ]
curtis.covington@gmail.com
1bdff5d203659dbbd67c359da39beac39477abce
5791b78c64fc4076330af128b950e5cc544e333b
/windows/pw6e.official/CPlusPlus/Chapter14/CircularGradient/CircularGradient/App.xaml.h
6f59f9f663c215185e14a3477d28def760b7bbf6
[ "MIT" ]
permissive
nnaabbcc/exercise
509e2c63389fec768ca07153844b71b864d63a20
b7ebb55adf9a75ed223555128d77e0f2548450b5
refs/heads/master
2023-02-26T07:52:40.093958
2023-02-22T01:12:56
2023-02-22T01:12:56
55,337,514
1
1
null
null
null
null
UTF-8
C++
false
false
569
h
// // App.xaml.h // Declaration of the App class. // #pragma once #include "App.g.h" namespace CircularGradient { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> ref class App sealed { public: App(); virtual void OnLaunched(Windows::ApplicationModel::Activation::LaunchActivatedEventArgs^ pArgs) override; private: void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ e); }; }
[ "nnaabbcc.zhao@gmail.com" ]
nnaabbcc.zhao@gmail.com
1073fb66c98d2146fa4d688f4618e75b5bbd11ad
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/chrome/browser/policy/messaging_layer/storage/storage_module.cc
ef86568ab826b483a3bce4d6c85b1ed6306bb2e9
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
2,267
cc
// Copyright 2020 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 <memory> #include <utility> #include "base/bind.h" #include "base/callback.h" #include "base/containers/span.h" #include "base/memory/ptr_util.h" #include "chrome/browser/policy/messaging_layer/storage/storage.h" #include "chrome/browser/policy/messaging_layer/storage/storage_module.h" #include "chrome/browser/policy/messaging_layer/util/status.h" #include "chrome/browser/policy/messaging_layer/util/statusor.h" #include "components/policy/proto/record.pb.h" #include "components/policy/proto/record_constants.pb.h" namespace reporting { StorageModule::StorageModule() = default; StorageModule::~StorageModule() = default; void StorageModule::AddRecord(reporting::EncryptedRecord record, reporting::Priority priority, base::OnceCallback<void(Status)> callback) { size_t record_size = record.ByteSizeLong(); auto data = std::make_unique<uint8_t[]>(record_size); record.SerializeToArray(data.get(), record_size); storage_->Write(priority, base::make_span(data.get(), record_size), std::move(callback)); } // static void StorageModule::Create( const Storage::Options& options, Storage::StartUploadCb start_upload_cb, base::OnceCallback<void(StatusOr<scoped_refptr<StorageModule>>)> callback) { scoped_refptr<StorageModule> instance = // Cannot base::MakeRefCounted, since constructor is protected. base::WrapRefCounted(new StorageModule()); Storage::Create( options, start_upload_cb, base::BindOnce( [](scoped_refptr<StorageModule> instance, base::OnceCallback<void(StatusOr<scoped_refptr<StorageModule>>)> callback, StatusOr<scoped_refptr<Storage>> storage) { if (!storage.ok()) { std::move(callback).Run(storage.status()); return; } instance->storage_ = std::move(storage.ValueOrDie()); std::move(callback).Run(std::move(instance)); }, std::move(instance), std::move(callback))); } } // namespace reporting
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
dacd2dcc46ecc39d89d5c946f932124612049597
60bb67415a192d0c421719de7822c1819d5ba7ac
/blazetest/src/mathtest/dmatdmatschur/MDbM16x8b.cpp
6971fb8661cf423c21c831b0887f9f1d00c0e31a
[ "BSD-3-Clause" ]
permissive
rtohid/blaze
48decd51395d912730add9bc0d19e617ecae8624
7852d9e22aeb89b907cb878c28d6ca75e5528431
refs/heads/master
2020-04-16T16:48:03.915504
2018-12-19T20:29:42
2018-12-19T20:29:42
165,750,036
0
0
null
null
null
null
UTF-8
C++
false
false
3,703
cpp
//================================================================================================= /*! // \file src/mathtest/dmatdmatschur/MDbM16x8b.cpp // \brief Source file for the MDbM16x8b dense matrix/dense matrix Schur product math test // // Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved // // This file is part of the Blaze library. You can redistribute it and/or modify it under // the terms of the New (Revised) BSD License. Redistribution and use in source and binary // forms, with or without modification, are permitted provided that the following conditions // are met: // // 1. Redistributions of source code must retain the above copyright notice, this list of // conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, this list // of conditions and the following disclaimer in the documentation and/or other materials // provided with the distribution. // 3. Neither the names of the Blaze development group nor the names of its contributors // may be used to endorse or promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT // SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED // TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR // BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH // DAMAGE. */ //================================================================================================= //************************************************************************************************* // Includes //************************************************************************************************* #include <cstdlib> #include <iostream> #include <blaze/math/DynamicMatrix.h> #include <blaze/math/StaticMatrix.h> #include <blazetest/mathtest/Creator.h> #include <blazetest/mathtest/dmatdmatschur/OperationTest.h> #include <blazetest/system/MathTest.h> //================================================================================================= // // MAIN FUNCTION // //================================================================================================= //************************************************************************************************* int main() { std::cout << " Running 'MDbM16x8b'..." << std::endl; using blazetest::mathtest::TypeB; try { // Matrix type definitions using MDb = blaze::DynamicMatrix<TypeB>; using M16x8b = blaze::StaticMatrix<TypeB,16UL,8UL>; // Creator type definitions using CMDb = blazetest::Creator<MDb>; using CM16x8b = blazetest::Creator<M16x8b>; // Running the tests RUN_DMATDMATSCHUR_OPERATION_TEST( CMDb( 16UL, 8UL ), CM16x8b() ); } catch( std::exception& ex ) { std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix Schur product:\n" << ex.what() << "\n"; return EXIT_FAILURE; } return EXIT_SUCCESS; } //*************************************************************************************************
[ "klaus.iglberger@gmail.com" ]
klaus.iglberger@gmail.com
170854b6c7ad8dab7fabb4d9db2c9508648b12e2
de16c9f7872b7bf41a1a36a01af8231d867e098e
/백준_알고리즘/10987_모음의_개수.cpp
0821501cf690395660dde1e9ce2462d3cbea335a
[]
no_license
Sunghee2/Algorithm
8dee32559f54d67cb465aeeb9a5d7de5980321d1
ae1ddac8232ea5e90d6917a9eab3ecfb14633232
refs/heads/master
2023-04-03T11:02:47.655978
2023-04-01T06:42:29
2023-04-01T06:42:29
166,176,789
1
0
null
null
null
null
UTF-8
C++
false
false
298
cpp
#include <iostream> #include <string> using namespace std; string str; int main() { cin >> str; int cnt = 0; for(int i = 0; i < str.length(); i++) { if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u') cnt++; } printf("%d\n", cnt); }
[ "630sunghee@gmail.com" ]
630sunghee@gmail.com
56c69d9790a1878b9fe17a306d1c9f6c975e2370
ad273708d98b1f73b3855cc4317bca2e56456d15
/aws-cpp-sdk-networkmanager/include/aws/networkmanager/model/DeviceState.h
ba1f5979c04e3129cbf8c1c147f225a62b1b3478
[ "MIT", "Apache-2.0", "JSON" ]
permissive
novaquark/aws-sdk-cpp
b390f2e29f86f629f9efcf41c4990169b91f4f47
a0969508545bec9ae2864c9e1e2bb9aff109f90c
refs/heads/master
2022-08-28T18:28:12.742810
2020-05-27T15:46:18
2020-05-27T15:46:18
267,351,721
1
0
Apache-2.0
2020-05-27T15:08:16
2020-05-27T15:08:15
null
UTF-8
C++
false
false
1,152
h
/* * 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. */ #pragma once #include <aws/networkmanager/NetworkManager_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace NetworkManager { namespace Model { enum class DeviceState { NOT_SET, PENDING, AVAILABLE, DELETING, UPDATING }; namespace DeviceStateMapper { AWS_NETWORKMANAGER_API DeviceState GetDeviceStateForName(const Aws::String& name); AWS_NETWORKMANAGER_API Aws::String GetNameForDeviceState(DeviceState value); } // namespace DeviceStateMapper } // namespace Model } // namespace NetworkManager } // namespace Aws
[ "aws-sdk-cpp-automation@github.com" ]
aws-sdk-cpp-automation@github.com
9a33df6604ba65b070e93280c2a8f942889aaa90
105345916a8d66b3ed341af28bcdaec807e3cc88
/src/vkg/render/model/shadow_map.cpp
33de90d1573b9151a3032a474c3a3f08166c619f
[ "MIT" ]
permissive
wumo/vkg
426de10ff3b12f29735619bc3d8c9a7170f81263
3318a4730fd5d9e069717745b419ba5f1aeb095a
refs/heads/master
2023-03-10T16:16:32.260933
2021-02-21T02:03:50
2021-02-21T02:03:50
282,849,334
5
0
null
null
null
null
UTF-8
C++
false
false
660
cpp
#include "shadow_map.hpp" namespace vkg { auto ShadowMapSetting::isEnabled() const -> bool { return enabled_; } auto ShadowMapSetting::enable(bool enabled) -> void { enabled_ = enabled; } auto ShadowMapSetting::numCascades() const -> uint32_t { return numCascades_; } void ShadowMapSetting::setNumCascades(uint32_t numCascades) { numCascades_ = numCascades; } auto ShadowMapSetting::textureSize() const -> uint32_t { return textureSize_; } void ShadowMapSetting::setTextureSize(uint32_t textureSize) { textureSize_ = textureSize; } auto ShadowMapSetting::zFar() const -> float { return zfar_; } void ShadowMapSetting::setZFar(float far) { zfar_ = far; } }
[ "wumo@outlook.com" ]
wumo@outlook.com
6ce46225d9a44d14b9f4b49c4019be5b8d25810d
06bd2b6fd35381452cd321382e6549475c48c7a0
/알고리즘 준비 9월/역사_1613.cpp
18e52f75a140050b87b76c4c925d194d89f6dceb
[]
no_license
toywwy/9M_algorithm
188f667a147346e0182e8658f8d9d6a2430bc80a
890822ec7662e3720f7b1ef248daaa5cdc98c105
refs/heads/master
2021-01-18T00:43:34.523529
2019-05-10T16:45:20
2019-05-10T16:45:20
68,367,712
0
0
null
null
null
null
UHC
C++
false
false
1,745
cpp
/* DFS 메모이제이션 실패 문제 : 역사 문제 번호: 1613 풀이법 : DFS, 메모이제이션 날짜 : 161011 기타 : 실패함.. DFS에 캐싱을 썼는데 실패했다. 왜냐하면 1->2->3->4->6 까지 캐싱을했다. x->1 ->6 으로되는것이다. but 1->2->3->4->6->7 x->7을 찾아갈땐 [1][7] 이 아직 탐색이 안됐기 떄문에 가지를 못했따. 결국 다시 저 경로를 탐색하면서 가는 문제가 발생... + 그리고 추가해야하는게 있었다. -1 찾았으나 못찾은 경우도 -1로 셋을해놔야한다. 이부분을 해결 하면 ... 진짜 할 수 있는 일도 많을것 같은데 */ #include<cstdio> #include<vector> #include<queue> #define N 400 using namespace std; vector<int> v[N + 2]; vector<int> q; bool dp[N + 2][N + 2]; bool resFlag; int target = 0; void recur(int x) { for (int k : v[x]) { for (int d : q) dp[d][k] |= 1;//정답이던 아닌던 얘는 갈수있음. if (k != target) { if (dp[k][target]) { resFlag = 1; break; } q.push_back(k); recur(k); q.pop_back(); } else { resFlag = 1; break; } } if (resFlag) return; } int main(void) { int n, m, a, b, qCnt; scanf("%d %d", &n, &m); while (m--) { scanf("%d %d", &a, &b); v[a].push_back(b);//아래로 내려가는거다. } scanf("%d", &qCnt); while (qCnt--) { scanf("%d %d", &a, &b); //a->b로 가는걸 찾으면거 dp에 저장을 하자. resFlag = 0; target = b; q.push_back(a); recur(a); q.pop_back(); if (resFlag) { printf("-1\n"); continue; } else { target = a; q.push_back(b); recur(b); q.pop_back(); if (resFlag) printf("1\n"); else printf("0\n"); } } return 0; }
[ "toywwy@gmail.com" ]
toywwy@gmail.com
98f93d2ab041987a44bc239cd4a215634f4b3aa4
624e9476816af5510904d171c0d2d290489920cf
/profiles/config/lattice_types_string.cpp
441ae807c1e097ce72e305ae9adc08cdeae0469c
[]
no_license
hutian09031035/misa-akmc
367a5891c9d0067f72b561f61dd3faf2fef36e68
fad92504cbfec21dc5ec028c8e1cb2c1514c645c
refs/heads/master
2023-03-27T04:29:00.437325
2020-01-26T05:28:07
2020-01-26T05:28:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,276
cpp
// // Created by genshen on 2019/9/19. // #include <stdexcept> #include "lattice_types_string.h" std::string lat::LatTypesString(LatticeTypes::lat_type lat_type) { switch (lat_type) { case LatticeTypes::V: return "V"; case LatticeTypes::Fe: return "Fe"; case LatticeTypes::Cu: return "Cu"; case LatticeTypes::Ni: return "Ni"; case LatticeTypes::Mn: return "Mn"; case LatticeTypes::FeFe: return "FeFe"; case LatticeTypes::FeCu: return "FeCu"; case LatticeTypes::FeNi: return "FeNi"; case LatticeTypes::FeMn: return "FeMn"; case LatticeTypes::CuCu: return "CuCu"; case LatticeTypes::CuNi: return "CuNi"; case LatticeTypes::CuMn: return "CuMn"; case LatticeTypes::NiNi: return "NiNi"; case LatticeTypes::NiMn: return "NiMn"; case LatticeTypes::MnMn: return "MnMn"; } } LatticeTypes::lat_type lat::LatTypes(const std::string &lat_type) { if (lat_type == "V") { return LatticeTypes::V; } else if (lat_type == "Fe") { return LatticeTypes::Fe; } else if (lat_type == "Cu") { return LatticeTypes::Cu; } else if (lat_type == "Ni") { return LatticeTypes::Ni; } else if (lat_type == "Mn") { return LatticeTypes::Mn; } else if (lat_type == "FeFe") { return LatticeTypes::FeFe; } else if (lat_type == "FeCu") { return LatticeTypes::FeCu; } else if (lat_type == "FeNi") { return LatticeTypes::FeNi; } else if (lat_type == "FeMn") { return LatticeTypes::FeMn; } else if (lat_type == "CuCu") { return LatticeTypes::CuCu; } else if (lat_type == "CuNi") { return LatticeTypes::CuNi; } else if (lat_type == "CuMn") { return LatticeTypes::CuMn; } else if (lat_type == "NiNi") { return LatticeTypes::NiNi; } else if (lat_type == "NiMn") { return LatticeTypes::NiMn; } else if (lat_type == "MnMn") { return LatticeTypes::MnMn; } else { throw std::invalid_argument("wrong lattice type"); } }
[ "genshenchu@gmail.com" ]
genshenchu@gmail.com
ebcaf11dcfb17f5feaf13649b312bf678d3a5310
b2e2e2549b0536951931721ff0c1c2a7232352d5
/rpc/include/TypeInfo.h
6316c0fc5deb49cff2355eb8bd06607923980e9e
[]
no_license
chenzhuoyu/SimpleRPC
acc02664bbe51a133bcfc30c9b73569aca0d89ae
99f6be084f080ad845c7a72b6f1306697c772f18
refs/heads/master
2021-11-09T23:01:37.064918
2021-10-28T14:14:26
2021-10-28T14:14:26
81,517,536
12
2
null
null
null
null
UTF-8
C++
false
false
17,136
h
/* Type information descriptor */ #ifndef SIMPLERPC_TYPEINFO_H #define SIMPLERPC_TYPEINFO_H #include <map> #include <string> #include <memory> #include <algorithm> #include <unordered_map> #include "Registry.h" #include "Exceptions.h" #include "Functional.h" namespace SimpleRPC { /****** Type descriptor ******/ class Type final { bool _isMutable; std::string _className; std::shared_ptr<Type> _keyType; std::shared_ptr<Type> _valueType; public: enum class TypeCode : int { /* void */ Void, /* signed integers */ Int8, Int16, Int32, Int64, /* unsigned integers */ UInt8, UInt16, UInt32, UInt64, /* floating point numbers */ Float, Double, /* boolean */ Boolean, /* STL string */ String, /* compond types */ Map, Array, Object }; private: TypeCode _typeCode; public: /* default void type */ explicit Type() : _typeCode(TypeCode::Void), _isMutable(false) {} public: /* primitive types */ explicit Type(TypeCode typeCode, bool isMutable) : _typeCode(typeCode), _isMutable(isMutable) { if (typeCode == TypeCode::Map || typeCode == TypeCode::Array || typeCode == TypeCode::Object) { fprintf(stderr, "assert_failed(): typeCode != TypeCode::Map && typeCode != TypeCode::Array && typeCode != TypeCode::Object"); abort(); } } public: /* map key-value type */ explicit Type(TypeCode typeCode, Type &&keyType, Type &&valueType, bool isMutable) : _typeCode(TypeCode::Map), _keyType(new Type(std::move(keyType))), _valueType(new Type(std::move(valueType))), _isMutable(isMutable) { if (keyType.isMutable()) { fprintf(stderr, "assert_failed(): !keyType.isMutable()"); abort(); } if (valueType.isMutable()) { fprintf(stderr, "assert_failed(): !valueType.isMutable()"); abort(); } if (typeCode != TypeCode::Map) { fprintf(stderr, "assert_failed(): typeCode == TypeCode::Map"); abort(); } } public: /* array sub-item type */ explicit Type(TypeCode typeCode, Type &&valueType, bool isMutable) : _typeCode(TypeCode::Array), _valueType(new Type(std::move(valueType))), _isMutable(isMutable) { if (valueType.isMutable()) { fprintf(stderr, "assert_failed(): !valueType.isMutable()"); abort(); } if (typeCode != TypeCode::Array) { fprintf(stderr, "assert_failed(): typeCode == TypeCode::Array"); abort(); } } public: /* object type */ explicit Type(TypeCode typeCode, std::string &&className, bool isMutable) : _typeCode(TypeCode::Object), _className(std::move(className)), _isMutable(isMutable) { if (typeCode != TypeCode::Object) { fprintf(stderr, "assert_failed(): typeCode == TypeCode::Object"); abort(); } } public: bool isMutable(void) const { return _isMutable; } TypeCode typeCode(void) const { return _typeCode; } const std::string &className(void) const { return _className; } public: bool operator!=(const Type &other) const { return !(*this == other); } bool operator==(const Type &other) const { switch (_typeCode) { case TypeCode::Void: case TypeCode::Int8: case TypeCode::Int16: case TypeCode::Int32: case TypeCode::Int64: case TypeCode::UInt8: case TypeCode::UInt16: case TypeCode::UInt32: case TypeCode::UInt64: case TypeCode::Float: case TypeCode::Double: case TypeCode::String: case TypeCode::Boolean: return _typeCode == other._typeCode; case TypeCode::Map: return (other._typeCode == TypeCode::Map) && (_keyType == other._keyType) && (_valueType == other._valueType); case TypeCode::Array: return (other._typeCode == TypeCode::Array) && (_valueType == other._valueType); case TypeCode::Object: return (other._typeCode == TypeCode::Object) && (_className == other._className); } } public: const Type &keyType(void) const { if (_typeCode == TypeCode::Map) return *_keyType; else throw Exceptions::TypeError("Only maps may have keys"); } public: const Type &valueType(void) const { if (_typeCode == TypeCode::Map || _typeCode == TypeCode::Array) return *_valueType; else throw Exceptions::TypeError("Only maps or arrays may have values"); } public: std::string toSignature(void) const { if (!_isMutable) { switch (_typeCode) { case TypeCode::Int8 : return "b"; case TypeCode::Int16 : return "h"; case TypeCode::Int32 : return "i"; case TypeCode::Int64 : return "q"; case TypeCode::UInt8 : return "B"; case TypeCode::UInt16 : return "H"; case TypeCode::UInt32 : return "I"; case TypeCode::UInt64 : return "Q"; case TypeCode::Float : return "f"; case TypeCode::Double : return "d"; case TypeCode::Boolean : return "?"; case TypeCode::Void : return "v"; case TypeCode::String : return "s"; case TypeCode::Object : return "<" + _className + ">"; case TypeCode::Map : return "{" + _keyType->toSignature() + ":" + _valueType->toSignature() + "}"; case TypeCode::Array : return "[" + _valueType->toSignature() + "]"; } } else { switch (_typeCode) { case TypeCode::Int8 : return "b&"; case TypeCode::Int16 : return "h&"; case TypeCode::Int32 : return "i&"; case TypeCode::Int64 : return "q&"; case TypeCode::UInt8 : return "B&"; case TypeCode::UInt16 : return "H&"; case TypeCode::UInt32 : return "I&"; case TypeCode::UInt64 : return "Q&"; case TypeCode::Float : return "f&"; case TypeCode::Double : return "d&"; case TypeCode::Boolean : return "?&"; case TypeCode::String : return "s&"; case TypeCode::Object : return "<" + _className + ">&"; case TypeCode::Map : return "{" + _keyType->toSignature() + ":" + _valueType->toSignature() + "}&"; case TypeCode::Array : return "[" + _valueType->toSignature() + "]&"; case TypeCode::Void: throw std::range_error("`void` should always be immutable"); } } } }; namespace Internal { /****** Type resolvers ******/ /* type size container */ template <size_t size> struct TypeSize; template <> struct TypeSize<sizeof(int8_t)> { static Type signedType(bool isMutable) { return Type(Type::TypeCode:: Int8, isMutable); } static Type unsignedType(bool isMutable) { return Type(Type::TypeCode::UInt8, isMutable); } }; template <> struct TypeSize<sizeof(int16_t)> { static Type signedType(bool isMutable) { return Type(Type::TypeCode:: Int16, isMutable); } static Type unsignedType(bool isMutable) { return Type(Type::TypeCode::UInt16, isMutable); } }; template <> struct TypeSize<sizeof(int32_t)> { static Type signedType(bool isMutable) { return Type(Type::TypeCode:: Int32, isMutable); } static Type unsignedType(bool isMutable) { return Type(Type::TypeCode::UInt32, isMutable); } }; template <> struct TypeSize<sizeof(int64_t)> { static Type signedType(bool isMutable) { return Type(Type::TypeCode:: Int64, isMutable); } static Type unsignedType(bool isMutable) { return Type(Type::TypeCode::UInt64, isMutable); } }; template <bool isSigned, bool isUnsigned, bool isStructLike, typename Item> struct TypeHelper { static Type type(bool isMutable) { /* types that not recognized */ static_assert(isSigned || isUnsigned || isStructLike, "Cannot serialize or deserialize arbitrary type"); abort(); } }; template <typename Item> struct TypeHelper<true, false, false, Item> { static Type type(bool isMutable) { /* signed integers */ return TypeSize<sizeof(Item)>::signedType(isMutable); } }; template <typename Item> struct TypeHelper<false, true, false, Item> { static Type type(bool isMutable) { /* unsigned integers */ return TypeSize<sizeof(Item)>::unsignedType(isMutable); } }; template <typename Item> struct TypeHelper<false, false, true, Item> { static Type type(bool isMutable) { /* structure types */ return Type(Type::TypeCode::Object, typeid(Item).name(), isMutable); } }; #pragma clang diagnostic push #pragma ide diagnostic ignored "OCSimplifyInspection" template <typename Item> struct TypeItem { static Type type(void) { /* doesn't support pointers or R-Value references */ static_assert(!std::is_pointer<Item>::value, "Pointers are not supported"); static_assert(!std::is_rvalue_reference<Item>::value, "R-Value references are not supported"); /* invoke type helper for detailed type information */ return TypeHelper< std::is_signed<std::decay_t<Item>>::value, std::is_unsigned<std::decay_t<Item>>::value, std::is_convertible<std::decay_t<Item> *, Serializable *>::value, Item >::type( std::is_lvalue_reference<Item>::value && !std::is_const<std::remove_reference<Item>>::value ); } }; #pragma clang diagnostic pop /* void type */ template <> struct TypeItem<void> { static Type type(void) { return Type(); } }; /* single precision floating point number */ template <> struct TypeItem< float > { static Type type(void) { return Type(Type::TypeCode::Float, false); } }; template <> struct TypeItem< float &> { static Type type(void) { return Type(Type::TypeCode::Float, true ); } }; template <> struct TypeItem<const float &> { static Type type(void) { return Type(Type::TypeCode::Float, false); } }; /* double precision floating point number */ template <> struct TypeItem< double > { static Type type(void) { return Type(Type::TypeCode::Double, false); } }; template <> struct TypeItem< double &> { static Type type(void) { return Type(Type::TypeCode::Double, true ); } }; template <> struct TypeItem<const double &> { static Type type(void) { return Type(Type::TypeCode::Double, false); } }; /* boolean */ template <> struct TypeItem< bool > { static Type type(void) { return Type(Type::TypeCode::Boolean, false); } }; template <> struct TypeItem< bool &> { static Type type(void) { return Type(Type::TypeCode::Boolean, true ); } }; template <> struct TypeItem<const bool &> { static Type type(void) { return Type(Type::TypeCode::Boolean, false); } }; /* STL string */ template <> struct TypeItem< std::string > { static Type type(void) { return Type(Type::TypeCode::String, false); } }; template <> struct TypeItem< std::string &> { static Type type(void) { return Type(Type::TypeCode::String, true ); } }; template <> struct TypeItem<const std::string &> { static Type type(void) { return Type(Type::TypeCode::String, false); } }; /* STL vector (arrays) */ template <typename Item> struct TypeItem< std::vector<Item> > { static Type type(void) { return Type(Type::TypeCode::Array, TypeItem<Item>::type(), false); }}; template <typename Item> struct TypeItem< std::vector<Item> &> { static Type type(void) { return Type(Type::TypeCode::Array, TypeItem<Item>::type(), true ); }}; template <typename Item> struct TypeItem<const std::vector<Item> &> { static Type type(void) { return Type(Type::TypeCode::Array, TypeItem<Item>::type(), false); }}; /* STL tree maps (maps) */ template <typename Key, typename Value> struct TypeItem< std::map<Key, Value> > { static Type type(void) { return Type(Type::TypeCode::Map, TypeItem<Key>::type(), TypeItem<Value>::type(), false); }}; template <typename Key, typename Value> struct TypeItem< std::map<Key, Value> &> { static Type type(void) { return Type(Type::TypeCode::Map, TypeItem<Key>::type(), TypeItem<Value>::type(), true ); }}; template <typename Key, typename Value> struct TypeItem<const std::map<Key, Value> &> { static Type type(void) { return Type(Type::TypeCode::Map, TypeItem<Key>::type(), TypeItem<Value>::type(), false); }}; /* STL unordered maps (maps) */ template <typename Key, typename Value> struct TypeItem< std::unordered_map<Key, Value> > { static Type type(void) { return Type(Type::TypeCode::Map, TypeItem<Key>::type(), TypeItem<Value>::type(), false); }}; template <typename Key, typename Value> struct TypeItem< std::unordered_map<Key, Value> &> { static Type type(void) { return Type(Type::TypeCode::Map, TypeItem<Key>::type(), TypeItem<Value>::type(), true ); }}; template <typename Key, typename Value> struct TypeItem<const std::unordered_map<Key, Value> &> { static Type type(void) { return Type(Type::TypeCode::Map, TypeItem<Key>::type(), TypeItem<Value>::type(), false); }}; /****** Type array resolvers ******/ template <typename ... Items> struct TypeArray; template <typename Item, typename ... Items> struct TypeArray<Item, Items ...> { static void resolve(std::vector<Type> &types) { types.push_back(TypeItem<Item>::type()); TypeArray<Items ...>::resolve(types); } }; template <> struct TypeArray<> { static void resolve(std::vector<Type> &) { /* final recursion, no arguments left */ /* thus nothing to do */ } }; /****** Method signature resolvers ******/ template <typename ... Args> struct MetaArgs { static std::vector<Type> type(void) { std::vector<Type> types; types.reserve(sizeof ... (Args)); TypeArray<Args ...>::resolve(types); return std::move(types); } }; template <typename ReturnType, typename ... Args> struct MetaMethod { Type result; std::string name; std::string signature; std::vector<Type> args; public: constexpr explicit MetaMethod() : MetaMethod("") {} constexpr explicit MetaMethod(const char *name) : name(name), args(MetaArgs<Args ...>::type()), result(TypeItem<ReturnType>::type()) { signature = name; signature += "("; for (const auto type : args) signature += type.toSignature(); signature += ")"; signature += TypeItem<ReturnType>::type().toSignature(); } }; /****** Utilities ******/ #pragma clang diagnostic push #pragma ide diagnostic ignored "OCSimplifyInspection" template <typename T> struct IsVector : public std::false_type {}; template <typename T> struct IsVector<std::vector<T>> : public std::true_type { typedef T ItemType; }; template <typename T> struct IsMap : public std::false_type {}; template <typename K, typename V> struct IsMap<std::map<K, V>> : public std::true_type { typedef K KeyType; typedef V ValueType; }; template <typename K, typename V> struct IsMap<std::unordered_map<K, V>> : public std::true_type { typedef K KeyType; typedef V ValueType; }; template <typename T> struct IsObjectReference { static const bool value = std::is_convertible< std::decay_t<T> *, Serializable * >::value; }; template <typename T> struct IsMutableReference { static const bool value = std::is_lvalue_reference<T>::value && !std::is_const<std::remove_reference_t<T>>::value; }; template <typename T> struct IsMutableObjectReference { static const bool value = IsObjectReference<T>::value && IsMutableReference<T>::value; }; template <typename T, typename Integer> struct IsSignedIntegerLike { static const bool value = !std::is_same <std::decay_t<T>, bool>::value && std::is_signed <std::decay_t<T> >::value && std::is_integral<std::decay_t<T> >::value && (sizeof(std::decay_t<T>) == sizeof(Integer)); }; template <typename T, typename Integer> struct IsUnsignedIntegerLike { static const bool value = !std::is_same <std::decay_t<T>, bool>::value && std::is_unsigned<std::decay_t<T> >::value && std::is_integral<std::decay_t<T> >::value && (sizeof(std::decay_t<T>) == sizeof(Integer)); }; #pragma clang diagnostic pop } } #endif /* SIMPLERPC_TYPEINFO_H */
[ "chenzhuoyu1992@gmail.com" ]
chenzhuoyu1992@gmail.com
8afd83425ce4ec593f0e97ba09dc79670be04b69
d9730d00fc0e9d32f80dfaeb216081e61aa563a2
/OtherProjects/NavMeshVisualiser/NavMeshRenderer.cpp
d22c0c49d33c01bc30c568ad2ed74f0a68e006fa
[]
no_license
Akeilee/Game-Tech
dd875c6b513b95581c6db9af5a7b6d68eba53784
0f3d1c8c7e7319c82de514517e21a29c29833de3
refs/heads/main
2023-02-28T08:09:53.118937
2021-02-10T17:31:53
2021-02-10T17:31:53
328,478,276
0
0
null
null
null
null
UTF-8
C++
false
false
3,565
cpp
#include "NavMeshRenderer.h" #include "../../Common/Assets.h" #include "../../Common/Camera.h" #include "../../Common/Vector3.h" #include "../../Common/Matrix4.h" #include "../../Common/MeshAnimation.h" #include <fstream> #include <iostream> using namespace NCL; NavMeshRenderer::NavMeshRenderer() : OGLRenderer(*Window::GetWindow()) { navMesh = new OGLMesh(); std::ifstream mapFile(Assets::DATADIR + "test.navmesh"); int vCount = 0; int iCount = 0; mapFile >> vCount; mapFile >> iCount; vector<Vector3> meshVerts; vector<Vector4> meshColours; vector<unsigned int> meshIndices; for (int i = 0; i < vCount; ++i) { Vector3 temp; mapFile >> temp.x; mapFile >> temp.y; mapFile >> temp.z; meshVerts.emplace_back(temp); meshColours.emplace_back(Vector4(0, 1, 0, 1)); } for (int i = 0; i < iCount; ++i) { unsigned int temp = -1; mapFile >> temp; meshIndices.emplace_back(temp); } struct TriNeighbours { int indices[3]; }; int numTris = iCount / 3; //the indices describe n / 3 triangles vector< TriNeighbours> allNeighbours; //Each of these triangles will be sharing edges with some other triangles //so it has a maximum of 3 'neighbours', desribed by an index into n / 3 tris //if its a -1, then the edge is along the edge of the map... for (int i = 0; i < numTris; ++i) { TriNeighbours neighbours; mapFile >> neighbours.indices[0]; mapFile >> neighbours.indices[1]; mapFile >> neighbours.indices[2]; allNeighbours.emplace_back(neighbours); } navMesh->SetVertexPositions(meshVerts); navMesh->SetVertexColours(meshColours); navMesh->SetVertexIndices(meshIndices); navMesh->UploadToGPU(); vector<Vector3> centroids; vector<Vector4> centreColours; vector<unsigned int> lines; for (int i = 0; i < iCount; i += 3) { Vector3 a = meshVerts[meshIndices[i + 0]]; Vector3 b = meshVerts[meshIndices[i + 1]]; Vector3 c = meshVerts[meshIndices[i + 2]]; Vector3 middle = (a + b + c) / 3.0f; centroids.emplace_back(middle); centreColours.emplace_back(Vector4(1, 0, 0, 1)); } for (int i = 0; i < numTris; ++i) { TriNeighbours& n = allNeighbours[i]; for (int j = 0; j < 3; ++j) { if (n.indices[j] != -1) { TriNeighbours& nj = allNeighbours[n.indices[j]]; lines.emplace_back(i); lines.emplace_back(n.indices[j]); } } } centroidMesh = new OGLMesh(); centroidMesh->SetVertexPositions(centroids); centroidMesh->SetVertexColours(centreColours); centroidMesh->SetVertexIndices(lines); centroidMesh->SetPrimitiveType(NCL::GeometryPrimitive::Lines); centroidMesh->UploadToGPU(); shader = new OGLShader("DebugVert.glsl", "DebugFrag.glsl"); camera = new Camera(); camera->SetNearPlane(1.0f); camera->SetFarPlane(1000.0f); camera->SetPosition(Vector3(0, 3, 10)); } NavMeshRenderer::~NavMeshRenderer() { delete navMesh; delete camera; } void NavMeshRenderer::Update(float dt) { camera->UpdateCamera(dt); } void NavMeshRenderer::RenderFrame() { //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); BindShader(shader); glEnable(GL_DEPTH_TEST); glDisable(GL_CULL_FACE); float screenAspect = (float)currentWidth / (float)currentHeight; Matrix4 viewMatrix = camera->BuildViewMatrix(); Matrix4 projMatrix = camera->BuildProjectionMatrix(screenAspect); Matrix4 vp = projMatrix * viewMatrix; int vpLocation = glGetUniformLocation(shader->GetProgramID(), "viewProjMatrix"); glUniformMatrix4fv(vpLocation, 1, false, (float*)&vp); BindMesh(navMesh); DrawBoundMesh(); BindMesh(centroidMesh); DrawBoundMesh(); //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); }
[ "62071096+jlee18ncl@users.noreply.github.com" ]
62071096+jlee18ncl@users.noreply.github.com
ba802fa0543cb45ea5c2cc40aaf2d9e68ea67582
98f9ef0856f3e271f26dfbff6c5c6e92ee8b21d1
/db/models/types/fshelicopter.cpp
d9c73c969d123cb93b1a33a21fec4bff57023917
[]
no_license
juhnowski/TargetContollerLib
b5e43adae54612b80db90f202b50e0e2bbc17e3e
3704b685f087b547ef71af9dd9c32463e53acf8c
refs/heads/master
2021-01-10T09:25:08.210717
2016-01-29T23:15:40
2016-01-29T23:15:40
50,697,802
0
0
null
null
null
null
UTF-8
C++
false
false
969
cpp
#include "fshelicopter.h" #include <QtCore/qmath.h> #include <QDebug> FSHelicopter::FSHelicopter(QObject *parent):Aircraft(parent) { name = new QString("FS Helicopter target"); } bool FSHelicopter::defineRelation(Data* newData, Data* latestData){ Coord* c_l = latestData->getCoord(); Coord* c_n = newData->getCoord(); float dt = newData->getTime() - latestData->getTime(); qDebug() << "defineRelation for" << *this->getName(); qDebug() << "dt=" << dt; int x_l = c_l->getX(); int x_n = c_n->getX(); int dx = x_n - x_l; qDebug() << "dx=" << dx; int y_l = c_l->getY(); int y_n = c_n->getY(); int dy = y_n - y_l; qDebug() << "dy=" << dy; int z_l = c_l->getZ(); int z_n = c_n->getZ(); int dz = z_n - z_l; qDebug() << "dz=" << dz; //Vmax Apache = 82 m/s float Vmax = 82.0; float v = sqrt(dx*dx+dy*dy+dz*dz)/dt; qDebug() << "Vmax=" << Vmax << " v=" << v; return v < Vmax; }
[ "juhnowski@gmail.com" ]
juhnowski@gmail.com
4f58e424a5cbdc6122cf34df869c84aaa8bea0c8
620ced74bccba847a8d824e7ae67b6c29f5bbf85
/Configuration/analysis/common/include/sampleHelpers.h
bb10d0208d0509177dda85e512fc220446fe4ca7
[]
no_license
muell149/TopAnalysis
3327eed360d18108fda3eb5a135b729ecbfcbfef
78ba2318d106b24367e96740f00feacadcf17331
refs/heads/master
2021-01-13T01:40:14.551811
2014-05-06T15:42:32
2014-05-06T15:42:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,089
h
#ifndef sampleHelpers_h #define sampleHelpers_h #include <string> #include <vector> class TString; /// Namespace to treat systematics as enum types namespace Systematic{ /// All systematics as needed in any part of the framework enum Systematic{ nominal, // nominal, i.e. no systematic variation applied mH110, // Higgs mass of 110 GeV mH115, // Higgs mass of 115 GeV mH120, // Higgs mass of 120 GeV mH1225, // Higgs mass of 122.5 GeV mH1275, // Higgs mass of 127.5 GeV mH130, // Higgs mass of 130 GeV mH135, // Higgs mass of 135 GeV mH140, // Higgs mass of 140 GeV lept_up, // scale up lepton ID/ISO data-to-MC scale factors lept_down, // scale down lepton ID/ISO data-to-MC scale factors trig_up, // scale up trigger data-to-MC scale factors trig_down, // scale down trigger ID/ISO data-to-MC scale factors pu_up, pu_down, dy_up, dy_down, bg_up, bg_down, kin_up, kin_down, btag_up, // scale up b-tagging data-to-MC scale factors of the b-/c-jets btag_down, // scale down b-tagging data-to-MC scale factors of the b-/c-jets btagPt_up, btagPt_down, btagEta_up, btagEta_down, btagLjet_up, // scale up b-tagging data-to-MC scale factors of the l-jets btagLjet_down, // scale down b-tagging data-to-MC scale factors of the l-jets btagLjetPt_up, btagLjetPt_down, btagLjetEta_up, btagLjetEta_down, btagBeff_up, btagBeff_down, btagCeff_up, btagCeff_down, btagLeff_up, btagLeff_down, jer_up, // scale up jet energy resolution scale factors jer_down, // scale down jet energy resolution scale factors jes_up, // scale up jet energy scale scale factors jes_down, // scale down jet energy scale scale factors mass_up, mass_down, match_up, match_down, scale_up, scale_down, powheg, mcatnlo, pdf, // PDF variations all, // All allowed systematics undefined // No systematic defined (also not nominal) }; /// All systematics allowed for analysis step in Top analysis /// Only systematics which run on the nominal ntuples, e.g. pileup reweighting /// (allow undefined to set default behaviour if no option is set, i.e. option is empty) const std::vector<Systematic> allowedSystematicsTopAnalysis {nominal, undefined}; /// All systematics allowed for plotting step in Top analysis const std::vector<Systematic> allowedSystematicsTopPlotting {nominal}; /// All systematics allowed for analysis step in Higgs analysis /// Only systematics which run on the nominal ntuples, e.g. pileup reweighting /// (allow undefined to set default behaviour if no option is set, i.e. option is empty) const std::vector<Systematic> allowedSystematicsHiggsAnalysis {nominal, lept_up, lept_down, trig_up, trig_down, undefined}; /// All systematics allowed for plotting step in Higgs analysis const std::vector<Systematic> allowedSystematicsHiggsPlotting {nominal, mH110, mH115, mH120, mH1225, mH1275, mH130, mH135, mH140}; /// Convert a systematic from string to typedef Systematic convertSystematic(const std::string& systematic); /// Convert a systematic from typedef to string std::string convertSystematic(const Systematic& systematic); /// Convert a vector of systematics from string to typedef std::vector<Systematic> convertSystematics(const std::vector<std::string>& systematics); /// Convert a vector of systematics from string to typedef std::vector<std::string> convertSystematics(const std::vector<Systematic>& systematics); } /// Namespace to treat decay channels as enum types namespace Channel{ /// All dileptonic decay channels as needed in any part of the framework enum Channel{ee, emu, mumu, combined, tautau, undefined}; /// All dileptonic decay channels allowed for analysis step /// (allow undefined to select all channels if no option is set, i.e. option is empty) const std::vector<Channel> allowedChannelsAnalysis {ee, emu, mumu, undefined}; /// All dileptonic decay channels allowed for plotting step const std::vector<Channel> allowedChannelsPlotting {ee, emu, mumu, combined}; /// Real analysis channels, i.e. all channels which describe a real final state const std::vector<Channel> realChannels {ee, emu, mumu}; /// Possible Drell-Yan decay channels const std::vector<Channel> dyDecayChannels {ee, mumu, tautau}; /// Convert a channel from string to typedef Channel convertChannel(const std::string& channel); /// Convert a channel from typedef to string std::string convertChannel(const Channel& channel); /// Return the label of a channel as used for drawing std::string channelLabel(const Channel& channel); /// Convert a vector of channels from string to typedef std::vector<Channel> convertChannels(const std::vector<std::string>& channels); /// Convert a vector of channels from string to typedef std::vector<std::string> convertChannels(const std::vector<Channel>& channels); } namespace common{ /// Create and assign an output folder depending on the channel and systematic TString assignFolder(const char* baseDir, const Channel::Channel& channel, const Systematic::Systematic& systematic); /// Access an already existing input folder TString accessFolder(const char* baseDir, const Channel::Channel& channel, const Systematic::Systematic& systematic, const bool allowNonexisting =false); } #endif
[ "johauk@desy-cms012.desy.de" ]
johauk@desy-cms012.desy.de
9c293835538d17640be2bad84c51356f8db9b3c0
2f659258316e88375b7c04dd9bb125a974906918
/jni/NativeBitmapFactory.cpp
f397d7d37e93f8223c65373013a651fd95da9188
[]
no_license
chundonglinlin/NativeBitmapFactory
0eb2e3fe0d7e93a0f0902ad117b47e25c3f50138
02e704b65f30ddcb13b7df4b042a96eed45b4fcd
refs/heads/master
2020-12-14T09:01:48.185911
2014-07-07T02:29:12
2014-07-07T02:29:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,043
cpp
#include <stdio.h> #include <stdlib.h> #include <jni.h> #include <SkBitmap.h> #include <GraphicsJNI.h> //#include <android/log.h> #include "NativeBitmapFactory.h" jobject createBitmap(JNIEnv * env ,jobject obj,jint w,jint h,SkBitmap::Config config,jboolean hasAlpha,int isMuttable) { SkBitmap* bm = new SkBitmap(); bm->setConfig(config, w, h); bm->setIsOpaque(!hasAlpha); bm->allocPixels(); bm->eraseColor(0); //__android_log_print(ANDROID_LOG_DEBUG, "NativeBitmap", "Created bitmap %d has width = %d, height = %d",bm, bm->width(), bm->height()); jobject result = GraphicsJNI::createBitmap(env,bm,isMuttable,NULL,-1); return result; } jobject Java_tv_cjump_jni_NativeBitmapFactory_createBitmap(JNIEnv * env ,jobject obj,jint w,jint h,SkBitmap::Config config,jboolean hasAlpha) { return createBitmap(env,obj,w,h,config,hasAlpha,true); } jobject Java_tv_cjump_jni_NativeBitmapFactory_createBitmap19(JNIEnv * env ,jobject obj,jint w,jint h,SkBitmap::Config config,jboolean hasAlpha) { return createBitmap(env,obj,w,h,config,hasAlpha,0x3); }
[ "calmer91@gmail.com" ]
calmer91@gmail.com
45d776925bc0e0c3ad31613e26a7d46fe16ede3a
334195768bad0fc7d8b01b6b01c5039378c37e8d
/src/legendwidget.cpp
8a0b7a2d2f04896c1afcc2e15b6e3ce301878ee8
[]
no_license
cran/mvgraph
2aadf0159897cfbfce4ccf84e422ac056df827a7
3fdce7fe7f42225b6bf4d86ab0c31b7ed5e3048a
refs/heads/master
2016-09-10T10:51:42.378846
2010-07-16T00:00:00
2010-07-16T00:00:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
565
cpp
#include "legendwidget.h" Legendwidget::Legendwidget(char** names, QWidget *parent) : QDialog(parent) { QVBoxLayout *layout = new QVBoxLayout(this); QLabel *label1 = new QLabel("<font color='red'>"+QString::fromUtf8(names[0])+"</font>"); layout->addWidget(label1); QLabel *label2 = new QLabel("<font color='green'>"+QString::fromUtf8(names[1])+"</font>"); layout->addWidget(label2); QLabel *label3 = new QLabel("<font color='blue'>"+QString::fromUtf8(names[2])+"</font>"); layout->addWidget(label3); setLayout(layout); setWindowTitle(tr("Legend")); }
[ "csardi.gabor@gmail.com" ]
csardi.gabor@gmail.com
f2853fa8202d2683c7df2a09d087f21b75895f16
96d444349f9c7726dfe4f05117cd001f2a4ba052
/Listlib/Nodes/Nodes.h
295435cf06ba4541dc3c6637c2ac872c439edcc4
[]
no_license
Llanyro/Llanylibcpp
ce8e1a41a31eefc9d9e84709acbb88bcf1789669
9a529e7a0bbe405c4219e5f5a5fe88a41fdaa00c
refs/heads/main
2023-06-27T01:14:53.607673
2021-08-03T22:52:56
2021-08-03T22:52:56
371,466,747
0
0
null
null
null
null
UTF-8
C++
false
false
3,176
h
/* * Nodes.h * * Created on: Jan 19, 2021 * Author: llanyro */ #ifndef LLANYLIB_CORE_CLASSES_NODES_NODES_H_ #define LLANYLIB_CORE_CLASSES_NODES_NODES_H_ /*#include "../../Classes/LlanyCore.h" namespace Llanylib { namespace Listlib { namespace Nodes { template<class T, const len_t numNodes> class Node : public Core::Classes::LlanyCore { protected: T** vector; public: Node() : LlanyCore() { this->vector = new T*[numNodes]; for (len_t i = 0; i < numNodes; ++i) this->vector[i] = nullptr; } virtual ~Node() { for (len_t i = 0; i < numNodes; ++i) this->vector[i] = nullptr; delete[] this->vector; } T* get(const len_t& position) { T* result = nullptr; if(position < numNodes) result = this->vector[position]; return result; } const T* getConst(const len_t& position) const { const T* result = nullptr; if(position < numNodes) result = this->vector[position]; return result; } ll_bool_t set(T* node, const len_t& position) { ll_bool_t result = true; if(position < numNodes) this->vector[position] = node; else result = false; return result; } //virtual void deleteRecursivo(const void* first) {} }; template<class T> class NodeDouble : protected Node<T, 2> { public: NodeDouble() : Node<T, 2>() {} virtual ~NodeDouble() {} T* getSiguienteNodo() { return Node<T, 2>::get(0); } const T* getConstSiguienteNodo() const { return Node<T, 2>::getConst(0); } ll_bool_t setSiguienteNodo(T* node) { return Node<T, 2>::set(node, 0); } T* getAnteriorNodo() { return Node<T, 2>::get(1); } const T* getConstAnteriorNodo() const { return Node<T, 2>::getConst(1); } ll_bool_t setAnteriorNodo(T* node) { return Node<T, 2>::set(node, 1); } /*virtual void deleteRecursivo(const NodeDouble<T>* first) { // Si no hay primero, este nodo es el primero // Si hay siguiente nodo if(first == nullptr && this->getSiguienteNodo() != nullptr) { // Si el siguiente nodo no es este nodo if(this->getSiguienteNodo() != this) this->getSiguienteNodo()->deleteRecursivo(this); // Si es el mismo nodo, no hacemos nada } else { // Si hay siguiente nodo y no es el primero if(this->getSiguienteNodo() != nullptr && this->getSiguienteNodo() != first) this->getSiguienteNodo()->deleteRecursivo(first); } delete this; }* }; template<class T> class NodeAVL : protected Node<T, 3> { public: NodeAVL() : Node<T, 3>() {} virtual ~NodeAVL() {} T* getParent() { return Node<T, 3>::get(0); } const T* getConstParent() const { return Node<T, 3>::getConst(0); } ll_bool_t setParent(T* node) { return Node<T, 3>::set(node, 0); } T* getLeftChild() { return Node<T, 3>::get(1); } const T* getConstLeftChild() const { return Node<T, 3>::get(1); } ll_bool_t setLeftChild(T* node) { return Node<T, 3>::set(node, 1); } T* getRightChild() { return Node<T, 3>::get(2); } const T* getConstRightChild() const { return Node<T, 3>::get(2); } ll_bool_t setRightChild(T* node) { return Node<T, 3>::set(node, 2); } };*/ } /* namespace Nodes */ } /* namespace Listlib */ } /* namespace Llanylib */ #endif /* LLANYLIB_CORE_CLASSES_NODES_NODES_H_ */
[ "Llanyro@gmail.com" ]
Llanyro@gmail.com
418585d585a99b908efff7fe6abe098a96c5f41b
dd8dd5cab1d4a678c412c64f30ef10f9c5d210f1
/cpp/leetcode/输出浮点数对小数点后精度有要求.cpp
db94f6e779fc04cfa7d3828c92af18af04c48e1e
[]
no_license
blacksea3/leetcode
e48a35ad7a1a1bb8dd9a98ffc1af6694c09061ee
18f87742b64253861ca37a2fb197bb8cb656bcf2
refs/heads/master
2021-07-12T04:45:59.428804
2020-07-19T02:01:29
2020-07-19T02:01:29
184,689,901
6
2
null
null
null
null
GB18030
C++
false
false
698
cpp
#include <iostream> #include <string> #include <iomanip> using namespace std; /* int main() { { string s; cin >> s; char oldChar = s[0]; int sSize = s.size(); int differents = 0; for (int index = 1; index < sSize; ++index) { if (s[index] != oldChar) { differents++; oldChar = s[index]; } } differents++; cout.setf(ios_base::fixed, ios_base::floatfield); //使用定点计数法,精度指的是小数点后面的位数,而不是总位数 cout.setf(ios_base::showpoint); //显示小数点后面的0 cout.precision(2); //使用定点计数法,显示小数点后面位数精度 cout << sSize / (double)differents << endl; } return 0; } */
[ "17865191779@163.com" ]
17865191779@163.com
901355004d3afe80dc7a4ea086f6d4ddc892d135
2d264d22193672a5b5ac48ed31cd9685166f3355
/src/nrf24_rx_h8_3d.h
f8baeade768926788c4a7cfb272fabb5b6be5763
[]
no_license
martinbudden/NRF24_RX
1b100a2410df0d772eb6506e4c90f09ad434b297
e744c7c43f7ad9efea0d8437df4d093c0400f8ff
refs/heads/master
2021-07-04T20:20:36.909391
2021-05-31T16:59:07
2021-05-31T16:59:07
63,960,412
8
6
null
2021-05-31T16:59:07
2016-07-22T14:39:49
C++
UTF-8
C++
false
false
1,905
h
/* * This file is part of the Arduino NRF24_RX library. * * Written by Martin Budden * * This library 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. * * 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 General Public License, <http://www.gnu.org/licenses/>, for * more details. * * All the above text and this condition must be included in any redistribution. */ #pragma once #include <stdbool.h> #include <stdint.h> #include "NRF24_RX.h" class H8_3D_RX : public NRF24_RX { private: enum {TX_ID_LEN = 4}; uint8_t txId[TX_ID_LEN]; // transmitter ID, sent in bind packet // radio channels for frequency hopping enum {RF_CHANNEL_COUNT = 4}; uint8_t rfChannelArray[RF_CHANNEL_COUNT]; enum {CRC_LEN = 2}; enum {PAYLOAD_SIZE = 20}; enum {STATE_BIND_0 = 0, STATE_BIND_1, STATE_DATA}; enum {RX_ADDR_LEN = 5}; static const uint8_t rxAddr[RX_ADDR_LEN]; uint32_t timeOfLastPacket; public: enum {RC_CHANNEL_COUNT = 14}; private: static uint16_t convertToPwm(uint8_t val, int16_t _min, int16_t _max); bool checkSumOK(void) const; protected: void setHoppingChannels(const uint8_t *txId); void setBound(const uint8_t *txId); virtual void hopToNextChannel(void); virtual bool checkBindPacket(void); public: virtual ~H8_3D_RX(); H8_3D_RX(NRF24L01 *nrf24); H8_3D_RX(uint8_t _ce_pin, uint8_t _csn_pin); virtual void begin(int protocol, const uint32_t *nrf24rx_id = 0); virtual void setRcDataFromPayload(uint16_t *rcData) const; virtual received_e dataReceived(void); };
[ "mjbudden@gmail.com" ]
mjbudden@gmail.com
93b3daa35a162f475c1866bdcce170db7fcbe285
71c8702211dc84b0311d52b7cfa08c85921d660b
/codeforces/785A - Anton and Polyhedrons.cpp
7b18422621eb9dce076f682e09617a1e772d34db
[]
no_license
mubasshir00/competitive-programming
b8a4301bba591e38384a8652f16b413853aa631b
7eda0bb3dcc2dc44c516ce47046eb5da725342ce
refs/heads/master
2023-07-19T21:01:18.273419
2023-07-08T19:05:44
2023-07-08T19:05:44
226,463,398
1
0
null
null
null
null
UTF-8
C++
false
false
676
cpp
#include<bits/stdc++.h> using namespace std ; int main() { vector<string>v; int n ; int ans = 0; cin>>n; for(int i=0;i<n;i++) { string x ; cin>>x; v.push_back(x); } for(int i=0;i<n;i++) { if(v[i]=="Icosahedron") { ans =ans+20; } if(v[i]=="Dodecahedron") { ans =ans +12; } if(v[i]=="Octahedron") { ans = ans +8; } if(v[i]=="Cube") { ans = ans + 6; } if(v[i]=="Tetrahedron") { ans = ans + 4; } } cout<<ans<<endl; return 0 ; }
[ "marakib178@Gmail.com" ]
marakib178@Gmail.com
be0b7d29ecff4577adac05baa666de17552cab12
a1d270d8fec9e1a4d09bdbc426d9141eb17ee453
/WaveSabrePlayerLib/include/WaveSabrePlayerLib/CriticalSection.h
84ce77e521e11893350e60277877ca0a3cc99345
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
thijskruithof/WaveSabre
356a2561252976e85a2cc84352f2ebae515d4629
f2e97ccadb03d073d5d2f54e70f1c85daf72aaf4
refs/heads/master
2023-08-22T21:03:55.687264
2023-07-26T18:34:44
2023-07-26T18:34:44
238,679,002
1
0
MIT
2020-02-06T12:01:34
2020-02-06T12:01:33
null
UTF-8
C++
false
false
505
h
#ifndef __WAVESABREPLAYERLIB_CRITICALSECTION__ #define __WAVESABREPLAYERLIB_CRITICALSECTION__ #include <Windows.h> namespace WaveSabrePlayerLib { class CriticalSection { public: class CriticalSectionGuard { public: CriticalSectionGuard(CriticalSection *criticalSection); ~CriticalSectionGuard(); private: CriticalSection *criticalSection; }; CriticalSection(); ~CriticalSection(); CriticalSectionGuard Enter(); private: CRITICAL_SECTION criticalSection; }; } #endif
[ "yupferris@gmail.com" ]
yupferris@gmail.com
530252c9a4e459870ba652049559305370ed3dac
18f0b70bc2fb7bd155bd32880589cd3dea0d696a
/ct_models/include/ct/models/QuadrotorWithLoad/generated/jacobians.h
aadc1933039438120e2b51d7ef8327f4ab942383
[ "BSD-2-Clause", "LicenseRef-scancode-unknown-license-reference" ]
permissive
crisdeodates/Robotics-control-toolbox
8a791989a47ee0dd6bee0bdacdcbc3b2a3561021
7d36e42ff665c9f4b6c5f3e4ddce04a0ab41628a
refs/heads/v3.0.2
2023-06-10T22:38:41.718705
2021-07-05T08:23:09
2021-07-05T08:23:09
337,681,994
0
0
BSD-2-Clause
2021-07-05T13:25:34
2021-02-10T09:59:09
null
UTF-8
C++
false
false
1,151
h
#ifndef CT_QUADROTOR_JACOBIANS_H_ #define CT_QUADROTOR_JACOBIANS_H_ #include <iit/rbd/TransformsBase.h> #include <iit/rbd/traits/DoubleTrait.h> #include "declarations.h" #include "kinematics_parameters.h" namespace iit { namespace ct_quadrotor { template<typename SCALAR, int COLS, class M> class JacobianT : public iit::rbd::JacobianBase<tpl::JointState<SCALAR>, COLS, M> {}; namespace tpl{ /** * */ template <typename TRAIT> class Jacobians { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW typedef typename TRAIT::Scalar SCALAR; typedef JointState<SCALAR> JState; class Type_fr_body_J_fr_ee : public JacobianT<SCALAR, 2, Type_fr_body_J_fr_ee> { public: EIGEN_MAKE_ALIGNED_OPERATOR_NEW Type_fr_body_J_fr_ee(); const Type_fr_body_J_fr_ee& update(const JState&); protected: }; public: Jacobians(); void updateParameters(); public: Type_fr_body_J_fr_ee fr_body_J_fr_ee; protected: }; } //namespace tpl using Jacobians = tpl::Jacobians<rbd::DoubleTrait>; #include "jacobians.impl.h" } } #endif
[ "neunertm@gmail.com" ]
neunertm@gmail.com
67db1d2bec4aa5fc9b5139212f7901b5f6e887f3
2da76374ddeb148fda3a458cf8436685d1557e6a
/prasctermotre/vec2.cpp
ec6db8046e1507e18d306fdfa1cdec733b1b280a
[]
no_license
h2oyo/Spaceinvader
88cb21aed6cb96fdc15620567c11b8a2066cbd0f
fe20388a2f18f834b1c1a5d8884fe38a5364a221
refs/heads/master
2021-01-10T11:01:46.943992
2015-12-15T19:51:58
2015-12-15T19:51:58
48,064,713
0
0
null
null
null
null
UTF-8
C++
false
false
1,036
cpp
#include "vec2.h" #include <cmath> #include <ctime> float lerp(float start, float end, float alpha) { return start + alpha*(end - start); } float randRange(float min, float max) { float alpha = rand()/(RAND_MAX*1.f); return min + alpha*(max -min); } float distance(vec2 a, vec2 b) { float dx = a.x - b.x; float dy = a.y - b.y; return sqrt(dx*dx + dy*dy); } bool circleOverlap(vec2 pos1, float rad1, vec2 pos2, float rad2) { float d = distance(pos1, pos2); float r = rad1 + rad2; return d < r; } vec2 operator+ (vec2 a, vec2 b) { vec2 retval; retval.x = a.x + b.x; retval.y = a.y + b.y; return retval; } vec2 operator- (vec2 a, vec2 b) { vec2 retval; retval.x = a.x - b.x; retval.y = a.y - b.y; return retval; } vec2 operator* (vec2 a, float b) { vec2 retval; retval.x = a.x *b; retval.y = a.y *b; return retval; } vec2 operator/ (vec2 a, float b) { vec2 retval; retval.x = a.x / b; retval.y = a.y / b; return retval; } vec2 integrate(vec2 pos, vec2 vel, float dt) { return pos + vel *dt; }
[ "sonofhoddy@hotmail.com" ]
sonofhoddy@hotmail.com
4af35a542f8296768f6b4515dc1d69d4dbf8f7d6
72beee62189769abfef938abe8c56bfd6df1a399
/robot/error_state.h
6dd4a58b23bc19926f8d6814748fab7cb1a12fd5
[]
no_license
charliedurrant/robot
ef9fbff55e96c02a58d92e4811c0f8419096021d
479887656defe6dbc718d08297472dc9e2c02560
refs/heads/master
2021-01-25T05:34:07.565066
2014-11-13T23:22:35
2014-11-13T23:22:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
250
h
#pragma once #include "headers.h" using namespace std; class ErrorState : public State { public: ErrorState(string messsage, Exception* ex); ~ErrorState(void); void OnEnter() override; private: string _message; Exception* _exception; };
[ "charliedurrant@gmail.com" ]
charliedurrant@gmail.com
6cbd433dbf3879e63f95e086e0a734d026f6fb36
dc8552cb9670c1463a973ac065c4652296c562b8
/IRBugCanLib/examples/Master/LibDebugMaster.ino
e8ae28fc534328df6f99881f7ef3197a77c32a79
[]
no_license
twbrandon7/IR-Bug-Can
4c5db4ba31896abcc09a2215014cd82f39d2c0b8
2e925c6c3b0fded77bf7d6911820a7223d12f995
refs/heads/master
2020-03-23T11:41:10.324997
2018-07-20T03:27:57
2018-07-20T03:27:57
141,516,003
1
0
null
null
null
null
UTF-8
C++
false
false
503
ino
#include <IrBugCanLib.h> SoftwareSerial ss(10,11); IrBugCanLib irBugCanLib(&ss,3,13,4800); void setup() { // put your setup code here, to run once: irBugCanLib.begin(); Serial.begin(9600); } void loop() { // put your main code here, to run repeatedly: IrBugCanData data; irBugCanLib.readData(data); if(data.has_data){ Serial.println(String(data.has_data)); Serial.println("Time Pass : " + String(data.time_pass)); Serial.println("Bug Pest : " + String(data.bug_pest)); } }
[ "b0543017@ems.niu.edu.tw" ]
b0543017@ems.niu.edu.tw
cf07b16df2c7e1f5385702ecbca845cf43ff3c94
3c05da5cfd78711ada4f77109fc46946e9d5dd26
/code/foundation/id_array.h
ea11ff7219a51bec81b88f88fefe0b33d349bfa9
[]
no_license
uhacz/BitBox3
dab8eb131c31772ea2a63fa9c2e15076fa6ed5de
01978d757feb548cbab52d4e94bd6c6b00eb5daf
refs/heads/master
2020-07-29T03:20:13.083151
2020-02-13T22:27:12
2020-02-13T22:27:12
209,649,323
0
0
null
null
null
null
UTF-8
C++
false
false
3,380
h
#include "containers.h" #define BX_ID_ARRAY_T_DEF uint32_t MAX, typename Tid #define BX_ID_ARRAY_T_ARG MAX, Tid namespace id_array { template <BX_ID_ARRAY_T_DEF> inline Tid create( id_array_t<BX_ID_ARRAY_T_ARG>& a ) { SYS_ASSERT_TXT( a._size < MAX, "Object list full" ); // Obtain a new id Tid id; id.id = ++a._next_id; // Recycle slot if there are any if( a._freelist < MAX ) { id.index = a._freelist; a._freelist = a._sparse[a._freelist].index; } else { id.index = a._size; } a._sparse[id.index] = id; a._sparse_to_dense[id.index] = a._size; a._dense_to_sparse[a._size] = id.index; a._size++; return id; } template <BX_ID_ARRAY_T_DEF> inline Tid invalidate( id_array_t<BX_ID_ARRAY_T_ARG>& a, Tid id ) { SYS_ASSERT_TXT( has( a, id ), "IdArray does not have ID: %d,%d", id.id, id.index ); a._sparse[id.index].id = ++a._next_id; return a._sparse[id.index]; } template <BX_ID_ARRAY_T_DEF> inline id_array_destroy_info_t destroy( id_array_t<BX_ID_ARRAY_T_ARG>& a, Tid id ) { SYS_ASSERT_TXT( has( a, id ), "IdArray does not have ID: %d,%d", id.id, id.index ); a._sparse[id.index].id = -1; a._sparse[id.index].index = a._freelist; a._freelist = id.index; // Swap with last element const uint32_t last = a._size - 1; SYS_ASSERT_TXT( last >= a._sparse_to_dense[id.index], "Swapping with previous item" ); id_array_destroy_info_t ret; ret.copy_data_from_index = last; ret.copy_data_to_index = a._sparse_to_dense[id.index]; // Update tables uint16_t std = a._sparse_to_dense[id.index]; uint16_t dts = a._dense_to_sparse[last]; a._sparse_to_dense[dts] = std; a._dense_to_sparse[std] = dts; a._size--; return ret; } template <BX_ID_ARRAY_T_DEF> inline void destroyAll( id_array_t<BX_ID_ARRAY_T_ARG>& a ) { while( a._size ) { const uint32_t last = a._size - 1; Tid lastId = a._sparse[a._dense_to_sparse[last]]; destroy( a, lastId ); } } template <BX_ID_ARRAY_T_DEF> inline int index( const id_array_t<BX_ID_ARRAY_T_ARG>& a, const Tid& id ) { SYS_ASSERT_TXT( has( a, id ), "IdArray does not have ID: %d,%d", id.id, id.index ); return (int)a._sparse_to_dense[id.index]; } template <BX_ID_ARRAY_T_DEF> inline id_t id( const id_array_t<BX_ID_ARRAY_T_ARG>& a, uint32_t dense_index ) { SYS_ASSERT_TXT( dense_index < a._size, "Invalid index" ); const uint16_t sparse_index = a._dense_to_sparse[dense_index]; SYS_ASSERT_TXT( sparse_index < a.capacity(), "sparse index out of range" ); const id_t result = a._sparse[sparse_index]; SYS_ASSERT_TXT( has( a, result ), "id is dead" ); return result; } template <BX_ID_ARRAY_T_DEF> inline bool has( const id_array_t<BX_ID_ARRAY_T_ARG>& a, Tid id ) { return id.index < MAX && a._sparse[id.index].id == id.id; } template <BX_ID_ARRAY_T_DEF> inline uint32_t size( const id_array_t<BX_ID_ARRAY_T_ARG>& a ) { return a._size; } }///
[ "uhacz33@gmail.com" ]
uhacz33@gmail.com
fc88043f8323bc51cc5f29adfe0e0044c4e0f76a
84062443f2c4d40a7d61e0151257657607fbb1f7
/C++/main.cpp
05f436748a1f47188c2d7d14f06a8fad1704096d
[ "MIT" ]
permissive
KyleBanks/XOREncryption
b85d6e7a4f75d4f6221b7bc1fafd48d076feb4cc
df2c17f070aacebdfc3420c7275f91369dc444b6
refs/heads/master
2023-08-25T15:28:12.585777
2023-03-07T07:46:48
2023-03-07T07:46:48
13,353,241
337
105
MIT
2022-05-23T11:58:32
2013-10-05T21:59:02
Visual Basic .NET
UTF-8
C++
false
false
685
cpp
// // main.cpp // // Created by Kyle Banks on 2013-10-05. // #include <iostream> using namespace std; string encryptDecrypt(string toEncrypt) { char key[3] = {'K', 'C', 'Q'}; //Any chars will work, in an array of any size string output = toEncrypt; for (int i = 0; i < toEncrypt.size(); i++) output[i] = toEncrypt[i] ^ key[i % (sizeof(key) / sizeof(char))]; return output; } int main(int argc, const char * argv[]) { string encrypted = encryptDecrypt("kylewbanks.com"); cout << "Encrypted:" << encrypted << "\n"; string decrypted = encryptDecrypt(encrypted); cout << "Decrypted:" << decrypted << "\n"; return 0; }
[ "kyle@nthgensoftware.com" ]
kyle@nthgensoftware.com
4978486ca1e0dcc2fcfa7d1437d5287f39aea418
d3baacca0b2cc9d2276debc0b4e25c374174e04b
/Lab2/lab2_7.cpp
53342e84caeb38f55e41eea2cffb33f8b5ad93ae
[]
no_license
Taisoul/C_plus_plus
58a0042f3e6cacc35cbd21aba47b4d63661a36b6
063fd40a11594b09e8e69d23c0f578fe8b7960da
refs/heads/main
2023-09-04T20:28:25.024136
2021-10-19T04:40:05
2021-10-19T04:40:05
413,714,800
0
0
null
null
null
null
UTF-8
C++
false
false
280
cpp
#include<iostream> using namespace std; int main(){ float f; int i ; char c; double d; cout << "f value is "<< f << endl; cout << "i value is "<< i << endl; cout << "c value is "<< c << endl; cout << "d value is "<< d << endl; return(0); }
[ "markkoko01@gmail.com" ]
markkoko01@gmail.com
acbc7126565c9407787f9633f0a6fae2e4bae838
298937a765fb5b45530805c6c3fdd0882153fc36
/GazeControl/GazeControl/Sensor.h
58eda7763017a959e3c25ce64ad04113cf3e6a93
[]
no_license
imagicwei/for-magicwei-depplearning-gaze-control
fbe91607525ab10de5b9fc6693dcf6d37a1824a0
2258ee9c995f62218853657c67e4fe89cd86adcc
refs/heads/master
2021-01-10T09:42:51.612496
2015-10-27T06:19:47
2015-10-27T06:19:47
45,019,908
0
0
null
null
null
null
BIG5
C++
false
false
759
h
#include "stdafx.h" //this files contains #if !defined( SENSOR_H ) #define SENSOR_H //放入 extern 等原本在header裡面的資料,避免重複宣告 class Sensor { public: //members double azimuthDegree; double compassZero; double relativeAzimuth; cv::KalmanFilter azimuthKF; cv::Mat azimuthMeasurement; //Constructor Sensor(void) { this->azimuthDegree = 0; this->compassZero = 0; this->relativeAzimuth = 0; this->initial(); } //Destructor ~Sensor(void) { } //Functions void initial(); void run(); void setCompassZero( double angle = 0 ); void setRelativeAzimuth(); void calcRelativeAzimuthByKalman(); void calcRelativeAzimuthByMediumFilter(); double getRelativeAzimuth(); double getWaistTilt(); }; #endif
[ "q59105021@hotmail.com" ]
q59105021@hotmail.com
aa2d11f4c8798c86174c74063d162af4da82abdf
5ecca7ae4a8cdde41ee9ff725b6532e9b5a9a75f
/CGraph.h
81887af416e32efe380fdca273f4da2818eec373
[]
no_license
CodeStarting-design/linaliankan_game
5ac08e477506c58ebada33e3f076d7656964de68
743d61a399dd88372cc5c9ef9699c8ace3b74a4c
refs/heads/master
2022-12-09T17:14:10.105008
2020-08-31T15:13:54
2020-08-31T15:13:54
291,749,066
0
0
null
null
null
null
GB18030
C++
false
false
790
h
#pragma once #include"global.h" class CGraph //图的存储结构类 { public: CGraph(void); ~CGraph(void); typedef bool AdjMatrix[MAX_VERTEX_NUM][MAX_VERTEX_NUM]; typedef int Vertices[MAX_VERTEX_NUM]; int AddVertex(int info);//添加顶点(数组中存储编号) void AddArc(int nIndex1,int nIndex2);//添加边 void InitGraph(); int GetVertex(int nIndex);//获取一维数组中的值 bool GetArc(int nIndex1, int nIndex2);//获取图中的某条边 void UpdateVertex(int nIndex,int info);//对顶点数组进行更新 int GetVexnum(); void ClearGraph();//通过后清空图 protected: Vertices m_Vertices; //顶点数组 int m_nVertexNum; //顶点个数 AdjMatrix m_AdjMatrix; //存储边的二维数组 int m_nArcNum; //边的数量 };
[ "1225499794@qq.com" ]
1225499794@qq.com
2ce63ed0f42a44a482ab36dbf87c289744402722
3db6b2af68a176214f81b96c7766f87e1461ba02
/Hardware 3D/PerfLog.h
9b2e36381713056e133d276dffab9f425df3b606
[]
no_license
ArjanKamphuis/Hardware-3D
61a64e69c508288e3229d7e1dd167d493e4c40f8
ad5900b0ed16230b9b03ae1ba52290d88e34cb64
refs/heads/master
2023-08-18T09:08:39.538938
2021-10-14T14:52:20
2021-10-14T14:52:20
347,116,696
0
0
null
null
null
null
UTF-8
C++
false
false
666
h
#pragma once #include <string> #include <vector> #include "ChiliTimer.h" class PerfLog { private: class Entry { public: Entry(std::wstring s, float t); void WriteTo(std::wostream& out) const noexcept; private: std::wstring mLabel; float mTime; }; public: static void Start(const std::wstring& label = L"") noexcept; static void Mark(const std::wstring& label = L"") noexcept; private: PerfLog() noexcept; ~PerfLog(); static PerfLog& Get_() noexcept; void Start_(const std::wstring& label = L"") noexcept; void Mark_(const std::wstring& label = L"") noexcept; void Flush_(); private: ChiliTimer mTimer; std::vector<Entry> mEntries; };
[ "arjan_kamphuis@hotmail.com" ]
arjan_kamphuis@hotmail.com
ef159869b3696b676629a34e3cd43e52e68b3405
6e5dcde9b18367f451acc76d331de106925e6b3b
/202010/30/_463_IslandPerimeter.cpp
cf6d0960bf41a015c3b559f1f895378c46ddf4cb
[ "Apache-2.0" ]
permissive
uaniheng/leetcode-cpp
91c90794342746061c871985c8ee4cc30cd82a19
d7b4c9ef43cca8ecb703da5a910d79af61eb3394
refs/heads/main
2023-04-20T18:28:15.265112
2021-05-25T02:25:30
2021-05-25T02:25:30
311,859,333
0
0
Apache-2.0
2020-11-12T07:48:44
2020-11-11T04:09:25
C++
UTF-8
C++
false
false
691
cpp
// // Created by gyc on 2020/10/30. // #include "../../common.h" class Solution { public: int islandPerimeter(vector<vector<int>> &grid) { int res = 0; for (int i = 0; i < grid.size(); ++i) { for (int j = 0; j < grid[0].size(); ++j) { if (grid[i][j] == 1) { res += i > 0 ? (grid[i - 1][j] == 0 ? 1 : 0) : 1; res += i + 1 < grid.size() ? (grid[i + 1][j] == 0 ? 1 : 0) : 1; res += j > 0 ? (grid[i][j - 1] == 0 ? 1 : 0) : 1; res += j + 1 < grid[0].size() ? (grid[i][j + 1] == 0 ? 1 : 0) : 1; } } } return res; } };
[ "uaniheng@qq.com" ]
uaniheng@qq.com
ea1211a8d4b7e70de931cee6db14549e077fe9f5
ebae550ed5a1f7a22f40e0e13eafccaaf89ca1f9
/PDFs/src/MitNtupleEvent.cc
799634ebeb4b3f9f70fc6455993a32b16bf12d97
[]
no_license
GuillelmoGomezCeballos/Analysis
2f3c6bcce12d0c0fd2f31f1dd3128c29e448621e
dcd62044e2f4185ef1d0135121b8943d53ab65ef
refs/heads/master
2020-08-23T17:27:31.794640
2015-12-27T20:58:57
2015-12-27T20:58:57
16,200,153
0
0
null
null
null
null
UTF-8
C++
false
false
1,508
cc
#define MitNtupleEvent_cxx #include "Analysis/PDFs/interface/MitNtupleEvent.h" #include <TH2.h> #include <TStyle.h> #include <TCanvas.h> void MitNtupleEvent::Loop() { // In a ROOT session, you can do: // Root > .L MitNtupleEvent.C // Root > MitNtupleEvent t // Root > t.GetEntry(12); // Fill t data members with entry number 12 // Root > t.Show(); // Show values of entry 12 // Root > t.Show(16); // Read and show values of entry 16 // Root > t.Loop(); // Loop on all entries // // This is the loop skeleton where: // jentry is the global entry number in the chain // ientry is the entry number in the current Tree // Note that the argument to GetEntry must be: // jentry for TChain::GetEntry // ientry for TTree::GetEntry and TBranch::GetEntry // // To read only selected branches, Insert statements like: // METHOD1: // fChain->SetBranchStatus("*",0); // disable all branches // fChain->SetBranchStatus("branchname",1); // activate branchname // METHOD2: replace line // fChain->GetEntry(jentry); //read all branches //by b_branchname->GetEntry(ientry); //read only this branch if (fChain == 0) return; Long64_t nentries = fChain->GetEntriesFast(); Long64_t nbytes = 0, nb = 0; for (Long64_t jentry=0; jentry<nentries;jentry++) { Long64_t ientry = LoadTree(jentry); if (ientry < 0) break; nb = fChain->GetEntry(jentry); nbytes += nb; // if (Cut(ientry) < 0) continue; } }
[ "ceballos@dtmit02.cern.ch" ]
ceballos@dtmit02.cern.ch
d309a017284581f7a059e0ef21f75928ec85a1ec
c4839d1103c8d8fa6f2bd465f25e3675fb5f899b
/hw8/main.cpp
bbe62de4872f9ad70da9e632700d283fb1e40d6d
[]
no_license
nchen2211/DataStructure
d9503184705d2f761b09bd665967f36cb6bc47c9
b6fe74d7d2226bd596d87f9e5b9e6ebbfd623897
refs/heads/master
2021-04-09T15:30:51.559111
2016-05-27T21:07:07
2016-05-27T21:07:07
59,861,948
0
0
null
null
null
null
UTF-8
C++
false
false
1,256
cpp
#include "hashtable.h" #include "splaybst.h" #include <fstream> #include <sstream> #include <ctime> int main(int argc, char* argv[]) { if(argc < 2) { std::cerr << "Please provide an option followed by an input file." << std::endl; return 1; } char* option(argv[1]); std::ifstream infile (argv[2]); if (!infile) { std::cerr << "Cannot open " << infile << "!" << std::endl; return 1; } std::stringstream ss; std::string word; std::ofstream output; clock_t start; double duration; start = clock(); if (*option == '4') { SplayTree splaytree; while (infile >> word) splaytree.tolower(word); output.open ("splaytree_output.txt"); splaytree.reportAll(output); output.close(); } else if (*option == '5') { Hashtable *hashtable = new Hashtable; while (infile >> word) hashtable->add(word); output.open ("hashtable_output.txt"); hashtable->reportAll(output); output.close(); delete hashtable; hashtable = NULL; } duration = ( clock() - start ) / (double) CLOCKS_PER_SEC; std::cout << duration << std::endl; return 0; }
[ "nchrysilla@gmail.com" ]
nchrysilla@gmail.com
d7da7ef34f7a8474720524376ba0232620d69d2d
5362384b6b1d392eab659ebd5e02a89edc33a46c
/include/cutempl/metafunctions/on_args.hpp
96a711c1490ef0c416bebcbbb4dba76d90fbdf52
[ "MIT" ]
permissive
dhollman/cutempl
55c9f2dd5a4642af8e47fac459cfef99bb4e2f6c
5bb6cae4423f0456c21e50454bcba210a94226b3
refs/heads/main
2023-06-15T01:08:19.580873
2021-07-07T18:00:30
2021-07-07T18:00:30
371,742,730
4
0
null
null
null
null
UTF-8
C++
false
false
1,027
hpp
#pragma once #include "cutempl/cutempl_fwd.hpp" #include "cutempl/metafunctions/apply.hpp" #include "cutempl/utils/lambda.hpp" #include "cutempl/utils/wrap.hpp" namespace cutempl { // A higher-order metafunction that turns a metafunction class that operates // on `k` arguments to one that operates on `n` arguments (with n > k) by // selected the positional arguments indicated by the wrapped values struct on_args_mfc : lambda_mfc<( []<class MFC, auto... Idxs>(wrap<MFC>, wrap<wrap_value<Idxs>>...) { return lambda_mfc<( []<class... Ts>(wrap<Ts>...) { return apply<MFC, filter_t< } )>{}; return compose< apply_of_t<MFC>, map_t< curry_t<curry_mfc, wrapped_at_mfc>, type_list<wrap_value<Idxs>...> > enumerate_mfc, make_type_list_mfc > } )> {}; template <class... Ts> using = typename _mfc::template apply<Ts...>; template <class... Ts> using _t = typename <Ts...>::type; } // namespace cutempl
[ "dhollman@google.com" ]
dhollman@google.com
d4bfaf3b5b7c6624e3e1bc13133168e2d6e749e3
2dba1dc8e5c62631ad9801222d8a34b72b8a5635
/UVa Online Judge/volume003/381 Making the Grade/program.cpp
eb217d31f4d1783bc2f7fec624cbf3c42cd810ba
[]
no_license
dingswork/Code
f9e875417238efd04294b86c0b4261b4da867923
669139b70d0dbc8eae238d52aa7b8c0782fb9003
refs/heads/master
2021-01-24T16:52:10.703835
2018-02-27T14:07:25
2018-02-27T14:07:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,492
cpp
// Making the Grade // UVa ID: 381 // Verdict: Accepted // Submission Date: 2016-07-04 // UVa Run Time: 0.000s // // 版权所有(C)2016,邱秋。metaphysis # yeah dot net #include <cmath> #include <iomanip> #include <iostream> #include <vector> using namespace std; struct student { double average; int bouns, absences, grade; }; double roundToTenth(double number) { return (int)(number * 10.0 + 0.5) / 10.0; } int main(int argc, char *argv[]) { ios::sync_with_stdio(false); vector <student> students; int N, S, T; cin >> N; cout << "MAKING THE GRADE OUTPUT" << endl; for (int i = 1; i <= N; i++) { cin >> S >> T; students.clear(); for (int j = 1; j <= S; j++) { double lowest = 100.0, sumOfScores = 0.0, score; for (int k = 1; k <= T; k++) { cin >> score; sumOfScores += score; lowest = min(lowest, score); } student aStudent; cin >> aStudent.bouns >> aStudent.absences; if (T > 2) aStudent.average = roundToTenth((sumOfScores - lowest) / (T - 1)); else aStudent.average = sumOfScores / T; students.push_back(aStudent); } double sumOfPoints = 0.0, mean, sd; for (int i = 0; i < students.size(); i++) sumOfPoints += students[i].average; mean = roundToTenth(sumOfPoints / S); for (int i = 0; i < students.size(); i++) sd += pow(students[i].average - mean, 2); sd = roundToTenth(sqrt(sd / S)); double sumOfGrade = 0; for (int i = 0; i < students.size(); i++) { students[i].average = roundToTenth(students[i].average + 3.0 * (students[i].bouns / 2)); if (students[i].average >= (mean + sd)) students[i].grade = 4; else if (students[i].average >= mean) students[i].grade = 3; else if (students[i].average >= (mean - sd)) students[i].grade = 2; else students[i].grade = 1; if (students[i].absences > 0) students[i].grade -= students[i].absences / 4; else students[i].grade++; if (students[i].grade < 0) students[i].grade = 0; else if (students[i].grade > 4) students[i].grade = 4; sumOfGrade += students[i].grade; } cout << fixed << setprecision(1) << (sumOfGrade / S) << endl; } cout << "END OF OUTPUT" << endl; return 0; }
[ "metaphysis@yeah.net" ]
metaphysis@yeah.net
e59cd860b17ea65ed493902cadba9fcc2725aa03
1d9e60a377ce2b0b94234e90c3156f212f2a7e9b
/6/MultipleDocument/MultipleDocumentDoc.h
cc06477d1aea4b967fa8f3319baf2fd09899114a
[]
no_license
seehunter/visual_c-_reff_skill_code
fd13ceec2c34bd827f2556638bbc190be46d9b93
1a99bd875c32a04cbcc07c785b61270821c58341
refs/heads/master
2020-04-09T21:28:33.030596
2018-12-06T01:59:25
2018-12-06T01:59:25
160,603,401
0
0
null
null
null
null
UTF-8
C++
false
false
1,528
h
// MultipleDocumentDoc.h : interface of the CMultipleDocumentDoc class // ///////////////////////////////////////////////////////////////////////////// #if !defined(AFX_MULTIPLEDOCUMENTDOC_H__4110452E_ED08_4A04_86E5_FF06F8B03EB2__INCLUDED_) #define AFX_MULTIPLEDOCUMENTDOC_H__4110452E_ED08_4A04_86E5_FF06F8B03EB2__INCLUDED_ #if _MSC_VER > 1000 #pragma once #endif // _MSC_VER > 1000 class CMultipleDocumentDoc : public CDocument { protected: // create from serialization only CMultipleDocumentDoc(); DECLARE_DYNCREATE(CMultipleDocumentDoc) // Attributes public: // Operations public: // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CMultipleDocumentDoc) public: virtual BOOL OnNewDocument(); virtual void Serialize(CArchive& ar); //}}AFX_VIRTUAL // Implementation public: virtual ~CMultipleDocumentDoc(); #ifdef _DEBUG virtual void AssertValid() const; virtual void Dump(CDumpContext& dc) const; #endif protected: // Generated message map functions protected: //{{AFX_MSG(CMultipleDocumentDoc) // NOTE - the ClassWizard will add and remove member functions here. // DO NOT EDIT what you see in these blocks of generated code ! //}}AFX_MSG DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// //{{AFX_INSERT_LOCATION}} // Microsoft Visual C++ will insert additional declarations immediately before the previous line. #endif // !defined(AFX_MULTIPLEDOCUMENTDOC_H__4110452E_ED08_4A04_86E5_FF06F8B03EB2__INCLUDED_)
[ "seehunter@163.com" ]
seehunter@163.com
1f3eae5964719346a91074989cff360cb3d236b3
637180a02f20aaea1396f5942cbdc60fa0225970
/Checkers/Solver0.h
7d1a421b914e7e5d57cd25bb97151adfcd882299
[]
no_license
kevinchahine/Checkers
5c5c94d19119b82a7dd924cf0ce956bc72f68638
d31dcfc40d04ada27d1e5cb7d413d05181075fa6
refs/heads/master
2020-05-18T05:05:12.700357
2019-05-20T03:17:24
2019-05-20T03:17:24
184,193,960
0
0
null
null
null
null
UTF-8
C++
false
false
247
h
#pragma once #include "Solver.h" class Solver0 : public Solver { public: Solver0(); ~Solver0(); stringstream toStream() const; int calcHeuristic(const CheckersEngine & game) const; int heuristic2(const CheckersEngine & game) const; };
[ "kchahine17@gmail.com" ]
kchahine17@gmail.com
e843d89a4e3ced678b1323a0f1a881801f5ae8f3
46c48c45124c347cdfa8506016f5537fba82bc42
/objectTracking/src/objectTracking/lib/motionbasedtracker.cpp
160206e2971ff30d42e7909f5a44b93b4cd06eb4
[]
no_license
yzbx/surveillance-video-system
66f9234375d6b51709e03ba407ad9da07278b5dc
c4dfbb2a81bcf1b574cd8129245fce59501d108a
refs/heads/master
2020-12-25T17:36:25.769446
2017-01-16T06:54:03
2017-01-16T06:54:03
41,910,929
3
2
null
null
null
null
UTF-8
C++
false
false
10,024
cpp
#include "motionbasedtracker.h" MotionBasedTracker::MotionBasedTracker() { } void MotionBasedTracker::process(QString configFile, QString videoFile, TrackingStatus *status) { qDebug()<<"MotionBasedTracking ................."; // maskFeature=new QYzbxTrackingFeature; boost::property_tree::ptree pt; boost::property_tree::ini_parser::read_ini(configFile.toStdString(),pt); QString BGSType=QString::fromStdString(pt.get<std::string>("General.BGSType")); bgsFactory_yzbx bgsFac; if(status==NULL){ qDebug()<<"wait to implement"; exit(-1); } else{ if(BGSType!=status->BGSType){ delete status->ibgs; status->BGSType=BGSType; status->ibgs=bgsFac.getBgsAlgorithm(BGSType); status->frameinput.init(videoFile); status->frameinput.initBgs(status->ibgs,status->initFrameNum); status->bgsInited=true; } cv::Mat img_input,img_foreground,img_background; status->frameinput.getNextFrame(videoFile,img_input); processOne(img_input,img_foreground,img_background,status); } globalTrackingStatus=status; this->start(); } void MotionBasedTracker::processOne(const Mat &img_input, Mat &img_foreground, Mat &img_background, TrackingStatus *status) { cv::Scalar Colors[] = { cv::Scalar(255, 0, 0), cv::Scalar(0, 255, 0), cv::Scalar(0, 0, 255), cv::Scalar(255, 255, 0), cv::Scalar(0, 255, 255), cv::Scalar(255, 0, 255), cv::Scalar(255, 127, 255), cv::Scalar(127, 0, 255), cv::Scalar(127, 0, 127) }; status->ibgs->process(img_input,img_foreground,img_background); QYzbxTrackingFeature *trackingFeature=new QYzbxTrackingFeature; FrameFeature frameFeature; frameFeature.frameNum=status->frameinput.frameNum; if(!img_foreground.empty()){ // vector<Mat> objects; // objects=maskFeature->getObjectsFromMask(img_foreground,true); trackingFeature->getObjects(img_input,img_foreground,frameFeature); // status->frameFeatureList.push_back(frameFeature); // if(status->frameFeatureList.size()>status->trackingWindowSize){ // status->frameFeatureList.pop_front(); // } // TrackingObjectAssociation toa; // toa.process(status); qDebug()<<"dump frameFeature *********************************"; for(uint i=0;i<frameFeature.features.size();i++){ std::cout<<"["<<frameFeature.features[i].pos<<" "<<frameFeature.features[i].size<<"],"; } std::cout<<std::endl; singleFrameTracking(frameFeature); cv::Mat img_tracking=img_input.clone(); for (uint i=0;i<frameFeature.features.size();i++) { cv::circle(img_tracking, frameFeature.features[i].pos, 3, cv::Scalar(0, 255, 0), 1, CV_AA); } for (uint i = 0; i < tracks.size(); i++) { if (tracks[i]->trace.size() > 1) { for (uint j = 0; j < tracks[i]->trace.size() - 1; j++) { cv::line(img_tracking, tracks[i]->trace[j], tracks[i]->trace[j + 1], Colors[tracks[i]->TrackID % 9], 2, CV_AA); } } } imshow("img_tracking",img_tracking); } } void MotionBasedTracker::objectTracking(DirectedGraph &g) { (void)g; } void MotionBasedTracker::singleFrameTracking(FrameFeature &ff) { //init if (tracks.size() == 0) { // If no tracks yet for (size_t i = 0; i < ff.features.size(); ++i) { tracks.push_back(std::make_unique<singleFrameTracker>(ff.features[i],NextTrackID++)); } } size_t N = tracks.size(); size_t M = ff.features.size(); assignments_t assignment; if (!tracks.empty()&&!ff.features.empty()) { //create and init dist matrix/cost matrix. distMatrix_t Cost(N * M); std::cout<<"M="<<M<<" N="<<N<<std::endl; std::cout<<"dist matrix is: "<<std::endl; for (size_t i = 0; i < tracks.size(); i++) { for (size_t j = 0; j < ff.features.size(); j++) { Cost[i + j * N] = tracks[i]->CalcDistance(ff.features[j]); std::cout<<Cost[i+j*N]<<" "; } std::cout<<std::endl; } // ----------------------------------- // Solving assignment problem (tracks and predictions of Kalman filter) // ----------------------------------- AssignmentProblemSolver APS; APS.Solve(Cost, N, M, assignment, AssignmentProblemSolver::optimal); // ----------------------------------- // clean assignment from pairs with large distance // ----------------------------------- for (size_t i = 0; i < assignment.size(); i++) { if (assignment[i] != -1) { if (Cost[i + assignment[i] * N] > Distance_Threshold) { assignment[i] = -1; tracks[i]->skipped_frames = 1; } } else { // If track have no assigned detect, then increment skipped frames counter. tracks[i]->skipped_frames++; } } // ----------------------------------- // If track didn't get detects long time, remove it. // ----------------------------------- qDebug()<<"tracks.size()="<<tracks.size(); for (int i = 0; i < static_cast<int>(tracks.size()); i++) { if (tracks[i]->skipped_frames > maximum_allowed_skipped_frames) { tracks.erase(tracks.begin() + i); assignment.erase(assignment.begin() + i); i--; } } } // ----------------------------------- // Search for unassigned detects and start new tracks for them. // ----------------------------------- for (size_t i = 0; i < ff.features.size(); ++i) { if (find(assignment.begin(), assignment.end(), i) == assignment.end()) { tracks.push_back(std::make_unique<singleFrameTracker>(ff.features[i],NextTrackID++)); } } // Update Kalman Filters state if(ff.features.empty()){ for(uint i=0;i<tracks.size();i++){ assignment.push_back(-1); } } for (size_t i = 0; i<assignment.size(); i++) { // If track updated less than one time, than filter state is not correct. if (assignment[i] != -1) // If we have assigned detect, then update using its coordinates, { tracks[i]->skipped_frames = 0; tracks[i]->Update(ff.features[assignment[i]], true, max_trace_length); } else // if not continue using predictions { ObjectFeature of; tracks[i]->Update(of,false, max_trace_length); } } } void MotionBasedTracker::initBgs(TrackingStatus *status) { status->frameinput.initBgs(status->ibgs,status->initFrameNum); status->bgsInited=true; } void MotionBasedTracker::run() { QString videoFilePath=globalTrackingStatus->frameinput.videoFilePath; while(!globalStop){ cv::Mat img_input,img_foreground,img_background; globalTrackingStatus->frameinput.getNextFrame(videoFilePath,img_input); if(img_input.empty()){ break; } processOne(img_input,img_foreground,img_background,globalTrackingStatus); } globalStop=false; } void MotionBasedTracker::stop() { globalStop=true; } void singleFrameTracker::Update(ObjectFeature &of, bool dataCorrect, size_t max_trace_length) { //update pos kalman Mat prediction = pos_kalman.predict(); cv::Point2f predictPt(prediction.at<float>(0),prediction.at<float>(1)); cv::Mat measurement(2,1,CV_32FC1); if(!dataCorrect){ measurement.at<float>(0)=predictPt.x; measurement.at<float>(1)=predictPt.y; } else{ measurement.at<float>(0) =of.pos.x; measurement.at<float>(1) =of.pos.y; this->objectFeature->pos=of.pos; } cv::Mat estiMated = pos_kalman.correct(measurement); cv::Point2f correctPt(estiMated.at<float>(0),estiMated.at<float>(0)); this->objectFeature->pos_predict= correctPt; //update trace if (trace.size() > max_trace_length) { trace.erase(trace.begin(), trace.end() - max_trace_length); } trace.push_back(of.pos_predict); } float singleFrameTracker::CalcDistance(ObjectFeature &b) { cv::Point2d pa=this->objectFeature->pos_predict; cv::Point2d pb=b.pos; float sa=this->objectFeature->size; float sb=b.size; qDebug()<<"CalcDistance: "; qDebug()<<pa.x<<pa.y<<sa; qDebug()<<pb.x<<pb.y<<sb; float dx=(pa.x-pb.x)/sa; float dy=(pa.y-pb.y)/sa; float posDist=sqrt(dx*dx+dy*dy); float sizeDist=max(sa/sb,sb/sa)-1; float alpha=0.5; float weight=alpha*posDist+(1-alpha)*sizeDist; if(weight<=0||sa==0||sb==0){ qDebug()<<"what's the fuck!!!"; } return weight; } singleFrameTracker::singleFrameTracker(ObjectFeature &of, int id) { TrackID=id; this->objectFeature=&of; objectFeature->pos_predict=objectFeature->pos; objectFeature->size=objectFeature->size; // intialization of KF... pos_kalman.init(4,2,0); pos_kalman.transitionMatrix = *(Mat_<float>(4, 4) << 1,0,1,0, 0,1,0,1, 0,0,1,0, 0,0,0,1); pos_kalman.statePre.at<float>(0) = of.pos.x; pos_kalman.statePre.at<float>(1) = of.pos.y; pos_kalman.statePre.at<float>(2) = 0; pos_kalman.statePre.at<float>(3) = 0; setIdentity(pos_kalman.measurementMatrix); setIdentity(pos_kalman.processNoiseCov, Scalar::all(1e-4)); setIdentity(pos_kalman.measurementNoiseCov, Scalar::all(10)); setIdentity(pos_kalman.errorCovPost, Scalar::all(.1)); trace.push_back(of.pos); } singleFrameTracker::~singleFrameTracker() { }
[ "youdaoyzbx@163.com" ]
youdaoyzbx@163.com
a4a9b6cf9e05ac5da6d4887c41d43eac0a879909
31ecf13e864713fc2577ad6bb289763d211b22c3
/certain/tiny_rpc/tiny_server.h
1897b5c832e1d569e841f8a1b094b14b89fda099
[ "BSD-3-Clause", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
coutamg/LearnPaxosStore
29b277a26bc3d7ac2ebd5a9d98e921b3d6a04726
56ed4b6a4f1547b3cc5f8cc016084eefd3f64086
refs/heads/master
2023-07-27T03:52:48.778626
2021-09-12T08:21:32
2021-09-12T08:21:32
405,586,072
0
0
null
null
null
null
UTF-8
C++
false
false
721
h
#pragma once #include <vector> #include "tiny_rpc/tiny_rpc.h" #include "utils/co_lock.h" #include "utils/routine_worker.h" namespace certain { class TinyServer : public RoutineWorker<TcpSocket> { public: TinyServer(std::string local_addr, google::protobuf::Service* service) : RoutineWorker<TcpSocket>("tiny_server", 64), local_addr_(local_addr), service_(service) {} int Init(); void Stop(); private: std::unique_ptr<TcpSocket> GetJob() final; void DoJob(std::unique_ptr<TcpSocket> job) final; void Tick() final { Tick::Run(); } private: std::string local_addr_; google::protobuf::Service* service_; std::unique_ptr<TcpSocket> listen_socket_; }; } // namespace certain
[ "rockzheng@tencent.com" ]
rockzheng@tencent.com
affc65bfed85716373326358fa59f82cb28624a9
a17f2f1a8df7036c2ea51c27f31acf3fb2443e0b
/nowcoder/NC15 求二叉树的层序遍历.cpp
44ac511959d7afc20a8de857920289f23d8dbda3
[]
no_license
xUhEngwAng/oj-problems
c6409bc6ba72765600b8a844b2b18bc9a4ff6f6b
0c21fad1ff689cbd4be9bd150d3b30c836bd3753
refs/heads/master
2022-11-04T01:59:08.502480
2022-10-18T03:34:41
2022-10-18T03:34:41
165,620,152
3
1
null
null
null
null
UTF-8
C++
false
false
1,108
cpp
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ vector<vector<int>> levelOrder(TreeNode* root) { // write code here int currcnt = 1, nextcnt = 0; TreeNode *curr; vector<vector<int>> ret; if(root == nullptr) return ret; vector<int> temp; queue<TreeNode*> q; q.push(root); while(!q.empty()){ curr = q.front(); q.pop(); if(curr->left){ q.push(curr->left); nextcnt += 1; } if(curr->right){ q.push(curr->right); nextcnt += 1; } temp.push_back(curr->val); if(--currcnt == 0){ ret.push_back(temp); temp.clear(); currcnt = nextcnt; nextcnt = 0; } } return ret; } };
[ "1551885@tongji.edu.cn" ]
1551885@tongji.edu.cn
d9d2a8372980e7e766c0beb903fd8e3177a0c930
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/enduser/netmeeting/av/nac/threads.cpp
c40d400f24a4a298b4f47bae5f342b9cf6f1a208
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
30,319
cpp
#include "precomp.h" #include "mixer.h" #include "agc.h" // #define LOGSTATISTICS_ON 1 DWORD SendAudioStream::RecordingThread () { HRESULT hr = DPR_SUCCESS; MediaPacket *pPacket; DWORD dwWait; HANDLE hEvent; DWORD dwDuplexType; DWORD dwVoiceSwitch; DWORD_PTR dwPropVal; DWORD dwSamplesPerPkt; DWORD dwSamplesPerSec; DWORD dwSilenceLimit, dwMaxStrength, dwLengthMS; WORD wPeakStrength; UINT u, uBufferSize; UINT uSilenceCount = 0; UINT uPrefeed = 0; UINT uTimeout = 0; DevMediaQueue dq; BOOL fSilent; AGC agc(NULL); // audio gain control object CMixerDevice *pMixer = NULL; int nFailCount = 0; bool bCanSignalOpen=true; // should we signal that the device is open // note: pMC is an artifact of when this thread was in the Datapump // namespace. We can probably start phasing this variable out. // in the mean time: "pMC = this" will suffice // SendAudioStream *pMC = (SendAudioStream *)(m_pDP->m_Audio.pSendStream); SendAudioStream *pMC = this; ASSERT(pMC && (pMC->m_DPFlags & DPFLAG_INITIALIZED)); TxStream *pStream = pMC->m_SendStream; AcmFilter *pAudioFilter = pMC->m_pAudioFilter; // warning: typecasting a base class ptr to a derived class ptr. WaveInControl *pMediaCtrl = (WaveInControl *)pMC->m_InMedia; FX_ENTRY ("DP::RcrdTh:") // get thread context if (pStream == NULL || pAudioFilter == NULL || pMediaCtrl == NULL) { return DPR_INVALID_PARAMETER; } // Enter critical section: QoS thread also reads the statistics EnterCriticalSection(&pMC->m_crsQos); // Initialize QoS structure ZeroMemory(&pMC->m_Stats, 4UL * sizeof(DWORD)); // Initialize oldest QoS callback timestamp pMC->m_Stats.dwNewestTs = pMC->m_Stats.dwOldestTs = timeGetTime(); // Leave critical section LeaveCriticalSection(&pMC->m_crsQos); pMediaCtrl->GetProp(MC_PROP_MEDIA_DEV_ID, &dwPropVal); if (dwPropVal != (DWORD)WAVE_MAPPER) { pMixer = CMixerDevice::GetMixerForWaveDevice(NULL, (DWORD)dwPropVal, MIXER_OBJECTF_WAVEIN); } // even if pMixer is null, this is fine, AGC will catch subsequent errors agc.SetMixer(pMixer); // get thresholds pMediaCtrl->GetProp (MC_PROP_TIMEOUT, &dwPropVal); uTimeout = (DWORD)dwPropVal; pMediaCtrl->GetProp (MC_PROP_PREFEED, &dwPropVal); uPrefeed = (DWORD)dwPropVal; // get duplex type pMediaCtrl->GetProp (MC_PROP_DUPLEX_TYPE, &dwPropVal); dwDuplexType = (DWORD)dwPropVal; // get Samples/Pkt and Samples/Sec pMediaCtrl->GetProp (MC_PROP_SPP, &dwPropVal); dwSamplesPerPkt = (DWORD)dwPropVal; pMediaCtrl->GetProp (MC_PROP_SPS, &dwPropVal); dwSamplesPerSec = (DWORD)dwPropVal; pMediaCtrl->GetProp (MC_PROP_SILENCE_DURATION, &dwPropVal); dwSilenceLimit = (DWORD)dwPropVal; // calculate silence limit in units of packets // silence_time_in_ms/packet_duration_in_ms dwSilenceLimit = dwSilenceLimit*dwSamplesPerSec/(dwSamplesPerPkt*1000); // length of a packet in millisecs dwLengthMS = (dwSamplesPerPkt * 1000) / dwSamplesPerSec; dq.SetSize (MAX_TXRING_SIZE); WaitForSignal: // DEBUGMSG (1, ("%s: WaitForSignal\r\n", _fx_)); { pMediaCtrl->GetProp (MC_PROP_MEDIA_DEV_HANDLE, &dwPropVal); if (dwPropVal) { DEBUGMSG (ZONE_DP, ("%s: already open\r\n", _fx_)); goto SendLoop; // sound device already open } // in the full-duplex case, open and prepare the device and charge ahead. // in the half duplex case wait for playback's signal before opening the device while (TRUE) { // should I stop now??? if (pMC->m_ThreadFlags & DPTFLAG_STOP_RECORD) { DEBUGMSG (ZONE_DP, ("%s: STOP_1\r\n", _fx_)); goto MyEndThread; } dwWait = (dwDuplexType & DP_FLAG_HALF_DUPLEX) ? WaitForSingleObject (g_hEventHalfDuplex, uTimeout) : WAIT_OBJECT_0; // now, let's check why I don't need to wait if (dwWait == WAIT_OBJECT_0) { //DEBUGMSG (ZONE_DP, ("%s: try to open audio dev\r\n", _fx_)); LOG((LOGMSG_OPEN_AUDIO)); hr = pMediaCtrl->Open (); if (hr != DPR_SUCCESS) { DEBUGMSG (ZONE_DP, ("%s: MediaCtrl::Open failed, hr=0x%lX\r\n", _fx_, hr)); pMediaCtrl->SetProp(MC_PROP_AUDIO_JAMMED, TRUE); SetEvent(g_hEventHalfDuplex); nFailCount++; if (nFailCount == MAX_FAILCOUNT) { // three attempts to open the device have failed // signal to the UI that something is wrong m_pDP->StreamEvent(MCF_SEND, MCF_AUDIO, STREAM_EVENT_DEVICE_FAILURE, 0); bCanSignalOpen = true; } Sleep(2000); // Sleep for two seconds continue; } // Notification is not used. if needed do it thru Channel //pMC->m_Connection->DoNotification(CONNECTION_OPEN_MIC); pMediaCtrl->PrepareHeaders (); goto SendLoop; } } // while } SendLoop: nFailCount = 0; pMediaCtrl->SetProp(MC_PROP_AUDIO_JAMMED, FALSE); if (bCanSignalOpen) { m_pDP->StreamEvent(MCF_SEND, MCF_AUDIO, STREAM_EVENT_DEVICE_OPEN, 0); bCanSignalOpen = false; // don't signal more than once per session } // DEBUGMSG (1, ("%s: SendLoop\r\n", _fx_)); // get event handle pMediaCtrl->GetProp (MC_PROP_EVENT_HANDLE, &dwPropVal); hEvent = (HANDLE) dwPropVal; if (hEvent == NULL) { DEBUGMSG (ZONE_DP, ("%s: invalid event\r\n", _fx_)); return DPR_CANT_CREATE_EVENT; } // hey, in the very beginning, let's 'Start' it hr = pMediaCtrl->Start (); if (hr != DPR_SUCCESS) { DEBUGMSG (ZONE_DP, ("%s: MediaControl::Start failed, hr=0x%lX\r\n", _fx_, hr)); goto MyEndThread; } // update timestamp to account for the 'sleep' period pMC->m_SendTimestamp += (GetTickCount() - pMC->m_SavedTickCount)*dwSamplesPerSec/1000; // let's feed four buffers first for (u = 0; u < uPrefeed; u++) { if ((pPacket = pStream->GetFree ()) != NULL) { if ((hr = pPacket->Record ()) != DPR_SUCCESS) { DEBUGMSG (ZONE_DP, ("%s: Record failed, hr=0x%lX\r\n", _fx_, hr)); } dq.Put (pPacket); } } // let's get into the loop, mm system notification loop pMC->m_fSending= FALSE; while (TRUE) { dwWait = WaitForSingleObject (hEvent, uTimeout); // should I stop now??? if (pMC->m_ThreadFlags & DPTFLAG_STOP_RECORD) { DEBUGMSG (ZONE_DP, ("%s: STOP_3\r\n", _fx_)); goto HalfDuplexYield; } // get current voice switching mode pMediaCtrl->GetProp (MC_PROP_VOICE_SWITCH, &dwPropVal); dwVoiceSwitch = (DWORD)dwPropVal; // see why I don't need to wait if (dwWait != WAIT_TIMEOUT) { while (TRUE) { if ((pPacket = dq.Peek ()) != NULL) { if (! pPacket->IsBufferDone ()) { break; } else { if (pMC->m_mmioSrc.fPlayFromFile && pMC->m_mmioSrc.hmmioSrc) pPacket->ReadFromFile (&pMC->m_mmioSrc); u--; // one less buffer with the wave device } } else { DEBUGMSG (ZONE_VERBOSE, ("%s: Peek is NULL\r\n", _fx_)); break; } pPacket = dq.Get (); ((AudioPacket*)pPacket)->ComputePower (&dwMaxStrength, &wPeakStrength); // is this packet silent? fSilent = pMC->m_AudioMonitor.SilenceDetect((WORD)dwMaxStrength); if((dwVoiceSwitch == DP_FLAG_AUTO_SWITCH) && fSilent) { // pPacket->SetState (MP_STATE_RESET); // note: done in Recycle if (++uSilenceCount >= dwSilenceLimit) { pMC->m_fSending = FALSE; // stop sending packets // if half duplex mode and playback thread may be waiting if (dwDuplexType & DP_FLAG_HALF_DUPLEX) { IMediaChannel *pIMC = NULL; RecvMediaStream *pRecv; m_pDP->GetMediaChannelInterface(MCF_RECV | MCF_AUDIO, &pIMC); if (pIMC) { pRecv = static_cast<RecvMediaStream *> (pIMC); if (pRecv->IsEmpty()==FALSE) { //DEBUGMSG (ZONE_DP, ("%s: too many silence and Yield\r\n", _fx_)); LOG((LOGMSG_REC_YIELD)); pPacket->Recycle (); pStream->PutNextRecorded (pPacket); uSilenceCount = 0; pIMC->Release(); goto HalfDuplexYield; } pIMC->Release(); } } } } else { switch(dwVoiceSwitch) { // either there was NO silence, or manual switching is in effect default: case DP_FLAG_AUTO_SWITCH: // this proves no silence (in this path because of non-silence) case DP_FLAG_MIC_ON: pMC->m_fSending = TRUE; uSilenceCount = 0; break; case DP_FLAG_MIC_OFF: pMC->m_fSending = FALSE; break; } } if (pMC->m_fSending) { pPacket->SetState (MP_STATE_RECORDED); // do AUTOMIX, but ignore DTMF tones if (pMC->m_bAutoMix) { agc.Update(wPeakStrength, dwLengthMS); } } else { pPacket->Recycle(); // Enter critical section: QoS thread also reads the statistics EnterCriticalSection(&pMC->m_crsQos); // Update total number of packets recorded pMC->m_Stats.dwCount++; // Leave critical section LeaveCriticalSection(&pMC->m_crsQos); } pPacket->SetProp(MP_PROP_TIMESTAMP,pMC->m_SendTimestamp); // pPacket->SetProp(MP_PROP_TIMESTAMP,GetTickCount()); pMC->m_SendTimestamp += dwSamplesPerPkt; pStream->PutNextRecorded (pPacket); } // while } else { if (dwDuplexType & DP_FLAG_HALF_DUPLEX) { DEBUGMSG (ZONE_DP, ("%s: Timeout and Yield\r\n", _fx_)); goto HalfDuplexYield; } } // if pMC->Send(); // Make sure the recorder has an adequate number of buffers while ((pPacket = pStream->GetFree()) != NULL) { if ((hr = pPacket->Record ()) == DPR_SUCCESS) { dq.Put (pPacket); } else { dq.Put (pPacket); DEBUGMSG (ZONE_DP, ("%s: Record FAILED, hr=0x%lX\r\n", _fx_, hr)); break; } u++; } if (u < uPrefeed) { DEBUGMSG (ZONE_DP, ("%s: NO FREE BUFFERS\r\n", _fx_)); } } // while TRUE goto MyEndThread; HalfDuplexYield: // stop and reset audio device pMediaCtrl->Reset (); // flush dq while ((pPacket = dq.Get ()) != NULL) { pStream->PutNextRecorded (pPacket); pPacket->Recycle (); } // save real time so we can update the timestamp when we restart pMC->m_SavedTickCount = GetTickCount(); // reset the event ResetEvent (hEvent); // close audio device pMediaCtrl->UnprepareHeaders (); pMediaCtrl->Close (); // signal playback thread to start SetEvent (g_hEventHalfDuplex); if (!(pMC->m_ThreadFlags & DPTFLAG_STOP_RECORD)) { // yield // playback has to claim the device within 100ms or we take it back. Sleep (100); // wait for playback's signal goto WaitForSignal; } MyEndThread: if (pMixer) delete pMixer; pMediaCtrl->SetProp(MC_PROP_AUDIO_JAMMED, FALSE); pMC->m_fSending = FALSE; DEBUGMSG (ZONE_DP, ("%s: Exiting.\r\n", _fx_)); return hr; } DWORD RecvAudioStream::PlaybackThread ( void) { HRESULT hr = DPR_SUCCESS; MediaPacket * pPacket; MediaPacket * pPrevPacket; MediaPacket * pNextPacket; DWORD dwWait; HANDLE hEvent; DWORD dwDuplexType; DWORD_PTR dwPropVal; UINT u; UINT uMissingCount = 0; UINT uPrefeed = 0; UINT uTimeout = 0; UINT uSamplesPerPkt=0; DevMediaQueue dq; UINT uGoodPacketsQueued = 0; int nFailCount = 0; bool bCanSignalOpen=true; //warning: casting from base to dervied class // note: pMC is an artifact of when this thread was in the Datapump // namespace. We can probably start phasing this variable out. // in the mean time: "pMC = this" will suffice // RecvAudioStream *pMC = (RecvAudioStream *)(m_pDP->m_Audio.pRecvStream); RecvAudioStream *pMC = this; RxStream *pStream = pMC->m_RecvStream; MediaControl *pMediaCtrl = pMC->m_OutMedia; #if 0 NETBUF * pStaticNetBuf; #endif FX_ENTRY ("DP::PlayTh") if (pStream == NULL || m_pAudioFilter == NULL || pMediaCtrl == NULL) { return DPR_INVALID_PARAMETER; } // get event handle pMediaCtrl->GetProp (MC_PROP_EVENT_HANDLE, &dwPropVal); hEvent = (HANDLE) dwPropVal; if (hEvent == NULL) { DEBUGMSG (ZONE_DP, ("%s: invalid event\r\n", _fx_)); return DPR_CANT_CREATE_EVENT; } // get thresholds pMediaCtrl->GetProp (MC_PROP_TIMEOUT, &dwPropVal); uTimeout = (DWORD)dwPropVal; uPrefeed = pStream->BufferDelay(); // get samples per pkt pMediaCtrl->GetProp(MC_PROP_SPP, &dwPropVal); uSamplesPerPkt = (DWORD)dwPropVal; // get duplex type pMediaCtrl->GetProp (MC_PROP_DUPLEX_TYPE, &dwPropVal); dwDuplexType = (DWORD)dwPropVal; // set dq size dq.SetSize (uPrefeed); WaitForSignal: // DEBUGMSG (1, ("%s: WaitForSignal\r\n", _fx_)); pMediaCtrl->GetProp (MC_PROP_MEDIA_DEV_HANDLE, &dwPropVal); if (dwPropVal) { DEBUGMSG (ZONE_DP, ("%s: already open\r\n", _fx_)); goto RecvLoop; // already open } // in the full-duplex case, open and prepare the device and charge ahead. // in the half duplex case wait for playback's signal before opening the device while (TRUE) { // should I stop now??? if (pMC->m_ThreadFlags & DPTFLAG_STOP_PLAY) { DEBUGMSG (ZONE_VERBOSE, ("%s: STOP_1\r\n", _fx_)); goto MyEndThread; } dwWait = (dwDuplexType & DP_FLAG_HALF_DUPLEX) ? WaitForSingleObject (g_hEventHalfDuplex, uTimeout) : WAIT_OBJECT_0; // to see why I don't need to wait if (dwWait == WAIT_OBJECT_0) { // DEBUGMSG (1, ("%s: try to open audio dev\r\n", _fx_)); pStream->FastForward(FALSE); // GJ - flush receive queue hr = pMediaCtrl->Open (); if (hr != DPR_SUCCESS) { // somebody may have commandeered the wave out device // this could be a temporary problem so lets give it some time DEBUGMSG (ZONE_DP, ("%s: MediaControl::Open failed, hr=0x%lX\r\n", _fx_, hr)); pMediaCtrl->SetProp(MC_PROP_AUDIO_JAMMED, TRUE); SetEvent(g_hEventHalfDuplex); nFailCount++; if (nFailCount == MAX_FAILCOUNT) { // three attempts to open the device have failed // signal to the UI that something is wrong m_pDP->StreamEvent(MCF_RECV, MCF_AUDIO, STREAM_EVENT_DEVICE_FAILURE, 0); bCanSignalOpen = true; } Sleep(2000); // sleep for two seconds continue; } // Notification is not used. if needed do it thru Channel //pMC->m_Connection->DoNotification(CONNECTION_OPEN_SPK); pMediaCtrl->PrepareHeaders (); goto RecvLoop; } } // while RecvLoop: nFailCount = 0; pMediaCtrl->SetProp(MC_PROP_AUDIO_JAMMED, FALSE); if (bCanSignalOpen) { m_pDP->StreamEvent(MCF_RECV, MCF_AUDIO, STREAM_EVENT_DEVICE_OPEN, 0); bCanSignalOpen = false; // don't signal open more than once per session } // Set my thread priority high // This thread doesnt do any compute intensive work (except maybe // interpolate?). // Its sole purpose is to stream ready buffers to the sound device SetThreadPriority(pMC->m_hRenderingThread, THREAD_PRIORITY_HIGHEST); // DEBUGMSG (1, ("%s: SendLoop\r\n", _fx_)); // let's feed four buffers first // But make sure the receive stream has enough buffering delay // so we dont read past the last packet. //if (uPrefeed > pStream->BufferDelay()) uGoodPacketsQueued = 0; for (u = 0; u < uPrefeed; u++) { if ((pPacket = pStream->GetNextPlay ()) != NULL) { if (pPacket->GetState () == MP_STATE_RESET) { // hr = pPacket->Play (pStaticNetBuf); hr = pPacket->Play (&pMC->m_mmioDest, MP_DATATYPE_SILENCE); } else { // hr = pPacket->Play (); hr = pPacket->Play (&pMC->m_mmioDest, MP_DATATYPE_FROMWIRE); uGoodPacketsQueued++; } if (hr != DPR_SUCCESS) { DEBUGMSG (ZONE_DP, ("%s: Play failed, hr=0x%lX\r\n", _fx_, hr)); SetEvent(hEvent); } dq.Put (pPacket); } } pMC->m_fReceiving = TRUE; // let's get into the loop uMissingCount = 0; while (TRUE) { dwWait = WaitForSingleObject (hEvent, uTimeout); // should I stop now??? if (pMC->m_ThreadFlags & DPTFLAG_STOP_PLAY) { DEBUGMSG (ZONE_VERBOSE, ("%s: STOP_3\r\n", _fx_)); goto HalfDuplexYield; } // see why I don't need to wait if (dwWait != WAIT_TIMEOUT) { while (TRUE) { if ((pPacket = dq.Peek ()) != NULL) { if (! pPacket->IsBufferDone ()) { break; } } else { DEBUGMSG (ZONE_VERBOSE, ("%s: Peek is NULL\r\n", _fx_)); break; } pPacket = dq.Get (); if (pPacket->GetState() != MP_STATE_PLAYING_SILENCE) uGoodPacketsQueued--; // a non-empty buffer just got done pMC->m_PlaybackTimestamp = pPacket->GetTimestamp() + uSamplesPerPkt; pPacket->Recycle (); pStream->Release (pPacket); if ((pPacket = pStream->GetNextPlay ()) != NULL) { // check if we are in half-duplex mode and also if // the recording thread is around. if (dwDuplexType & DP_FLAG_HALF_DUPLEX) { IMediaChannel *pIMC = NULL; BOOL fSending = FALSE; m_pDP->GetMediaChannelInterface(MCF_SEND | MCF_AUDIO, &pIMC); if (pIMC) { fSending = (pIMC->GetState() == MSSTATE_STARTED); pIMC->Release(); } if (fSending) { if (pPacket->GetState () == MP_STATE_RESET) { // Decide if its time to yield // Dont want to yield until we've finished playing all data packets // if (!uGoodPacketsQueued && (pStream->IsEmpty() || ++uMissingCount >= DEF_MISSING_LIMIT)) { //DEBUGMSG (ZONE_DP, ("%s: too many missings and Yield\r\n", _fx_)); LOG( (LOGMSG_PLAY_YIELD)); pPacket->Recycle (); pStream->Release (pPacket); goto HalfDuplexYield; } } else { uMissingCount = 0; } } } if (pPacket->GetState () == MP_STATE_RESET) { pPrevPacket = pStream->PeekPrevPlay (); pNextPacket = pStream->PeekNextPlay (); hr = pPacket->Interpolate(pPrevPacket, pNextPacket); if (hr != DPR_SUCCESS) { //DEBUGMSG (ZONE_DP, ("%s: Interpolate failed, hr=0x%lX\r\n", _fx_, hr)); hr = pPacket->Play (&pMC->m_mmioDest, MP_DATATYPE_SILENCE); } else hr = pPacket->Play (&pMC->m_mmioDest, MP_DATATYPE_INTERPOLATED); } else { // hr = pPacket->Play (); hr = pPacket->Play (&pMC->m_mmioDest, MP_DATATYPE_FROMWIRE); uGoodPacketsQueued++; } if (hr != DPR_SUCCESS) { DEBUGMSG (ZONE_DP, ("%s: Play failed, hr=0x%lX\r\n", _fx_, hr)); SetEvent(hEvent); } dq.Put (pPacket); } else { DEBUGMSG( ZONE_DP, ("%s: NO PLAY BUFFERS!",_fx_)); } } // while } else { if (dwDuplexType & DP_FLAG_HALF_DUPLEX) { DEBUGMSG (ZONE_DP, ("%s: Timeout and Yield!\r\n", _fx_)); goto HalfDuplexYield; } } } // while TRUE goto MyEndThread; HalfDuplexYield: pMC->m_fReceiving = FALSE; // stop and reset audio device pMediaCtrl->Reset (); // flush dq while ((pPacket = dq.Get ()) != NULL) { pPacket->Recycle (); pStream->Release (pPacket); } // reset the event ResetEvent (hEvent); // close audio device pMediaCtrl->UnprepareHeaders (); pMediaCtrl->Close (); // signal recording thread to start SetEvent (g_hEventHalfDuplex); if (!(pMC->m_ThreadFlags & DPTFLAG_STOP_PLAY)) { // yield Sleep (0); // wait for recording's signal // restore thread priority SetThreadPriority(pMC->m_hRenderingThread,THREAD_PRIORITY_NORMAL); goto WaitForSignal; } MyEndThread: pMediaCtrl->SetProp(MC_PROP_AUDIO_JAMMED, FALSE); DEBUGMSG(ZONE_DP, ("%s: Exiting.\n", _fx_)); return hr; } DWORD SendAudioStream::Send() { MMRESULT mmr; MediaPacket *pAP; void *pBuffer; DWORD dwBeforeEncode; DWORD dwAfterEncode; DWORD dwPacketSize; UINT uBytesSent; #ifdef LOGSTATISTICS_ON char szDebug[256]; DWORD dwDebugSaveBits; #endif while ( pAP = m_SendStream->GetNext()) { if (!(m_ThreadFlags & DPTFLAG_PAUSE_SEND)) { dwBeforeEncode = timeGetTime(); mmr = m_pAudioFilter->Convert((AudioPacket*)pAP, AP_ENCODE); if (mmr == MMSYSERR_NOERROR) { pAP->SetState(MP_STATE_ENCODED); } // Time the encoding operation dwAfterEncode = timeGetTime() - dwBeforeEncode; if (mmr == MMSYSERR_NOERROR) { SendPacket((AudioPacket*)pAP, &uBytesSent); } else { uBytesSent = 0; } UPDATE_COUNTER(g_pctrAudioSendBytes, uBytesSent*8); // Enter critical section: QoS thread also reads the statistics EnterCriticalSection(&m_crsQos); // Update total number of packets recorded m_Stats.dwCount++; // Save the perfs in our stats structure for QoS #ifdef LOGSTATISTICS_ON dwDebugSaveBits = m_Stats.dwBits; #endif // Add this new frame size to the cumulated size m_Stats.dwBits += (uBytesSent * 8); // Add this compression time to total compression time m_Stats.dwMsComp += dwAfterEncode; #ifdef LOGSTATISTICS_ON wsprintf(szDebug, " A: (Voiced) dwBits = %ld up from %ld (file: %s line: %ld)\r\n", m_Stats.dwBits, dwDebugSaveBits, __FILE__, __LINE__); OutputDebugString(szDebug); #endif // Leave critical section LeaveCriticalSection(&m_crsQos); } // whether or not we sent the packet, we need to return // it to the free queue pAP->m_fMark=0; pAP->SetState(MP_STATE_RESET); m_SendStream->Release(pAP); } return DPR_SUCCESS; } // queues and sends the packet // if the packet failed the encode process, it doesn't get sent HRESULT SendAudioStream::SendPacket(AudioPacket *pAP, UINT *puBytesSent) { PS_QUEUE_ELEMENT psq; UINT uLength; int nPacketsSent=0; if (pAP->GetState() != MP_STATE_ENCODED) { DEBUGMSG (ZONE_ACM, ("SendAudioStream::SendPacket: Packet not compressed\r\n")); *puBytesSent = 0; return E_FAIL; } ASSERT(m_pRTPSend); psq.pMP = pAP; psq.dwPacketType = PS_AUDIO; psq.pRTPSend = m_pRTPSend; pAP->GetNetData((void**)(&(psq.data)), &uLength); ASSERT(psq.data); psq.dwSize = uLength; psq.fMark = pAP->m_fMark; psq.pHeaderInfo = NULL; psq.dwHdrSize = 0; *puBytesSent = uLength + sizeof(RTP_HDR) + IP_HEADER_SIZE + UDP_HEADER_SIZE; // add audio packets to the front of the queue m_pDP->m_PacketSender.m_SendQueue.PushFront(psq); while (m_pDP->m_PacketSender.SendPacket()) { ; } return S_OK; }; #ifdef OLDSTUFF /* // Winsock 1 receive thread // Creates a hidden window and a message loop to process WINSOCK window // messages. Also processes private messages from the datapump to start/stop // receiving on a particular media stream */ DWORD DataPump::CommonRecvThread (void ) { HRESULT hr; HWND hWnd = (HWND)NULL; RecvMediaStream *pRecvMC; BOOL fChange = FALSE; MSG msg; DWORD curTime, nextUpdateTime = 0, t; UINT timerId = 0; FX_ENTRY ("DP::RecvTh") // Create hidden window hWnd = CreateWindowEx( WS_EX_NOPARENTNOTIFY, "SockMgrWClass", /* See RegisterClass() call. */ NULL, WS_CHILD , /* Window style. */ CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, m_hAppWnd, /* the application window is the parent. */ (HMENU)this, /* hardcoded ID */ m_hAppInst, /* the application owns this window. */ NULL /* Pointer not needed. */ ); if(!hWnd) { hr = GetLastError(); DEBUGMSG(ZONE_DP,("CreateWindow returned %d\n",hr)); goto CLEANUPEXIT; } SetThreadPriority(m_hRecvThread, THREAD_PRIORITY_ABOVE_NORMAL); // This function is guaranteed to create a queue on this thread PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE); // notify thread creator that we're ready to recv messages SetEvent(m_hRecvThreadAckEvent); // Wait for control messages from Start()/Stop() or Winsock messages directed to // our hidden window while (GetMessage(&msg, NULL, 0, 0)) { switch(msg.message) { case MSG_START_RECV: // Start receiving on the specified media stream DEBUGMSG(ZONE_VERBOSE,("%s: MSG_START_RECV\n",_fx_)); pRecvMC = (RecvMediaStream *)msg.lParam; // call the stream to post recv buffers and // tell Winsock to start sending socket msgs to our window pRecvMC->StartRecv(hWnd); fChange = TRUE; break; case MSG_STOP_RECV: // Stop receiving on the specified media stream DEBUGMSG(ZONE_VERBOSE,("%s: MSG_STOP_RECV\n",_fx_)); pRecvMC = (RecvMediaStream *)msg.lParam; // call the stream to cancel outstanding recvs etc. // currently we assume this can be done synchronously pRecvMC->StopRecv(); fChange = TRUE; break; case MSG_EXIT_RECV: // Exit the recv thread. // Assume that we are not currently receving on any stream. DEBUGMSG(ZONE_VERBOSE,("%s: MSG_EXIT_RECV\n",_fx_)); fChange = TRUE; if (DestroyWindow(hWnd)) { break; } DEBUGMSG(ZONE_DP,("DestroyWindow returned %d\n",GetLastError())); // fall thru to PostQuitMessage() case WM_DESTROY: PostQuitMessage(0); break; case WM_TIMER: if (msg.hwnd == NULL) { // this timer is for the benefit of ThreadTimer::UpdateTime() // however, we are calling UpdateTime after every message (see below) // so we dont do anything special here. break; } default: TranslateMessage(&msg); DispatchMessage(&msg); } if (fChange) { // the thread MSGs need to be acked SetEvent(m_hRecvThreadAckEvent); fChange = FALSE; } t = m_RecvTimer.UpdateTime(curTime=GetTickCount()); if (t != nextUpdateTime) { // Thread timer wants to change its update time nextUpdateTime = t; if (timerId) { KillTimer(NULL,timerId); timerId = 0; } // if nextTime is zero, there are no scheduled timeouts so we dont need to call UpdateTime if (nextUpdateTime) timerId = SetTimer(NULL, 0, nextUpdateTime - curTime + 50, NULL); } } CLEANUPEXIT: DEBUGMSG(ZONE_DP,("%s terminating.\n", _fx_)); return hr; } #endif /* Winsock 2 receive thread. Main differnce here is that it has a WaitEx loop where we wait for Start/Stop commands from the datapump while allowing WS2 APCs to be handled. Note: Only way to use the same thread routine for WS1 and WS2 is with MsgWaitForMultipleObjectsEx, which unfortunately is not implemented in Win95 */ DWORD DataPump::CommonWS2RecvThread (void ) { HRESULT hr; RecvMediaStream *pRecvMC; BOOL fChange = FALSE, fExit = FALSE; DWORD dwWaitStatus; DWORD curTime, t; FX_ENTRY ("DP::WS2RecvTh") SetThreadPriority(m_hRecvThread, THREAD_PRIORITY_ABOVE_NORMAL); // notify thread creator that we're ready to recv messages SetEvent(m_hRecvThreadAckEvent); while (!fExit) { // Wait for control messages from Start()/Stop() or Winsock async // thread callbacks // dispatch expired timeouts and check how long we need to wait t = m_RecvTimer.UpdateTime(curTime=GetTickCount()); t = (t ? t-curTime+50 : INFINITE); dwWaitStatus = WaitForSingleObjectEx(m_hRecvThreadSignalEvent,t,TRUE); if (dwWaitStatus == WAIT_OBJECT_0) { switch(m_CurRecvMsg) { case MSG_START_RECV: // Start receiving on the specified media stream DEBUGMSG(ZONE_VERBOSE,("%s: MSG_START_RECV\n",_fx_)); pRecvMC = m_pCurRecvStream; // call the stream to post recv buffers and // tell Winsock to start sending socket msgs to our window pRecvMC->StartRecv(NULL); fChange = TRUE; break; case MSG_STOP_RECV: // Stop receiving on the specified media stream DEBUGMSG(ZONE_VERBOSE,("%s: MSG_STOP_RECV\n",_fx_)); pRecvMC = m_pCurRecvStream; // call the stream to cancel outstanding recvs etc. // currently we assume this can be done synchronously pRecvMC->StopRecv(); fChange = TRUE; break; case MSG_EXIT_RECV: // Exit the recv thread. // Assume that we are not currently receving on any stream. DEBUGMSG(ZONE_VERBOSE,("%s: MSG_EXIT_RECV\n",_fx_)); fChange = TRUE; fExit = TRUE; break; case MSG_PLAY_SOUND: fChange = TRUE; pRecvMC->OnDTMFBeep(); break; default: // shouldnt be anything else ASSERT(0); } if (fChange) { // the thread MSGs need to be acked SetEvent(m_hRecvThreadAckEvent); fChange = FALSE; } } else if (dwWaitStatus == WAIT_IO_COMPLETION) { // nothing to do here } else if (dwWaitStatus != WAIT_TIMEOUT) { DEBUGMSG(ZONE_DP,("%s: Wait failed with %d",_fx_,GetLastError())); fExit=TRUE; } } DEBUGMSG(ZONE_DP,("%s terminating.\n", _fx_)); return 0; } void ThreadTimer::SetTimeout(TTimeout *pTObj) { DWORD time = pTObj->GetDueTime(); // insert in increasing order of timeout for (TTimeout *pT = m_TimeoutList.pNext; pT != &m_TimeoutList; pT = pT->pNext) { if ((int)(pT->m_DueTime- m_CurTime) > (int) (time - m_CurTime)) break; } pTObj->InsertAfter(pT->pPrev); } void ThreadTimer::CancelTimeout(TTimeout *pTObj) { pTObj->Remove(); // remove from list } // Called by thread with the current time as input (usually obtained from GetTickCount()) // Returns the time by which UpdateTime() should be called again or currentTime+0xFFFFFFFF if there // are no scheduled timeouts DWORD ThreadTimer::UpdateTime(DWORD curTime) { TTimeout *pT; m_CurTime = curTime; // figure out which timeouts have elapsed and do the callbacks while (!IsEmpty()) { pT = m_TimeoutList.pNext; if ((int)(pT->m_DueTime-m_CurTime) <= 0) { pT->Remove(); pT->TimeoutIndication(); } else break; } return (IsEmpty() ? m_CurTime+INFINITE : m_TimeoutList.pNext->m_DueTime); } 
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com
fa29357e6d76620e29ca4191c5ecf921c7e32acb
fdfbebcc3a5e635b8273d1b39492e797932d547f
/wxRaytracer/raytracer/Textures/ImageTexture.cpp
290ea178d75d826582be7252c78e660b7a3ccede
[]
no_license
WindyPaper/raytracing
eca738ff67ce420be8e151d5c6a4ce62ac749ae4
2e38260e33fd87c1ff07f6212bc394470d89dbbc
refs/heads/master
2021-01-23T06:45:15.360491
2017-09-07T15:29:26
2017-09-07T15:29:26
86,397,382
0
1
null
null
null
null
UTF-8
C++
false
false
2,866
cpp
// Copyright (C) Kevin Suffern 2000-2007. // Revised by mp77 at 2012 // This C++ code is for non-commercial purposes only. // This C++ code is licensed under the GNU General Public License Version 2. // See the file COPYING.txt for the full license. #include "ImageTexture.h" // ---------------------------------------------------------------- default constructor ImageTexture::ImageTexture(void) : Texture(), hres(100), vres(100), image_ptr(NULL), mapping_ptr(NULL) {} // ---------------------------------------------------------------- constructor ImageTexture::ImageTexture(Image* _image_ptr) : Texture(), hres(_image_ptr->get_hres()), vres(_image_ptr->get_vres()), image_ptr(_image_ptr), mapping_ptr(NULL) {} // ---------------------------------------------------------------- copy constructor ImageTexture::ImageTexture(const ImageTexture& it) : Texture(it), hres(it.hres), vres(it.vres) { if (it.image_ptr) *image_ptr = *it.image_ptr; else image_ptr = NULL; if (it.mapping_ptr) mapping_ptr = it.mapping_ptr->clone(); else mapping_ptr = NULL; } // ---------------------------------------------------------------- assignment operator ImageTexture& ImageTexture::operator= (const ImageTexture& rhs) { if (this == &rhs) return (*this); Texture::operator= (rhs); hres = rhs.hres; vres = rhs.vres; if (image_ptr) { delete image_ptr; image_ptr = NULL; } if (rhs.image_ptr) *image_ptr = *rhs.image_ptr; if (mapping_ptr) { delete mapping_ptr; mapping_ptr = NULL; } if (rhs.mapping_ptr) mapping_ptr = rhs.mapping_ptr->clone(); return (*this); } // ---------------------------------------------------------------- clone ImageTexture* ImageTexture::clone(void) const { return (new ImageTexture (*this)); } // ---------------------------------------------------------------- destructor ImageTexture::~ImageTexture (void) { if (image_ptr) { delete image_ptr; image_ptr = NULL; } if (mapping_ptr) { delete mapping_ptr; mapping_ptr = NULL; } } // ---------------------------------------------------------------- get_color // When we ray trace a triangle mesh object with uv mapping, the mapping pointer may be NULL // because we can define uv coordinates on an arbitrary triangle mesh. // In this case we don't use the local hit point because the pixel coordinates are computed // from the uv coordinates stored in the ShadeRec object in the uv triangles' hit functions // See, for example, Listing 29.12. RGBColor ImageTexture::get_color(const ShadeRec& sr) const { int row; int column; if (mapping_ptr) mapping_ptr->get_texel_coordinates(sr.local_hit_point, hres, vres, row, column); else { row = (int)(sr.v * (vres - 1)); column = (int)(sr.u * (hres - 1)); } return (image_ptr->get_color(row, column)); }
[ "windy_max@163.com" ]
windy_max@163.com
689ef7d99fd7727ab605c436c94d5861f6b13b6d
a438c1571c6a051d508af92dbe0993ebc44a6ddc
/Weekly 2/Weekly 2.cpp
4304eb74598e840138fe9e86f17d1391fbf2b450
[]
no_license
Ivar1999/Weekly-2
7e471e3cd0fd3ba6e997db21f56105df350f3910
b1838990dca4d3d9ba177bb1ba6188d5800982ba
refs/heads/master
2022-12-17T22:21:46.011142
2020-09-10T17:02:22
2020-09-10T17:02:22
294,465,942
0
0
null
null
null
null
UTF-8
C++
false
false
1,452
cpp
#include <iostream> #include <string> using namespace std; int n; int m; int kk = 1; int k = 1; int l = 5; int a = 1; int b = 5; int c = 5; int d = 5; int e = 5; int f = 5; int g = 1; int h = 1; int q = 1; int aa = 1; int cc = 1; int ll = 5; int dd = 5; int main() { for (int i = 1; i <= 100; i++) { cout << i << " "; } cout << "\n"; cout << "\n\nHow far do you want me to count? "; cin >> n; for (int i = 1; i <= n; i++) { cout << i << " "; } cout << "\n\nAnd now I'll count down for you:\n\n"; system("pause"); for (int j = 100; j > 0; j--) { cout << j << " "; } cout << "\n"; cout << "\n\nWhat number would you like me to count down from? "; cin >> m; for (int j = m; j > 0; j--) { cout << j << " "; } cout << "\n"; cout << "And now to the do-while & while-loop\n"; system("pause"); do { cout << k << " "; k++; } while (k <= 100); cout << "\n"; system("pause"); while (kk <= 100) { cout << kk << " "; kk++; } system("pause"); do { cout << l << " "; l = b * ++a; } while (l <=50); system("pause"); while (c <=50) { cout << c << " "; c = b * ++g; } system("pause"); for (int d = b*h; d <= 50; d=b*++h) { cout << d << " "; } system("pause"); while (q <= 100) { cout << q << " "; q++; } system("pause"); while (ll <= 50) { cout << ll << " "; ll = b * ++aa; } system("pause"); do { cout << dd << " "; dd = b * ++cc; } while (dd <= 50); return 0; }
[ "drednikeu@gmail.com" ]
drednikeu@gmail.com
8185313bd653846d895d1b5273250dbf3c523ed3
d8a195cf59770530b0abeaaca62ed9d5adadc177
/pi.cpp
4205d3d4625b24ad0f7223479bc9f2b3adef2777
[]
no_license
KevinParnell/cpp-school
e1d6e51d73d8a0b42c82e1d24c1c303d5d7c4f18
0cc5e980db6c888fe532b89bde4ba034ab2a5723
refs/heads/master
2021-06-13T16:03:22.962962
2016-11-28T16:04:02
2016-11-28T16:04:02
null
0
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
// This is pi stuff #include <iostream> #include <cmath> using namespace std; int main() { // declare variables const double PI = 3.14159; double volume,radius, height; // Prompt for data cout << "This program will tell you the volume of\n"; cout << "a cylinder-shaped fuel tank.\n"; cout << "How tall is the tank? "; cin >> height; cout << "What is the radius of the tank? "; cin >> radius; // Calculate volume v=PIrrh volume = PI * pow(radius, 2) * height; cout << " The volume is: " << volume << endl; return 0; }
[ "kpbballer@gmail.com" ]
kpbballer@gmail.com
3f3fdc1eb5a8996c319118a252c9ad81af055b69
674ed4458856a70456dce2ba02bd78b85820a101
/shortest path finding for two agents/main.cpp
f1075f68a4bf491177b290717b61d56a8c91fccb
[]
no_license
BurakGurbuz97/algorithms
bacb5aca9dac7b3a97538f38f0e255c99499dce5
e23ec4c719f58656c44a05e5b693790d1a08e9ed
refs/heads/master
2022-11-27T19:21:59.366501
2020-07-31T13:32:17
2020-07-31T13:32:17
284,043,684
0
0
null
null
null
null
UTF-8
C++
false
false
841
cpp
/* Mustafa Burak Gurbuz 150150082 mustafaburakgurbuz@gmail.com */ #include <iostream> #include <fstream> #include <vector> #include "graph.h" using namespace std; int main(int argc, char** argv) { if (argc < 2) { cout<<"No test file specified!"<<endl; return 1; } vector<edgeTriplet> edge_list; int JH, JD, LH, LD, number_of_nodes; ifstream file; file.open(argv[1]); file >> number_of_nodes; file >> JH >> JD >> LH >> LD; //Parses lines and fill edge_list until it is unable to parse for(edgeTriplet edge ;file >> edge.src_index >> edge.dst_index >> edge.weight; edge_list.push_back(edge)); Graph city_network(number_of_nodes, JH, JD, LH, LD); city_network.build(edge_list); //solve_one = false: solves all city_network.simulate(false); return 0; }
[ "mustafaburakgurbuz@gmail.com" ]
mustafaburakgurbuz@gmail.com
5751118053070a05ede63c0c1b834f8afb3f064e
6e319b8eba4dcfbb8ee9d6446c0f8721d1db98b3
/src/var_manager.cpp
b59c9e34f9b320fdae2ea03e9be74060ca494cc2
[ "MIT" ]
permissive
MrDerpySour/FEL
b380d6f6364ed083a7bdac0a7e564e2a51e7b2e0
4a3f84dfdff9976084c9653ecf1fb384ec8f9e68
refs/heads/master
2020-12-03T02:26:46.710851
2017-06-26T02:26:20
2017-06-26T02:26:20
95,939,305
1
0
null
2017-07-01T03:21:03
2017-07-01T03:21:03
null
UTF-8
C++
false
false
417
cpp
#include "var_manager.hpp" #include "manager.hpp" void fel::modules::variables::VariablesManager::reg() { try { parent_->registerFunction("REG", &regcmd_); parent_->registerFunction("SET", &setcmd_); parent_->registerFunction("DEL", &delcmd_); parent_->registerFunction("CMP", &cmpcmd_); } catch (...) { parent_->context()->print("Error: something went wrong registering function\n"); } }
[ "Lunatoid@users.noreply.github.com" ]
Lunatoid@users.noreply.github.com
90909859648e3bfdc79d5fdf7bc0fb519c683218
b9c06dda65807c8915b1fe1b6c422a56c7af49f0
/pollardsRho.cpp
f0587b160ef31aeaffa191bde6a2ba26e5e5703b
[]
no_license
austinJames96/MA311
c35f7f26453927b2bc9c30471979ca0767e183d6
3a44b6b7f7e521f2296edaf1ab31c3f22b240156
refs/heads/master
2020-09-06T02:35:47.907251
2019-11-07T17:12:14
2019-11-07T17:12:14
220,289,496
0
0
null
null
null
null
UTF-8
C++
false
false
1,708
cpp
/* C++ program to find a prime factor of composite using Pollard's Rho algorithm */ #include<bits/stdc++.h> using namespace std; long long int modular_pow(long long int base, int exponent, long long int modulus) { long long int result = 1; while (exponent > 0) { if (exponent & 1){ result = (result * base) % modulus; } exponent = exponent >> 1; base = (base * base) % modulus; } return result; } long long int PollardRho(long long int n) { srand (time(NULL)); if (n==1) return n; if (n % 2 == 0){ return 2; } long long int x = (rand()%(n-2))+2; long long int y = x; long long int c = (rand()%(n-1))+1; long long int d = 1; while (d==1) { x = (modular_pow(x, 2, n) + c + n)%n; y = (modular_pow(y, 2, n) + c + n)%n; y = (modular_pow(y, 2, n) + c + n)%n; d = __gcd(abs(x-y), n); if (d==n){ return PollardRho(n); } } return d; } /* driver function */ int main() { unsigned long long int n[4] = {19238291,184865893,187189186201,15466048015829}; /* for(int i = 0; i<sizeof(n); i++){ if(n[i]==n[0]||n[1]||n[2]||n[3]){ printf("A divisors for %lld is %lld.\n", n[i], PollardRho(n[i])); } }*/ printf("A divisor for %lld is %lld.\n", n[0], PollardRho(n[0])); printf("A divisor for %lld is %lld.\n", n[1], PollardRho(n[1])); printf("A divisor for %lld is %lld.\n", n[2], PollardRho(n[2])); printf("A divisor for %lld is %lld.\n", n[3], PollardRho(n[3])); return 0; }
[ "57360655+austinJames96@users.noreply.github.com" ]
57360655+austinJames96@users.noreply.github.com
286fd8639993f2dbf2410c82dd64e96b97f4a47f
952db6059cb03cab2524e9d492715f0dfffeb70f
/MeshSubdivision_Debug/ShowOrClear.cpp
6d0aa41daced92cb90f5f2a64ab5bf6e6607f5b3
[]
no_license
jingyangcarl/MeshSubdivision_Debug
b70500edec9b7e7f00e93c91991e97e204095428
ed7296f176ad70ada8b915271e002696490c6068
refs/heads/master
2021-09-10T22:24:13.079394
2018-04-03T06:24:14
2018-04-03T06:24:14
124,614,138
2
0
null
null
null
null
UTF-8
C++
false
false
22,831
cpp
#include "MeshSubdivision_Debug.h" void MeshSubdivision_Debug::ShowMesh_1() { // Carl: show mesh_6 to QVTKWidget if (layoutStatus >= 1) { viewer_1->addPolygonMesh(mesh_1, "mesh_1"); viewer_1->resetCamera(); qvtkWidget_1->update(); OutputTextEditFinished("Show Mesh_1 finished;"); } else OutputTextEditError("QVTKWidget_1 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMesh_2() { // Carl: show mesh_2 to QVTKWidget if (layoutStatus >= 2) { viewer_2->addPolygonMesh(mesh_2, "mesh_2"); viewer_2->resetCamera(); qvtkWidget_2->update(); OutputTextEditFinished("Show Mesh_2 finished;"); } else OutputTextEditError("QVTKWidget_2 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMesh_3() { // Carl: show mesh_3 to QVTKWidget if (layoutStatus >= 3) { viewer_3->addPolygonMesh(mesh_3, "mesh_3"); viewer_3->resetCamera(); qvtkWidget_3->update(); OutputTextEditFinished("Show Mesh_3 finished;"); } else OutputTextEditError("QVTKWidget_3 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMesh_4() { // Carl: show mesh_4 to QVTKWidget if (layoutStatus >= 4) { viewer_4->addPolygonMesh(mesh_4, "mesh_4"); viewer_4->resetCamera(); qvtkWidget_4->update(); OutputTextEditFinished("Show Mesh_4 finished;"); } else OutputTextEditError("QVTKWidget_4 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMesh_5() { // Carl: show mesh_5 to QVTKWidget if (layoutStatus >= 5) { viewer_5->addPolygonMesh(mesh_5, "mesh_5"); viewer_5->resetCamera(); qvtkWidget_5->update(); OutputTextEditFinished("Show Mesh_5 finished;"); } else OutputTextEditError("QVTKWidget_5 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMesh_6() { // Carl: show mesh_6 to QVTKWidget if (layoutStatus >= 6) { viewer_6->addPolygonMesh(mesh_6, "mesh_6"); viewer_6->resetCamera(); qvtkWidget_6->update(); OutputTextEditFinished("Show Mesh_6 finished;"); } else OutputTextEditError("QVTKWidget_6 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMeshStatus_1() { if(layoutStatus >= 1){ QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Mesh_1 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_1.cloud.height*mesh_1.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Faces: " + QString::number(mesh_1.polygons.size()) + "] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_1 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMeshStatus_2() { if (layoutStatus >= 2) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Mesh_2 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_2.cloud.height*mesh_2.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Faces: " + QString::number(mesh_2.polygons.size()) + "] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_2 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMeshStatus_3() { if (layoutStatus >= 3) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Mesh_3 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_3.cloud.height*mesh_3.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Faces: " + QString::number(mesh_3.polygons.size()) + "] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_3 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMeshStatus_4() { if(layoutStatus >= 4){ QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Mesh_4 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_4.cloud.height*mesh_4.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Faces: " + QString::number(mesh_4.polygons.size()) + "] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_4 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMeshStatus_5() { if (layoutStatus >= 5) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Mesh_5 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_5.cloud.height*mesh_5.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Faces: " + QString::number(mesh_5.polygons.size()) + "] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_5 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowMeshStatus_6() { if (layoutStatus >= 6) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Mesh_6 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_6.cloud.height*mesh_6.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Faces: " + QString::number(mesh_6.polygons.size()) + "] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_6 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearMesh_1() { // Carl: clear mesh_1 to QVTKWidget if (layoutStatus >= 1) { viewer_1->removePolygonMesh("mesh_1"); viewer_1->updateCamera(); qvtkWidget_1->update(); OutputTextEditFinished("Clear Mesh_1 finished;"); } else OutputTextEditError("QVTKWidget_1 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearMesh_2() { // Carl: clear mesh_2 to QVTKWidget if (layoutStatus >= 2) { viewer_2->removePolygonMesh("mesh_2"); viewer_2->updateCamera(); qvtkWidget_2->update(); OutputTextEditFinished("Clear Mesh_2 finished;"); } else OutputTextEditError("QVTKWidget_2 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearMesh_3() { // Carl: clear mesh_3 to QVTKWidget if (layoutStatus >= 3) { viewer_3->removePolygonMesh("mesh_3"); viewer_3->updateCamera(); qvtkWidget_3->update(); OutputTextEditFinished("Clear Mesh_3 finished;"); } else OutputTextEditError("QVTKWidget_3 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearMesh_4() { // Carl: clear mesh_4 to QVTKWidget if (layoutStatus >= 4) { viewer_4->removePolygonMesh("mesh_4"); viewer_4->updateCamera(); qvtkWidget_4->update(); OutputTextEditFinished("Clear Mesh_4 finished;"); } else OutputTextEditError("QVTKWidget_4 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearMesh_5() { // Carl: clear mesh_5 to QVTKWidget if (layoutStatus >= 5) { viewer_5->removePolygonMesh("mesh_5"); viewer_5->updateCamera(); qvtkWidget_5->update(); OutputTextEditFinished("Clear Mesh_5 finished;"); } else OutputTextEditError("QVTKWidget_5 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearMesh_6() { // Carl: clear mesh_6 to QVTKWidget if (layoutStatus >= 6) { viewer_6->removePolygonMesh("mesh_6"); viewer_6->updateCamera(); qvtkWidget_6->update(); OutputTextEditFinished("Clear Mesh_6 finished;"); } else OutputTextEditError("QVTKWidget_6 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloud_1() { // Carl: show cloud_1 to QVTKWidget if (layoutStatus >= 1) { viewer_1->addPointCloud(cloud_1, "cloud_1"); viewer_1->resetCamera(); qvtkWidget_1->update(); OutputTextEditFinished("Show Cloud_1 finished;"); } else OutputTextEditError("QVTKWidget_1 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloud_2() { // Carl: show cloud_2 to QVTKWidget if (layoutStatus >= 2) { viewer_2->addPointCloud(cloud_2, "cloud_2"); viewer_2->resetCamera(); qvtkWidget_2->update(); OutputTextEditFinished("Show Cloud_2 finished;"); } else OutputTextEditError("QVTKWidget_2 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloud_3() { // Carl: show cloud_3 to QVTKWidget if (layoutStatus >= 3) { viewer_3->addPointCloud(cloud_3, "cloud_3"); viewer_3->resetCamera(); qvtkWidget_3->update(); OutputTextEditFinished("Show Cloud_3 finished;"); } else OutputTextEditError("QVTKWidget_3 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloud_4() { // Carl: show cloud_4 to QVTKWidget if (layoutStatus >= 4) { viewer_4->addPointCloud(cloud_4, "cloud_4"); viewer_4->resetCamera(); qvtkWidget_4->update(); OutputTextEditFinished("Show Cloud_4 finished;"); } else OutputTextEditError("QVTKWidget_4 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloud_5() { // Carl: show cloud_5 to QVTKWidget if (layoutStatus >= 5) { viewer_5->addPointCloud(cloud_5, "cloud_5"); viewer_5->resetCamera(); qvtkWidget_5->update(); OutputTextEditFinished("Show Cloud_5 finished;"); } else OutputTextEditError("QVTKWidget_5 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloud_6() { // Carl: show cloud_6 to QVTKWidget if (layoutStatus >= 6) { viewer_6->addPointCloud(cloud_6, "cloud_6"); viewer_6->resetCamera(); qvtkWidget_6->update(); OutputTextEditFinished("Show Cloud_6 finished;"); } else OutputTextEditError("QVTKWidget_6 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloudStatus_1() { if (layoutStatus >= 1) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Cloud_1 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_1.cloud.height*mesh_1.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Keypoints: " + (keypointList_1.isEmpty() ? "no status" : (QString::number(keypointList_1.count(true))) + " - " + QString::number((double)keypointList_1.count(true) / (mesh_6.cloud.height*mesh_1.cloud.width) * 100)) + "%] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_1 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloudStatus_2() { if (layoutStatus >= 2) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Cloud_2 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_2.cloud.height*mesh_2.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Keypoints: " + (keypointList_2.isEmpty() ? "no status" : (QString::number(keypointList_2.count(true))) + " - " + QString::number((double)keypointList_2.count(true) / (mesh_6.cloud.height*mesh_2.cloud.width) * 100)) + "%] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_2 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloudStatus_3() { if (layoutStatus >= 3) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Cloud_3 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_3.cloud.height*mesh_3.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Keypoints: " + (keypointList_3.isEmpty() ? "no status" : (QString::number(keypointList_3.count(true))) + " - " + QString::number((double)keypointList_3.count(true) / (mesh_6.cloud.height*mesh_3.cloud.width) * 100)) + "%] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_3 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloudStatus_4() { if (layoutStatus >= 4) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Cloud_4 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_4.cloud.height*mesh_4.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Keypoints: " + (keypointList_4.isEmpty() ? "no status" : (QString::number(keypointList_4.count(true))) + " - " + QString::number((double)keypointList_4.count(true) / (mesh_6.cloud.height*mesh_4.cloud.width) * 100)) + "%] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_4 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloudStatus_5() { if (layoutStatus >= 5) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Cloud_5 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_5.cloud.height*mesh_5.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Keypoints: " + (keypointList_5.isEmpty() ? "no status" : (QString::number(keypointList_5.count(true))) + " - " + QString::number((double)keypointList_5.count(true) / (mesh_5.cloud.height*mesh_5.cloud.width) * 100)) + "%] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_5 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowCloudStatus_6() { if (layoutStatus >= 6) { QVector<QPair<QColor, QString>> output; output.append(QPair<QColor, QString>(QColor("gray"), "Cloud_6 Info: ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Points: " + QString::number(mesh_6.cloud.height*mesh_6.cloud.width) + "] ")); output.append(QPair<QColor, QString>(QColor("yellow"), "[Keypoints: " + (keypointList_6.isEmpty() ? "no status" : (QString::number(keypointList_6.count(true))) + " - " + QString::number((double)keypointList_6.count(true)/ (mesh_6.cloud.height*mesh_6.cloud.width) * 100)) + "%] ")); OutputTextEditColoredString(output); } else OutputTextEditError("QVTKWidget_6 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearCloud_1() { // Carl: clear cloud_1 to QVTKWidget if (layoutStatus >= 1) { viewer_1->removePointCloud("cloud_1"); viewer_1->updateCamera(); qvtkWidget_1->update(); OutputTextEditFinished("Clear Cloud_1 finished;"); } else OutputTextEditError("QVTKWidget_1 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearCloud_2() { // Carl: clear cloud_2 to QVTKWidget if (layoutStatus >= 2) { viewer_2->removePointCloud("cloud_2"); viewer_2->updateCamera(); qvtkWidget_2->update(); OutputTextEditFinished("Clear Cloud_2 finished;"); } else OutputTextEditError("QVTKWidget_2 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearCloud_3() { // Carl: clear cloud_3 to QVTKWidget if (layoutStatus >= 3) { viewer_3->removePointCloud("cloud_3"); viewer_3->updateCamera(); qvtkWidget_3->update(); OutputTextEditFinished("Clear Cloud_3 finished;"); } else OutputTextEditError("QVTKWidget_3 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearCloud_4() { // Carl: clear cloud_4 to QVTKWidget if (layoutStatus >= 4) { viewer_4->removePointCloud("cloud_4"); viewer_4->updateCamera(); qvtkWidget_4->update(); OutputTextEditFinished("Clear Cloud_4 finished;"); } else OutputTextEditError("QVTKWidget_4 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearCloud_5() { // Carl: clear cloud_5 to QVTKWidget if (layoutStatus >= 5) { viewer_5->removePointCloud("cloud_5"); viewer_5->updateCamera(); qvtkWidget_5->update(); OutputTextEditFinished("Clear Cloud_5 finished;"); } else OutputTextEditError("QVTKWidget_5 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ClearCloud_6() { // Carl: clear cloud_6 to QVTKWidget if (layoutStatus >= 6) { viewer_6->removePointCloud("cloud_6"); viewer_6->updateCamera(); qvtkWidget_6->update(); OutputTextEditFinished("Clear Cloud_6 finished;"); } else OutputTextEditError("QVTKWidget_6 hasn't been initialized;"); return; } void MeshSubdivision_Debug::ShowKeypoint_1() { // Carl: show keypoint on cloud for (int i = 0; i < cloud_1->points.size(); i++) { if (keypointList_1.at(i)) { cloud_1->points[i].r = colorCloud_1.red(); cloud_1->points[i].g = colorCloud_1.green(); cloud_1->points[i].b = colorCloud_1.blue(); cloud_1->points[i].a = colorCloud_1.alpha(); } } viewer_1->updatePointCloud(cloud_1, "cloud_1"); ShowCloud_1(); QVector<QPair<QColor, QString>> content; content.append(QPair<QColor, QString>(QColor("gray"), "Show Cloud_1 ")); content.append(QPair<QColor, QString>(colorCloud_1, "keypoint")); content.append(QPair<QColor, QString>(QColor("gray"), " finished;")); OutputTextEditColoredString(content); return; } void MeshSubdivision_Debug::ShowKeypoint_2() { // Carl: show keypoint on cloud for (int i = 0; i < cloud_2->points.size(); i++) { if (keypointList_2.at(i)) { cloud_2->points[i].r = colorCloud_2.red(); cloud_2->points[i].g = colorCloud_2.green(); cloud_2->points[i].b = colorCloud_2.blue(); cloud_2->points[i].a = colorCloud_2.alpha(); } } viewer_2->updatePointCloud(cloud_2, "cloud_2"); ShowCloud_2(); QVector<QPair<QColor, QString>> content; content.append(QPair<QColor, QString>(QColor("gray"), "Show Cloud_2 ")); content.append(QPair<QColor, QString>(colorCloud_2, "keypoint")); content.append(QPair<QColor, QString>(QColor("gray"), " finished;")); OutputTextEditColoredString(content); return; } void MeshSubdivision_Debug::ShowKeypoint_3() { // Carl: show keypoint on cloud for (int i = 0; i < cloud_3->points.size(); i++) { if (keypointList_3.at(i)) { cloud_3->points[i].r = colorCloud_3.red(); cloud_3->points[i].g = colorCloud_3.green(); cloud_3->points[i].b = colorCloud_3.blue(); cloud_3->points[i].a = colorCloud_3.alpha(); } } viewer_3->updatePointCloud(cloud_3, "cloud_3"); ShowCloud_3(); QVector<QPair<QColor, QString>> content; content.append(QPair<QColor, QString>(QColor("gray"), "Show Cloud_3 ")); content.append(QPair<QColor, QString>(colorCloud_3, "keypoint")); content.append(QPair<QColor, QString>(QColor("gray"), " finished;")); OutputTextEditColoredString(content); return; } void MeshSubdivision_Debug::ShowKeypoint_4() { // Carl: show keypoint on cloud for (int i = 0; i < cloud_4->points.size(); i++) { if (keypointList_4.at(i)) { cloud_4->points[i].r = colorCloud_4.red(); cloud_4->points[i].g = colorCloud_4.green(); cloud_4->points[i].b = colorCloud_4.blue(); cloud_4->points[i].a = colorCloud_4.alpha(); } } viewer_4->updatePointCloud(cloud_4, "cloud_4"); ShowCloud_4(); QVector<QPair<QColor, QString>> content; content.append(QPair<QColor, QString>(QColor("gray"), "Show Cloud_4 ")); content.append(QPair<QColor, QString>(colorCloud_4, "keypoint")); content.append(QPair<QColor, QString>(QColor("gray"), " finished;")); OutputTextEditColoredString(content); return; } void MeshSubdivision_Debug::ShowKeypoint_5() { // Carl: show keypoint on cloud for (int i = 0; i < cloud_5->points.size(); i++) { if (keypointList_5.at(i)) { cloud_5->points[i].r = colorCloud_5.red(); cloud_5->points[i].g = colorCloud_5.green(); cloud_5->points[i].b = colorCloud_5.blue(); cloud_5->points[i].a = colorCloud_5.alpha(); } } viewer_5->updatePointCloud(cloud_5, "cloud_5"); ShowCloud_5(); QVector<QPair<QColor, QString>> content; content.append(QPair<QColor, QString>(QColor("gray"), "Show Cloud_5 ")); content.append(QPair<QColor, QString>(colorCloud_5, "keypoint")); content.append(QPair<QColor, QString>(QColor("gray"), " finished;")); OutputTextEditColoredString(content); return; } void MeshSubdivision_Debug::ShowKeypoint_6() { // Carl: show keypoint on cloud for (int i = 0; i < cloud_6->points.size(); i++) { if (keypointList_6.at(i)) { cloud_6->points[i].r = colorCloud_6.red(); cloud_6->points[i].g = colorCloud_6.green(); cloud_6->points[i].b = colorCloud_6.blue(); cloud_6->points[i].a = colorCloud_6.alpha(); } } viewer_6->updatePointCloud(cloud_6, "cloud_6"); ShowCloud_6(); QVector<QPair<QColor, QString>> content; content.append(QPair<QColor, QString>(QColor("gray"), "Show Cloud_6 ")); content.append(QPair<QColor, QString>(colorCloud_6, "keypoint")); content.append(QPair<QColor, QString>(QColor("gray"), " finished;")); OutputTextEditColoredString(content); return; } void MeshSubdivision_Debug::ClearKeypoint_1() { //Carl: clear keypoint on cloud for (int i = 0; i < cloud_1->points.size(); i++) { cloud_1->points[i].r = 255; cloud_1->points[i].g = 255; cloud_1->points[i].b = 255; cloud_1->points[i].a = 255; } viewer_1->updatePointCloud(cloud_1, "cloud_1"); qvtkWidget_1->update(); OutputTextEditFinished("Clear Cloud_1 Keypoint finished;"); return; } void MeshSubdivision_Debug::ClearKeypoint_2() { //Carl: clear keypoint on cloud for (int i = 0; i < cloud_2->points.size(); i++) { cloud_2->points[i].r = 255; cloud_2->points[i].g = 255; cloud_2->points[i].b = 255; cloud_2->points[i].a = 255; } viewer_2->updatePointCloud(cloud_2, "cloud_2"); qvtkWidget_2->update(); OutputTextEditFinished("Clear Cloud_2 Keypoint finished;"); return; } void MeshSubdivision_Debug::ClearKeypoint_3() { //Carl: clear keypoint on cloud for (int i = 0; i < cloud_3->points.size(); i++) { cloud_3->points[i].r = 255; cloud_3->points[i].g = 255; cloud_3->points[i].b = 255; cloud_3->points[i].a = 255; } viewer_3->updatePointCloud(cloud_3, "cloud_3"); qvtkWidget_3->update(); OutputTextEditFinished("Clear Cloud_3 Keypoint finished;"); return; } void MeshSubdivision_Debug::ClearKeypoint_4() { //Carl: clear keypoint on cloud for (int i = 0; i < cloud_4->points.size(); i++) { cloud_4->points[i].r = 255; cloud_4->points[i].g = 255; cloud_4->points[i].b = 255; cloud_4->points[i].a = 255; } viewer_4->updatePointCloud(cloud_4, "cloud_4"); qvtkWidget_4->update(); OutputTextEditFinished("Clear Cloud_4 Keypoint finished;"); return; } void MeshSubdivision_Debug::ClearKeypoint_5() { //Carl: clear keypoint on cloud for (int i = 0; i < cloud_5->points.size(); i++) { cloud_5->points[i].r = 255; cloud_5->points[i].g = 255; cloud_5->points[i].b = 255; cloud_5->points[i].a = 255; } viewer_5->updatePointCloud(cloud_5, "cloud_5"); qvtkWidget_5->update(); OutputTextEditFinished("Clear Cloud_5 Keypoint finished;"); return; } void MeshSubdivision_Debug::ClearKeypoint_6() { //Carl: clear keypoint on cloud for (int i = 0; i < cloud_6->points.size(); i++) { cloud_6->points[i].r = 255; cloud_6->points[i].g = 255; cloud_6->points[i].b = 255; cloud_6->points[i].a = 255; } viewer_6->updatePointCloud(cloud_6, "cloud_6"); qvtkWidget_6->update(); OutputTextEditFinished("Clear Cloud_6 Keypoint finished;"); return; }
[ "jingyang_carl@qq.com" ]
jingyang_carl@qq.com
951c95ee39e8fddb693a94060593882ae8d3eda7
4548923182ab7ce8927f72f6f8dd5da0c35a58d7
/ControlRegion/ZprimeJetsClass_MC_ZJets.h
a266101480b903f073b7de95be6e1d96f995d3b5
[]
no_license
uhussain/ZprimeTools
28cfb1d12c49ca6cd056d93a064484c9ceb283f6
b7a6c3ba2c3a2b32ad6d33e5d4553c8bfa4d9ed5
refs/heads/master
2021-03-27T20:18:18.731660
2019-02-26T13:13:12
2019-02-26T13:13:12
108,257,384
0
4
null
2018-10-29T16:07:20
2017-10-25T10:52:36
C
UTF-8
C++
false
false
58,936
h
////////////////////////////////////////////////////////// // This class has been automatically generated on // Wed Mar 8 10:15:33 2017 by ROOT version 6.06/01 // from TTree EventTree/Event data (tag V08_00_24_00) // found on file: /hdfs/store/user/uhussain/Zprime_Ntuples_Mar7/WJetsToLNu_HT-400To600_TuneCUETP8M1_13TeV-madgraphMLM-pythia8/crab_W3Jets/170306_174919/0000/ggtree_mc_53.root ////////////////////////////////////////////////////////// #ifndef ZprimeJetsClass_MC_ZJets_h #define ZprimeJetsClass_MC_ZJets_h #include <TROOT.h> #include <TChain.h> #include <TFile.h> #include <iostream> #include <fstream> #include <iomanip> #include <cmath> #include <map> #include <list> #include <vector> #include <bitset> #include <TCanvas.h> #include <TSystem.h> #include <TPostScript.h> #include <TH2.h> #include <TH1.h> #include <TF1.h> #include <TMath.h> #include <TLegend.h> #include <TProfile.h> #include <TGraph.h> #include <TRef.h> #include <TList.h> #include <TSystemFile.h> #include <TSystemDirectory.h> #include <TDCacheFile.h> #include <TLorentzVector.h> #include "TIterator.h" // Header file for the classes stored in the TTree if any. #include "vector" #include "vector" #include "TString.h" #include "vector" using namespace std; class ZprimeJetsClass_MC_ZJets { public : TTree *fChain; //!pointer to the analyzed TTree or TChain Int_t fCurrent; //!current Tree number in a TChain TFile *fileName; TTree *tree; //Categorizing events based on no.of charged Hadrons in PencilJet int NoPosPFCons,NoNegPFCons,NoPhoPFCons; double j1PFPosConsPt, j1PFPosConsEta,j1PFPosConsPhi, j1PFNegConsPt,j1PFNegConsEta,j1PFNegConsPhi,j1PFPhoConsPt,j1PFPhoConsEta,j1PFPhoConsPhi; int TwoChPFCons,TwoChPFConsPlusPho; double PF12PtFrac_ID_1,PF12PtFrac_ID_2,dR_PF12_ID_1,dR_PF12_ID_2,PF123PtFrac_ID_2; //CR variables int lepindex_leading, lepindex_subleading; double dilepton_mass,dilepton_pt,Recoil; float leptoMET_phi_to_use; //getPFCandidates int TotalPFCandidates, ChargedPFCandidates,NeutralPFCandidates,GammaPFCandidates; TH1F *h_nVtx[16], *h_metcut, *h_dphimin,*h_metFilters[16],*h_pfMETall[16],*h_pfMET200[16],*h_nJets[16],*h_pfMET[16],*h_pfMETPhi[16],*h_j1nCategory1[16],*h_j1nCategory2[16],*h_j1dRPF12_ID_1[16],*h_j1dRPF12_ID_2[16]; TH1F *h_j1Pt[16], *h_j1Eta[16], *h_j1Phi[16], *h_j1etaWidth[16], *h_j1phiWidth[16],*h_j1nCons[16], *h_j1PF12PtFrac_ID_1[16], *h_j1PF12PtFrac_ID_2[16],*h_j1PFPtFrac_ID_2[16]; TH1F *h_j1TotPFCands[16], *h_j1ChPFCands[16], *h_j1NeutPFCands[16], *h_j1GammaPFCands[16], *h_j1CHF[16], *h_j1NHF[16], *h_j1ChMultiplicity[16], *h_j1NeutMultiplicity[16],*h_j1Mt[16]; //CR histograms TH1F *h_leadingLeptonPt[16], *h_leadingLeptonEta[16],*h_leadingLeptonPhi[16],*h_subleadingLeptonPt[16],*h_subleadingLeptonEta[16], *h_subleadingLeptonPhi[16],*h_dileptonPt[16],*h_dileptonM[16]; // Fixed size dimensions of array or collections stored in the TTree if any. TH1F *h_recoil[16]; TH1D *h_cutflow; // Declaration of leaf types Int_t run; Long64_t event; Int_t lumis; Bool_t isData; Int_t nVtx; Int_t nGoodVtx; Int_t nTrksPV; Bool_t isPVGood; Float_t vtx; Float_t vty; Float_t vtz; Float_t rho; Float_t rhoCentral; ULong64_t HLTEleMuX; ULong64_t HLTPho; ULong64_t HLTJet; ULong64_t HLTEleMuXIsPrescaled; ULong64_t HLTPhoIsPrescaled; ULong64_t HLTJetIsPrescaled; vector<int> *phoPrescale; vector<float> *pdf; Float_t pthat; Float_t processID; Float_t genWeight; Float_t genHT; TString *EventTag; Int_t nPUInfo; vector<int> *nPU; vector<int> *puBX; vector<float> *puTrue; Int_t nMC; vector<int> *mcPID; vector<float> *mcVtx; vector<float> *mcVty; vector<float> *mcVtz; vector<float> *mcPt; vector<float> *mcMass; vector<float> *mcEta; vector<float> *mcPhi; vector<float> *mcE; vector<float> *mcEt; vector<int> *mcGMomPID; vector<int> *mcMomPID; vector<float> *mcMomPt; vector<float> *mcMomMass; vector<float> *mcMomEta; vector<float> *mcMomPhi; vector<unsigned short> *mcStatusFlag; vector<int> *mcParentage; vector<int> *mcStatus; vector<float> *mcCalIsoDR03; vector<float> *mcTrkIsoDR03; vector<float> *mcCalIsoDR04; vector<float> *mcTrkIsoDR04; Float_t genMET; Float_t genMETPhi; Int_t metFilters; Float_t pfMET; Float_t caloMET; //ROOT::Math::DisplacementVector2D<ROOT::Math::Cartesian2D<float>,ROOT::Math::DefaultCoordinateSystemTag> *caloMet; Float_t fCoordinates_fX; Float_t fCoordinates_fY; Float_t pfMETPhi; Float_t pfMETsumEt; Float_t pfMETmEtSig; Float_t pfMETSig; Float_t pfMET_T1JERUp; Float_t pfMET_T1JERDo; Float_t pfMET_T1JESUp; Float_t pfMET_T1JESDo; Float_t pfMET_T1UESUp; Float_t pfMET_T1UESDo; Float_t pfMETPhi_T1JESUp; Float_t pfMETPhi_T1JESDo; Float_t pfMETPhi_T1UESUp; Float_t pfMETPhi_T1UESDo; Int_t nPho; vector<float> *phoE; vector<float> *phoEt; vector<float> *phoEta; vector<float> *phoPhi; vector<float> *phoCalibE; vector<float> *phoCalibEt; vector<float> *phoSCE; vector<float> *phoSCRawE; vector<float> *phoESEn; vector<float> *phoESEnP1; vector<float> *phoESEnP2; vector<float> *phoSCEta; vector<float> *phoSCPhi; vector<float> *phoSCEtaWidth; vector<float> *phoSCPhiWidth; vector<float> *phoSCBrem; vector<int> *phohasPixelSeed; vector<int> *phoEleVeto; vector<float> *phoR9; vector<float> *phoHoverE; vector<float> *phoE1x3; vector<float> *phoE1x5; vector<float> *phoE2x2; vector<float> *phoE2x5Max; vector<float> *phoE5x5; vector<float> *phoESEffSigmaRR; vector<float> *phoSigmaIEtaIEtaFull5x5; vector<float> *phoSigmaIEtaIPhiFull5x5; vector<float> *phoSigmaIPhiIPhiFull5x5; vector<float> *phoE1x3Full5x5; vector<float> *phoE1x5Full5x5; vector<float> *phoE2x2Full5x5; vector<float> *phoE2x5MaxFull5x5; vector<float> *phoE5x5Full5x5; vector<float> *phoR9Full5x5; vector<float> *phoPFChIso; vector<float> *phoPFPhoIso; vector<float> *phoPFNeuIso; vector<float> *phoPFChWorstIso; vector<float> *phoCITKChIso; vector<float> *phoCITKPhoIso; vector<float> *phoCITKNeuIso; vector<float> *phoIDMVA; vector<unsigned int> *phoFiredSingleTrgs; vector<unsigned int> *phoFiredDoubleTrgs; vector<unsigned int> *phoFiredL1Trgs; vector<float> *phoSeedTime; vector<float> *phoSeedEnergy; vector<unsigned short> *phoxtalBits; vector<unsigned short> *phoIDbit; Int_t npfPho; vector<float> *pfphoEt; vector<float> *pfphoEta; vector<float> *pfphoPhi; Int_t nEle; vector<int> *eleCharge; vector<int> *eleChargeConsistent; vector<float> *eleEn; vector<float> *eleSCEn; vector<float> *eleESEn; vector<float> *eleESEnP1; vector<float> *eleESEnP2; vector<float> *eleD0; vector<float> *eleDz; vector<float> *eleSIP; vector<float> *elePt; vector<float> *eleEta; vector<float> *elePhi; vector<float> *eleR9; vector<float> *eleCalibPt; vector<float> *eleCalibEn; vector<float> *eleSCEta; vector<float> *eleSCPhi; vector<float> *eleSCRawEn; vector<float> *eleSCEtaWidth; vector<float> *eleSCPhiWidth; vector<float> *eleHoverE; vector<float> *eleEoverP; vector<float> *eleEoverPout; vector<float> *eleEoverPInv; vector<float> *eleBrem; vector<float> *eledEtaAtVtx; vector<float> *eledPhiAtVtx; vector<float> *eledEtaAtCalo; vector<float> *eleSigmaIEtaIEtaFull5x5; vector<float> *eleSigmaIPhiIPhiFull5x5; vector<int> *eleConvVeto; vector<int> *eleMissHits; vector<float> *eleESEffSigmaRR; vector<float> *elePFChIso; vector<float> *elePFPhoIso; vector<float> *elePFNeuIso; vector<float> *elePFPUIso; vector<float> *elePFClusEcalIso; vector<float> *elePFClusHcalIso; vector<float> *elePFMiniIso; vector<float> *eleIDMVA; vector<float> *eleIDMVAHZZ; vector<float> *eledEtaseedAtVtx; vector<float> *eleE1x5; vector<float> *eleE2x5; vector<float> *eleE5x5; vector<float> *eleE1x5Full5x5; vector<float> *eleE2x5Full5x5; vector<float> *eleE5x5Full5x5; vector<float> *eleR9Full5x5; vector<int> *eleEcalDrivenSeed; vector<float> *eleDr03EcalRecHitSumEt; vector<float> *eleDr03HcalDepth1TowerSumEt; vector<float> *eleDr03HcalDepth2TowerSumEt; vector<float> *eleDr03HcalTowerSumEt; vector<float> *eleDr03TkSumPt; vector<float> *elecaloEnergy; vector<float> *eleTrkdxy; vector<float> *eleKFHits; vector<float> *eleKFChi2; vector<float> *eleGSFChi2; vector<vector<float> > *eleGSFPt; vector<vector<float> > *eleGSFEta; vector<vector<float> > *eleGSFPhi; vector<vector<float> > *eleGSFCharge; vector<vector<int> > *eleGSFHits; vector<vector<int> > *eleGSFMissHits; vector<vector<int> > *eleGSFNHitsMax; vector<vector<float> > *eleGSFVtxProb; vector<vector<float> > *eleGSFlxyPV; vector<vector<float> > *eleGSFlxyBS; vector<vector<float> > *eleBCEn; vector<vector<float> > *eleBCEta; vector<vector<float> > *eleBCPhi; vector<vector<float> > *eleBCS25; vector<vector<float> > *eleBCS15; vector<vector<float> > *eleBCSieie; vector<vector<float> > *eleBCSieip; vector<vector<float> > *eleBCSipip; vector<unsigned int> *eleFiredSingleTrgs; vector<unsigned int> *eleFiredDoubleTrgs; vector<unsigned int> *eleFiredL1Trgs; vector<unsigned short> *eleIDbit; Int_t npfHF; vector<float> *pfHFEn; vector<float> *pfHFECALEn; vector<float> *pfHFHCALEn; vector<float> *pfHFPt; vector<float> *pfHFEta; vector<float> *pfHFPhi; vector<float> *pfHFIso; Int_t nMu; vector<float> *muPt; vector<float> *muEn; vector<float> *muEta; vector<float> *muPhi; vector<int> *muCharge; vector<int> *muType; vector<unsigned short> *muIDbit; vector<float> *muD0; vector<float> *muDz; vector<float> *muSIP; vector<float> *muChi2NDF; vector<float> *muInnerD0; vector<float> *muInnerDz; vector<int> *muTrkLayers; vector<int> *muPixelLayers; vector<int> *muPixelHits; vector<int> *muMuonHits; vector<int> *muStations; vector<int> *muMatches; vector<int> *muTrkQuality; vector<float> *muIsoTrk; vector<float> *muPFChIso; vector<float> *muPFPhoIso; vector<float> *muPFNeuIso; vector<float> *muPFPUIso; vector<float> *muPFMiniIso; vector<unsigned int> *muFiredTrgs; vector<unsigned int> *muFiredL1Trgs; vector<float> *muInnervalidFraction; vector<float> *musegmentCompatibility; vector<float> *muchi2LocalPosition; vector<float> *mutrkKink; vector<float> *muBestTrkPtError; vector<float> *muBestTrkPt; Int_t nJet; Double_t j1etaWidth; Double_t j1phiWidth; Double_t j1nPhotons; Double_t j1nCHPions; Double_t j1nMisc; vector<int> *j1MiscPID; vector<double> *j1PFConsPt; vector<double> *j1PFConsEta; vector<double> *j1PFConsPhi; vector<double> *j1PFConsEt; vector<int> *j1PFConsPID; vector<float> *jetPt; vector<float> *jetEn; vector<float> *jetEta; vector<float> *jetPhi; vector<float> *jetRawPt; vector<float> *jetRawEn; vector<float> *jetMt; vector<float> *jetArea; vector<float> *jetLeadTrackPt; vector<float> *jetLeadTrackEta; vector<float> *jetLeadTrackPhi; vector<int> *jetLepTrackPID; vector<float> *jetLepTrackPt; vector<float> *jetLepTrackEta; vector<float> *jetLepTrackPhi; vector<float> *jetCSV2BJetTags; vector<float> *jetJetProbabilityBJetTags; vector<float> *jetpfCombinedMVAV2BJetTags; vector<int> *jetPartonID; vector<int> *jetHadFlvr; vector<float> *jetGenJetEn; vector<float> *jetGenJetPt; vector<float> *jetGenJetEta; vector<float> *jetGenJetPhi; vector<int> *jetGenPartonID; vector<float> *jetGenEn; vector<float> *jetGenPt; vector<float> *jetGenEta; vector<float> *jetGenPhi; vector<int> *jetGenPartonMomID; vector<float> *jetP4Smear; vector<float> *jetP4SmearUp; vector<float> *jetP4SmearDo; vector<bool> *jetPFLooseId; vector<int> *jetID; vector<float> *jetPUID; vector<int> *jetPUFullID; vector<float> *jetJECUnc; vector<unsigned int> *jetFiredTrgs; vector<float> *jetCHF; vector<float> *jetNHF; vector<float> *jetCEF; vector<float> *jetNEF; vector<int> *jetNCH; vector<int> *jetNNP; vector<float> *jetMUF; vector<float> *jetVtxPt; vector<float> *jetVtxMass; vector<float> *jetVtxNtrks; vector<float> *jetVtx3DVal; vector<float> *jetVtx3DSig; // List of branches TBranch *b_run; //! TBranch *b_event; //! TBranch *b_lumis; //! TBranch *b_isData; //! TBranch *b_nVtx; //! TBranch *b_nGoodVtx; //! TBranch *b_nTrksPV; //! TBranch *b_isPVGood; //! TBranch *b_vtx; //! TBranch *b_vty; //! TBranch *b_vtz; //! TBranch *b_rho; //! TBranch *b_rhoCentral; //! TBranch *b_HLTEleMuX; //! TBranch *b_HLTPho; //! TBranch *b_HLTJet; //! TBranch *b_HLTEleMuXIsPrescaled; //! TBranch *b_HLTPhoIsPrescaled; //! TBranch *b_HLTJetIsPrescaled; //! TBranch *b_phoPrescale; //! TBranch *b_pdf; //! TBranch *b_pthat; //! TBranch *b_processID; //! TBranch *b_genWeight; //! TBranch *b_genHT; //! TBranch *b_EventTag; //! TBranch *b_nPUInfo; //! TBranch *b_nPU; //! TBranch *b_puBX; //! TBranch *b_puTrue; //! TBranch *b_nMC; //! TBranch *b_mcPID; //! TBranch *b_mcVtx; //! TBranch *b_mcVty; //! TBranch *b_mcVtz; //! TBranch *b_mcPt; //! TBranch *b_mcMass; //! TBranch *b_mcEta; //! TBranch *b_mcPhi; //! TBranch *b_mcE; //! TBranch *b_mcEt; //! TBranch *b_mcGMomPID; //! TBranch *b_mcMomPID; //! TBranch *b_mcMomPt; //! TBranch *b_mcMomMass; //! TBranch *b_mcMomEta; //! TBranch *b_mcMomPhi; //! TBranch *b_mcStatusFlag; //! TBranch *b_mcParentage; //! TBranch *b_mcStatus; //! TBranch *b_mcCalIsoDR03; //! TBranch *b_mcTrkIsoDR03; //! TBranch *b_mcCalIsoDR04; //! TBranch *b_mcTrkIsoDR04; //! TBranch *b_genMET; //! TBranch *b_genMETPhi; //! TBranch *b_metFilters; //! TBranch *b_pfMET; //! TBranch *b_caloMET; //! TBranch *b_caloMet_fCoordinates_fX; //! TBranch *b_caloMet_fCoordinates_fY; //! TBranch *b_pfMETPhi; //! TBranch *b_pfMETsumEt; //! TBranch *b_pfMETmEtSig; //! TBranch *b_pfMETSig; //! TBranch *b_pfMET_T1JERUp; //! TBranch *b_pfMET_T1JERDo; //! TBranch *b_pfMET_T1JESUp; //! TBranch *b_pfMET_T1JESDo; //! TBranch *b_pfMET_T1UESUp; //! TBranch *b_pfMET_T1UESDo; //! TBranch *b_pfMETPhi_T1JESUp; //! TBranch *b_pfMETPhi_T1JESDo; //! TBranch *b_pfMETPhi_T1UESUp; //! TBranch *b_pfMETPhi_T1UESDo; //! TBranch *b_nPho; //! TBranch *b_phoE; //! TBranch *b_phoEt; //! TBranch *b_phoEta; //! TBranch *b_phoPhi; //! TBranch *b_phoCalibE; //! TBranch *b_phoCalibEt; //! TBranch *b_phoSCE; //! TBranch *b_phoSCRawE; //! TBranch *b_phoESEn; //! TBranch *b_phoESEnP1; //! TBranch *b_phoESEnP2; //! TBranch *b_phoSCEta; //! TBranch *b_phoSCPhi; //! TBranch *b_phoSCEtaWidth; //! TBranch *b_phoSCPhiWidth; //! TBranch *b_phoSCBrem; //! TBranch *b_phohasPixelSeed; //! TBranch *b_phoEleVeto; //! TBranch *b_phoR9; //! TBranch *b_phoHoverE; //! TBranch *b_phoE1x3; //! TBranch *b_phoE1x5; //! TBranch *b_phoE2x2; //! TBranch *b_phoE2x5Max; //! TBranch *b_phoE5x5; //! TBranch *b_phoESEffSigmaRR; //! TBranch *b_phoSigmaIEtaIEtaFull5x5; //! TBranch *b_phoSigmaIEtaIPhiFull5x5; //! TBranch *b_phoSigmaIPhiIPhiFull5x5; //! TBranch *b_phoE1x3Full5x5; //! TBranch *b_phoE1x5Full5x5; //! TBranch *b_phoE2x2Full5x5; //! TBranch *b_phoE2x5MaxFull5x5; //! TBranch *b_phoE5x5Full5x5; //! TBranch *b_phoR9Full5x5; //! TBranch *b_phoPFChIso; //! TBranch *b_phoPFPhoIso; //! TBranch *b_phoPFNeuIso; //! TBranch *b_phoPFChWorstIso; //! TBranch *b_phoCITKChIso; //! TBranch *b_phoCITKPhoIso; //! TBranch *b_phoCITKNeuIso; //! TBranch *b_phoIDMVA; //! TBranch *b_phoFiredSingleTrgs; //! TBranch *b_phoFiredDoubleTrgs; //! TBranch *b_phoFiredL1Trgs; //! TBranch *b_phoSeedTime; //! TBranch *b_phoSeedEnergy; //! TBranch *b_phoxtalBits; //! TBranch *b_phoIDbit; //! TBranch *b_npfPho; //! TBranch *b_pfphoEt; //! TBranch *b_pfphoEta; //! TBranch *b_pfphoPhi; //! TBranch *b_nEle; //! TBranch *b_eleCharge; //! TBranch *b_eleChargeConsistent; //! TBranch *b_eleEn; //! TBranch *b_eleSCEn; //! TBranch *b_eleESEn; //! TBranch *b_eleESEnP1; //! TBranch *b_eleESEnP2; //! TBranch *b_eleD0; //! TBranch *b_eleDz; //! TBranch *b_eleSIP; //! TBranch *b_elePt; //! TBranch *b_eleEta; //! TBranch *b_elePhi; //! TBranch *b_eleR9; //! TBranch *b_eleCalibPt; //! TBranch *b_eleCalibEn; //! TBranch *b_eleSCEta; //! TBranch *b_eleSCPhi; //! TBranch *b_eleSCRawEn; //! TBranch *b_eleSCEtaWidth; //! TBranch *b_eleSCPhiWidth; //! TBranch *b_eleHoverE; //! TBranch *b_eleEoverP; //! TBranch *b_eleEoverPout; //! TBranch *b_eleEoverPInv; //! TBranch *b_eleBrem; //! TBranch *b_eledEtaAtVtx; //! TBranch *b_eledPhiAtVtx; //! TBranch *b_eledEtaAtCalo; //! TBranch *b_eleSigmaIEtaIEtaFull5x5; //! TBranch *b_eleSigmaIPhiIPhiFull5x5; //! TBranch *b_eleConvVeto; //! TBranch *b_eleMissHits; //! TBranch *b_eleESEffSigmaRR; //! TBranch *b_elePFChIso; //! TBranch *b_elePFPhoIso; //! TBranch *b_elePFNeuIso; //! TBranch *b_elePFPUIso; //! TBranch *b_elePFClusEcalIso; //! TBranch *b_elePFClusHcalIso; //! TBranch *b_elePFMiniIso; //! TBranch *b_eleIDMVA; //! TBranch *b_eleIDMVAHZZ; //! TBranch *b_eledEtaseedAtVtx; //! TBranch *b_eleE1x5; //! TBranch *b_eleE2x5; //! TBranch *b_eleE5x5; //! TBranch *b_eleE1x5Full5x5; //! TBranch *b_eleE2x5Full5x5; //! TBranch *b_eleE5x5Full5x5; //! TBranch *b_eleR9Full5x5; //! TBranch *b_eleEcalDrivenSeed; //! TBranch *b_eleDr03EcalRecHitSumEt; //! TBranch *b_eleDr03HcalDepth1TowerSumEt; //! TBranch *b_eleDr03HcalDepth2TowerSumEt; //! TBranch *b_eleDr03HcalTowerSumEt; //! TBranch *b_eleDr03TkSumPt; //! TBranch *b_elecaloEnergy; //! TBranch *b_eleTrkdxy; //! TBranch *b_eleKFHits; //! TBranch *b_eleKFChi2; //! TBranch *b_eleGSFChi2; //! TBranch *b_eleGSFPt; //! TBranch *b_eleGSFEta; //! TBranch *b_eleGSFPhi; //! TBranch *b_eleGSFCharge; //! TBranch *b_eleGSFHits; //! TBranch *b_eleGSFMissHits; //! TBranch *b_eleGSFNHitsMax; //! TBranch *b_eleGSFVtxProb; //! TBranch *b_eleGSFlxyPV; //! TBranch *b_eleGSFlxyBS; //! TBranch *b_eleBCEn; //! TBranch *b_eleBCEta; //! TBranch *b_eleBCPhi; //! TBranch *b_eleBCS25; //! TBranch *b_eleBCS15; //! TBranch *b_eleBCSieie; //! TBranch *b_eleBCSieip; //! TBranch *b_eleBCSipip; //! TBranch *b_eleFiredSingleTrgs; //! TBranch *b_eleFiredDoubleTrgs; //! TBranch *b_eleFiredL1Trgs; //! TBranch *b_eleIDbit; //! TBranch *b_npfHF; //! TBranch *b_pfHFEn; //! TBranch *b_pfHFECALEn; //! TBranch *b_pfHFHCALEn; //! TBranch *b_pfHFPt; //! TBranch *b_pfHFEta; //! TBranch *b_pfHFPhi; //! TBranch *b_pfHFIso; //! TBranch *b_nMu; //! TBranch *b_muPt; //! TBranch *b_muEn; //! TBranch *b_muEta; //! TBranch *b_muPhi; //! TBranch *b_muCharge; //! TBranch *b_muType; //! TBranch *b_muIDbit; //! TBranch *b_muD0; //! TBranch *b_muDz; //! TBranch *b_muSIP; //! TBranch *b_muChi2NDF; //! TBranch *b_muInnerD0; //! TBranch *b_muInnerDz; //! TBranch *b_muTrkLayers; //! TBranch *b_muPixelLayers; //! TBranch *b_muPixelHits; //! TBranch *b_muMuonHits; //! TBranch *b_muStations; //! TBranch *b_muMatches; //! TBranch *b_muTrkQuality; //! TBranch *b_muIsoTrk; //! TBranch *b_muPFChIso; //! TBranch *b_muPFPhoIso; //! TBranch *b_muPFNeuIso; //! TBranch *b_muPFPUIso; //! TBranch *b_muPFMiniIso; //! TBranch *b_muFiredTrgs; //! TBranch *b_muFiredL1Trgs; //! TBranch *b_muInnervalidFraction; //! TBranch *b_musegmentCompatibility; //! TBranch *b_muchi2LocalPosition; //! TBranch *b_mutrkKink; //! TBranch *b_muBestTrkPtError; //! TBranch *b_muBestTrkPt; //! TBranch *b_nJet; //! TBranch *b_j1etaWidth; //! TBranch *b_j1phiWidth; //! TBranch *b_j1nPhotons; //! TBranch *b_j1nCHPions; //! TBranch *b_j1nMisc; //! TBranch *b_j1MiscPID; //! TBranch *b_j1PFConsPt; //! TBranch *b_j1PFConsEta; //! TBranch *b_j1PFConsPhi; //! TBranch *b_j1PFConsEt; //! TBranch *b_j1PFConsPID; //! TBranch *b_jetPt; //! TBranch *b_jetEn; //! TBranch *b_jetEta; //! TBranch *b_jetPhi; //! TBranch *b_jetRawPt; //! TBranch *b_jetRawEn; //! TBranch *b_jetMt; //! TBranch *b_jetArea; //! TBranch *b_jetLeadTrackPt; //! TBranch *b_jetLeadTrackEta; //! TBranch *b_jetLeadTrackPhi; //! TBranch *b_jetLepTrackPID; //! TBranch *b_jetLepTrackPt; //! TBranch *b_jetLepTrackEta; //! TBranch *b_jetLepTrackPhi; //! TBranch *b_jetCSV2BJetTags; //! TBranch *b_jetJetProbabilityBJetTags; //! TBranch *b_jetpfCombinedMVAV2BJetTags; //! TBranch *b_jetPartonID; //! TBranch *b_jetHadFlvr; //! TBranch *b_jetGenJetEn; //! TBranch *b_jetGenJetPt; //! TBranch *b_jetGenJetEta; //! TBranch *b_jetGenJetPhi; //! TBranch *b_jetGenPartonID; //! TBranch *b_jetGenEn; //! TBranch *b_jetGenPt; //! TBranch *b_jetGenEta; //! TBranch *b_jetGenPhi; //! TBranch *b_jetGenPartonMomID; //! TBranch *b_jetP4Smear; //! TBranch *b_jetP4SmearUp; //! TBranch *b_jetP4SmearDo; //! TBranch *b_jetPFLooseId; //! TBranch *b_jetID; //! TBranch *b_jetPUID; //! TBranch *b_jetPUFullID; //! TBranch *b_jetJECUnc; //! TBranch *b_jetFiredTrgs; //! TBranch *b_jetCHF; //! TBranch *b_jetNHF; //! TBranch *b_jetCEF; //! TBranch *b_jetNEF; //! TBranch *b_jetNCH; //! TBranch *b_jetNNP; //! TBranch *b_jetMUF; //! TBranch *b_jetVtxPt; //! TBranch *b_jetVtxMass; //! TBranch *b_jetVtxNtrks; //! TBranch *b_jetVtx3DVal; //! TBranch *b_jetVtx3DSig; //! ZprimeJetsClass_MC_ZJets(const char* file1,const char* file2); virtual ~ZprimeJetsClass_MC_ZJets(); virtual Int_t Cut(Long64_t entry); virtual Int_t GetEntry(Long64_t entry); virtual Long64_t LoadTree(Long64_t entry); virtual void Init(TTree *tree); virtual void Loop(Long64_t maxEvents, int reportEvery); virtual Bool_t Notify(); virtual void Show(Long64_t entry = -1); virtual void BookHistos(const char* file2); virtual double deltaR(double eta1, double phi1, double eta2, double phi2); virtual void fillHistos(int histoNumber,double event_weight); virtual float DeltaPhi(float phi1, float phi2); virtual vector<int> getJetCand(double jetPtCut, double jetEtaCut, double jetNHFCut, double jetCHFCut); virtual vector<int> JetVetoDecision(int leading_ele_index, int subleading_ele_index); virtual bool btagVeto(); virtual bool dPhiJetMETcut(std::vector<int> jets); virtual float dPhiJetMETmin(std::vector<int> jets); virtual vector<int> electron_veto_tightID(int jet_index, float elePtCut); virtual vector<int> electron_veto_looseID(int jet_index, int leading_mu_index, int subleading_mu_index, float elePtCut); virtual vector<int> muon_veto_tightID(int jet_index, float muPtCut); virtual vector<int> muon_veto_looseID(int jet_index, int leading_ele_index, int subleading_ele_index, float muPtCut); virtual vector<int>getPFCandidates(); }; #endif #ifdef ZprimeJetsClass_MC_ZJets_cxx ZprimeJetsClass_MC_ZJets::ZprimeJetsClass_MC_ZJets(const char* file1,const char* file2) { TChain *chain = new TChain("ggNtuplizer/EventTree"); TString path = file1; TSystemDirectory sourceDir("hi",path); TList* fileList = sourceDir.GetListOfFiles(); TIter nextlist(fileList); TSystemFile* filename; int fileNumber = 0; int maxFiles = -1; while ((filename = (TSystemFile*)nextlist()) && fileNumber > maxFiles) { //Debug std::cout<<"file path found: "<<(path+filename->GetName())<<std::endl; std::cout<<"name: "<<(filename->GetName())<<std::endl; std::cout<<"fileNumber: "<<fileNumber<<std::endl; TString dataset = "ggtree_mc_"; TString FullPathInputFile = (path+filename->GetName()); TString name = filename->GetName(); if(name.Contains(dataset)) { std::cout<<"Adding FullPathInputFile to chain:"<<FullPathInputFile<<std::endl; std::cout<<std::endl; chain->Add(FullPathInputFile); } fileNumber++; } std::cout<<"All files added."<<std::endl; std::cout<<"Initializing chain."<<std::endl; Init(chain); BookHistos(file2); } ZprimeJetsClass_MC_ZJets::~ZprimeJetsClass_MC_ZJets() { if (!fChain) return; delete fChain->GetCurrentFile(); fileName->cd(); fileName->Write(); tree->Write(); fileName->Close(); } Int_t ZprimeJetsClass_MC_ZJets::GetEntry(Long64_t entry) { // Read contents of entry. if (!fChain) return 0; return fChain->GetEntry(entry); } Long64_t ZprimeJetsClass_MC_ZJets::LoadTree(Long64_t entry) { // Set the environment to read one entry if (!fChain) return -5; Long64_t centry = fChain->LoadTree(entry); if (centry < 0) return centry; if (fChain->GetTreeNumber() != fCurrent) { fCurrent = fChain->GetTreeNumber(); Notify(); } return centry; } void ZprimeJetsClass_MC_ZJets::Init(TTree *tree) { // The Init() function is called when the selector needs to initialize // a new tree or chain. Typically here the branch addresses and branch // pointers of the tree will be set. // It is normally not necessary to make changes to the generated // code, but the routine can be extended by the user if needed. // Init() will be called many times when running on PROOF // (once per file to be processed). // Set object pointer phoPrescale = 0; pdf = 0; EventTag = 0; nPU = 0; puBX = 0; puTrue = 0; mcPID = 0; mcVtx = 0; mcVty = 0; mcVtz = 0; mcPt = 0; mcMass = 0; mcEta = 0; mcPhi = 0; mcE = 0; mcEt = 0; mcGMomPID = 0; mcMomPID = 0; mcMomPt = 0; mcMomMass = 0; mcMomEta = 0; mcMomPhi = 0; mcStatusFlag = 0; mcParentage = 0; mcStatus = 0; mcCalIsoDR03 = 0; mcTrkIsoDR03 = 0; mcCalIsoDR04 = 0; mcTrkIsoDR04 = 0; phoE = 0; phoEt = 0; phoEta = 0; phoPhi = 0; phoCalibE = 0; phoCalibEt = 0; phoSCE = 0; phoSCRawE = 0; phoESEn = 0; phoESEnP1 = 0; phoESEnP2 = 0; phoSCEta = 0; phoSCPhi = 0; phoSCEtaWidth = 0; phoSCPhiWidth = 0; phoSCBrem = 0; phohasPixelSeed = 0; phoEleVeto = 0; phoR9 = 0; phoHoverE = 0; phoE1x3 = 0; phoE1x5 = 0; phoE2x2 = 0; phoE2x5Max = 0; phoE5x5 = 0; phoESEffSigmaRR = 0; phoSigmaIEtaIEtaFull5x5 = 0; phoSigmaIEtaIPhiFull5x5 = 0; phoSigmaIPhiIPhiFull5x5 = 0; phoE1x3Full5x5 = 0; phoE1x5Full5x5 = 0; phoE2x2Full5x5 = 0; phoE2x5MaxFull5x5 = 0; phoE5x5Full5x5 = 0; phoR9Full5x5 = 0; phoPFChIso = 0; phoPFPhoIso = 0; phoPFNeuIso = 0; phoPFChWorstIso = 0; phoCITKChIso = 0; phoCITKPhoIso = 0; phoCITKNeuIso = 0; phoIDMVA = 0; phoFiredSingleTrgs = 0; phoFiredDoubleTrgs = 0; phoFiredL1Trgs = 0; phoSeedTime = 0; phoSeedEnergy = 0; phoxtalBits = 0; phoIDbit = 0; pfphoEt = 0; pfphoEta = 0; pfphoPhi = 0; eleCharge = 0; eleChargeConsistent = 0; eleEn = 0; eleSCEn = 0; eleESEn = 0; eleESEnP1 = 0; eleESEnP2 = 0; eleD0 = 0; eleDz = 0; eleSIP = 0; elePt = 0; eleEta = 0; elePhi = 0; eleR9 = 0; eleCalibPt = 0; eleCalibEn = 0; eleSCEta = 0; eleSCPhi = 0; eleSCRawEn = 0; eleSCEtaWidth = 0; eleSCPhiWidth = 0; eleHoverE = 0; eleEoverP = 0; eleEoverPout = 0; eleEoverPInv = 0; eleBrem = 0; eledEtaAtVtx = 0; eledPhiAtVtx = 0; eledEtaAtCalo = 0; eleSigmaIEtaIEtaFull5x5 = 0; eleSigmaIPhiIPhiFull5x5 = 0; eleConvVeto = 0; eleMissHits = 0; eleESEffSigmaRR = 0; elePFChIso = 0; elePFPhoIso = 0; elePFNeuIso = 0; elePFPUIso = 0; elePFClusEcalIso = 0; elePFClusHcalIso = 0; elePFMiniIso = 0; eleIDMVA = 0; eleIDMVAHZZ = 0; eledEtaseedAtVtx = 0; eleE1x5 = 0; eleE2x5 = 0; eleE5x5 = 0; eleE1x5Full5x5 = 0; eleE2x5Full5x5 = 0; eleE5x5Full5x5 = 0; eleR9Full5x5 = 0; eleEcalDrivenSeed = 0; eleDr03EcalRecHitSumEt = 0; eleDr03HcalDepth1TowerSumEt = 0; eleDr03HcalDepth2TowerSumEt = 0; eleDr03HcalTowerSumEt = 0; eleDr03TkSumPt = 0; elecaloEnergy = 0; eleTrkdxy = 0; eleKFHits = 0; eleKFChi2 = 0; eleGSFChi2 = 0; eleGSFPt = 0; eleGSFEta = 0; eleGSFPhi = 0; eleGSFCharge = 0; eleGSFHits = 0; eleGSFMissHits = 0; eleGSFNHitsMax = 0; eleGSFVtxProb = 0; eleGSFlxyPV = 0; eleGSFlxyBS = 0; eleBCEn = 0; eleBCEta = 0; eleBCPhi = 0; eleBCS25 = 0; eleBCS15 = 0; eleBCSieie = 0; eleBCSieip = 0; eleBCSipip = 0; eleFiredSingleTrgs = 0; eleFiredDoubleTrgs = 0; eleFiredL1Trgs = 0; eleIDbit = 0; pfHFEn = 0; pfHFECALEn = 0; pfHFHCALEn = 0; pfHFPt = 0; pfHFEta = 0; pfHFPhi = 0; pfHFIso = 0; muPt = 0; muEn = 0; muEta = 0; muPhi = 0; muCharge = 0; muType = 0; muIDbit = 0; muD0 = 0; muDz = 0; muSIP = 0; muChi2NDF = 0; muInnerD0 = 0; muInnerDz = 0; muTrkLayers = 0; muPixelLayers = 0; muPixelHits = 0; muMuonHits = 0; muStations = 0; muMatches = 0; muTrkQuality = 0; muIsoTrk = 0; muPFChIso = 0; muPFPhoIso = 0; muPFNeuIso = 0; muPFPUIso = 0; muPFMiniIso = 0; muFiredTrgs = 0; muFiredL1Trgs = 0; muInnervalidFraction = 0; musegmentCompatibility = 0; muchi2LocalPosition = 0; mutrkKink = 0; muBestTrkPtError = 0; muBestTrkPt = 0; j1MiscPID = 0; j1PFConsPt = 0; j1PFConsEta = 0; j1PFConsPhi = 0; j1PFConsEt = 0; j1PFConsPID = 0; jetPt = 0; jetEn = 0; jetEta = 0; jetPhi = 0; jetRawPt = 0; jetRawEn = 0; jetMt = 0; jetArea = 0; jetLeadTrackPt = 0; jetLeadTrackEta = 0; jetLeadTrackPhi = 0; jetLepTrackPID = 0; jetLepTrackPt = 0; jetLepTrackEta = 0; jetLepTrackPhi = 0; jetCSV2BJetTags = 0; jetJetProbabilityBJetTags = 0; jetpfCombinedMVAV2BJetTags = 0; jetPartonID = 0; jetHadFlvr = 0; jetGenJetEn = 0; jetGenJetPt = 0; jetGenJetEta = 0; jetGenJetPhi = 0; jetGenPartonID = 0; jetGenEn = 0; jetGenPt = 0; jetGenEta = 0; jetGenPhi = 0; jetGenPartonMomID = 0; jetP4Smear = 0; jetP4SmearUp = 0; jetP4SmearDo = 0; jetPFLooseId = 0; jetID = 0; jetPUID = 0; jetPUFullID = 0; jetJECUnc = 0; jetFiredTrgs = 0; jetCHF = 0; jetNHF = 0; jetCEF = 0; jetNEF = 0; jetNCH = 0; jetNNP = 0; jetMUF = 0; jetVtxPt = 0; jetVtxMass = 0; jetVtxNtrks = 0; jetVtx3DVal = 0; jetVtx3DSig = 0; // Set branch addresses and branch pointers if (!tree) return; fChain = tree; fCurrent = -1; fChain->SetMakeClass(1); fChain->SetBranchAddress("run", &run, &b_run); fChain->SetBranchAddress("event", &event, &b_event); fChain->SetBranchAddress("lumis", &lumis, &b_lumis); fChain->SetBranchAddress("isData", &isData, &b_isData); fChain->SetBranchAddress("nVtx", &nVtx, &b_nVtx); fChain->SetBranchAddress("nGoodVtx", &nGoodVtx, &b_nGoodVtx); fChain->SetBranchAddress("nTrksPV", &nTrksPV, &b_nTrksPV); fChain->SetBranchAddress("isPVGood", &isPVGood, &b_isPVGood); fChain->SetBranchAddress("vtx", &vtx, &b_vtx); fChain->SetBranchAddress("vty", &vty, &b_vty); fChain->SetBranchAddress("vtz", &vtz, &b_vtz); fChain->SetBranchAddress("rho", &rho, &b_rho); fChain->SetBranchAddress("rhoCentral", &rhoCentral, &b_rhoCentral); fChain->SetBranchAddress("HLTEleMuX", &HLTEleMuX, &b_HLTEleMuX); fChain->SetBranchAddress("HLTPho", &HLTPho, &b_HLTPho); fChain->SetBranchAddress("HLTJet", &HLTJet, &b_HLTJet); fChain->SetBranchAddress("HLTEleMuXIsPrescaled", &HLTEleMuXIsPrescaled, &b_HLTEleMuXIsPrescaled); fChain->SetBranchAddress("HLTPhoIsPrescaled", &HLTPhoIsPrescaled, &b_HLTPhoIsPrescaled); fChain->SetBranchAddress("HLTJetIsPrescaled", &HLTJetIsPrescaled, &b_HLTJetIsPrescaled); fChain->SetBranchAddress("phoPrescale", &phoPrescale, &b_phoPrescale); fChain->SetBranchAddress("pdf", &pdf, &b_pdf); fChain->SetBranchAddress("pthat", &pthat, &b_pthat); fChain->SetBranchAddress("processID", &processID, &b_processID); fChain->SetBranchAddress("genWeight", &genWeight, &b_genWeight); fChain->SetBranchAddress("genHT", &genHT, &b_genHT); fChain->SetBranchAddress("EventTag", &EventTag, &b_EventTag); fChain->SetBranchAddress("nPUInfo", &nPUInfo, &b_nPUInfo); fChain->SetBranchAddress("nPU", &nPU, &b_nPU); fChain->SetBranchAddress("puBX", &puBX, &b_puBX); fChain->SetBranchAddress("puTrue", &puTrue, &b_puTrue); fChain->SetBranchAddress("nMC", &nMC, &b_nMC); fChain->SetBranchAddress("mcPID", &mcPID, &b_mcPID); fChain->SetBranchAddress("mcVtx", &mcVtx, &b_mcVtx); fChain->SetBranchAddress("mcVty", &mcVty, &b_mcVty); fChain->SetBranchAddress("mcVtz", &mcVtz, &b_mcVtz); fChain->SetBranchAddress("mcPt", &mcPt, &b_mcPt); fChain->SetBranchAddress("mcMass", &mcMass, &b_mcMass); fChain->SetBranchAddress("mcEta", &mcEta, &b_mcEta); fChain->SetBranchAddress("mcPhi", &mcPhi, &b_mcPhi); fChain->SetBranchAddress("mcE", &mcE, &b_mcE); fChain->SetBranchAddress("mcEt", &mcEt, &b_mcEt); fChain->SetBranchAddress("mcGMomPID", &mcGMomPID, &b_mcGMomPID); fChain->SetBranchAddress("mcMomPID", &mcMomPID, &b_mcMomPID); fChain->SetBranchAddress("mcMomPt", &mcMomPt, &b_mcMomPt); fChain->SetBranchAddress("mcMomMass", &mcMomMass, &b_mcMomMass); fChain->SetBranchAddress("mcMomEta", &mcMomEta, &b_mcMomEta); fChain->SetBranchAddress("mcMomPhi", &mcMomPhi, &b_mcMomPhi); fChain->SetBranchAddress("mcStatusFlag", &mcStatusFlag, &b_mcStatusFlag); fChain->SetBranchAddress("mcParentage", &mcParentage, &b_mcParentage); fChain->SetBranchAddress("mcStatus", &mcStatus, &b_mcStatus); fChain->SetBranchAddress("mcCalIsoDR03", &mcCalIsoDR03, &b_mcCalIsoDR03); fChain->SetBranchAddress("mcTrkIsoDR03", &mcTrkIsoDR03, &b_mcTrkIsoDR03); fChain->SetBranchAddress("mcCalIsoDR04", &mcCalIsoDR04, &b_mcCalIsoDR04); fChain->SetBranchAddress("mcTrkIsoDR04", &mcTrkIsoDR04, &b_mcTrkIsoDR04); fChain->SetBranchAddress("genMET", &genMET, &b_genMET); fChain->SetBranchAddress("genMETPhi", &genMETPhi, &b_genMETPhi); fChain->SetBranchAddress("metFilters", &metFilters, &b_metFilters); fChain->SetBranchAddress("pfMET", &pfMET, &b_pfMET); fChain->SetBranchAddress("caloMET", &caloMET, &b_caloMET); fChain->SetBranchAddress("fCoordinates.fX", &fCoordinates_fX, &b_caloMet_fCoordinates_fX); fChain->SetBranchAddress("fCoordinates.fY", &fCoordinates_fY, &b_caloMet_fCoordinates_fY); fChain->SetBranchAddress("pfMETPhi", &pfMETPhi, &b_pfMETPhi); fChain->SetBranchAddress("pfMETsumEt", &pfMETsumEt, &b_pfMETsumEt); fChain->SetBranchAddress("pfMETmEtSig", &pfMETmEtSig, &b_pfMETmEtSig); fChain->SetBranchAddress("pfMETSig", &pfMETSig, &b_pfMETSig); fChain->SetBranchAddress("pfMET_T1JERUp", &pfMET_T1JERUp, &b_pfMET_T1JERUp); fChain->SetBranchAddress("pfMET_T1JERDo", &pfMET_T1JERDo, &b_pfMET_T1JERDo); fChain->SetBranchAddress("pfMET_T1JESUp", &pfMET_T1JESUp, &b_pfMET_T1JESUp); fChain->SetBranchAddress("pfMET_T1JESDo", &pfMET_T1JESDo, &b_pfMET_T1JESDo); fChain->SetBranchAddress("pfMET_T1UESUp", &pfMET_T1UESUp, &b_pfMET_T1UESUp); fChain->SetBranchAddress("pfMET_T1UESDo", &pfMET_T1UESDo, &b_pfMET_T1UESDo); fChain->SetBranchAddress("pfMETPhi_T1JESUp", &pfMETPhi_T1JESUp, &b_pfMETPhi_T1JESUp); fChain->SetBranchAddress("pfMETPhi_T1JESDo", &pfMETPhi_T1JESDo, &b_pfMETPhi_T1JESDo); fChain->SetBranchAddress("pfMETPhi_T1UESUp", &pfMETPhi_T1UESUp, &b_pfMETPhi_T1UESUp); fChain->SetBranchAddress("pfMETPhi_T1UESDo", &pfMETPhi_T1UESDo, &b_pfMETPhi_T1UESDo); fChain->SetBranchAddress("nPho", &nPho, &b_nPho); fChain->SetBranchAddress("phoE", &phoE, &b_phoE); fChain->SetBranchAddress("phoEt", &phoEt, &b_phoEt); fChain->SetBranchAddress("phoEta", &phoEta, &b_phoEta); fChain->SetBranchAddress("phoPhi", &phoPhi, &b_phoPhi); fChain->SetBranchAddress("phoCalibE", &phoCalibE, &b_phoCalibE); fChain->SetBranchAddress("phoCalibEt", &phoCalibEt, &b_phoCalibEt); fChain->SetBranchAddress("phoSCE", &phoSCE, &b_phoSCE); fChain->SetBranchAddress("phoSCRawE", &phoSCRawE, &b_phoSCRawE); fChain->SetBranchAddress("phoESEn", &phoESEn, &b_phoESEn); fChain->SetBranchAddress("phoESEnP1", &phoESEnP1, &b_phoESEnP1); fChain->SetBranchAddress("phoESEnP2", &phoESEnP2, &b_phoESEnP2); fChain->SetBranchAddress("phoSCEta", &phoSCEta, &b_phoSCEta); fChain->SetBranchAddress("phoSCPhi", &phoSCPhi, &b_phoSCPhi); fChain->SetBranchAddress("phoSCEtaWidth", &phoSCEtaWidth, &b_phoSCEtaWidth); fChain->SetBranchAddress("phoSCPhiWidth", &phoSCPhiWidth, &b_phoSCPhiWidth); fChain->SetBranchAddress("phoSCBrem", &phoSCBrem, &b_phoSCBrem); fChain->SetBranchAddress("phohasPixelSeed", &phohasPixelSeed, &b_phohasPixelSeed); fChain->SetBranchAddress("phoEleVeto", &phoEleVeto, &b_phoEleVeto); fChain->SetBranchAddress("phoR9", &phoR9, &b_phoR9); fChain->SetBranchAddress("phoHoverE", &phoHoverE, &b_phoHoverE); fChain->SetBranchAddress("phoE1x3", &phoE1x3, &b_phoE1x3); fChain->SetBranchAddress("phoE1x5", &phoE1x5, &b_phoE1x5); fChain->SetBranchAddress("phoE2x2", &phoE2x2, &b_phoE2x2); fChain->SetBranchAddress("phoE2x5Max", &phoE2x5Max, &b_phoE2x5Max); fChain->SetBranchAddress("phoE5x5", &phoE5x5, &b_phoE5x5); fChain->SetBranchAddress("phoESEffSigmaRR", &phoESEffSigmaRR, &b_phoESEffSigmaRR); fChain->SetBranchAddress("phoSigmaIEtaIEtaFull5x5", &phoSigmaIEtaIEtaFull5x5, &b_phoSigmaIEtaIEtaFull5x5); fChain->SetBranchAddress("phoSigmaIEtaIPhiFull5x5", &phoSigmaIEtaIPhiFull5x5, &b_phoSigmaIEtaIPhiFull5x5); fChain->SetBranchAddress("phoSigmaIPhiIPhiFull5x5", &phoSigmaIPhiIPhiFull5x5, &b_phoSigmaIPhiIPhiFull5x5); fChain->SetBranchAddress("phoE1x3Full5x5", &phoE1x3Full5x5, &b_phoE1x3Full5x5); fChain->SetBranchAddress("phoE1x5Full5x5", &phoE1x5Full5x5, &b_phoE1x5Full5x5); fChain->SetBranchAddress("phoE2x2Full5x5", &phoE2x2Full5x5, &b_phoE2x2Full5x5); fChain->SetBranchAddress("phoE2x5MaxFull5x5", &phoE2x5MaxFull5x5, &b_phoE2x5MaxFull5x5); fChain->SetBranchAddress("phoE5x5Full5x5", &phoE5x5Full5x5, &b_phoE5x5Full5x5); fChain->SetBranchAddress("phoR9Full5x5", &phoR9Full5x5, &b_phoR9Full5x5); fChain->SetBranchAddress("phoPFChIso", &phoPFChIso, &b_phoPFChIso); fChain->SetBranchAddress("phoPFPhoIso", &phoPFPhoIso, &b_phoPFPhoIso); fChain->SetBranchAddress("phoPFNeuIso", &phoPFNeuIso, &b_phoPFNeuIso); fChain->SetBranchAddress("phoPFChWorstIso", &phoPFChWorstIso, &b_phoPFChWorstIso); fChain->SetBranchAddress("phoCITKChIso", &phoCITKChIso, &b_phoCITKChIso); fChain->SetBranchAddress("phoCITKPhoIso", &phoCITKPhoIso, &b_phoCITKPhoIso); fChain->SetBranchAddress("phoCITKNeuIso", &phoCITKNeuIso, &b_phoCITKNeuIso); fChain->SetBranchAddress("phoIDMVA", &phoIDMVA, &b_phoIDMVA); fChain->SetBranchAddress("phoFiredSingleTrgs", &phoFiredSingleTrgs, &b_phoFiredSingleTrgs); fChain->SetBranchAddress("phoFiredDoubleTrgs", &phoFiredDoubleTrgs, &b_phoFiredDoubleTrgs); fChain->SetBranchAddress("phoFiredL1Trgs", &phoFiredL1Trgs, &b_phoFiredL1Trgs); fChain->SetBranchAddress("phoSeedTime", &phoSeedTime, &b_phoSeedTime); fChain->SetBranchAddress("phoSeedEnergy", &phoSeedEnergy, &b_phoSeedEnergy); fChain->SetBranchAddress("phoxtalBits", &phoxtalBits, &b_phoxtalBits); fChain->SetBranchAddress("phoIDbit", &phoIDbit, &b_phoIDbit); fChain->SetBranchAddress("npfPho", &npfPho, &b_npfPho); fChain->SetBranchAddress("pfphoEt", &pfphoEt, &b_pfphoEt); fChain->SetBranchAddress("pfphoEta", &pfphoEta, &b_pfphoEta); fChain->SetBranchAddress("pfphoPhi", &pfphoPhi, &b_pfphoPhi); fChain->SetBranchAddress("nEle", &nEle, &b_nEle); fChain->SetBranchAddress("eleCharge", &eleCharge, &b_eleCharge); fChain->SetBranchAddress("eleChargeConsistent", &eleChargeConsistent, &b_eleChargeConsistent); fChain->SetBranchAddress("eleEn", &eleEn, &b_eleEn); fChain->SetBranchAddress("eleSCEn", &eleSCEn, &b_eleSCEn); fChain->SetBranchAddress("eleESEn", &eleESEn, &b_eleESEn); fChain->SetBranchAddress("eleESEnP1", &eleESEnP1, &b_eleESEnP1); fChain->SetBranchAddress("eleESEnP2", &eleESEnP2, &b_eleESEnP2); fChain->SetBranchAddress("eleD0", &eleD0, &b_eleD0); fChain->SetBranchAddress("eleDz", &eleDz, &b_eleDz); fChain->SetBranchAddress("eleSIP", &eleSIP, &b_eleSIP); fChain->SetBranchAddress("elePt", &elePt, &b_elePt); fChain->SetBranchAddress("eleEta", &eleEta, &b_eleEta); fChain->SetBranchAddress("elePhi", &elePhi, &b_elePhi); fChain->SetBranchAddress("eleR9", &eleR9, &b_eleR9); fChain->SetBranchAddress("eleCalibPt", &eleCalibPt, &b_eleCalibPt); fChain->SetBranchAddress("eleCalibEn", &eleCalibEn, &b_eleCalibEn); fChain->SetBranchAddress("eleSCEta", &eleSCEta, &b_eleSCEta); fChain->SetBranchAddress("eleSCPhi", &eleSCPhi, &b_eleSCPhi); fChain->SetBranchAddress("eleSCRawEn", &eleSCRawEn, &b_eleSCRawEn); fChain->SetBranchAddress("eleSCEtaWidth", &eleSCEtaWidth, &b_eleSCEtaWidth); fChain->SetBranchAddress("eleSCPhiWidth", &eleSCPhiWidth, &b_eleSCPhiWidth); fChain->SetBranchAddress("eleHoverE", &eleHoverE, &b_eleHoverE); fChain->SetBranchAddress("eleEoverP", &eleEoverP, &b_eleEoverP); fChain->SetBranchAddress("eleEoverPout", &eleEoverPout, &b_eleEoverPout); fChain->SetBranchAddress("eleEoverPInv", &eleEoverPInv, &b_eleEoverPInv); fChain->SetBranchAddress("eleBrem", &eleBrem, &b_eleBrem); fChain->SetBranchAddress("eledEtaAtVtx", &eledEtaAtVtx, &b_eledEtaAtVtx); fChain->SetBranchAddress("eledPhiAtVtx", &eledPhiAtVtx, &b_eledPhiAtVtx); fChain->SetBranchAddress("eledEtaAtCalo", &eledEtaAtCalo, &b_eledEtaAtCalo); fChain->SetBranchAddress("eleSigmaIEtaIEtaFull5x5", &eleSigmaIEtaIEtaFull5x5, &b_eleSigmaIEtaIEtaFull5x5); fChain->SetBranchAddress("eleSigmaIPhiIPhiFull5x5", &eleSigmaIPhiIPhiFull5x5, &b_eleSigmaIPhiIPhiFull5x5); fChain->SetBranchAddress("eleConvVeto", &eleConvVeto, &b_eleConvVeto); fChain->SetBranchAddress("eleMissHits", &eleMissHits, &b_eleMissHits); fChain->SetBranchAddress("eleESEffSigmaRR", &eleESEffSigmaRR, &b_eleESEffSigmaRR); fChain->SetBranchAddress("elePFChIso", &elePFChIso, &b_elePFChIso); fChain->SetBranchAddress("elePFPhoIso", &elePFPhoIso, &b_elePFPhoIso); fChain->SetBranchAddress("elePFNeuIso", &elePFNeuIso, &b_elePFNeuIso); fChain->SetBranchAddress("elePFPUIso", &elePFPUIso, &b_elePFPUIso); fChain->SetBranchAddress("elePFClusEcalIso", &elePFClusEcalIso, &b_elePFClusEcalIso); fChain->SetBranchAddress("elePFClusHcalIso", &elePFClusHcalIso, &b_elePFClusHcalIso); fChain->SetBranchAddress("elePFMiniIso", &elePFMiniIso, &b_elePFMiniIso); fChain->SetBranchAddress("eleIDMVA", &eleIDMVA, &b_eleIDMVA); fChain->SetBranchAddress("eleIDMVAHZZ", &eleIDMVAHZZ, &b_eleIDMVAHZZ); fChain->SetBranchAddress("eledEtaseedAtVtx", &eledEtaseedAtVtx, &b_eledEtaseedAtVtx); fChain->SetBranchAddress("eleE1x5", &eleE1x5, &b_eleE1x5); fChain->SetBranchAddress("eleE2x5", &eleE2x5, &b_eleE2x5); fChain->SetBranchAddress("eleE5x5", &eleE5x5, &b_eleE5x5); fChain->SetBranchAddress("eleE1x5Full5x5", &eleE1x5Full5x5, &b_eleE1x5Full5x5); fChain->SetBranchAddress("eleE2x5Full5x5", &eleE2x5Full5x5, &b_eleE2x5Full5x5); fChain->SetBranchAddress("eleE5x5Full5x5", &eleE5x5Full5x5, &b_eleE5x5Full5x5); fChain->SetBranchAddress("eleR9Full5x5", &eleR9Full5x5, &b_eleR9Full5x5); fChain->SetBranchAddress("eleEcalDrivenSeed", &eleEcalDrivenSeed, &b_eleEcalDrivenSeed); fChain->SetBranchAddress("eleDr03EcalRecHitSumEt", &eleDr03EcalRecHitSumEt, &b_eleDr03EcalRecHitSumEt); fChain->SetBranchAddress("eleDr03HcalDepth1TowerSumEt", &eleDr03HcalDepth1TowerSumEt, &b_eleDr03HcalDepth1TowerSumEt); fChain->SetBranchAddress("eleDr03HcalDepth2TowerSumEt", &eleDr03HcalDepth2TowerSumEt, &b_eleDr03HcalDepth2TowerSumEt); fChain->SetBranchAddress("eleDr03HcalTowerSumEt", &eleDr03HcalTowerSumEt, &b_eleDr03HcalTowerSumEt); fChain->SetBranchAddress("eleDr03TkSumPt", &eleDr03TkSumPt, &b_eleDr03TkSumPt); fChain->SetBranchAddress("elecaloEnergy", &elecaloEnergy, &b_elecaloEnergy); fChain->SetBranchAddress("eleTrkdxy", &eleTrkdxy, &b_eleTrkdxy); fChain->SetBranchAddress("eleKFHits", &eleKFHits, &b_eleKFHits); fChain->SetBranchAddress("eleKFChi2", &eleKFChi2, &b_eleKFChi2); fChain->SetBranchAddress("eleGSFChi2", &eleGSFChi2, &b_eleGSFChi2); fChain->SetBranchAddress("eleGSFPt", &eleGSFPt, &b_eleGSFPt); fChain->SetBranchAddress("eleGSFEta", &eleGSFEta, &b_eleGSFEta); fChain->SetBranchAddress("eleGSFPhi", &eleGSFPhi, &b_eleGSFPhi); fChain->SetBranchAddress("eleGSFCharge", &eleGSFCharge, &b_eleGSFCharge); fChain->SetBranchAddress("eleGSFHits", &eleGSFHits, &b_eleGSFHits); fChain->SetBranchAddress("eleGSFMissHits", &eleGSFMissHits, &b_eleGSFMissHits); fChain->SetBranchAddress("eleGSFNHitsMax", &eleGSFNHitsMax, &b_eleGSFNHitsMax); fChain->SetBranchAddress("eleGSFVtxProb", &eleGSFVtxProb, &b_eleGSFVtxProb); fChain->SetBranchAddress("eleGSFlxyPV", &eleGSFlxyPV, &b_eleGSFlxyPV); fChain->SetBranchAddress("eleGSFlxyBS", &eleGSFlxyBS, &b_eleGSFlxyBS); fChain->SetBranchAddress("eleBCEn", &eleBCEn, &b_eleBCEn); fChain->SetBranchAddress("eleBCEta", &eleBCEta, &b_eleBCEta); fChain->SetBranchAddress("eleBCPhi", &eleBCPhi, &b_eleBCPhi); fChain->SetBranchAddress("eleBCS25", &eleBCS25, &b_eleBCS25); fChain->SetBranchAddress("eleBCS15", &eleBCS15, &b_eleBCS15); fChain->SetBranchAddress("eleBCSieie", &eleBCSieie, &b_eleBCSieie); fChain->SetBranchAddress("eleBCSieip", &eleBCSieip, &b_eleBCSieip); fChain->SetBranchAddress("eleBCSipip", &eleBCSipip, &b_eleBCSipip); fChain->SetBranchAddress("eleFiredSingleTrgs", &eleFiredSingleTrgs, &b_eleFiredSingleTrgs); fChain->SetBranchAddress("eleFiredDoubleTrgs", &eleFiredDoubleTrgs, &b_eleFiredDoubleTrgs); fChain->SetBranchAddress("eleFiredL1Trgs", &eleFiredL1Trgs, &b_eleFiredL1Trgs); fChain->SetBranchAddress("eleIDbit", &eleIDbit, &b_eleIDbit); fChain->SetBranchAddress("npfHF", &npfHF, &b_npfHF); fChain->SetBranchAddress("pfHFEn", &pfHFEn, &b_pfHFEn); fChain->SetBranchAddress("pfHFECALEn", &pfHFECALEn, &b_pfHFECALEn); fChain->SetBranchAddress("pfHFHCALEn", &pfHFHCALEn, &b_pfHFHCALEn); fChain->SetBranchAddress("pfHFPt", &pfHFPt, &b_pfHFPt); fChain->SetBranchAddress("pfHFEta", &pfHFEta, &b_pfHFEta); fChain->SetBranchAddress("pfHFPhi", &pfHFPhi, &b_pfHFPhi); fChain->SetBranchAddress("pfHFIso", &pfHFIso, &b_pfHFIso); fChain->SetBranchAddress("nMu", &nMu, &b_nMu); fChain->SetBranchAddress("muPt", &muPt, &b_muPt); fChain->SetBranchAddress("muEn", &muEn, &b_muEn); fChain->SetBranchAddress("muEta", &muEta, &b_muEta); fChain->SetBranchAddress("muPhi", &muPhi, &b_muPhi); fChain->SetBranchAddress("muCharge", &muCharge, &b_muCharge); fChain->SetBranchAddress("muType", &muType, &b_muType); fChain->SetBranchAddress("muIDbit", &muIDbit, &b_muIDbit); fChain->SetBranchAddress("muD0", &muD0, &b_muD0); fChain->SetBranchAddress("muDz", &muDz, &b_muDz); fChain->SetBranchAddress("muSIP", &muSIP, &b_muSIP); fChain->SetBranchAddress("muChi2NDF", &muChi2NDF, &b_muChi2NDF); fChain->SetBranchAddress("muInnerD0", &muInnerD0, &b_muInnerD0); fChain->SetBranchAddress("muInnerDz", &muInnerDz, &b_muInnerDz); fChain->SetBranchAddress("muTrkLayers", &muTrkLayers, &b_muTrkLayers); fChain->SetBranchAddress("muPixelLayers", &muPixelLayers, &b_muPixelLayers); fChain->SetBranchAddress("muPixelHits", &muPixelHits, &b_muPixelHits); fChain->SetBranchAddress("muMuonHits", &muMuonHits, &b_muMuonHits); fChain->SetBranchAddress("muStations", &muStations, &b_muStations); fChain->SetBranchAddress("muMatches", &muMatches, &b_muMatches); fChain->SetBranchAddress("muTrkQuality", &muTrkQuality, &b_muTrkQuality); fChain->SetBranchAddress("muIsoTrk", &muIsoTrk, &b_muIsoTrk); fChain->SetBranchAddress("muPFChIso", &muPFChIso, &b_muPFChIso); fChain->SetBranchAddress("muPFPhoIso", &muPFPhoIso, &b_muPFPhoIso); fChain->SetBranchAddress("muPFNeuIso", &muPFNeuIso, &b_muPFNeuIso); fChain->SetBranchAddress("muPFPUIso", &muPFPUIso, &b_muPFPUIso); fChain->SetBranchAddress("muPFMiniIso", &muPFMiniIso, &b_muPFMiniIso); fChain->SetBranchAddress("muFiredTrgs", &muFiredTrgs, &b_muFiredTrgs); fChain->SetBranchAddress("muFiredL1Trgs", &muFiredL1Trgs, &b_muFiredL1Trgs); fChain->SetBranchAddress("muInnervalidFraction", &muInnervalidFraction, &b_muInnervalidFraction); fChain->SetBranchAddress("musegmentCompatibility", &musegmentCompatibility, &b_musegmentCompatibility); fChain->SetBranchAddress("muchi2LocalPosition", &muchi2LocalPosition, &b_muchi2LocalPosition); fChain->SetBranchAddress("mutrkKink", &mutrkKink, &b_mutrkKink); fChain->SetBranchAddress("muBestTrkPtError", &muBestTrkPtError, &b_muBestTrkPtError); fChain->SetBranchAddress("muBestTrkPt", &muBestTrkPt, &b_muBestTrkPt); fChain->SetBranchAddress("nJet", &nJet, &b_nJet); fChain->SetBranchAddress("j1etaWidth", &j1etaWidth, &b_j1etaWidth); fChain->SetBranchAddress("j1phiWidth", &j1phiWidth, &b_j1phiWidth); fChain->SetBranchAddress("j1nPhotons", &j1nPhotons, &b_j1nPhotons); fChain->SetBranchAddress("j1nCHPions", &j1nCHPions, &b_j1nCHPions); fChain->SetBranchAddress("j1nMisc", &j1nMisc, &b_j1nMisc); fChain->SetBranchAddress("j1MiscPID", &j1MiscPID, &b_j1MiscPID); fChain->SetBranchAddress("j1PFConsPt", &j1PFConsPt, &b_j1PFConsPt); fChain->SetBranchAddress("j1PFConsEta", &j1PFConsEta, &b_j1PFConsEta); fChain->SetBranchAddress("j1PFConsPhi", &j1PFConsPhi, &b_j1PFConsPhi); fChain->SetBranchAddress("j1PFConsEt", &j1PFConsEt, &b_j1PFConsEt); fChain->SetBranchAddress("j1PFConsPID", &j1PFConsPID, &b_j1PFConsPID); fChain->SetBranchAddress("jetPt", &jetPt, &b_jetPt); fChain->SetBranchAddress("jetEn", &jetEn, &b_jetEn); fChain->SetBranchAddress("jetEta", &jetEta, &b_jetEta); fChain->SetBranchAddress("jetPhi", &jetPhi, &b_jetPhi); fChain->SetBranchAddress("jetRawPt", &jetRawPt, &b_jetRawPt); fChain->SetBranchAddress("jetRawEn", &jetRawEn, &b_jetRawEn); fChain->SetBranchAddress("jetMt", &jetMt, &b_jetMt); fChain->SetBranchAddress("jetArea", &jetArea, &b_jetArea); fChain->SetBranchAddress("jetLeadTrackPt", &jetLeadTrackPt, &b_jetLeadTrackPt); fChain->SetBranchAddress("jetLeadTrackEta", &jetLeadTrackEta, &b_jetLeadTrackEta); fChain->SetBranchAddress("jetLeadTrackPhi", &jetLeadTrackPhi, &b_jetLeadTrackPhi); fChain->SetBranchAddress("jetLepTrackPID", &jetLepTrackPID, &b_jetLepTrackPID); fChain->SetBranchAddress("jetLepTrackPt", &jetLepTrackPt, &b_jetLepTrackPt); fChain->SetBranchAddress("jetLepTrackEta", &jetLepTrackEta, &b_jetLepTrackEta); fChain->SetBranchAddress("jetLepTrackPhi", &jetLepTrackPhi, &b_jetLepTrackPhi); fChain->SetBranchAddress("jetCSV2BJetTags", &jetCSV2BJetTags, &b_jetCSV2BJetTags); fChain->SetBranchAddress("jetJetProbabilityBJetTags", &jetJetProbabilityBJetTags, &b_jetJetProbabilityBJetTags); fChain->SetBranchAddress("jetpfCombinedMVAV2BJetTags", &jetpfCombinedMVAV2BJetTags, &b_jetpfCombinedMVAV2BJetTags); fChain->SetBranchAddress("jetPartonID", &jetPartonID, &b_jetPartonID); fChain->SetBranchAddress("jetHadFlvr", &jetHadFlvr, &b_jetHadFlvr); fChain->SetBranchAddress("jetGenJetEn", &jetGenJetEn, &b_jetGenJetEn); fChain->SetBranchAddress("jetGenJetPt", &jetGenJetPt, &b_jetGenJetPt); fChain->SetBranchAddress("jetGenJetEta", &jetGenJetEta, &b_jetGenJetEta); fChain->SetBranchAddress("jetGenJetPhi", &jetGenJetPhi, &b_jetGenJetPhi); fChain->SetBranchAddress("jetGenPartonID", &jetGenPartonID, &b_jetGenPartonID); fChain->SetBranchAddress("jetGenEn", &jetGenEn, &b_jetGenEn); fChain->SetBranchAddress("jetGenPt", &jetGenPt, &b_jetGenPt); fChain->SetBranchAddress("jetGenEta", &jetGenEta, &b_jetGenEta); fChain->SetBranchAddress("jetGenPhi", &jetGenPhi, &b_jetGenPhi); fChain->SetBranchAddress("jetGenPartonMomID", &jetGenPartonMomID, &b_jetGenPartonMomID); fChain->SetBranchAddress("jetP4Smear", &jetP4Smear, &b_jetP4Smear); fChain->SetBranchAddress("jetP4SmearUp", &jetP4SmearUp, &b_jetP4SmearUp); fChain->SetBranchAddress("jetP4SmearDo", &jetP4SmearDo, &b_jetP4SmearDo); fChain->SetBranchAddress("jetPFLooseId", &jetPFLooseId, &b_jetPFLooseId); fChain->SetBranchAddress("jetID", &jetID, &b_jetID); fChain->SetBranchAddress("jetPUID", &jetPUID, &b_jetPUID); fChain->SetBranchAddress("jetPUFullID", &jetPUFullID, &b_jetPUFullID); fChain->SetBranchAddress("jetJECUnc", &jetJECUnc, &b_jetJECUnc); fChain->SetBranchAddress("jetFiredTrgs", &jetFiredTrgs, &b_jetFiredTrgs); fChain->SetBranchAddress("jetCHF", &jetCHF, &b_jetCHF); fChain->SetBranchAddress("jetNHF", &jetNHF, &b_jetNHF); fChain->SetBranchAddress("jetCEF", &jetCEF, &b_jetCEF); fChain->SetBranchAddress("jetNEF", &jetNEF, &b_jetNEF); fChain->SetBranchAddress("jetNCH", &jetNCH, &b_jetNCH); fChain->SetBranchAddress("jetNNP", &jetNNP, &b_jetNNP); fChain->SetBranchAddress("jetMUF", &jetMUF, &b_jetMUF); fChain->SetBranchAddress("jetVtxPt", &jetVtxPt, &b_jetVtxPt); fChain->SetBranchAddress("jetVtxMass", &jetVtxMass, &b_jetVtxMass); fChain->SetBranchAddress("jetVtxNtrks", &jetVtxNtrks, &b_jetVtxNtrks); fChain->SetBranchAddress("jetVtx3DVal", &jetVtx3DVal, &b_jetVtx3DVal); fChain->SetBranchAddress("jetVtx3DSig", &jetVtx3DSig, &b_jetVtx3DSig); Notify(); } Bool_t ZprimeJetsClass_MC_ZJets::Notify() { // The Notify() function is called when a new file is opened. This // can be either for a new TTree in a TChain or when when a new TTree // is started when using PROOF. It is normally not necessary to make changes // to the generated code, but the routine can be extended by the // user if needed. The return value is currently not used. return kTRUE; } void ZprimeJetsClass_MC_ZJets::Show(Long64_t entry) { // Print contents of entry. // If entry is not specified, print current entry if (!fChain) return; fChain->Show(entry); } Int_t ZprimeJetsClass_MC_ZJets::Cut(Long64_t entry) { // This function may be called from Loop. // returns 1 if entry is accepted. // returns -1 otherwise. return 1; } #endif // #ifdef ZprimeJetsClass_MC_ZJets_cxx
[ "uhussain@wisc.edu" ]
uhussain@wisc.edu
c9066150d96c60b2048bcf1e48b7d320676e9f1a
03f037d0f6371856ede958f0c9d02771d5402baf
/graphics/VTK-7.0.0/Filters/General/vtkYoungsMaterialInterface.cxx
f11bffc588585dd3eb257585f3c3763f10d02da1
[ "BSD-3-Clause" ]
permissive
hlzz/dotfiles
b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb
0591f71230c919c827ba569099eb3b75897e163e
refs/heads/master
2021-01-10T10:06:31.018179
2016-09-27T08:13:18
2016-09-27T08:13:18
55,040,954
4
0
null
null
null
null
UTF-8
C++
false
false
116,438
cxx
/*========================================================================= Program: Visualization Toolkit Module: vtkYoungsMaterialInterface.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ // .SECTION Thanks // This file is part of the generalized Youngs material interface reconstruction algorithm contributed by // CEA/DIF - Commissariat a l'Energie Atomique, Centre DAM Ile-De-France <br> // BP12, F-91297 Arpajon, France. <br> // Implementation by Thierry Carrard (CEA) and Philippe Pebay (Kitware SAS) #include "vtkYoungsMaterialInterface.h" #include "vtkObjectFactory.h" #include "vtkCell.h" #include "vtkEmptyCell.h" #include "vtkPolygon.h" #include "vtkConvexPointSet.h" #include "vtkDataSet.h" #include "vtkMultiBlockDataSet.h" #include "vtkCellData.h" #include "vtkPointData.h" #include "vtkDataArray.h" #include "vtkUnsignedCharArray.h" #include "vtkIdTypeArray.h" #include "vtkIntArray.h" #include "vtkPoints.h" #include "vtkCellArray.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkUnstructuredGrid.h" #include "vtkDoubleArray.h" #include "vtkMath.h" #include "vtkIdList.h" #include "vtkCompositeDataIterator.h" #include "vtkSmartPointer.h" #ifndef DBG_ASSERT #define DBG_ASSERT(c) (void)0 #endif #include <vector> #include <set> #include <string> #include <map> #include <algorithm> #include <math.h> #include <cassert> class vtkYoungsMaterialInterfaceCellCut { public: enum { MAX_CELL_POINTS = 128, MAX_CELL_TETRAS = 128 }; static void cellInterface3D( // Inputs int ncoords, double coords[][3], int nedge, int cellEdges[][2], int ntetra, int tetraPointIds[][4], double fraction, double normal[3] , bool useFractionAsDistance, // Outputs int & np, int eids[], double weights[] , int & nInside, int inPoints[], int & nOutside, int outPoints[] ); static double findTetraSetCuttingPlane( const double normal[3], const double fraction, const int vertexCount, const double vertices[][3], const int tetraCount, const int tetras[][4] ); static bool cellInterfaceD( // Inputs double points[][3], int nPoints, int triangles[][3], int nTriangles, double fraction, double normal[3] , bool axisSymetric, bool useFractionAsDistance, // Outputs int eids[4], double weights[2] , int &polygonPoints, int polygonIds[], int &nRemPoints, int remPoints[] ); static double findTriangleSetCuttingPlane( const double normal[3], const double fraction, const int vertexCount, const double vertices[][3], const int triangleCount, const int triangles[][3], bool axisSymetric=false ); } ; class vtkYoungsMaterialInterfaceInternals { public: struct MaterialDescription { private: std::string Volume, Normal, NormalX, NormalY, NormalZ, Ordering; public: std::set<int> blocks; void setVolume(const std::string& str) { this->Volume = str; } void setNormal(const std::string& str) { this->Normal = str; } void setNormalX(const std::string& str) { this->NormalX = str; } void setNormalY(const std::string& str) { this->NormalY = str; } void setNormalZ(const std::string& str) { this->NormalZ = str; } void setOrdering(const std::string& str) { this->Ordering = str; } const std::string& volume() const { return this->Volume; } const std::string& normal(const vtkYoungsMaterialInterfaceInternals& storage) const { if (this->Normal.empty() && this->NormalX.empty() && this->NormalY.empty() && this->NormalZ.empty() && storage.NormalArrayMap.find(this->Volume) != storage.NormalArrayMap.end()) { return storage.NormalArrayMap.find(this->Volume)->second; } return this->Normal; } const std::string& ordering(const vtkYoungsMaterialInterfaceInternals& storage) const { if (this->Ordering.empty() && storage.OrderingArrayMap.find(this->Volume) != storage.OrderingArrayMap.end()) { return storage.OrderingArrayMap.find(this->Volume)->second; } return this->Ordering; } const std::string& normalX() const { return this->NormalX; } const std::string& normalY() const { return this->NormalY; } const std::string& normalZ() const { return this->NormalZ; } }; std::vector<MaterialDescription> Materials; // original implementation uses index to save all normal and ordering array // associations. To make it easier for ParaView, we needed to add an API to // associate normal and ordering arrays using the volume fraction array names // and hence we've added these two maps. These are only used if // MaterialDescription has empty values for normal and ordering. // Eventually, we may want to consolidate these data-structures. std::map<std::string, std::string> NormalArrayMap; std::map<std::string, std::string> OrderingArrayMap; }; // standard constructors and factory vtkStandardNewMacro(vtkYoungsMaterialInterface); /*! The default constructor \sa ~vtkYoungsMaterialInterface() */ vtkYoungsMaterialInterface::vtkYoungsMaterialInterface() { this->FillMaterial = 0; this->InverseNormal = 0; this->AxisSymetric = 0; this->OnionPeel = 0; this->ReverseMaterialOrder = 0; this->UseFractionAsDistance = 0; this->VolumeFractionRange[0] = 0.01; this->VolumeFractionRange[1] = 0.99; this->NumberOfDomains = -1; this->Internals = new vtkYoungsMaterialInterfaceInternals; this->MaterialBlockMapping = vtkSmartPointer<vtkIntArray>::New(); this->UseAllBlocks = true; vtkDebugMacro(<<"vtkYoungsMaterialInterface::vtkYoungsMaterialInterface() ok\n"); } /*! The destrcutor \sa vtkYoungsMaterialInterface() */ vtkYoungsMaterialInterface::~vtkYoungsMaterialInterface() { delete this->Internals; } void vtkYoungsMaterialInterface::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os,indent); os << indent << "FillMaterial: " << this->FillMaterial << "\n"; os << indent << "InverseNormal: " << this->InverseNormal << "\n"; os << indent << "AxisSymetric: " << this->AxisSymetric << "\n"; os << indent << "OnionPeel: " << this->OnionPeel << "\n"; os << indent << "ReverseMaterialOrder: " << this->ReverseMaterialOrder << "\n"; os << indent << "UseFractionAsDistance: " << this->UseFractionAsDistance << "\n"; os << indent << "VolumeFractionRange: [" << this->VolumeFractionRange[0] << ";" << this->VolumeFractionRange[1] <<"]\n"; os << indent << "NumberOfDomains" << this->NumberOfDomains <<"\n"; os << indent << "UseAllBlocks:" << this->UseAllBlocks << "\n"; } void vtkYoungsMaterialInterface::SetNumberOfMaterials(int n) { // vtkDebugMacro(<<"Resize Materials to "<<n<<"\n"); this->NumberOfDomains = -1; this->Internals->Materials.resize(n); this->Modified(); } int vtkYoungsMaterialInterface::GetNumberOfMaterials() { return static_cast<int>( this->Internals->Materials.size() ); } void vtkYoungsMaterialInterface::SetMaterialVolumeFractionArray( int M, const char* volume ) { vtkDebugMacro(<<"SetMaterialVolumeFractionArray "<<M<<" : "<<volume<<"\n"); this->NumberOfDomains = -1; if( M<0 ) { vtkErrorMacro(<<"Bad material index "<<M<<"\n"); return; } else if( M>=this->GetNumberOfMaterials() ) { this->SetNumberOfMaterials(M+1); } this->Internals->Materials[M].setVolume(volume); this->Modified(); } void vtkYoungsMaterialInterface::SetMaterialNormalArray( int M, const char* normal ) { vtkDebugMacro(<<"SetMaterialNormalArray "<<M<<" : "<<normal<<"\n"); this->NumberOfDomains = -1; if( M<0 ) { vtkErrorMacro(<<"Bad material index "<<M<<"\n"); return; } else if( M>=this->GetNumberOfMaterials() ) { this->SetNumberOfMaterials(M+1); } std::string n = normal; vtkIdType s = n.find(' '); if( s == static_cast<int>( std::string::npos ) ) { this->Internals->Materials[M].setNormal(n); this->Internals->Materials[M].setNormalX(""); this->Internals->Materials[M].setNormalY(""); this->Internals->Materials[M].setNormalZ(""); } else { vtkIdType s2 = n.rfind(' '); this->Internals->Materials[M].setNormal(""); this->Internals->Materials[M].setNormalX(n.substr(0,s)); this->Internals->Materials[M].setNormalY(n.substr(s+1,s2-s-1)); this->Internals->Materials[M].setNormalZ(n.substr(s2+1)); } this->Modified(); } void vtkYoungsMaterialInterface::SetMaterialOrderingArray( int M, const char* ordering ) { vtkDebugMacro(<<"SetMaterialOrderingArray "<<M<<" : "<<ordering<<"\n"); this->NumberOfDomains = -1; if( M<0 ) { vtkErrorMacro(<<"Bad material index "<<M<<"\n"); return; } else if( M>=this->GetNumberOfMaterials() ) { this->SetNumberOfMaterials(M+1); } this->Internals->Materials[M].setOrdering(ordering); this->Modified(); } void vtkYoungsMaterialInterface::SetMaterialArrays( int M, const char* volume, const char* normal, const char* ordering ) { this->NumberOfDomains = -1; if( M<0 ) { vtkErrorMacro(<<"Bad material index "<<M<<"\n"); return; } else if( M>=this->GetNumberOfMaterials() ) { this->SetNumberOfMaterials(M+1); } vtkDebugMacro(<<"Set Material "<<M<<" : "<<volume<<","<<normal<<","<<ordering<<"\n"); vtkYoungsMaterialInterfaceInternals::MaterialDescription md; md.setVolume(volume); md.setNormal(normal); md.setNormalX(""); md.setNormalY(""); md.setNormalZ(""); md.setOrdering(ordering); this->Internals->Materials[M] = md; this->Modified(); } void vtkYoungsMaterialInterface::SetMaterialArrays( int M, const char* volume, const char* normalX, const char* normalY, const char* normalZ, const char* ordering ) { this->NumberOfDomains = -1; if( M < 0 ) { vtkErrorMacro(<<"Bad material index "<<M<<"\n"); return; } else if( M >= this->GetNumberOfMaterials() ) { this->SetNumberOfMaterials(M+1); } vtkDebugMacro(<<"Set Material "<<M<<" : "<<volume<<","<<normalX<<","<<normalY<<","<<normalZ<<","<<ordering<<"\n"); vtkYoungsMaterialInterfaceInternals::MaterialDescription md; md.setVolume(volume); md.setNormal(""); md.setNormalX(normalX); md.setNormalY(normalY); md.setNormalZ(normalZ); md.setOrdering(ordering); this->Internals->Materials[M] = md; this->Modified(); } //----------------------------------------------------------------------------- void vtkYoungsMaterialInterface::SetMaterialNormalArray( const char* volume, const char* normal) { // not sure why this is done, but all SetMaterialNormalArray(int,..) variants // do it, and hence ... this->NumberOfDomains = -1; if (volume && normal && this->Internals->NormalArrayMap[volume] != normal) { this->Internals->NormalArrayMap[volume] = normal; this->Modified(); } } //----------------------------------------------------------------------------- void vtkYoungsMaterialInterface::SetMaterialOrderingArray( const char* volume, const char* ordering) { // not sure why this is done, but all SetMaterialOrderingArray(int,..) variants // do it, and hence ... this->NumberOfDomains = -1; if (volume && ordering && this->Internals->OrderingArrayMap[volume] != ordering) { this->Internals->OrderingArrayMap[volume] = ordering; this->Modified(); } } //----------------------------------------------------------------------------- void vtkYoungsMaterialInterface::RemoveAllMaterials() { this->NumberOfDomains = -1; vtkDebugMacro(<<"Remove All Materials\n"); this->Internals->NormalArrayMap.clear(); this->Internals->OrderingArrayMap.clear(); this->SetNumberOfMaterials(0); } int vtkYoungsMaterialInterface::FillInputPortInformation(int, vtkInformation *info) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkCompositeDataSet"); //info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(), 0); return 1; } // internal classes struct vtkYoungsMaterialInterface_IndexedValue { double value; int index; inline bool operator < ( const vtkYoungsMaterialInterface_IndexedValue& iv ) const { return value < iv.value; } }; struct vtkYoungsMaterialInterface_Mat { // input vtkDataArray* fractionArray; vtkDataArray* normalArray; vtkDataArray* normalXArray; vtkDataArray* normalYArray; vtkDataArray* normalZArray; vtkDataArray* orderingArray; // temporary vtkIdType numberOfCells; vtkIdType numberOfPoints; vtkIdType cellCount; vtkIdType cellArrayCount; vtkIdType pointCount; vtkIdType* pointMap; // output std::vector<unsigned char> cellTypes; std::vector<vtkIdType> cells; vtkDataArray** outCellArrays; vtkDataArray** outPointArrays; // last point array is point coords }; static inline void vtkYoungsMaterialInterface_GetPointData( int nPointData, vtkDataArray** inPointArrays, vtkDataSet * input, std::vector<std::pair<int, vtkIdType> > & prevPointsMap, int vtkNotUsed(nmat), vtkYoungsMaterialInterface_Mat * Mats, int a, vtkIdType i, double* t) { if ((i) >= 0) { if (a < (nPointData - 1)) { DBG_ASSERT( i<inPointArrays[a]->GetNumberOfTuples()); inPointArrays[a]->GetTuple(i, t); } else { DBG_ASSERT( a == (nPointData-1) ); DBG_ASSERT( i<input->GetNumberOfPoints()); input->GetPoint(i, t); } } else { int j = -i - 1; DBG_ASSERT(j>=0 && j<prevPointsMap.size()); int prev_m = prevPointsMap[j].first; DBG_ASSERT(prev_m>=0); vtkIdType prev_i = (prevPointsMap[j].second); DBG_ASSERT(prev_i>=0 && prev_i<Mats[prev_m].outPointArrays[a]->GetNumberOfTuples()); Mats[prev_m].outPointArrays[a]->GetTuple(prev_i, t); } } #define GET_POINT_DATA(a,i,t) vtkYoungsMaterialInterface_GetPointData(nPointData,inPointArrays,input,prevPointsMap,nmat,Mats,a,i,t) struct CellInfo { double points[vtkYoungsMaterialInterface::MAX_CELL_POINTS][3]; vtkIdType pointIds[vtkYoungsMaterialInterface::MAX_CELL_POINTS]; int triangulation[vtkYoungsMaterialInterface::MAX_CELL_POINTS*4]; int edges[vtkYoungsMaterialInterface::MAX_CELL_POINTS][2]; int dim; int np; int nf; int ntri; int type; int nEdges; bool triangulationOk; bool needTriangulation; inline CellInfo() : dim(2), np(0), nf(0), ntri(0), type(VTK_EMPTY_CELL), nEdges(0), triangulationOk(false), needTriangulation(false) {} }; int vtkYoungsMaterialInterface::CellProduceInterface( int dim, int np, double fraction, double minFrac, double maxFrac ) { return ( (dim==3 && np>=4) || (dim==2 && np>=3) ) && ( this->UseFractionAsDistance || ( ( fraction > minFrac ) && ( fraction < maxFrac || this->FillMaterial ) ) ) ; } void vtkYoungsMaterialInterface::RemoveAllMaterialBlockMappings() { vtkDebugMacro(<<"RemoveAllMaterialBlockMappings\n"); this->MaterialBlockMapping->Reset(); } void vtkYoungsMaterialInterface::AddMaterialBlockMapping(int b) { vtkDebugMacro(<<"AddMaterialBlockMapping "<<b<<"\n"); this->MaterialBlockMapping->InsertNextValue(b); } void vtkYoungsMaterialInterface::UpdateBlockMapping() { int n = this->MaterialBlockMapping->GetNumberOfTuples(); int curmat = -1; for( int i = 0; i < n; ++ i ) { int b = this->MaterialBlockMapping->GetValue(i); vtkDebugMacro(<<"MaterialBlockMapping "<<b<<"\n"); if( b < 0 ) curmat = (-b) - 1; else { vtkDebugMacro(<<"Material "<<curmat<<": Adding block "<<b<<"\n"); this->Internals->Materials[curmat].blocks.insert(b); } } } //----------------------------------------------------------------------------- void vtkYoungsMaterialInterface::Aggregate( int nmat, int* inputsPerMaterial ) { // Calculate number of domains this->NumberOfDomains = 0; for ( int m = 0; m < nmat; ++ m ) { // Sum all counts from all processes int inputsPerMaterialSum = inputsPerMaterial[m]; if( inputsPerMaterialSum > this->NumberOfDomains ) { this->NumberOfDomains = inputsPerMaterialSum; } // Reset array inputsPerMaterial[m] = 0; } } //----------------------------------------------------------------------------- int vtkYoungsMaterialInterface::RequestData( vtkInformation *vtkNotUsed(request), vtkInformationVector **inputVector, vtkInformationVector *outputVector) { vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); vtkInformation *outInfo = outputVector->GetInformationObject(0); this->UpdateBlockMapping(); this->NumberOfDomains = -1; // get composite input vtkCompositeDataSet * compositeInput = vtkCompositeDataSet::SafeDownCast( inInfo->Get(vtkDataObject::DATA_OBJECT())); // get typed output vtkMultiBlockDataSet * output = vtkMultiBlockDataSet::SafeDownCast( outInfo->Get(vtkDataObject::DATA_OBJECT())); if (compositeInput == 0 || output == 0) { vtkErrorMacro(<<"Invalid algorithm connection\n"); return 0; } // debug statistics vtkIdType debugStats_PrimaryTriangulationfailed = 0; vtkIdType debugStats_Triangulationfailed = 0; vtkIdType debugStats_NullNormal = 0; vtkIdType debugStats_NoInterfaceFound = 0; // Initialize number of materials int nmat = static_cast<int>( this->Internals->Materials.size() ); if (nmat <= 0) { vtkErrorMacro(<<"Invalid materials size\n"); return 0; } // alocate composite iterator vtkSmartPointer<vtkCompositeDataIterator> inputIterator; inputIterator.TakeReference(compositeInput->NewIterator()); inputIterator->SkipEmptyNodesOn(); inputIterator->InitTraversal(); inputIterator->GoToFirstItem(); // first compute number of domains int* inputsPerMaterial = new int[nmat]; for ( int i = 0; i < nmat; ++ i ) { inputsPerMaterial[i] = 0; } while ( ! inputIterator->IsDoneWithTraversal() ) { vtkDataSet * input = vtkDataSet::SafeDownCast( inputIterator->GetCurrentDataObject() ); // Composite indices begin at 1 (0 is the root) int composite_index = inputIterator->GetCurrentFlatIndex(); inputIterator->GoToNextItem(); if ( input && input->GetNumberOfCells() > 0 ) { int m = 0; for (std::vector<vtkYoungsMaterialInterfaceInternals::MaterialDescription>::iterator it = this->Internals->Materials.begin(); it!= this->Internals->Materials.end(); ++it, ++m) { vtkDataArray* fraction = input->GetCellData()->GetArray((*it).volume().c_str()); bool materialHasBlock = ( (*it).blocks.find(composite_index)!= (*it).blocks.end() ); if ( fraction && ( this->UseAllBlocks || materialHasBlock ) ) { double range[2]; fraction->GetRange(range); if (range[1] > this->VolumeFractionRange[0]) { ++ inputsPerMaterial[m]; } } } } } // Perform parallel aggregation when needed (nothing in serial) this->Aggregate( nmat, inputsPerMaterial ); // map containing output blocks std::map<int, vtkSmartPointer<vtkUnstructuredGrid> > outputBlocks; // iterate over input blocks inputIterator->InitTraversal(); inputIterator->GoToFirstItem(); while (inputIterator->IsDoneWithTraversal() == 0) { vtkDataSet * input = vtkDataSet::SafeDownCast( inputIterator->GetCurrentDataObject()); // Composite indices begin at 1 (0 is the root) int composite_index = inputIterator->GetCurrentFlatIndex(); inputIterator->GoToNextItem(); // make some variables visible by the debugger int nCellData = input->GetCellData()->GetNumberOfArrays(); int nPointData = input->GetPointData()->GetNumberOfArrays(); vtkIdType nCells = input->GetNumberOfCells(); vtkIdType nPoints = input->GetNumberOfPoints(); // -------------- temporary data initialization ------------------- vtkDataArray** inCellArrays = new vtkDataArray*[nCellData]; for (int i = 0; i < nCellData; i++) { inCellArrays[i] = input->GetCellData()->GetArray(i); } vtkDataArray** inPointArrays = new vtkDataArray*[nPointData + 1]; // last point array is point coords int* pointArrayOffset = new int[nPointData + 1]; int pointDataComponents = 0; for (int i = 0; i < nPointData; i++) { inPointArrays[i] = input->GetPointData()->GetArray(i); pointArrayOffset[i] = pointDataComponents; pointDataComponents += inPointArrays[i]->GetNumberOfComponents(); } // we add another data array for point coords pointArrayOffset[nPointData] = pointDataComponents; pointDataComponents += 3; nPointData++; vtkYoungsMaterialInterface_Mat* Mats = new vtkYoungsMaterialInterface_Mat[nmat]; { int m = 0; for (std::vector< vtkYoungsMaterialInterfaceInternals::MaterialDescription>::iterator it = this->Internals->Materials.begin(); it != this->Internals->Materials.end(); ++it, ++m) { Mats[m].fractionArray = input->GetCellData()->GetArray( (*it).volume().c_str() ); Mats[m].normalArray = input->GetCellData()->GetArray( (*it).normal(*this->Internals).c_str() ); Mats[m].normalXArray = input->GetCellData()->GetArray( (*it).normalX().c_str() ); Mats[m].normalYArray = input->GetCellData()->GetArray( (*it).normalY().c_str() ); Mats[m].normalZArray = input->GetCellData()->GetArray( (*it).normalZ().c_str() ); Mats[m].orderingArray = input->GetCellData()->GetArray( (*it).ordering(*this->Internals).c_str() ); if ( ! Mats[m].fractionArray ) { vtkDebugMacro(<<"Material "<<m<<": volume fraction array '"<< (*it).volume()<<"' not found\n"); } if( ! Mats[m].orderingArray ) { vtkDebugMacro(<<"Material "<<m<<" material ordering array '"<< (*it).ordering(*this->Internals)<<"' not found\n"); } if( ! Mats[m].normalArray && ! Mats[m].normalXArray && ! Mats[m].normalYArray && ! Mats[m].normalZArray ) { vtkDebugMacro(<<"Material "<<m<<" normal array '"<< (*it).normal(*this->Internals)<<"' not found\n"); } bool materialHasBlock = ( (*it).blocks.find(composite_index) != (*it).blocks.end() ); if( ! this->UseAllBlocks && ! materialHasBlock ) { Mats[m].fractionArray = 0; // TODO: we certainly can do better to avoid material calculations } Mats[m].numberOfCells = 0; Mats[m].cellCount = 0; Mats[m].cellArrayCount = 0; Mats[m].outCellArrays = new vtkDataArray* [ nCellData ]; for( int i = 0; i < nCellData; ++ i ) { Mats[m].outCellArrays[i] = vtkDataArray::CreateDataArray( inCellArrays[i]->GetDataType() ); Mats[m].outCellArrays[i]->SetName( inCellArrays[i]->GetName() ); Mats[m].outCellArrays[i]->SetNumberOfComponents( inCellArrays[i]->GetNumberOfComponents() ); } Mats[m].numberOfPoints = 0; Mats[m].pointCount = 0; Mats[m].outPointArrays = new vtkDataArray* [ nPointData ]; for( int i = 0;i<(nPointData-1);i++) { Mats[m].outPointArrays[i] = vtkDataArray::CreateDataArray( inPointArrays[i]->GetDataType() ); Mats[m].outPointArrays[i]->SetName( inPointArrays[i]->GetName() ); Mats[m].outPointArrays[i]->SetNumberOfComponents( inPointArrays[i]->GetNumberOfComponents() ); } Mats[m].outPointArrays[nPointData-1] = vtkDoubleArray::New(); Mats[m].outPointArrays[nPointData-1]->SetName("Points"); Mats[m].outPointArrays[nPointData-1]->SetNumberOfComponents(3); } } // --------------- per material number of interfaces estimation ------------ for(vtkIdType c=0;c<nCells;c++) { vtkCell* vtkcell = input->GetCell(c); int cellDim = vtkcell->GetCellDimension(); int np = vtkcell->GetNumberOfPoints(); int nf = vtkcell->GetNumberOfFaces(); for(int m=0;m<nmat;m++) { double fraction = ( Mats[m].fractionArray != 0 ) ? Mats[m].fractionArray->GetTuple1(c) : 0; if( this->CellProduceInterface(cellDim,np,fraction,this->VolumeFractionRange[0],this->VolumeFractionRange[1]) ) { if( cellDim == 2 ) { Mats[m].numberOfPoints += 2; } else { Mats[m].numberOfPoints += nf; } if( this->FillMaterial ) { Mats[m].numberOfPoints += np-1; } Mats[m].numberOfCells ++; } } } // allocation of output arrays for(int m=0;m<nmat;m++) { vtkDebugMacro(<<"Mat #"<<m<<" : cells="<<Mats[m].numberOfCells<<", points="<<Mats[m].numberOfPoints<<", FillMaterial="<<this->FillMaterial<<"\n"); for(int i = 0;i<nCellData;i++) { Mats[m].outCellArrays[i]->Allocate( Mats[m].numberOfCells * Mats[m].outCellArrays[i]->GetNumberOfComponents() ); } for(int i = 0;i<nPointData;i++) { Mats[m].outPointArrays[i]->Allocate( Mats[m].numberOfPoints * Mats[m].outPointArrays[i]->GetNumberOfComponents() ); } Mats[m].cellTypes.reserve( Mats[m].numberOfCells ); Mats[m].cells.reserve( Mats[m].numberOfCells + Mats[m].numberOfPoints ); Mats[m].pointMap = new vtkIdType[ nPoints ]; for(vtkIdType i = 0;i<nPoints;i++) { Mats[m].pointMap[i] = -1;} } // --------------------------- core computation -------------------------- vtkIdList *ptIds = vtkIdList::New(); vtkPoints *pts = vtkPoints::New(); vtkConvexPointSet* cpsCell = vtkConvexPointSet::New(); double* interpolatedValues = new double[ MAX_CELL_POINTS * pointDataComponents ]; vtkYoungsMaterialInterface_IndexedValue * matOrdering = new vtkYoungsMaterialInterface_IndexedValue[nmat]; std::vector< std::pair<int,vtkIdType> > prevPointsMap; prevPointsMap.reserve( MAX_CELL_POINTS*nmat ); for(vtkIdType ci = 0;ci<nCells;ci++) { int interfaceEdges[MAX_CELL_POINTS*2]; double interfaceWeights[MAX_CELL_POINTS]; int nInterfaceEdges; int insidePointIds[MAX_CELL_POINTS]; int nInsidePoints; int outsidePointIds[MAX_CELL_POINTS]; int nOutsidePoints; int outCellPointIds[MAX_CELL_POINTS]; int nOutCellPoints; double referenceVolume = 1.0; double normal[3]; bool normaleNulle = false; prevPointsMap.clear(); // sort materials int nEffectiveMat = 0; for(int mi = 0;mi<nmat;mi++) { matOrdering[mi].index = mi; matOrdering[mi].value = ( Mats[mi].orderingArray != 0 ) ? Mats[mi].orderingArray->GetTuple1(ci) : 0.0; double fraction = ( Mats[mi].fractionArray != 0 ) ? Mats[mi].fractionArray->GetTuple1(ci) : 0; if( this->UseFractionAsDistance || fraction>this->VolumeFractionRange[0] ) nEffectiveMat++; } std::stable_sort( matOrdering , matOrdering+nmat ); // read cell information for the first iteration // a temporary cell will then be generated after each iteration for the next one. vtkCell* vtkcell = input->GetCell(ci); CellInfo cell; cell.dim = vtkcell->GetCellDimension(); cell.np = vtkcell->GetNumberOfPoints(); cell.nf = vtkcell->GetNumberOfFaces(); cell.type = vtkcell->GetCellType(); /* copy points and point ids to lacal arrays. IMPORTANT NOTE : A negative point id refers to a point in the previous material. the material number and real point id can be found through the prevPointsMap. */ for(int p=0;p<cell.np;p++) { cell.pointIds[p] = vtkcell->GetPointId(p); DBG_ASSERT( cell.pointIds[p]>=0 && cell.pointIds[p]<nPoints ); vtkcell->GetPoints()->GetPoint( p , cell.points[p] ); } /* Triangulate cell. IMPORTANT NOTE: triangulation is given with mesh point ids (not local cell ids) and are translated to cell local point ids. */ cell.needTriangulation = false; cell.triangulationOk = ( vtkcell->Triangulate(ci,ptIds,pts) != 0 ); cell.ntri = 0; if( cell.triangulationOk ) { cell.ntri = ptIds->GetNumberOfIds() / (cell.dim+1); for(int i = 0;i<(cell.ntri*(cell.dim+1));i++) { vtkIdType j = std::find( cell.pointIds , cell.pointIds+cell.np , ptIds->GetId(i) ) - cell.pointIds; DBG_ASSERT( j>=0 && j<cell.np ); cell.triangulation[i] = j; } } else { debugStats_PrimaryTriangulationfailed ++; vtkWarningMacro(<<"Triangulation failed on primary cell\n"); } // get 3D cell edges. if( cell.dim == 3 ) { vtkCell3D* cell3D = vtkCell3D::SafeDownCast( vtkcell ); cell.nEdges = vtkcell->GetNumberOfEdges(); for(int i = 0;i<cell.nEdges;i++) { int tmp[4]; int * edgePoints = tmp; cell3D->GetEdgePoints(i,edgePoints); cell.edges[i][0] = edgePoints[0]; DBG_ASSERT( cell.edges[i][0]>=0 && cell.edges[i][0]<cell.np ); cell.edges[i][1] = edgePoints[1]; DBG_ASSERT( cell.edges[i][1]>=0 && cell.edges[i][1]<cell.np ); } } // For debugging : ensure that we don't read anything from cell, but only from previously filled arrays vtkcell = 0; int processedEfectiveMat = 0; // Loop for each material. Current cell is iteratively cut. for(int mi = 0;mi<nmat;mi++) { int m = this->ReverseMaterialOrder ? matOrdering[nmat-1-mi].index : matOrdering[mi].index; // Get volume fraction and interface plane normal from input arrays double fraction = ( Mats[m].fractionArray != 0 ) ? Mats[m].fractionArray->GetTuple1(ci) : 0; // Normalize remaining volume fraction fraction = (referenceVolume>0) ? (fraction/referenceVolume) : 0.0; if( this->CellProduceInterface(cell.dim,cell.np,fraction,this->VolumeFractionRange[0],this->VolumeFractionRange[1]) ) { CellInfo nextCell; // empty cell by default int interfaceCellType = VTK_EMPTY_CELL; if( ( ! mi ) || ( ! this->OnionPeel ) ) { normal[0]=0; normal[1]=0; normal[2]=0; if( Mats[m].normalArray != 0 ) Mats[m].normalArray->GetTuple(ci,normal); if( Mats[m].normalXArray != 0 ) normal[0] = Mats[m].normalXArray->GetTuple1(ci); if( Mats[m].normalYArray != 0 ) normal[1] = Mats[m].normalYArray->GetTuple1(ci); if( Mats[m].normalZArray != 0 ) normal[2] = Mats[m].normalZArray->GetTuple1(ci); // work-around for degenerated normals if( vtkMath::Norm(normal) == 0.0 ) // should it be <EPSILON ? { debugStats_NullNormal ++; normaleNulle=true; normal[0]=1.0; normal[1]=0.0; normal[2]=0.0; } else { vtkMath::Normalize( normal ); } if( this->InverseNormal ) { normal[0] = -normal[0]; normal[1] = -normal[1]; normal[2] = -normal[2]; } } // count how many materials we've processed so far if( fraction > this->VolumeFractionRange[0] ) { processedEfectiveMat ++; } // -= case where the entire input cell is passed through =- if( ( !this->UseFractionAsDistance && fraction>this->VolumeFractionRange[1] && this->FillMaterial ) || ( this->UseFractionAsDistance && normaleNulle ) ) { interfaceCellType = cell.type; //Mats[m].cellTypes.push_back( cell.type ); nOutCellPoints = nInsidePoints = cell.np; nInterfaceEdges = 0; nOutsidePoints = 0; for(int p=0;p<cell.np;p++) { outCellPointIds[p] = insidePointIds[p] = p;} // remaining volume is an empty cell (nextCell is left as is) } // -= case where the entire cell is ignored =- else if ( !this->UseFractionAsDistance && ( fraction<this->VolumeFractionRange[0] || (fraction>this->VolumeFractionRange[1] && !this->FillMaterial) || !cell.triangulationOk ) ) { interfaceCellType = VTK_EMPTY_CELL; //Mats[m].cellTypes.push_back( VTK_EMPTY_CELL ); nOutCellPoints = 0; nInterfaceEdges = 0; nInsidePoints = 0; nOutsidePoints = 0; // remaining volume is the same cell nextCell = cell; if( !cell.triangulationOk ) { debugStats_Triangulationfailed ++; vtkWarningMacro(<<"Cell triangulation failed\n"); } } // -= 2D case =- else if( cell.dim == 2 ) { int nRemCellPoints; int remCellPointIds[MAX_CELL_POINTS]; int triangles[MAX_CELL_POINTS][3]; for(int i = 0;i<cell.ntri;i++) for(int j = 0;j<3;j++) { triangles[i][j] = cell.triangulation[i*3+j]; DBG_ASSERT( triangles[i][j]>=0 && triangles[i][j]<cell.np ); } bool interfaceFound = vtkYoungsMaterialInterfaceCellCut::cellInterfaceD( cell.points, cell.np, triangles, cell.ntri, fraction, normal, this->AxisSymetric != 0, this->UseFractionAsDistance != 0, interfaceEdges, interfaceWeights, nOutCellPoints, outCellPointIds, nRemCellPoints, remCellPointIds ); if( interfaceFound ) { nInterfaceEdges = 2; interfaceCellType = this->FillMaterial ? VTK_POLYGON : VTK_LINE; //Mats[m].cellTypes.push_back( this->FillMaterial ? VTK_POLYGON : VTK_LINE ); // remaining volume is a polygon nextCell.dim = 2; nextCell.np = nRemCellPoints; nextCell.nf = nRemCellPoints; nextCell.type = VTK_POLYGON; // build polygon triangulation for next iteration nextCell.ntri = nextCell.np-2; for(int i = 0;i<nextCell.ntri;i++) { nextCell.triangulation[i*3+0] = 0; nextCell.triangulation[i*3+1] = i+1; nextCell.triangulation[i*3+2] = i+2; } nextCell.triangulationOk = true; nextCell.needTriangulation = false; // populate prevPointsMap and next iteration cell point ids int ni = 0; for(int i = 0;i<nRemCellPoints;i++) { vtkIdType id = remCellPointIds[i]; if( id < 0 ) { id = - (int)( prevPointsMap.size() + 1 ); DBG_ASSERT( (-id-1) == prevPointsMap.size() ); prevPointsMap.push_back( std::make_pair( m , Mats[m].pointCount+ni ) ); // intersection points will be added first ni++; } else { DBG_ASSERT( id>=0 && id<cell.np ); id = cell.pointIds[ id ]; } nextCell.pointIds[i] = id; } DBG_ASSERT( ni == nInterfaceEdges ); // filter out points inside material volume nInsidePoints = 0; for(int i = 0;i<nOutCellPoints;i++) { if( outCellPointIds[i] >= 0 ) insidePointIds[nInsidePoints++] = outCellPointIds[i]; } if( ! this->FillMaterial ) // keep only interface points { int n = 0; for(int i = 0;i<nOutCellPoints;i++) { if( outCellPointIds[i] < 0 ) outCellPointIds[n++] = outCellPointIds[i]; } nOutCellPoints = n; } } else { vtkWarningMacro(<<"no interface found for cell "<<ci<<", mi="<<mi<<", m="<<m<<", frac="<<fraction<<"\n"); nInterfaceEdges = 0; nOutCellPoints = 0; nInsidePoints = 0; nOutsidePoints = 0; interfaceCellType = VTK_EMPTY_CELL; //Mats[m].cellTypes.push_back( VTK_EMPTY_CELL ); // remaining volume is the original cell left unmodified nextCell = cell; } } // -= 3D case =- else { int tetras[MAX_CELL_POINTS][4]; for(int i = 0;i<cell.ntri;i++) for(int j = 0;j<4;j++) { tetras[i][j] = cell.triangulation[i*4+j]; } // compute innterface polygon vtkYoungsMaterialInterfaceCellCut::cellInterface3D( cell.np, cell.points, cell.nEdges, cell.edges, cell.ntri, tetras, fraction, normal, this->UseFractionAsDistance != 0, nInterfaceEdges, interfaceEdges, interfaceWeights, nInsidePoints, insidePointIds, nOutsidePoints, outsidePointIds ); if( nInterfaceEdges>cell.nf || nInterfaceEdges<3 ) // degenerated case, considered as null interface { debugStats_NoInterfaceFound ++; vtkDebugMacro(<<"no interface found for cell "<<ci<<", mi="<<mi<<", m="<<m<<", frac="<<fraction<<"\n"); nInterfaceEdges = 0; nOutCellPoints = 0; nInsidePoints = 0; nOutsidePoints = 0; interfaceCellType = VTK_EMPTY_CELL; //Mats[m].cellTypes.push_back( VTK_EMPTY_CELL ); // in this case, next iteration cell is the same nextCell = cell; } else { nOutCellPoints = 0; for(int e = 0;e<nInterfaceEdges;e++) { outCellPointIds[nOutCellPoints++] = -e -1; } if(this->FillMaterial) { interfaceCellType = VTK_CONVEX_POINT_SET; //Mats[m].cellTypes.push_back( VTK_CONVEX_POINT_SET ); for(int p=0;p<nInsidePoints;p++) { outCellPointIds[nOutCellPoints++] = insidePointIds[p]; } } else { interfaceCellType = VTK_POLYGON; //Mats[m].cellTypes.push_back( VTK_POLYGON ); } // NB: Remaining volume is a convex point set // IMPORTANT NOTE: next iteration cell cannot be entirely built right now. // in this particular case we'll finish it at the end of the material loop. // If no other material remains to be processed, then skip this step. if( mi < ( nmat - 1 ) && processedEfectiveMat < nEffectiveMat ) { nextCell.type = VTK_CONVEX_POINT_SET; nextCell.np = nInterfaceEdges + nOutsidePoints; vtkcell = cpsCell; vtkcell->Points->Reset(); vtkcell->PointIds->Reset(); vtkcell->Points->SetNumberOfPoints( nextCell.np ); vtkcell->PointIds->SetNumberOfIds( nextCell.np ); for(int i = 0;i<nextCell.np;i++) { vtkcell->PointIds->SetId( i, i ); } // nf, ntri and triangulation have to be computed later on, when point coords are computed nextCell.needTriangulation = true; } for(int i = 0;i<nInterfaceEdges;i++) { vtkIdType id = - (int) ( prevPointsMap.size() + 1 ); DBG_ASSERT( (-id-1) == prevPointsMap.size() ); // Interpolated points will be added consecutively prevPointsMap.push_back( std::make_pair( m , Mats[m].pointCount+i ) ); nextCell.pointIds[i] = id; } for(int i = 0;i<nOutsidePoints;i++) { nextCell.pointIds[nInterfaceEdges+i] = cell.pointIds[ outsidePointIds[i] ]; } } // check correctness of next cell's point ids for(int i = 0;i<nextCell.np;i++) { DBG_ASSERT( ( nextCell.pointIds[i]<0 && (-nextCell.pointIds[i]-1)<prevPointsMap.size() ) || ( nextCell.pointIds[i]>=0 && nextCell.pointIds[i]<nPoints ) ); } } // End 3D case // create output cell if( interfaceCellType != VTK_EMPTY_CELL ) { // set type of cell Mats[m].cellTypes.push_back( interfaceCellType ); // interpolate point values for cut edges for(int e = 0;e<nInterfaceEdges;e++) { double t = interfaceWeights[e]; for(int p=0;p<nPointData;p++) { double v0[16]; double v1[16]; int nc = Mats[m].outPointArrays[p]->GetNumberOfComponents(); int ep0 = cell.pointIds[ interfaceEdges[e*2+0] ]; int ep1 = cell.pointIds[ interfaceEdges[e*2+1] ]; GET_POINT_DATA( p , ep0 , v0 ); GET_POINT_DATA( p , ep1 , v1 ); for(int c=0;c<nc;c++) { interpolatedValues[ e*pointDataComponents + pointArrayOffset[p] + c ] = v0[c] + t * ( v1[c] - v0[c] ); } } } // copy point values for(int e = 0;e<nInterfaceEdges;e++) { for(int a = 0;a<nPointData;a++) { DBG_ASSERT( nptId == Mats[m].outPointArrays[a]->GetNumberOfTuples() ); Mats[m].outPointArrays[a]->InsertNextTuple( interpolatedValues + e*pointDataComponents + pointArrayOffset[a] ); } } int pointsCopied = 0; int prevMatInterfToBeAdded = 0; if( this->FillMaterial ) { for(int p=0;p<nInsidePoints;p++) { vtkIdType ptId = cell.pointIds[ insidePointIds[p] ]; if( ptId>=0 ) { if( Mats[m].pointMap[ptId] == -1 ) { vtkIdType nptId = Mats[m].pointCount + nInterfaceEdges + pointsCopied; Mats[m].pointMap[ptId] = nptId; pointsCopied++; for(int a = 0;a<nPointData;a++) { DBG_ASSERT( nptId == Mats[m].outPointArrays[a]->GetNumberOfTuples() ); double tuple[16]; GET_POINT_DATA( a, ptId, tuple ); Mats[m].outPointArrays[a]->InsertNextTuple( tuple ); } } } else { prevMatInterfToBeAdded++; } } } // Populate connectivity array and add extra points from previous // edge intersections that are used but not inserted yet int prevMatInterfAdded = 0; Mats[m].cells.push_back( nOutCellPoints ); Mats[m].cellArrayCount++; for( int p = 0; p < nOutCellPoints; ++ p ) { int nptId; int pointIndex = outCellPointIds[p]; if( pointIndex >= 0 ) { // An original point is encountered (not an edge intersection) DBG_ASSERT( pointIndex>=0 && pointIndex<cell.np ); int ptId = cell.pointIds[ pointIndex ]; if( ptId >= 0 ) { // Interface from a previous iteration DBG_ASSERT( ptId>=0 && ptId<nPoints ); nptId = Mats[m].pointMap[ptId]; } else { nptId = Mats[m].pointCount + nInterfaceEdges + pointsCopied + prevMatInterfAdded; prevMatInterfAdded++; for(int a = 0;a<nPointData;a++) { DBG_ASSERT( nptId == Mats[m].outPointArrays[a]->GetNumberOfTuples() ); double tuple[16]; GET_POINT_DATA( a, ptId, tuple ); Mats[m].outPointArrays[a]->InsertNextTuple( tuple ); } } } else { int interfaceIndex = -pointIndex - 1; DBG_ASSERT( interfaceIndex>=0 && interfaceIndex<nInterfaceEdges ); nptId = Mats[m].pointCount + interfaceIndex; } DBG_ASSERT( nptId>=0 && nptId<(Mats[m].pointCount+nInterfaceEdges+pointsCopied+prevMatInterfToBeAdded) ); Mats[m].cells.push_back( nptId ); Mats[m].cellArrayCount++; } Mats[m].pointCount += nInterfaceEdges + pointsCopied + prevMatInterfAdded; // Copy cell arrays for(int a = 0;a<nCellData;a++) { Mats[m].outCellArrays[a]->InsertNextTuple( inCellArrays[a]->GetTuple(ci) ); } Mats[m].cellCount ++; // Check for equivalence between counters and container sizes DBG_ASSERT( Mats[m].cellCount == Mats[m].cellTypes.size() ); DBG_ASSERT( Mats[m].cellArrayCount == Mats[m].cells.size() ); // Populate next iteration cell point coordinates for(int i = 0;i<nextCell.np;i++) { DBG_ASSERT( ( nextCell.pointIds[i]<0 && (-nextCell.pointIds[i]-1)<prevPointsMap.size() ) || ( nextCell.pointIds[i]>=0 && nextCell.pointIds[i]<nPoints ) ); GET_POINT_DATA( (nPointData-1) , nextCell.pointIds[i] , nextCell.points[i] ); } // for the convex point set, we need to first compute point coords before triangulation (no fixed topology) if( nextCell.needTriangulation && mi<(nmat-1) && processedEfectiveMat<nEffectiveMat ) { // for(int myi = 0;myi<nextCell.np;myi++) // { // cerr<<"p["<<myi<<"]=("<<nextCell.points[myi][0]<<','<<nextCell.points[myi][1]<<','<<nextCell.points[myi][2]<<") "; // } // cerr<<endl; vtkcell->Initialize(); nextCell.nf = vtkcell->GetNumberOfFaces(); if( nextCell.dim == 3 ) { vtkCell3D* cell3D = vtkCell3D::SafeDownCast( vtkcell ); nextCell.nEdges = vtkcell->GetNumberOfEdges(); for(int i = 0;i<nextCell.nEdges;i++) { int tmp[4]; int * edgePoints = tmp; cell3D->GetEdgePoints(i,edgePoints); nextCell.edges[i][0] = edgePoints[0]; DBG_ASSERT( nextCell.edges[i][0]>=0 && nextCell.edges[i][0]<nextCell.np ); nextCell.edges[i][1] = edgePoints[1]; DBG_ASSERT( nextCell.edges[i][1]>=0 && nextCell.edges[i][1]<nextCell.np ); } } nextCell.triangulationOk = ( vtkcell->Triangulate(ci,ptIds,pts) != 0 ); nextCell.ntri = 0; if( nextCell.triangulationOk ) { nextCell.ntri = ptIds->GetNumberOfIds() / (nextCell.dim+1); for(int i = 0;i<(nextCell.ntri*(nextCell.dim+1));i++) { vtkIdType j = ptIds->GetId(i); // cell ids have been set with local ids DBG_ASSERT( j>=0 && j<nextCell.np ); nextCell.triangulation[i] = j; } } else { debugStats_Triangulationfailed ++; vtkWarningMacro(<<"Triangulation failed. Info: cell "<<ci<<", material "<<mi<<", np="<<nextCell.np<<", nf="<<nextCell.nf<<", ne="<<nextCell.nEdges<<"\n"); } nextCell.needTriangulation = false; vtkcell = 0; } // switch to next cell cell = nextCell; } // end of 'interface was found' else { vtkcell = 0; } } // end of 'cell is ok' // else // cell is ignored // { // //vtkWarningMacro(<<"ignoring cell #"<<ci<<", m="<<m<<", mi="<<mi<<", frac="<<fraction<<"\n"); // } // update reference volume referenceVolume -= fraction; } // for materials } // for cells delete [] pointArrayOffset; delete [] inPointArrays; delete [] inCellArrays; ptIds->Delete(); pts->Delete(); cpsCell->Delete(); delete [] interpolatedValues; delete [] matOrdering; // finish output creation // output->SetNumberOfBlocks( nmat ); for( int m=0;m<nmat;m++) { if( Mats[m].cellCount>0 && Mats[m].pointCount>0 ) { vtkDebugMacro(<<"Mat #"<<m<<" : cellCount="<<Mats[m].cellCount<<", numberOfCells="<<Mats[m].numberOfCells<<", pointCount="<<Mats[m].pointCount<<", numberOfPoints="<<Mats[m].numberOfPoints<<"\n"); } delete [] Mats[m].pointMap; vtkSmartPointer<vtkUnstructuredGrid> ugOutput = vtkSmartPointer<vtkUnstructuredGrid>::New(); // set points Mats[m].outPointArrays[nPointData-1]->Squeeze(); vtkPoints* points = vtkPoints::New(); points->SetDataTypeToDouble(); points->SetNumberOfPoints( Mats[m].pointCount ); points->SetData( Mats[m].outPointArrays[nPointData-1] ); Mats[m].outPointArrays[nPointData-1]->Delete(); ugOutput->SetPoints( points ); points->Delete(); // set cell connectivity vtkIdTypeArray* cellArrayData = vtkIdTypeArray::New(); cellArrayData->SetNumberOfValues( Mats[m].cellArrayCount ); vtkIdType* cellArrayDataPtr = cellArrayData->WritePointer(0,Mats[m].cellArrayCount); for(vtkIdType i = 0;i<Mats[m].cellArrayCount;i++) cellArrayDataPtr[i] = Mats[m].cells[i]; vtkCellArray* cellArray = vtkCellArray::New(); cellArray->SetCells( Mats[m].cellCount , cellArrayData ); cellArrayData->Delete(); // set cell types vtkUnsignedCharArray *cellTypes = vtkUnsignedCharArray::New(); cellTypes->SetNumberOfValues( Mats[m].cellCount ); unsigned char* cellTypesPtr = cellTypes->WritePointer(0,Mats[m].cellCount); for(vtkIdType i = 0;i<Mats[m].cellCount;i++) cellTypesPtr[i] = Mats[m].cellTypes[i]; // set cell locations vtkIdTypeArray* cellLocations = vtkIdTypeArray::New(); cellLocations->SetNumberOfValues( Mats[m].cellCount ); vtkIdType counter = 0; for(vtkIdType i = 0;i<Mats[m].cellCount;i++) { cellLocations->SetValue(i,counter); counter += Mats[m].cells[counter] + 1; } // attach conectivity arrays to data set ugOutput->SetCells( cellTypes, cellLocations, cellArray ); cellArray->Delete(); cellTypes->Delete(); cellLocations->Delete(); // attach point arrays for(int i = 0;i<nPointData-1;i++) { Mats[m].outPointArrays[i]->Squeeze(); ugOutput->GetPointData()->AddArray( Mats[m].outPointArrays[i] ); Mats[m].outPointArrays[i]->Delete(); } // attach cell arrays for(int i = 0;i<nCellData;i++) { Mats[m].outCellArrays[i]->Squeeze(); ugOutput->GetCellData()->AddArray( Mats[m].outCellArrays[i] ); Mats[m].outCellArrays[i]->Delete(); } delete [] Mats[m].outCellArrays; delete [] Mats[m].outPointArrays; // activate attributes similarly to input for ( int i = 0; i < vtkDataSetAttributes::NUM_ATTRIBUTES; ++ i ) { vtkDataArray* attr = input->GetCellData()->GetAttribute(i); if( attr!=0 ) { ugOutput->GetCellData()->SetActiveAttribute(attr->GetName(),i); } } for ( int i = 0; i < vtkDataSetAttributes::NUM_ATTRIBUTES; ++ i ) { vtkDataArray* attr = input->GetPointData()->GetAttribute(i); if( attr!=0 ) { ugOutput->GetPointData()->SetActiveAttribute(attr->GetName(),i); } } // add material data set to multiblock output if( ugOutput && ugOutput->GetNumberOfCells()>0 ) { int domain = inputsPerMaterial[m]; outputBlocks[ domain * nmat + m ] = ugOutput; ++ inputsPerMaterial[m]; } } delete [] Mats; } // Iterate over input blocks delete [] inputsPerMaterial; if ( debugStats_PrimaryTriangulationfailed ) { vtkDebugMacro(<<"PrimaryTriangulationfailed "<<debugStats_PrimaryTriangulationfailed<<"\n"); } if ( debugStats_Triangulationfailed ) { vtkDebugMacro(<<"Triangulationfailed "<<debugStats_Triangulationfailed<<"\n"); } if ( debugStats_NullNormal ) { vtkDebugMacro(<<"NullNormal "<<debugStats_NullNormal<<"\n"); } if( debugStats_NoInterfaceFound ) { vtkDebugMacro(<<"NoInterfaceFound "<<debugStats_NoInterfaceFound<<"\n"); } // Build final composite output. also tagging blocks with their associated Id vtkDebugMacro(<<this->NumberOfDomains<<" Domains, "<<nmat<<" Materials\n"); output->SetNumberOfBlocks(0); output->SetNumberOfBlocks(nmat); for ( int m = 0; m < nmat; ++ m ) { vtkMultiBlockDataSet* matBlock = vtkMultiBlockDataSet::New(); matBlock->SetNumberOfBlocks(this->NumberOfDomains); output->SetBlock(m, matBlock); matBlock->Delete(); } int blockIndex=0; for( std::map<int,vtkSmartPointer<vtkUnstructuredGrid> >::iterator it=outputBlocks.begin(); it!=outputBlocks.end(); ++ it, ++ blockIndex ) { if( it->second->GetNumberOfCells() > 0 ) { int mat = it->first % nmat; int dom = it->first / nmat; vtkMultiBlockDataSet* matBlock = vtkMultiBlockDataSet::SafeDownCast(output->GetBlock(mat)); matBlock->SetBlock(dom,it->second); } } return 1; } #undef GET_POINT_DATA /* ------------------------------------------------------------------------------------------ --- Low level computations including interface placement and intersection line/polygon --- ------------------------------------------------------------------------------------------ */ // here after the low-level functions that compute placement of the interface given a normal vector and a set of simplices namespace vtkYoungsMaterialInterfaceCellCutInternals { #define REAL_PRECISION 64 // use double precision #define REAL_COORD REAL3 // double by default #ifndef REAL_PRECISION #define REAL_PRECISION 64 #endif // float = lowest precision #if ( REAL_PRECISION == 32 ) #define REAL float #define REAL2 float2 #define REAL3 float3 #define REAL4 float4 #define make_REAL1 make_float1 #define make_REAL2 make_float2 #define make_REAL3 make_float3 #define make_REAL4 make_float4 #define SQRT sqrtf #define FABS fabsf #define REAL_CONST(x) ((float)(x)) //( x##f ) // long double = highest precision #elif ( REAL_PRECISION > 64 ) #define REAL long double #define REAL2 ldouble2 #define REAL3 ldouble3 #define REAL4 ldouble4 #define make_REAL1 make_ldouble1 #define make_REAL2 make_ldouble2 #define make_REAL3 make_ldouble3 #define make_REAL4 make_ldouble4 #define SQRT sqrtl #define FABS fabsl #define REAL_CONST(x) ((long double)(x)) //( x##l ) // double = default precision #else #define REAL double #define REAL2 double2 #define REAL3 double3 #define REAL4 double4 #define make_REAL1 make_double1 #define make_REAL2 make_double2 #define make_REAL3 make_double3 #define make_REAL4 make_double4 #define SQRT sqrt #define FABS fabs #define REAL_CONST(x) x #endif #ifndef __CUDACC__ /* compiling with host compiler (gcc, icc, etc.) */ #ifndef FUNC_DECL #define FUNC_DECL static inline #endif #ifndef KERNEL_DECL #define KERNEL_DECL /* exported function */ #endif #ifndef REAL_PRECISION #define REAL_PRECISION 64 /* defaults to 64 bits floating point */ #endif #else /* compiling with cuda */ #ifndef FUNC_DECL #define FUNC_DECL __device__ #endif #ifndef KERNEL_DECL #define KERNEL_DECL __global__ #endif #ifndef REAL_PRECISION #define REAL_PRECISION 32 /* defaults to 32 bits floating point */ #endif #endif /* __CUDACC__ */ /* Some of the vector functions where found in the file vector_operators.h from the NVIDIA's CUDA Toolkit. Please read the above notice. */ /* * Copyright 1993-2007 NVIDIA Corporation. All rights reserved. * * NOTICE TO USER: * * This source code is subject to NVIDIA ownership rights under U.S. and * international Copyright laws. Users and possessors of this source code * are hereby granted a nonexclusive, royalty-free license to use this code * in individual and commercial software. * * NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE * CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR * IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. * IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOURCE CODE. * * U.S. Government End Users. This source code is a "commercial item" as * that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of * "commercial computer software" and "commercial computer software * documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995) * and is provided to the U.S. Government only as a commercial end item. * Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through * 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the * source code with only those rights set forth herein. * * Any use of this source code in individual and commercial software must * include, in the user documentation and internal comments to the code, * the above Disclaimer and U.S. Government End Users Notice. */ // define base vector types and operators or use those provided by CUDA #ifndef __CUDACC__ struct float2 { float x,y; }; struct float3 { float x,y,z; }; struct float4 { float x,y,z,w; }; struct double2 { double x,y; }; struct uint3 {unsigned int x,y,z; }; struct uint4 {unsigned int x,y,z,w; }; struct uchar4 {unsigned char x,y,z,w; }; struct uchar3 {unsigned char x,y,z; }; #else #include <vector_types.h> #include <vector_functions.h> #endif #ifndef FUNC_DECL #define FUNC_DECL static inline #endif /* -------------------------------------------------------- */ /* ----------- FLOAT ------------------------------------- */ /* -------------------------------------------------------- */ #if REAL_PRECISION <= 32 FUNC_DECL float3 operator *(float3 a, float3 b) { return make_float3(a.x*b.x, a.y*b.y, a.z*b.z); } FUNC_DECL float3 operator *(float f, float3 v) { return make_float3(v.x*f, v.y*f, v.z*f); } FUNC_DECL float2 operator *(float f, float2 v) { return make_float2(v.x*f, v.y*f); } FUNC_DECL float3 operator *(float3 v, float f) { return make_float3(v.x*f, v.y*f, v.z*f); } FUNC_DECL float2 operator *(float2 v,float f) { return make_float2(v.x*f, v.y*f); } FUNC_DECL float4 operator *(float4 v, float f) { return make_float4(v.x*f, v.y*f, v.z*f, v.w*f); } FUNC_DECL float4 operator *(float f, float4 v) { return make_float4(v.x*f, v.y*f, v.z*f, v.w*f); } FUNC_DECL float2 operator +(float2 a, float2 b) { return make_float2(a.x+b.x, a.y+b.y); } FUNC_DECL float3 operator +(float3 a, float3 b) { return make_float3(a.x+b.x, a.y+b.y, a.z+b.z); } FUNC_DECL void operator +=(float3 & b, float3 a) { b.x += a.x; b.y += a.y; b.z += a.z; } FUNC_DECL void operator +=(float2 & b, float2 a) { b.x += a.x; b.y += a.y; } FUNC_DECL void operator +=(float4 & b, float4 a) { b.x += a.x; b.y += a.y; b.z += a.z; b.w += a.w; } FUNC_DECL float3 operator -(float3 a, float3 b) { return make_float3(a.x-b.x, a.y-b.y, a.z-b.z); } FUNC_DECL float2 operator -(float2 a, float2 b) { return make_float2(a.x-b.x, a.y-b.y); } FUNC_DECL void operator -=(float3 & b, float3 a) { b.x -= a.x; b.y -= a.y; b.z -= a.z; } FUNC_DECL float3 operator /(float3 v, float f) { float inv = 1.0f / f; return v * inv; } FUNC_DECL void operator /=(float2 & b, float f) { float inv = 1.0f / f; b.x *= inv; b.y *= inv; } FUNC_DECL void operator /=(float3 & b, float f) { float inv = 1.0f / f; b.x *= inv; b.y *= inv; b.z *= inv; } FUNC_DECL float dot(float2 a, float2 b) { return a.x * b.x + a.y * b.y; } FUNC_DECL float dot(float3 a, float3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } FUNC_DECL float dot(float4 a, float4 b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } FUNC_DECL float3 cross( float3 A, float3 B) { return make_float3( A.y * B.z - A.z * B.y , A.z * B.x - A.x * B.z , A.x * B.y - A.y * B.x ); } #endif /* REAL_PRECISION <= 32 */ #ifndef __CUDACC__ /* -------------------------------------------------------- */ /* ----------- DOUBLE ------------------------------------- */ /* -------------------------------------------------------- */ #if REAL_PRECISION == 64 struct double3 { double x,y,z; }; struct double4 { double x,y,z,w; }; FUNC_DECL double min(double a, double b){ return (a<b)?a:b; } FUNC_DECL double2 make_double2(double x,double y) { double2 v = {x,y}; return v; } FUNC_DECL double3 make_double3(double x,double y,double z) { double3 v = {x,y,z}; return v; } FUNC_DECL double4 make_double4(double x,double y,double z,double w) { double4 v = {x,y,z,w}; return v; } FUNC_DECL double3 operator *(double f, double3 v) { return make_double3(v.x*f, v.y*f, v.z*f); } FUNC_DECL double2 operator *(double f, double2 v) { return make_double2(v.x*f, v.y*f); } FUNC_DECL double3 operator +(double3 a, double3 b) { return make_double3(a.x+b.x, a.y+b.y, a.z+b.z); } FUNC_DECL double2 operator +(double2 a, double2 b) { return make_double2(a.x+b.x, a.y+b.y); } FUNC_DECL void operator +=(double3 & b, double3 a) { b.x += a.x; b.y += a.y; b.z += a.z; } FUNC_DECL void operator +=(double2 & b, double2 a) { b.x += a.x; b.y += a.y; } FUNC_DECL double3 operator - (double3 a, double3 b) { return make_double3(a.x-b.x, a.y-b.y, a.z-b.z); } FUNC_DECL double2 operator - (double2 a, double2 b) { return make_double2(a.x-b.x, a.y-b.y); } FUNC_DECL void operator /=(double2 & b, double f) { b.x /= f; b.y /= f; } FUNC_DECL void operator /=(double3 & b, double f) { b.x /= f; b.y /= f; b.z /= f; } FUNC_DECL double dot(double2 a, double2 b) { return a.x * b.x + a.y * b.y ; } FUNC_DECL double dot(double3 a, double3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } FUNC_DECL double3 cross( double3 A, double3 B) { return make_double3( A.y * B.z - A.z * B.y , A.z * B.x - A.x * B.z , A.x * B.y - A.y * B.x ); } #endif /* REAL_PRECISION == 64 */ /* -------------------------------------------------------- */ /* ----------- LONG DOUBLE -------------------------------- */ /* -------------------------------------------------------- */ #if REAL_PRECISION > 64 struct ldouble2 { long double x,y; }; struct ldouble3 { long double x,y,z; }; struct ldouble4 { long double x,y,z,w; }; FUNC_DECL long double min(long double a, long double b){ return (a<b)?a:b; } FUNC_DECL long double max(long double a, long double b){ return (a>b)?a:b; } FUNC_DECL ldouble2 make_ldouble2(long double x,long double y) { ldouble2 v = {x,y}; return v; } FUNC_DECL ldouble3 make_ldouble3(long double x,long double y,long double z) { ldouble3 v = {x,y,z}; return v; } FUNC_DECL ldouble4 make_ldouble4(long double x,long double y,long double z,long double w) { ldouble4 v = {x,y,z,w}; return v; } FUNC_DECL ldouble3 operator *(ldouble3 a, ldouble3 b) { return make_ldouble3(a.x*b.x, a.y*b.y, a.z*b.z); } FUNC_DECL ldouble2 operator * (long double f, ldouble2 v) { return make_ldouble2(v.x*f, v.y*f); } FUNC_DECL ldouble3 operator *(long double f, ldouble3 v) { return make_ldouble3(v.x*f, v.y*f, v.z*f); } FUNC_DECL ldouble2 operator * (ldouble2 v, long double f) { return make_ldouble2(v.x*f, v.y*f); } FUNC_DECL ldouble3 operator *(ldouble3 v, long double f) { return make_ldouble3(v.x*f, v.y*f, v.z*f); } FUNC_DECL ldouble4 operator *(ldouble4 v, long double f) { return make_ldouble4(v.x*f, v.y*f, v.z*f, v.w*f); } FUNC_DECL ldouble4 operator *(long double f, ldouble4 v) { return make_ldouble4(v.x*f, v.y*f, v.z*f, v.w*f); } FUNC_DECL ldouble2 operator +(ldouble2 a, ldouble2 b) { return make_ldouble2(a.x+b.x, a.y+b.y); } FUNC_DECL ldouble3 operator +(ldouble3 a, ldouble3 b) { return make_ldouble3(a.x+b.x, a.y+b.y, a.z+b.z); } FUNC_DECL void operator += (ldouble3 & b, ldouble3 a) { b.x += a.x; b.y += a.y; b.z += a.z; } FUNC_DECL void operator += (ldouble2 & b, ldouble2 a) { b.x += a.x; b.y += a.y; } FUNC_DECL void operator += (ldouble4 & b, ldouble4 a) { b.x += a.x; b.y += a.y; b.z += a.z; b.w += a.w; } FUNC_DECL ldouble2 operator - (ldouble2 a, ldouble2 b) { return make_ldouble2(a.x-b.x, a.y-b.y); } FUNC_DECL ldouble3 operator - (ldouble3 a, ldouble3 b) { return make_ldouble3(a.x-b.x, a.y-b.y, a.z-b.z); } FUNC_DECL void operator -= (ldouble3 & b, ldouble3 a) { b.x -= a.x; b.y -= a.y; b.z -= a.z; } FUNC_DECL ldouble3 operator / (ldouble3 v, long double f) { return make_ldouble3( v.x/f, v.y/f, v.z/f ); } FUNC_DECL void operator /= (ldouble3 & b, long double f) { b.x /= f; b.y /= f; b.z /= f; } FUNC_DECL long double dot(ldouble2 a, ldouble2 b) { return a.x * b.x + a.y * b.y ; } FUNC_DECL long double dot(ldouble3 a, ldouble3 b) { return a.x * b.x + a.y * b.y + a.z * b.z; } FUNC_DECL long double dot(ldouble4 a, ldouble4 b) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } FUNC_DECL ldouble3 cross( ldouble3 A, ldouble3 B) { return make_ldouble3( A.y * B.z - A.z * B.y , A.z * B.x - A.x * B.z , A.x * B.y - A.y * B.x ); } #endif /* REAL_PRECISION > 64 */ #endif /* __CUDACC__ */ #ifndef M_PI #define M_PI vtkMath::Pi() #endif /************************************** *** Precision dependent constants *** ***************************************/ // float #if ( REAL_PRECISION <= 32 ) #define EPSILON 1e-7 #define NEWTON_NITER 16 // long double #elif ( REAL_PRECISION > 64 ) #define EPSILON 1e-31 #define NEWTON_NITER 64 // double ( default ) #else #define EPSILON 1e-15 #define NEWTON_NITER 32 #endif /************************************** *** Debugging *** ***************************************/ #define DBG_MESG(m) (void)0 /************************************** *** Macros *** ***************************************/ // local arrays allocation #ifdef __CUDACC__ // ensure a maximum alignment of arrays #define ROUND_SIZE(n) (n) //( (n+sizeof(REAL)-1) & ~(sizeof(REAL)-1) ) #define ALLOC_LOCAL_ARRAY(name,type,n) \ type * name = (type*)sdata; \ sdata += ROUND_SIZE( sizeof(type)*(n) ) #define FREE_LOCAL_ARRAY(name,type,n) sdata -= ROUND_SIZE( sizeof(type)*(n) ) #elif defined(__GNUC__) // Warning, this is a gcc extension, not all compiler accept it #define ALLOC_LOCAL_ARRAY(name,type,n) type name[(n)] #define FREE_LOCAL_ARRAY(name,type,n) #else #include <malloc.h> #define ALLOC_LOCAL_ARRAY(name,type,n) type* name = (type*) malloc( sizeof(type) * (n) ) #define FREE_LOCAL_ARRAY(name,type,n) free(name) #endif #ifdef __GNUC__ #define LOCAL_ARRAY_SIZE(n) n #else #define LOCAL_ARRAY_SIZE(n) 128 #endif /********************* *** Triangle area *** *********************/ /* Formula from VTK in vtkTriangle.cxx, method TriangleArea */ FUNC_DECL REAL triangleSurf( REAL3 p1, REAL3 p2, REAL3 p3 ) { const REAL3 e1 = p2-p1; const REAL3 e2 = p3-p2; const REAL3 e3 = p1-p3; const REAL a = dot(e1,e1); const REAL b = dot(e2,e2); const REAL c = dot(e3,e3); return REAL_CONST(0.25) * SQRT( FABS( 4*a*c - (a-b+c)*(a-b+c) ) ) ; } /************************* *** Tetrahedra volume *** *************************/ FUNC_DECL REAL tetraVolume( REAL3 p0, REAL3 p1, REAL3 p2, REAL3 p3 ) { REAL3 A = p1 - p0; REAL3 B = p2 - p0; REAL3 C = p3 - p0; REAL3 BC = cross(B,C); return FABS( dot(A,BC) / REAL_CONST(6.0) ); } /******************************************* *** Evaluation of a polynomial function *** *******************************************/ FUNC_DECL REAL evalPolynomialFunc(const REAL2 F, const REAL x) { return F.x * x + F.y ; } FUNC_DECL REAL evalPolynomialFunc(const REAL3 F, const REAL x) { REAL y = ( F.x * x + F.y ) * x ; return y + F.z; } FUNC_DECL REAL evalPolynomialFunc(const REAL4 F, const REAL x) { REAL y = ( ( F.x * x + F.y ) * x + F.z ) * x; return y + F.w; // this increases numerical stability when compiled with -ffloat-store } /***************************************** *** Intergal of a polynomial function *** *****************************************/ FUNC_DECL REAL3 integratePolynomialFunc( REAL2 linearFunc ) { return make_REAL3( linearFunc.x/2 , linearFunc.y, 0 ); } FUNC_DECL REAL4 integratePolynomialFunc( REAL3 quadFunc ) { return make_REAL4( quadFunc.x/3, quadFunc.y/2, quadFunc.z, 0 ); } /**************************** *** Linear interpolation *** ****************************/ FUNC_DECL REAL3 linearInterp( REAL t0, REAL3 x0, REAL t1, REAL3 x1, REAL t ) { REAL f = (t1!=t0) ? (t-t0)/(t1-t0) : 0 ; return x0 + f * (x1-x0) ; } FUNC_DECL REAL2 linearInterp( REAL t0, REAL2 x0, REAL t1, REAL2 x1, REAL t ) { REAL f = (t1!=t0) ? (t-t0)/(t1-t0) : REAL_CONST(0.0) ; return x0 + f * (x1-x0) ; } /**************************************** *** Quadratic interpolation function *** ****************************************/ FUNC_DECL REAL3 quadraticInterpFunc( REAL x0, REAL y0, REAL x1, REAL y1, REAL x2, REAL y2 ) { // Formula from the book 'Maillages', page 409 // non-degenerated case (really a quadratic function) if( x1>x0 && x2>x1 ) { // denominators const REAL d0 = ( x0 - x1 ) * ( x0 - x2 ); const REAL d1 = ( x1 - x0 ) * ( x1 - x2 ); const REAL d2 = ( x2 - x0 ) * ( x2 - x1 ); // coefficients for the quadratic interpolation of (x0,y0) , (x1,y1) and p2(x2,y2) return make_REAL3( ( y0 / d0 ) + ( y1 / d1 ) + ( y2 / d2 ) , // x^2 term ( y0*(-x1-x2) / d0 ) + ( y1*(-x0-x2) / d1 ) + ( y2*(-x0-x1) / d2 ) , // x term ( y0*(x1*x2) / d0 ) + ( y1*(x0*x2) / d1 ) + ( y2*(x0*x1) / d2 ) ); // constant term } // linear case : 2 out of the 3 points are the same else if( x2 > x0 ) { return make_REAL3( 0 , // x^2 term ( y2 - y0 ) / ( x2 - x0 ) , // x term y0 ); // constant term } // degenerated case return make_REAL3(0,0,0); } /**************************** *** Newton search method *** ****************************/ FUNC_DECL REAL newtonSearchPolynomialFunc( REAL3 F, REAL2 dF, const REAL value, const REAL xmin, const REAL xmax ) { // translate F, because newton searches for the 0 of the derivative F.z -= value; // start with x, the closest of xmin, xmean and xmax const REAL ymin = evalPolynomialFunc( F, xmin ); const REAL ymax = evalPolynomialFunc( F, xmax ); REAL x = ( xmin + xmax ) * REAL_CONST(0.5); REAL y = evalPolynomialFunc(F,x); // search x where F(x) = 0 #ifdef __CUDACC__ #pragma unroll #endif for(int i = 0;i<NEWTON_NITER;i++) { DBG_MESG("F("<<x<<")="<<y); // Xi+1 = Xi - F'(x)/F''(x) REAL d = evalPolynomialFunc(dF,x); if( d==0 ) { d=1; y=0; } x = x - ( y / d ); y = evalPolynomialFunc(F,x); } // check that the solution is not worse than the 2 bounds DBG_MESG("F("<<xmin<<")="<<ymin<<", "<<"F("<<x<<")="<<y<<", "<<"F("<<xmax<<")="<<ymax); y = FABS( y ); if( FABS(ymin) < y ) { x = xmin; } if( FABS(ymax) < y ) { x = xmax; } DBG_MESG("F("<<x<<")="<<y); return x; } FUNC_DECL REAL newtonSearchPolynomialFunc( REAL4 F, REAL3 dF, const REAL value, const REAL xmin, const REAL xmax ) { // translate F, because newton searches for the 0 of the derivative F.w -= value; // start with x, the closest of xmin, xmean and xmax const REAL ymin = evalPolynomialFunc( F, xmin ); const REAL ymax = evalPolynomialFunc( F, xmax ); REAL x = ( xmin + xmax ) * REAL_CONST(0.5); REAL y = evalPolynomialFunc(F,x); // search x where F(x) = 0 #ifdef __CUDACC__ #pragma unroll #endif for(int i = 0;i<NEWTON_NITER;i++) { DBG_MESG("F("<<x<<")="<<y); // Xi+1 = Xi - F'(x)/F''(x) REAL d = evalPolynomialFunc(dF,x); if( d==0 ) { d=1; y=0; } x = x - ( y / d ); y = evalPolynomialFunc(F,x); } // check that the solution is not worse than taking one of the 2 bounds DBG_MESG("F("<<xmin<<")="<<ymin<<", "<<"F("<<x<<")="<<y<<", "<<"F("<<xmax<<")="<<ymax); y = FABS( y ); if( FABS(ymin) < y ) { x = xmin; } if( FABS(ymax) < y ) { x = xmax; } DBG_MESG("F("<<x<<")="<<y); return x; } /*********************** *** Sorting methods *** ***********************/ FUNC_DECL uchar3 sortTriangle( uchar3 t , unsigned char* i ) { #define SWAP(a,b) { unsigned char tmp=a; a=b; b=tmp; } if( i[t.y] < i[t.x] ) SWAP(t.x,t.y); if( i[t.z] < i[t.y] ) SWAP(t.y,t.z); if( i[t.y] < i[t.x] ) SWAP(t.x,t.y); #undef SWAP return t; } typedef unsigned char IntType; /*********************** *** Sorting methods *** ***********************/ FUNC_DECL void sortVertices( const int n, const REAL3* vertices, const REAL3 normal, IntType* indices ) { // insertion sort : slow but symmetrical across all instances #define SWAP(a,b) { IntType t = indices[a]; indices[a] = indices[b]; indices[b] = t; } for(int i = 0;i<n;i++) { int imin = i; REAL dmin = dot(vertices[indices[i]],normal); for(int j=i+1;j<n;j++) { REAL d = dot(vertices[indices[j]],normal); imin = ( d < dmin ) ? j : imin; dmin = min( dmin , d ); } SWAP( i, imin ); } #undef SWAP } FUNC_DECL void sortVertices( const int n, const REAL2* vertices, const REAL2 normal, IntType* indices ) { // insertion sort : slow but symmetrical across all instances #define SWAP(a,b) { IntType t = indices[a]; indices[a] = indices[b]; indices[b] = t; } for(int i = 0;i<n;i++) { int imin = i; REAL dmin = dot(vertices[indices[i]],normal); for(int j=i+1;j<n;j++) { REAL d = dot(vertices[indices[j]],normal); imin = ( d < dmin ) ? j : imin; dmin = min( dmin , d ); } SWAP( i, imin ); } #undef SWAP } FUNC_DECL uchar4 sortTetra( uchar4 t , IntType* i ) { #define SWAP(a,b) { IntType tmp=a; a=b; b=tmp; } if( i[t.y] < i[t.x] ) SWAP(t.x,t.y); if( i[t.w] < i[t.z] ) SWAP(t.z,t.w); if( i[t.z] < i[t.y] ) SWAP(t.y,t.z); if( i[t.y] < i[t.x] ) SWAP(t.x,t.y); if( i[t.w] < i[t.z] ) SWAP(t.z,t.w); if( i[t.z] < i[t.y] ) SWAP(t.y,t.z); #undef SWAP return t; } FUNC_DECL REAL makeTriangleSurfaceFunctions( const uchar3 triangle, const REAL_COORD* vertices, const REAL_COORD normal, REAL2 func[2] ) { // 1. load the data const REAL_COORD v0 = vertices[ triangle.x ]; const REAL_COORD v1 = vertices[ triangle.y ]; const REAL_COORD v2 = vertices[ triangle.z ]; const REAL d0 = dot( v0 , normal ); const REAL d1 = dot( v1 , normal ); const REAL d2 = dot( v2 , normal ); DBG_MESG("v0 = "<<v0.x<<','<<v0.y<<" d0="<<d0); DBG_MESG("v1 = "<<v1.x<<','<<v1.y<<" d1="<<d1); DBG_MESG("v2 = "<<v2.x<<','<<v2.y<<" d2="<<d2); // 2. compute // compute vector from point on v0-v2 that has distance d1 from Plane0 REAL_COORD I = linearInterp( d0, v0, d2, v2 , d1 ); DBG_MESG("I = "<<I.x<<','<<I.y); REAL_COORD vec = v1 - I; REAL length = sqrt( dot(vec,vec) ); DBG_MESG("length = "<<length); // side length function = (x-d0) * length / (d1-d0) = (length/(d1-d0)) * x - length * d0 / (d1-d0) REAL2 linearFunc01 = make_REAL2( length/(d1-d0) , - length * d0 / (d1-d0) ); // surface function = integral of distance function starting at d0 func[0] = make_REAL2(0,0); if( d1 > d0 ) { func[0] = linearFunc01; } // side length function = (d2-x) * length / (d2-d1) = (-length/(d2-d1)) * x + d2*length / (d2-d1) REAL2 linearFunc12 = make_REAL2( -length/(d2-d1) , d2*length/(d2-d1) ); // surface function = integral of distance function starting at d1 func[1] = make_REAL2(0,0); if( d2 > d1 ) { func[1] = linearFunc12; } return triangleSurf( v0, v1, v2 ); } FUNC_DECL REAL findTriangleSetCuttingPlane( const REAL_COORD normal, // IN , normal vector const REAL fraction, // IN , volume fraction const int nv, // IN , number of vertices const int nt, // IN , number of triangles const uchar3* tv, // IN , triangles connectivity, size=nt const REAL_COORD* vertices // IN , vertex coordinates, size=nv #ifdef __CUDACC__ ,char* sdata // TEMP Storage #endif ) { ALLOC_LOCAL_ARRAY( derivatives, REAL2, nv-1 ); ALLOC_LOCAL_ARRAY( index, unsigned char, nv ); ALLOC_LOCAL_ARRAY( rindex, unsigned char, nv ); // initialization for(int i = 0;i<nv;i++) { index[i] = i; } for(int i = 0;i<(nv-1);i++) { derivatives[i] = make_REAL2(0,0); } // sort vertices in the normal vector direction sortVertices( nv, vertices, normal, index ); // reverse indirection table for(int i = 0;i<nv;i++) { rindex[ index[i] ] = i; } // total area REAL surface = 0; // construction of the truncated volume piecewise cubic function for(int i = 0;i<nt;i++) { // area of the interface-tetra intersection at points P1 and P2 uchar3 triangle = sortTriangle( tv[i] , rindex ); DBG_MESG( "\ntriangle "<<i<<" : "<<tv[i].x<<','<<tv[i].y<<','<<tv[i].z<<" -> "<<triangle.x<<','<<triangle.y<<','<<triangle.z ); // compute the volume function derivative pieces REAL2 triangleSurfFunc[2]; surface += makeTriangleSurfaceFunctions( triangle, vertices, normal, triangleSurfFunc ); #ifdef DEBUG for(int k = 0;k<2;k++) { DBG_MESG( "surf'["<<k<<"] = "<<triangleSurfFunc[k].x<<','<<triangleSurfFunc[k].y ); } #endif // surface function bounds unsigned int i0 = rindex[ triangle.x ]; unsigned int i1 = rindex[ triangle.y ]; unsigned int i2 = rindex[ triangle.z ]; DBG_MESG( "surf(x) steps = "<<i0<<','<<i1<<','<<i2 ); DBG_MESG( "Adding surfFunc onto ["<<i0<<';'<<i1<<"]" ); for(unsigned int j=i0;j<i1;j++) { derivatives[j] += triangleSurfFunc[0]; } DBG_MESG( "Adding surfFunc onto ["<<i1<<';'<<i2<<"]" ); for(unsigned int j=i1;j<i2;j++) { derivatives[j] += triangleSurfFunc[1]; } } // target volume fraction we're looking for REAL y = surface*fraction; DBG_MESG( "surface = "<<surface<<", surface*fraction = "<<y ); // integrate area function pieces to obtain volume function pieces REAL sum = 0; REAL3 surfaceFunction = make_REAL3(0,0,0); REAL xmin = 0; REAL xmax = dot( vertices[index[0]], normal ) ; int s = -1; while( sum<y && s<(nv-2) ) { xmin = xmax; y -= sum; ++ s; REAL3 F = integratePolynomialFunc( derivatives[s] ); F.z = - evalPolynomialFunc( F , xmin ); surfaceFunction = F; xmax = dot( vertices[index[s+1]] , normal ); sum = evalPolynomialFunc( F, xmax ); } if( s<0) s=0; DBG_MESG( "step="<<s<<", x in ["<<xmin<<';'<<xmax<<']' ); DBG_MESG( "surface reminder = "<< y ); // newton search REAL x = newtonSearchPolynomialFunc( surfaceFunction, derivatives[s], y, xmin, xmax ); DBG_MESG( "final x = "<< x ); FREE_LOCAL_ARRAY( derivatives, REAL2, nv-1 ); FREE_LOCAL_ARRAY( index, unsigned char, nv ); FREE_LOCAL_ARRAY( rindex, unsigned char, nv ); return x ; } /* compute the derivatives of the piecewise cubic function of the volume behind the cutting cone ( axis symetric 2D plane) */ FUNC_DECL void makeConeVolumeDerivatives( const uchar3 triangle, const REAL2* vertices, const REAL2 normal, REAL3 deriv[2] ) { // 1. load the data const REAL2 v0 = vertices[ triangle.x ]; const REAL2 v1 = vertices[ triangle.y ]; const REAL2 v2 = vertices[ triangle.z ]; // 2. compute const REAL d0 = dot( v0 , normal ); const REAL d1 = dot( v1 , normal ); const REAL d2 = dot( v2 , normal ); DBG_MESG("v0 = "<<v0.x<<','<<v0.y<<" d0="<<d0); DBG_MESG("v1 = "<<v1.x<<','<<v1.y<<" d1="<<d1); DBG_MESG("v2 = "<<v2.x<<','<<v2.y<<" d2="<<d2); // compute vector from point on v0-v2 that has distance d1 from Plane0 REAL2 I = linearInterp( d0, v0, d2, v2 , d1 ); DBG_MESG("I = "<<I.x<<','<<I.y); REAL2 vec = v1 - I; REAL length = sqrt( dot(vec,vec) ); DBG_MESG("length = "<<length); // compute truncated cone surface at d1 REAL Isurf = REAL_CONST(M_PI) * FABS(I.y+v1.y) * length; // 2 * REAL_CONST(M_PI) * ( (I.y+v1.y) * 0.5 ) * length ; REAL coef; // build cubic volume functions derivatives coef = ( d1 > d0 ) ? ( Isurf / ((d1-d0)*(d1-d0)) ) : REAL_CONST(0.0) ; deriv[0] = coef * make_REAL3( 1 , -2*d0 , d0*d0 ) ; coef = ( d2 > d1 ) ? ( Isurf / ((d2-d1)*(d2-d1)) ) : REAL_CONST(0.0) ; deriv[1] = coef * make_REAL3( 1 , -2*d2 , d2*d2 ) ; } FUNC_DECL REAL findTriangleSetCuttingCone( const REAL2 normal, // IN , normal vector const REAL fraction, // IN , volume fraction const int nv, // IN , number of vertices const int nt, // IN , number of triangles const uchar3* tv, // IN , triangles connectivity, size=nt const REAL2* vertices // IN , vertex coordinates, size=nv #ifdef __CUDACC__ ,char* sdata // TEMP Storage #endif ) { ALLOC_LOCAL_ARRAY( derivatives, REAL3, nv-1 ); ALLOC_LOCAL_ARRAY( index, unsigned char, nv ); ALLOC_LOCAL_ARRAY( rindex, unsigned char, nv ); // initialization for(int i = 0;i<nv;i++) { index[i] = i; } for(int i = 0;i<(nv-1);i++) { derivatives[i] = make_REAL3(0,0,0); } // sort vertices along normal vector sortVertices( nv, vertices, normal, index ); // reverse indirection table for(int i = 0;i<nv;i++) { rindex[ index[i] ] = i; } // construction of the truncated volume piecewise cubic function for(int i = 0;i<nt;i++) { // area of the interface-tetra intersection at points P1 and P2 uchar3 triangle = sortTriangle( tv[i] , rindex ); DBG_MESG( "\ntriangle "<<i<<" : "<<tv[i].x<<','<<tv[i].y<<','<<tv[i].z<<" -> "<<triangle.x<<','<<triangle.y<<','<<triangle.z ); // compute the volume function derivatives pieces REAL3 coneVolDeriv[2]; makeConeVolumeDerivatives( triangle, vertices, normal, coneVolDeriv ); // area function bounds unsigned int i0 = rindex[ triangle.x ]; unsigned int i1 = rindex[ triangle.y ]; unsigned int i2 = rindex[ triangle.z ]; DBG_MESG( "surf(x) steps = "<<i0<<','<<i1<<','<<i2 ); DBG_MESG( "Adding surfFunc onto ["<<i0<<';'<<i1<<"]" ); for(unsigned int j=i0;j<i1;j++) { derivatives[j] += coneVolDeriv[0]; } DBG_MESG( "Adding surfFunc onto ["<<i1<<';'<<i2<<"]" ); for(unsigned int j=i1;j<i2;j++) { derivatives[j] += coneVolDeriv[1]; } } REAL surface = 0; REAL xmin = 0; REAL xmax = dot( vertices[index[0]], normal ) ; for(int i = 0;i<(nv-1);i++) { xmin = xmax; REAL4 F = integratePolynomialFunc( derivatives[i] ); F.w = - evalPolynomialFunc( F , xmin ); xmax = dot( vertices[index[i+1]] , normal ); surface += evalPolynomialFunc( F, xmax ); } REAL y = surface*fraction; DBG_MESG( "surface = "<<surface<<", surface*fraction = "<<y ); // integrate area function pieces to obtain volume function pieces REAL sum = 0; REAL4 volumeFunction = make_REAL4(0,0,0,0); xmax = dot( vertices[index[0]], normal ) ; int s = -1; while( sum<y && s<(nv-2) ) { xmin = xmax; y -= sum; ++ s; REAL4 F = integratePolynomialFunc( derivatives[s] ); F.w = - evalPolynomialFunc( F , xmin ); volumeFunction = F; xmax = dot( vertices[index[s+1]] , normal ); sum = evalPolynomialFunc( F, xmax ); } if( s<0) s=0; // look for the function piece that contain the target volume DBG_MESG( "step="<<s<<", x in ["<<xmin<<';'<<xmax<<']' ); DBG_MESG( "surface reminder = "<< y ); // newton search method REAL x = newtonSearchPolynomialFunc( volumeFunction, derivatives[s], y, xmin, xmax ); DBG_MESG( "final x = "<< x ); FREE_LOCAL_ARRAY( derivatives, REAL3 , nv-1 ); FREE_LOCAL_ARRAY( index , unsigned char, nv ); FREE_LOCAL_ARRAY( rindex , unsigned char, nv ); return x ; } /* Computes the area of the intersection between the plane, orthognal to the 'normal' vector, that passes through P1 (resp. P2), and the given tetrahedron. the resulting area function, is a function of the intersection area given the distance of the cutting plane to the origin. */ FUNC_DECL REAL tetraPlaneSurfFunc( const uchar4 tetra, const REAL3* vertices, const REAL3 normal, REAL3 func[3] ) { // 1. load the data const REAL3 v0 = vertices[ tetra.x ]; const REAL3 v1 = vertices[ tetra.y ]; const REAL3 v2 = vertices[ tetra.z ]; const REAL3 v3 = vertices[ tetra.w ]; const REAL d0 = dot( v0 , normal ); const REAL d1 = dot( v1 , normal ); const REAL d2 = dot( v2 , normal ); const REAL d3 = dot( v3 , normal ); #ifdef DEBUG bool ok = (d0<=d1 && d1<=d2 && d2<=d3); if( !ok ) { DBG_MESG( "d0="<<d0<<", d1="<<d1<<", d2="<<d2<<", d3="<<d3 ); } assert( d0<=d1 && d1<=d2 && d2<=d3 ); #endif // 2. compute // Intersection surface in p1 const REAL surf1 = triangleSurf( v1, linearInterp( d0, v0, d2, v2, d1 ), linearInterp( d0, v0, d3, v3, d1 ) ); // Compute the intersection surfice in the middle of p1 and p2. // The intersection is a quadric of a,b,c,d const REAL d12 = (d1+d2) * REAL_CONST(0.5) ; const REAL3 a = linearInterp( d0, v0, d2, v2, d12); const REAL3 b = linearInterp( d0, v0, d3, v3, d12); const REAL3 c = linearInterp( d1, v1, d3, v3, d12); const REAL3 d = linearInterp( d1, v1, d2, v2, d12); const REAL surf12 = triangleSurf( a,b,d ) + triangleSurf( b,c,d ); // intersection surface in p2 const REAL surf2 = triangleSurf( v2, linearInterp( d0, v0, d3, v3, d2 ) , linearInterp( d1, v1, d3, v3, d2 ) ); // Construct the surface functions REAL coef; // Search S0(x) = coef * (x-d0)^2 coef = ( d1 > d0 ) ? ( surf1 / ((d1-d0)*(d1-d0)) ) : REAL_CONST(0.0) ; func[0] = coef * make_REAL3( 1 , -2*d0 , d0*d0 ) ; // Search S1(x) = quadric interpolation of surf1, surf12, surf2 at the points d1, d12, d2 func[1] = quadraticInterpFunc( d1, surf1, d12, surf12, d2, surf2 ); // S(x) = coef * (d3-x)^2 coef = ( d3 > d2 ) ? ( surf2 / ((d3-d2)*(d3-d2)) ) : REAL_CONST(0.0) ; func[2] = coef * make_REAL3( 1 , -2*d3 , d3*d3 ) ; return tetraVolume( v0, v1, v2, v3 ); } FUNC_DECL REAL findTetraSetCuttingPlane( const REAL3 normal, // IN , normal vector const REAL fraction, // IN , volume fraction const int nv, // IN , number of vertices const int nt, // IN , number of tetras const uchar4* tv, // IN , tetras connectivity, size=nt const REAL3* vertices // IN , vertex coordinates, size=nv #ifdef __CUDACC__ ,char* sdata // TEMP Storage #endif ) { ALLOC_LOCAL_ARRAY( rindex, unsigned char, nv ); ALLOC_LOCAL_ARRAY( index, unsigned char, nv ); ALLOC_LOCAL_ARRAY( derivatives, REAL3, nv-1 ); // initialization for(int i = 0;i<nv;i++) { index[i] = i; } // sort vertices in the normal vector direction sortVertices( nv, vertices, normal, index ); // reverse indirection table for(int i = 0;i<nv;i++) { rindex[ index[i] ] = i; } #ifdef DEBUG for(int i = 0;i<nv;i++) { DBG_MESG("index["<<i<<"]="<<index[i]<<", rindex["<<i<<"]="<<rindex[i]); } #endif for(int i = 0;i<(nv-1);i++) { derivatives[i] = make_REAL3(0,0,0); } REAL volume = 0; // construction of the truncated volume piecewise cubic function for(int i = 0;i<nt;i++) { // area of the interface-tetra intersection at points P1 and P2 uchar4 tetra = sortTetra( tv[i] , rindex ); DBG_MESG( "\ntetra "<<i<<" : "<<tv[i].x<<','<<tv[i].y<<','<<tv[i].z<<','<<tv[i].w<<" -> "<<tetra.x<<','<<tetra.y<<','<<tetra.z<<','<<tetra.w ); // compute the volume function derivative pieces REAL3 tetraSurfFunc[3]; volume += tetraPlaneSurfFunc( tetra, vertices, normal, tetraSurfFunc ); #ifdef DEBUG for(int k = 0;k<3;k++) { DBG_MESG( "surf["<<k<<"] = "<<tetraSurfFunc[k].x<<','<<tetraSurfFunc[k].y<<','<<tetraSurfFunc[k].z ); } #endif // surface function bounds unsigned int i0 = rindex[ tetra.x ]; unsigned int i1 = rindex[ tetra.y ]; unsigned int i2 = rindex[ tetra.z ]; unsigned int i3 = rindex[ tetra.w ]; DBG_MESG( "surf(x) steps = "<<i0<<','<<i1<<','<<i2<<','<<i3 ); DBG_MESG( "Adding surfFunc onto ["<<i0<<';'<<i1<<"]" ); for(unsigned int j=i0;j<i1;j++) derivatives[j] += tetraSurfFunc[0] ; DBG_MESG( "Adding surfFunc onto ["<<i1<<';'<<i2<<"]" ); for(unsigned int j=i1;j<i2;j++) derivatives[j] += tetraSurfFunc[1] ; DBG_MESG( "Adding surfFunc onto ["<<i2<<';'<<i3<<"]" ); for(unsigned int j=i2;j<i3;j++) derivatives[j] += tetraSurfFunc[2] ; } // target volume fraction we're looking for REAL y = volume*fraction; DBG_MESG( "volume = "<<volume<<", volume*fraction = "<<y ); // integrate area function pieces to obtain volume function pieces REAL sum = 0; REAL4 volumeFunction = make_REAL4(0,0,0,0); REAL xmin = 0; REAL xmax = dot( vertices[index[0]], normal ) ; int s = -1; while( sum<y && s<(nv-2) ) { xmin = xmax; y -= sum; ++ s; REAL4 F = integratePolynomialFunc( derivatives[s] ); F.w = - evalPolynomialFunc( F , xmin ); volumeFunction = F; xmax = dot( vertices[index[s+1]] , normal ); sum = evalPolynomialFunc( F, xmax ); } if( s<0) s=0; // F, F' : free derivatives // search the function range that contains the value DBG_MESG( "step="<<s<<", x in ["<<xmin<<';'<<xmax<<']' ); /* each function pieces start from 0, compute the volume in this function piece. */ //y -= sum; DBG_MESG( "volume reminder = "<< y ); // search by newton REAL x = newtonSearchPolynomialFunc( volumeFunction, derivatives[s], y, xmin, xmax ); DBG_MESG( "final x = "<< x ); FREE_LOCAL_ARRAY( rindex, unsigned char, nv ); FREE_LOCAL_ARRAY( index, unsigned char, nv ); FREE_LOCAL_ARRAY( derivatives, REAL3, nv-1 ); return x ; } typedef REAL Real; typedef REAL2 Real2; typedef REAL3 Real3; typedef REAL4 Real4; #undef REAL_PRECISION #undef REAL_COORD struct VertexInfo { double coord[3]; double weight; int eid[2]; }; struct CWVertex { double angle; double coord[3]; double weight; int eid[2]; inline bool operator < (const CWVertex& v) const { return angle < v.angle; } }; } /* namespace vtkYoungsMaterialInterfaceCellCutInternals */ // useful to avoid numerical errors #define Clamp(x,min,max) if(x<min) x=min; else if(x>max) x=max // ------------------------------------ // #### #### // # # # // ### # # // # # # // #### #### // ------------------------------------ void vtkYoungsMaterialInterfaceCellCut::cellInterface3D( int ncoords, double coords[][3], int nedge, int cellEdges[][2], int ntetra, int tetraPointIds[][4], double fraction, double normal[3] , bool useFractionAsDistance, int & np, int eids[], double weights[] , int & nInside, int inPoints[], int & nOutside, int outPoints[] ) { // normalize the normal vector if the norm >0 double nlen2 = normal[0]*normal[0] + normal[1]*normal[1] + normal[2]*normal[2]; if( nlen2 > 0 ) { double nlen = sqrt(nlen2); normal[0] /= nlen; normal[1] /= nlen; normal[2] /= nlen; } else { normal[0] = 1; normal[1] = 0; normal[2] = 0; } double dmin, dmax; dmin = dmax = coords[0][0]*normal[0] + coords[0][1]*normal[1] + coords[0][2]*normal[2]; for(int i = 0;i<ncoords;i++) { double d = coords[i][0]*normal[0] + coords[i][1]*normal[1] + coords[i][2]*normal[2]; if( d<dmin ) dmin=d; else if( d>dmax ) dmax=d; } // compute plane's offset ( D parameter in Ax+By+Cz+D=0 ) double d = useFractionAsDistance ? fraction : findTetraSetCuttingPlane( normal, fraction, ncoords, coords, ntetra, tetraPointIds ); // compute vertex distances to interface plane double dist[MAX_CELL_POINTS]; for(int i = 0;i<ncoords;i++) { dist[i] = coords[i][0]*normal[0] + coords[i][1]*normal[1] + coords[i][2]*normal[2] + d; } // get in/out points nInside = 0; nOutside = 0; for(int i = 0;i<ncoords;i++) { if( dist[i] <= 0.0 ) { inPoints[nInside++] = i; } else { outPoints[nOutside++] = i; } } double center[3] = {0,0,0}; double polygon[MAX_CELL_POINTS][3]; // compute intersections between edges and interface plane np = 0; for(int i = 0;i<nedge;i++) { int e0 = cellEdges[i][0]; int e1 = cellEdges[i][1]; if( dist[e0]*dist[e1] < 0 ) { double edist = dist[e1] - dist[e0]; double t; if(edist!=0) { t = ( 0 - dist[e0] ) / edist ; Clamp(t,0,1); } else { t = 0; } for(int c=0;c<3;c++) { polygon[np][c] = coords[e0][c] + t * ( coords[e1][c] - coords[e0][c] ) ; center[c] += polygon[np][c]; } eids[np*2+0] = e0; eids[np*2+1] = e1; weights[np] = t; np++; } } // sort points if(np>3) { // compute the center of the polygon for(int comp=0;comp<3;comp++) { center[comp] /= np; } // compute the main direction to be in a 2D case int maxDim = 0; if( fabs(normal[1]) > fabs(normal[maxDim]) ) maxDim=1; if( fabs(normal[2]) > fabs(normal[maxDim]) ) maxDim=2; int xd=0, yd=1; switch(maxDim) { case 0: xd=1; yd=2; break; case 1: xd=0; yd=2; break; case 2: xd=0; yd=1; break; } // compute the angles of the polygon vertices vtkYoungsMaterialInterfaceCellCutInternals::CWVertex pts[MAX_CELL_POINTS]; for(int i = 0;i<np;i++) { double vec[3]; for(int comp=0;comp<3;comp++) { pts[i].coord[comp] = polygon[i][comp]; vec[comp] = polygon[i][comp]-center[comp]; } pts[i].weight = weights[i]; pts[i].eid[0] = eids[i*2+0]; pts[i].eid[1] = eids[i*2+1]; pts[i].angle = atan2( vec[yd], vec[xd] ); } std::sort( pts , pts+np ); for(int i = 0;i<np;i++) { weights[i] = pts[i].weight; eids[i*2+0] = pts[i].eid[0]; eids[i*2+1] = pts[i].eid[1]; } } } double vtkYoungsMaterialInterfaceCellCut::findTetraSetCuttingPlane( const double normal[3], const double fraction, const int vertexCount, const double vertices[][3], const int tetraCount, const int tetras[][4] ) { vtkYoungsMaterialInterfaceCellCutInternals::Real3 N = { normal[0], normal[1], normal[2] }; vtkYoungsMaterialInterfaceCellCutInternals::Real3 V[LOCAL_ARRAY_SIZE(vertexCount)]; vtkYoungsMaterialInterfaceCellCutInternals::uchar4 tet[LOCAL_ARRAY_SIZE(tetraCount)]; for(int i = 0;i<vertexCount;i++) { V[i].x = vertices[i][0] - vertices[0][0] ; V[i].y = vertices[i][1] - vertices[0][1] ; V[i].z = vertices[i][2] - vertices[0][2] ; } vtkYoungsMaterialInterfaceCellCutInternals::Real3 vmin,vmax; vtkYoungsMaterialInterfaceCellCutInternals::Real scale; vmin = vmax = V[0]; for(int i=1;i<vertexCount;i++) { if( V[i].x < vmin.x ) vmin.x = V[i].x; if( V[i].x > vmax.x ) vmax.x = V[i].x; if( V[i].y < vmin.y ) vmin.y = V[i].y; if( V[i].y > vmax.y ) vmax.y = V[i].y; if( V[i].z < vmin.z ) vmin.z = V[i].z; if( V[i].z > vmax.z ) vmax.z = V[i].z; } scale = vmax.x - vmin.x; if( (vmax.y-vmin.y) > scale ) scale = vmax.y-vmin.y; if( (vmax.z-vmin.z) > scale ) scale = vmax.z-vmin.z; for(int i = 0;i<vertexCount;i++) V[i] /= scale; for(int i = 0;i<tetraCount;i++) { tet[i].x = tetras[i][0]; tet[i].y = tetras[i][1]; tet[i].z = tetras[i][2]; tet[i].w = tetras[i][3]; } double dist0 = vertices[0][0]*normal[0] + vertices[0][1]*normal[1] + vertices[0][2]*normal[2]; double d = dist0 + vtkYoungsMaterialInterfaceCellCutInternals::findTetraSetCuttingPlane(N, fraction, vertexCount, tetraCount, tet, V ) * scale; return - d; } // ------------------------------------ // #### #### // # # # // ### # # // # # # // ##### #### // ------------------------------------ bool vtkYoungsMaterialInterfaceCellCut::cellInterfaceD( double points[][3], int nPoints, int triangles[][3], // TODO: int [] pour plus d'integration au niveau du dessus int nTriangles, double fraction, double normal[3] , bool axisSymetric, bool useFractionAsDistance, int eids[4], double weights[2] , int &polygonPoints, int polygonIds[], int &nRemPoints, int remPoints[] ) { double d = useFractionAsDistance ? fraction : findTriangleSetCuttingPlane( normal, fraction, nPoints, points, nTriangles, triangles , axisSymetric ); // compute vertex distances to interface plane double dist[LOCAL_ARRAY_SIZE(nPoints)]; for(int i = 0;i<nPoints;i++) { dist[i] = points[i][0]*normal[0] + points[i][1]*normal[1] + points[i][2]*normal[2] + d; } // compute intersections between edges and interface line int np = 0; nRemPoints = 0; polygonPoints = 0; for(int i = 0;i<nPoints;i++) { int edge[2]; edge[0] = i; edge[1] = (i+1)%nPoints; if( dist[i] <= 0.0 ) { polygonIds[polygonPoints++] = i; } else { remPoints[nRemPoints++] = i; } if( np < 2 ) { if( dist[edge[0]]*dist[edge[1]] < 0.0 ) { double t = ( 0 - dist[edge[0]] ) / ( dist[edge[1]] - dist[edge[0]] ); Clamp(t,0,1); eids[np*2+0] = edge[0]; eids[np*2+1] = edge[1]; weights[np] = t; np++; polygonIds[polygonPoints++] = -np; remPoints[nRemPoints++] = -np; } } } return (np==2); } double vtkYoungsMaterialInterfaceCellCut::findTriangleSetCuttingPlane( const double normal[3], const double fraction, const int vertexCount, const double vertices[][3], const int triangleCount, const int triangles[][3], bool axisSymetric ) { double d; vtkYoungsMaterialInterfaceCellCutInternals::uchar3 tri[LOCAL_ARRAY_SIZE(triangleCount)]; for(int i = 0;i<triangleCount;i++) { tri[i].x = triangles[i][0]; tri[i].y = triangles[i][1]; tri[i].z = triangles[i][2]; } if( axisSymetric ) { vtkYoungsMaterialInterfaceCellCutInternals::Real2 N = { normal[0], normal[1] }; vtkYoungsMaterialInterfaceCellCutInternals::Real2 V[LOCAL_ARRAY_SIZE(vertexCount)]; for(int i = 0;i<vertexCount;i++) { V[i].x = vertices[i][0] - vertices[0][0] ; V[i].y = vertices[i][1] - vertices[0][1] ; } vtkYoungsMaterialInterfaceCellCutInternals::Real2 vmin,vmax; vtkYoungsMaterialInterfaceCellCutInternals::Real scale; vmin = vmax = V[0]; for(int i=1;i<vertexCount;i++) { if( V[i].x < vmin.x ) vmin.x = V[i].x; if( V[i].x > vmax.x ) vmax.x = V[i].x; if( V[i].y < vmin.y ) vmin.y = V[i].y; if( V[i].y > vmax.y ) vmax.y = V[i].y; } scale = vmax.x - vmin.x; if( (vmax.y-vmin.y) > scale ) scale = vmax.y-vmin.y; for(int i = 0;i<vertexCount;i++) V[i] /= scale; double dist0 = vertices[0][0]*normal[0] + vertices[0][1]*normal[1] ; d = dist0 + vtkYoungsMaterialInterfaceCellCutInternals::findTriangleSetCuttingCone(N, fraction, vertexCount, triangleCount, tri, V ) * scale; } else { vtkYoungsMaterialInterfaceCellCutInternals::Real3 N = { normal[0], normal[1], normal[2] }; vtkYoungsMaterialInterfaceCellCutInternals::Real3 V[LOCAL_ARRAY_SIZE(vertexCount)]; for(int i = 0;i<vertexCount;i++) { V[i].x = vertices[i][0] - vertices[0][0] ; V[i].y = vertices[i][1] - vertices[0][1] ; V[i].z = vertices[i][2] - vertices[0][2] ; } vtkYoungsMaterialInterfaceCellCutInternals::Real3 vmin,vmax; vtkYoungsMaterialInterfaceCellCutInternals::Real scale; vmin = vmax = V[0]; for(int i=1;i<vertexCount;i++) { if( V[i].x < vmin.x ) vmin.x = V[i].x; if( V[i].x > vmax.x ) vmax.x = V[i].x; if( V[i].y < vmin.y ) vmin.y = V[i].y; if( V[i].y > vmax.y ) vmax.y = V[i].y; if( V[i].z < vmin.z ) vmin.z = V[i].z; if( V[i].z > vmax.z ) vmax.z = V[i].z; } scale = vmax.x - vmin.x; if( (vmax.y-vmin.y) > scale ) scale = vmax.y-vmin.y; if( (vmax.z-vmin.z) > scale ) scale = vmax.z-vmin.z; for(int i = 0;i<vertexCount;i++) V[i] /= scale; double dist0 = vertices[0][0]*normal[0] + vertices[0][1]*normal[1] + vertices[0][2]*normal[2]; d = dist0 + vtkYoungsMaterialInterfaceCellCutInternals::findTriangleSetCuttingPlane(N, fraction, vertexCount, triangleCount, tri, V ) * scale; } return - d; }
[ "shentianweipku@gmail.com" ]
shentianweipku@gmail.com
cb08e31788fa31a282e53e6f9049f2e0a118ecc3
fec5213f5c2ff4783163148edb31d3e7aff59654
/src/lib/Application/Option.h
8dcc27fc8f0e1e32c333c4b6d8ec164bc78a9137
[ "MIT" ]
permissive
Eric2-Praxinos/GuessHowMuch
35a588a31741fe91877505221b5103f126e4b11c
f2120981e28af0b19691f1dea3749b3ae10f2f2b
refs/heads/master
2020-09-20T13:02:52.200564
2019-12-01T21:50:41
2019-12-01T21:50:41
224,488,282
0
0
null
null
null
null
UTF-8
C++
false
false
1,631
h
#pragma once #include <string> #include "../Base/Parser.h" namespace nApplication { class cOption { public: /** Destructor */ ~cOption(); /** Constructor */ cOption(const ::std::string iName); public: /** Get the option name */ const std::string& Name() const; /** Parse the String and set the value */ virtual void Parse(const ::std::string& iString) const = 0; /** Sets the value to default */ virtual void SetValueToDefaultValue() const = 0; private: ::std::string mName; }; template <typename T> class cOptionT : public cOption { public: /** Destructor */ virtual ~cOptionT(); /** Constructor */ cOptionT(const ::std::string iName, ::nBase::cParser<T>* iParser, T* iValue, const T& iDefaultValue); public: /** Sets the value of the option */ virtual void Parse(const ::std::string& iString) const; /** Sets the value to default */ virtual void SetValueToDefaultValue() const; private: T* mValue; ::nBase::cParser<T>* mParser; T mDefaultValue; }; template<typename T> cOptionT<T>::~cOptionT() { delete mParser; } template<typename T> cOptionT<T>::cOptionT(const ::std::string iName, ::nBase::cParser<T>* iParser, T* iValue, const T& iDefaultValue) : cOption(iName), mParser(iParser), mValue(iValue), mDefaultValue(iDefaultValue) { } template<typename T> void cOptionT<T>::Parse(const ::std::string& iString) const { *mValue = mParser->Parse(iString, mDefaultValue); } template<typename T> void cOptionT<T>::SetValueToDefaultValue() const { *mValue = mDefaultValue; } } // namespace nApplication
[ "eric.scholl@praxinos.coop" ]
eric.scholl@praxinos.coop
5373aad63132bbbb7a66f7cb389fb743dcb860d6
877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a
/app/src/main/cpp/dir0/file365.cpp
5b140f966fdb106daf99b580dcea008875904b58
[]
no_license
tgeng/HugeProject
829c3bdfb7cbaf57727c41263212d4a67e3eb93d
4488d3b765e8827636ce5e878baacdf388710ef2
refs/heads/master
2022-08-21T16:58:54.161627
2020-05-28T01:54:03
2020-05-28T01:54:03
267,468,475
0
0
null
null
null
null
UTF-8
C++
false
false
107
cpp
#ifndef file365 #error "macro file365 must be defined" #endif static const char* file365String = "file365";
[ "tgeng@google.com" ]
tgeng@google.com
236776ad6b63250266a05c39dffe497181eef364
b5ba5c578810105c9148fecadc61f124ae68118c
/src-x64/RcppExports.cpp
c31f3ae242150d7021fca365cdb1ae4795e7ff2e
[]
no_license
dangulod/ECTools
cce57dfe0189ee324922d4d014cb7a72bd97817d
a927092249a92ced28c6c50fe7b26588049a07d0
refs/heads/master
2021-01-25T10:51:04.021720
2018-05-16T10:31:25
2018-05-16T10:31:25
93,886,888
1
1
null
null
null
null
UTF-8
C++
false
false
8,482
cpp
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <Rcpp.h> using namespace Rcpp; // RcOut std::vector<double> RcOut(double A, double B, double C, double D, std::vector<double> PD, std::vector<double> LGD, std::vector<double> weight, std::vector<double> EAD, std::vector<double> CORR, std::vector<double> UL); RcppExport SEXP _ECTools_RcOut(SEXP ASEXP, SEXP BSEXP, SEXP CSEXP, SEXP DSEXP, SEXP PDSEXP, SEXP LGDSEXP, SEXP weightSEXP, SEXP EADSEXP, SEXP CORRSEXP, SEXP ULSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< double >::type A(ASEXP); Rcpp::traits::input_parameter< double >::type B(BSEXP); Rcpp::traits::input_parameter< double >::type C(CSEXP); Rcpp::traits::input_parameter< double >::type D(DSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type PD(PDSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type LGD(LGDSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type weight(weightSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type EAD(EADSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type CORR(CORRSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type UL(ULSEXP); rcpp_result_gen = Rcpp::wrap(RcOut(A, B, C, D, PD, LGD, weight, EAD, CORR, UL)); return rcpp_result_gen; END_RCPP } // resid double resid(double A, double B, double C, double D, std::vector<double> PD, std::vector<double> LGD, std::vector<double> weight, std::vector<double> EAD, std::vector<double> CORR, std::vector<double> UL, std::vector<double> RcIn); RcppExport SEXP _ECTools_resid(SEXP ASEXP, SEXP BSEXP, SEXP CSEXP, SEXP DSEXP, SEXP PDSEXP, SEXP LGDSEXP, SEXP weightSEXP, SEXP EADSEXP, SEXP CORRSEXP, SEXP ULSEXP, SEXP RcInSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< double >::type A(ASEXP); Rcpp::traits::input_parameter< double >::type B(BSEXP); Rcpp::traits::input_parameter< double >::type C(CSEXP); Rcpp::traits::input_parameter< double >::type D(DSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type PD(PDSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type LGD(LGDSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type weight(weightSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type EAD(EADSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type CORR(CORRSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type UL(ULSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type RcIn(RcInSEXP); rcpp_result_gen = Rcpp::wrap(resid(A, B, C, D, PD, LGD, weight, EAD, CORR, UL, RcIn)); return rcpp_result_gen; END_RCPP } // mat NumericMatrix mat(NumericVector FG, NumericMatrix FL, DataFrame RU, CharacterVector col); RcppExport SEXP _ECTools_mat(SEXP FGSEXP, SEXP FLSEXP, SEXP RUSEXP, SEXP colSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericVector >::type FG(FGSEXP); Rcpp::traits::input_parameter< NumericMatrix >::type FL(FLSEXP); Rcpp::traits::input_parameter< DataFrame >::type RU(RUSEXP); Rcpp::traits::input_parameter< CharacterVector >::type col(colSEXP); rcpp_result_gen = Rcpp::wrap(mat(FG, FL, RU, col)); return rcpp_result_gen; END_RCPP } // fgyfl NumericMatrix fgyfl(NumericVector x, double lim, CharacterVector n); RcppExport SEXP _ECTools_fgyfl(SEXP xSEXP, SEXP limSEXP, SEXP nSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< NumericVector >::type x(xSEXP); Rcpp::traits::input_parameter< double >::type lim(limSEXP); Rcpp::traits::input_parameter< CharacterVector >::type n(nSEXP); rcpp_result_gen = Rcpp::wrap(fgyfl(x, lim, n)); return rcpp_result_gen; END_RCPP } // k1 double k1(std::vector<double> x); RcppExport SEXP _ECTools_k1(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(k1(x)); return rcpp_result_gen; END_RCPP } // k2 double k2(std::vector<double> x); RcppExport SEXP _ECTools_k2(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(k2(x)); return rcpp_result_gen; END_RCPP } // k3 double k3(std::vector<double> x); RcppExport SEXP _ECTools_k3(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(k3(x)); return rcpp_result_gen; END_RCPP } // k4 double k4(std::vector<double> x); RcppExport SEXP _ECTools_k4(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(k4(x)); return rcpp_result_gen; END_RCPP } // k5 double k5(std::vector<double> x); RcppExport SEXP _ECTools_k5(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(k5(x)); return rcpp_result_gen; END_RCPP } // k6 double k6(std::vector<double> x); RcppExport SEXP _ECTools_k6(SEXP xSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type x(xSEXP); rcpp_result_gen = Rcpp::wrap(k6(x)); return rcpp_result_gen; END_RCPP } // st_cumulants std::vector<double> st_cumulants(double location, double escala, double shape, double df); RcppExport SEXP _ECTools_st_cumulants(SEXP locationSEXP, SEXP escalaSEXP, SEXP shapeSEXP, SEXP dfSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< double >::type location(locationSEXP); Rcpp::traits::input_parameter< double >::type escala(escalaSEXP); Rcpp::traits::input_parameter< double >::type shape(shapeSEXP); Rcpp::traits::input_parameter< double >::type df(dfSEXP); rcpp_result_gen = Rcpp::wrap(st_cumulants(location, escala, shape, df)); return rcpp_result_gen; END_RCPP } // minfunc double minfunc(std::vector<double> par, std::vector<double> x, int n_days); RcppExport SEXP _ECTools_minfunc(SEXP parSEXP, SEXP xSEXP, SEXP n_daysSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type par(parSEXP); Rcpp::traits::input_parameter< std::vector<double> >::type x(xSEXP); Rcpp::traits::input_parameter< int >::type n_days(n_daysSEXP); rcpp_result_gen = Rcpp::wrap(minfunc(par, x, n_days)); return rcpp_result_gen; END_RCPP } // k4m double k4m(std::vector<double> k, double s); RcppExport SEXP _ECTools_k4m(SEXP kSEXP, SEXP sSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type k(kSEXP); Rcpp::traits::input_parameter< double >::type s(sSEXP); rcpp_result_gen = Rcpp::wrap(k4m(k, s)); return rcpp_result_gen; END_RCPP } // k4m_1st double k4m_1st(std::vector<double> k, double s); RcppExport SEXP _ECTools_k4m_1st(SEXP kSEXP, SEXP sSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type k(kSEXP); Rcpp::traits::input_parameter< double >::type s(sSEXP); rcpp_result_gen = Rcpp::wrap(k4m_1st(k, s)); return rcpp_result_gen; END_RCPP } // k4m_2nd double k4m_2nd(std::vector<double> k, double s); RcppExport SEXP _ECTools_k4m_2nd(SEXP kSEXP, SEXP sSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< std::vector<double> >::type k(kSEXP); Rcpp::traits::input_parameter< double >::type s(sSEXP); rcpp_result_gen = Rcpp::wrap(k4m_2nd(k, s)); return rcpp_result_gen; END_RCPP }
[ "angulo.davi@gmail.com" ]
angulo.davi@gmail.com
0b2749de888341dbac16e95b3dd5faaf6b224224
682c266e6b5fffd4ece6871ccab0d4ff55d1e08f
/The cpp program language 4th/ch13/ex13-1-9.cpp
af11782ed32af114e35ef5a79c05ce437e0ceb67
[]
no_license
mooniron/learn-cpp
046e026b876ed1e70cbc26ed00aebf61aed0be7f
189afeada700118b47a01d0b10588f4d521d3aab
refs/heads/master
2021-01-20T22:16:00.457586
2017-08-29T23:10:57
2017-08-29T23:10:57
101,811,287
0
0
null
null
null
null
UTF-8
C++
false
false
3,739
cpp
/************************************************************** * Name : ex13-1-9.cpp * Author : Bronze Lee * Version : 0.1 * Date : 2017年5月23日 **************************************************************/ /* example 13.5 : throwing and catching exceptions section 13.5.2 : catching exceptions */ void f() { try { throw E {}; } catch (H) { // when do we get here? } } void g() { int x1; try { int x2 = x1; // ... } catch (Error) { // ok ++x1; // error : x2 not in scope ++x2; int x3 = 7; // ... } catch (...) { // error : x3 not in scope ++x3; // ... } // ok ++x1; // error : x2 not in scope ++x2; // error : x3 not in scope ++x3; } // section 13.5.2.1 : rethrow void h() { try { // ... code that might throw an exception ... } catch (std::exception& err) { if (can_handle_it_completely) { // ... handle it ... return; } else { // ... do what can be done here ... // rethrow the exception throw; } } } // section 13.5.2.2 catch every exception void m() { try { // ... do something ... } catch (std::exception& err) { // handle every standard library exception // ... cleanup ... throw; } } void m() { try { // ... something ... } catch (...) { // handle every exception // ... cleanup ... throw; } } // section 13.5.2.3 : multiple handlers void f() { try { // ... } catch (std::ios_base::failure) { // ... handle any iostream error ... } catch (std::exception& e) { // ... handle any standard library exception ... } catch (...) { // ... handle any other exception ... } } void g() { try { // ... } catch (...) { // ... handle every exception ... } catch (std::exception& e) { // ... handle any standard library ... } catch (std::bad_cast) { // ... handle dynamic_cast failure ... } } // section 13.5.2.4 function try-blocks int main() try { // ... do something ... } catch (...) { // ... handle exception ... } class X { vector<int> vi; vector<string> vs; // ... public : X(int, int); // ... }; X::X(int sz1, int sz2) try // construct vi with sz1 ints : vi(sz1), // construct vs with sz2 strings vs(sz2), { // ... } catch (std::exception& err) { // exceptions thrown for vi and vs are caught here // the best way is to rethrow } // section 13.5.2.5 termination // from <exception> using terminate_handler = void(*)(); // a terminate handler cannot return [[noreturn]] void my_handler() { // handle termination my way } // very! void dangerous() { terminate_handler old = set_terminate(my_handler); // ... // restore the old terminate handler set_terminate(old); } int main() try { // ... } catch (const My_error& err) { // ... handle my error ... } catch (const std::range_error&) { cerr << "range error : Not again!\n"; } catch (const std::bad_alloc&) { cerr << "new ran out of memory\n"; } catch (...) { // ... } // section 13.5.3 exceptions and threads try { // ... do the work ... } catch (...) { prom.set_exception(current_exception()); }
[ "mooniron@outlook.com" ]
mooniron@outlook.com
ffacdda98365e796f0eee9fec9dcf43b97329428
45c8e3f7a294c60d830e5b5dcabf8e05c00ff0d3
/Src/Buff/KBullet.h
9d7009d4ae107e08124a89a33a3f807075c0e268
[]
no_license
zhengguo07q/GameWorld
14fadd3ca56d0f8367acd13e9a02c3eebc9ce682
4c980edebdaa2a1d5d6949e7114b81bd66da152d
refs/heads/master
2021-01-25T08:43:21.285513
2018-03-19T07:55:23
2018-03-19T07:55:23
40,157,367
3
0
null
null
null
null
UTF-8
C++
false
false
1,162
h
// *************************************************************** // Copyright(c) Kingsoft // FileName : KBullet.h // Creator : Xiayong // Date : 01/11/2012 // Comment : // *************************************************************** #pragma once #include "Ksdef.h" #include "KMovableObject.h" #include "KBulletInfoMgr.h" class KSkill; class KHero; struct KBulletInfo; class KBullet : public KMovableObject { public: KBullet(); virtual ~KBullet(); void Activate(int nCurLoop); KSceneObjectType GetType() const; virtual void ProcessRebounds(); virtual int GetCurrentGravity(); void ApplyBulletInfo(KBulletInfo* pInfo); BOOL CollideHero(KHero* pHero); DWORD m_dwCasterID; KSkill* m_pSkill; int m_nStartFrame; int m_nLifeTime; int m_nGravity; int m_nSide; KBulletInfo* m_pBulletTemplate; private: void OnDeleteFlagSetted(); BOOL Blast(); BOOL IsInAttackInterval(DWORD dwHeroID); BOOL RecordAttackedHero(DWORD dwHeroID); private: BOOL m_bBlastedOnCurFrame; KATTACKED_OBJ_LIST m_AttackedObjList; };
[ "85938406@qq.com" ]
85938406@qq.com
98f7638bac400962b3b77bed9c2ba220646847dd
f6cc0009dbd9d69228258b038d051a01f7af4467
/Main Controller/lpc1758_project_final/L5_Application/project.hpp
4417525bad8adaee1a0024bf7bde406c5830d0dd
[]
no_license
koson/Protocol_Interface_I2C_Can_Bridge
ef76191fd50fdd22ec1b4503b18281696414fff5
373e39923aa798ebcc8845f5d0b6f819bc7133d8
refs/heads/master
2021-01-17T10:25:53.949091
2015-05-25T04:58:00
2015-05-25T04:58:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,102
hpp
/* * project.hpp * * Created on: Apr 5, 2015 * Author: Mitesh_Sanghvi */ #ifndef L5_APPLICATION_PROJECT_HPP_ #define L5_APPLICATION_PROJECT_HPP_ #include "can.h" #include "stdio.h" #include "stdlib.h" #include "stdint.h" #include "io.hpp" #include "utilities.h" #include "printf_lib.h" #include "i2c_base.hpp" #include "i2c2.hpp" #include "scheduler_task.hpp" #define slaveAddress 0x50 #define BAUDRATE 100 #define RX_QUEUE 10 #define TX_QUEUE 10 #define DEFAULT_MAILBOX_SIZE 15 typedef struct mailbox_t { uint8_t mask : 1; uint8_t size : 4; uint16_t id : 11; uint16_t mask_id: 11; uint8_t num : 4; uint8_t data[10*16]; } mailbox_t; const uint32_t ld3 = (1 << 20); extern uint8_t i2c_mem[30+10]; extern int interrupted_mailbox; extern bool status; extern uint32_t status_register; extern mailbox_t mailbox[16]; extern SemaphoreHandle_t i2c_receive; class i2cTask : public scheduler_task { public: i2cTask(uint8_t priority) : scheduler_task("I2C", 512*2, priority) { I2C2 &i2c = I2C2::getInstance(); // Initializing I2C as a Slave Device i2c.initSlave(slaveAddress, &i2c_mem[0]); LPC_GPIO1->FIODIR |= ld3; for(int i = 0; i < 16; i++) // Loop for configuring the default mailbox size to max value i.e. 15 { mailbox[i].size = DEFAULT_MAILBOX_SIZE; mailbox[i].mask = false; } LD.clear(); // Clearing the LED display which is used to display the number of frames in a mailbox } bool run(void *p) { return true; } }; class can_rxTask : public scheduler_task { public: can_rxTask(uint8_t priority) : scheduler_task("can_rx", 512*2, priority) { CAN_init(can1, BAUDRATE, RX_QUEUE, TX_QUEUE, NULL, NULL); // Initializing CAN bus CAN_bypass_filter_accept_all_msgs(); CAN_reset_bus(can1); status_register = 0; // Reset Status Register } bool run(void *p) { int i = 0, j = 0, k = 0; can_msg_t rxmsg; // Creating object for sending message over CAN rxmsg.data.qword = 0; // Clearing the data bytes of CAN object if(CAN_rx(can1, &rxmsg, portMAX_DELAY)) // Waiting forever to receive a message over CAN bus { for(i = 0; i < 16; i++) // Loop for checking received CAN_id == configured CAN_id { uint16_t temp_mask_id = mailbox[i].id; for(j = 0; j < 11; j++) // Loop for checking received CAN_id with all combinations of configured CAN_id considering Mask Bits { if((1 << j) & (mailbox[i].mask_id)) { if((1<<j) & rxmsg.msg_id) temp_mask_id |= (1 << j); else temp_mask_id &= ~(1 << j); } } if(((rxmsg.msg_id == temp_mask_id)) && (mailbox[i].num < mailbox[i].size)) { printf("CAN Received from %x; \n", (unsigned int)rxmsg.msg_id); for(j = mailbox[i].num*10, k = 0; k < 8; j++, k++) // Storing data into respective mailbox mailbox[i].data[j+2] = rxmsg.data.bytes[k]; mailbox[i].data[j-8] = rxmsg.msg_id >> 8; // Storing received CAN msg_id to mailbox mailbox[i].data[j-7] = rxmsg.msg_id; mailbox[i].num++; if(mailbox[i].num >= mailbox[i].size) { if(!(status_register & (1 << i))) // Check if number of frame in a mailbox >= configured size { LE.toggle(1); // Giving a trigger signal to I2C Master LPC_GPIO1->FIOSET = ld3; delay_us(50); LPC_GPIO1->FIOCLR = ld3; status_register |= (1 << i); // Setting the respective bit in Status Register } } char disp = (char)mailbox[1].num*10 + (char)mailbox[7].num; LD.setNumber(disp); break; } } } return true; } }; class can_txTask : public scheduler_task { public: can_txTask(uint8_t priority) : scheduler_task("can_tx", 512*2, priority) { CAN_init(can1, BAUDRATE, RX_QUEUE, TX_QUEUE, NULL, NULL); CAN_bypass_filter_accept_all_msgs(); CAN_reset_bus(can1); } bool run(void *p) { can_msg_t txmsg; txmsg.frame_fields.is_29bit = 0; if(xSemaphoreTake(i2c_receive, portMAX_DELAY)) // Wait forever for semaphore that is given by i2ctask when data is received by I2C Master to be sent on CAN bus { txmsg.frame_fields.data_len = i2c_mem[0] >> 3; for(int i = 0; i < txmsg.frame_fields.data_len; i++) txmsg.data.bytes[i] = i2c_mem[i+2]; // Fill the data to be sent on CAN txmsg.msg_id = ((i2c_mem[0] << 8) | i2c_mem[1]); if(CAN_tx(can1, &txmsg, portMAX_DELAY)) // Wait forever till the message is sent over CAN bus printf("CAN Transmit Done\n"); } return true; } }; #endif /* L5_APPLICATION_PROJECT_HPP_ */
[ "sanghvimails@gmail.com" ]
sanghvimails@gmail.com
83a550d08572bced494d2a48ab25e6248a12bab3
a83378a11aa6b7f766374b50bd5082a2acb7ae54
/Xtreme/Vulkan/VulkanTexture.h
d2004d8198d54f92f774ec79187008d76301599a
[]
no_license
Spritutu/Common
5e21579fa767621b6d3e487bdd9f12209d8f0948
311e512d896f563a9353c743bb0878dafcca1b5b
refs/heads/master
2022-12-25T16:36:40.449491
2020-09-27T09:48:18
2020-09-27T09:50:10
null
0
0
null
null
null
null
UTF-8
C++
false
false
896
h
#ifndef XTREME_Vulkan_TEXTURE_H #define XTREME_Vulkan_TEXTURE_H #include <Xtreme/XTexture.h> #include <vulkan/vulkan.h> #include <list> class VulkanTexture : public XTexture { public: GR::u32 m_TransparentColor; GR::u32 m_MipMapLevels; std::list<GR::String> m_listFileNames; std::list<GR::Graphic::ImageData> m_StoredImageData; bool AllowUsageAsRenderTarget; VkImage m_TextureImage; VkDeviceMemory m_TextureImageMemory; VkDevice m_Device; VulkanTexture(); virtual ~VulkanTexture(); virtual bool Release(); virtual bool RequiresRebuild(); }; #endif // XTREME_Vulkan_TEXTURE_H
[ "georg@georg-rottensteiner.de" ]
georg@georg-rottensteiner.de
c55b8a0379edd2197ff773d3ab7ab83eac2d9759
120d865d5970d06559a23ab8c75689924e794faa
/modules/dnn/inference/dnn_super_resolution.cpp
51236632f81eebac4c3a668e25f9640ce35ae741
[ "Apache-2.0" ]
permissive
liuyinhangx/libxcam
f105598bf719fe77ebabc42fdbdc9396250022e5
231a1d5243cd45c7a6b511b667f1ec52178fdda8
refs/heads/master
2021-07-25T01:42:50.066317
2020-12-24T03:15:51
2020-12-24T03:17:11
327,479,959
3
1
NOASSERTION
2021-01-07T02:19:19
2021-01-07T02:19:19
null
UTF-8
C++
false
false
6,169
cpp
/* * dnn_super_resolution.cpp - super resolution * * Copyright (c) 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: Zong Wei <wei.zong@intel.com> */ #include <inference_engine.hpp> #include "dnn_super_resolution.h" using namespace std; using namespace InferenceEngine; namespace XCam { DnnSuperResolution::DnnSuperResolution (DnnInferConfig& config) : DnnInferenceEngine (config) { XCAM_LOG_DEBUG ("DnnSuperResolution::DnnSuperResolution"); set_output_layer_type ("Convolution"); } DnnSuperResolution::~DnnSuperResolution () { } XCamReturn DnnSuperResolution::set_output_layer_type (const char* type) { _output_layer_type.insert (DnnOutputLayerType::value_type (DnnInferSuperResolution, type)); return XCAM_RETURN_NO_ERROR; } XCamReturn DnnSuperResolution::get_model_input_info (DnnInferInputOutputInfo& info) { if (NULL == _ie.ptr ()) { XCAM_LOG_ERROR ("Please create inference engine"); return XCAM_RETURN_ERROR_ORDER; } InputsDataMap inputs_info (_network.getInputsInfo ()); InputInfo::Ptr input_info = nullptr; int id = 0; InferenceEngine::Precision precision; for (auto & item : inputs_info) { if (item.second->getInputData()->getTensorDesc().getDims().size() == 4) { input_info = item.second; XCAM_LOG_DEBUG ("Batch size is: %d", _network.getBatchSize()); precision = Precision::U8; item.second->setPrecision(Precision::U8); } else if (item.second->getInputData()->getTensorDesc().getDims().size() == 2) { precision = Precision::FP32; item.second->setPrecision(Precision::FP32); if ((item.second->getTensorDesc().getDims()[1] != 3 && item.second->getTensorDesc().getDims()[1] != 6)) { XCAM_LOG_ERROR ("Invalid input info. Should be 3 or 6 values length"); return XCAM_RETURN_ERROR_PARAM; } } info.width[id] = inputs_info[item.first]->getTensorDesc().getDims()[3]; info.height[id] = inputs_info[item.first]->getTensorDesc().getDims()[2]; info.channels[id] = inputs_info[item.first]->getTensorDesc().getDims()[1]; info.object_size[id] = inputs_info[item.first]->getTensorDesc().getDims()[0]; info.precision[id] = convert_precision_type (precision); id++; } info.batch_size = get_batch_size (); info.numbers = inputs_info.size (); return XCAM_RETURN_NO_ERROR; } XCamReturn DnnSuperResolution::set_model_input_info (DnnInferInputOutputInfo& info) { XCAM_LOG_DEBUG ("DnnSuperResolution::set_model_input_info"); if (NULL == _ie.ptr ()) { XCAM_LOG_ERROR ("Please create inference engine"); return XCAM_RETURN_ERROR_ORDER; } InputsDataMap inputs_info (_network.getInputsInfo ()); if (info.numbers != inputs_info.size ()) { XCAM_LOG_ERROR ("Input size is not matched with model info numbers %d !", info.numbers); return XCAM_RETURN_ERROR_PARAM; } int idx = 0; for (auto & in : inputs_info) { Precision precision = convert_precision_type (info.precision[idx]); in.second->setPrecision (precision); Layout layout = convert_layout_type (info.layout[idx]); in.second->setLayout (layout); idx ++; } return XCAM_RETURN_NO_ERROR; } XCamReturn DnnSuperResolution::get_model_output_info (DnnInferInputOutputInfo& info) { if (NULL == _ie.ptr ()) { XCAM_LOG_ERROR ("Please create inference engine"); return XCAM_RETURN_ERROR_ORDER; } std::string output_name; OutputsDataMap outputs_info (_network.getOutputsInfo ()); DataPtr output_info; uint32_t idx = 0; for (const auto& out : outputs_info) { if (output_name.empty ()) { output_name = out.first; } output_info = out.second; if (output_info.get ()) { const InferenceEngine::SizeVector output_dims = output_info->getTensorDesc().getDims(); info.object_size[idx] = output_dims[0]; info.channels[idx] = output_dims[1]; info.height[idx] = output_dims[2]; info.width[idx] = output_dims[3]; info.precision[idx] = convert_precision_type (output_info->getPrecision()); info.layout[idx] = convert_layout_type (output_info->getLayout()); info.data_type[idx] = DnnInferDataTypeImage; info.format[idx] = DnnInferImageFormatBGRPlanar; info.batch_size = idx + 1; info.numbers = outputs_info.size (); } else { XCAM_LOG_ERROR ("output data pointer is not valid"); return XCAM_RETURN_ERROR_UNKNOWN; } idx ++; out.second->setPrecision (Precision::FP32); } return XCAM_RETURN_NO_ERROR; } XCamReturn DnnSuperResolution::set_model_output_info (DnnInferInputOutputInfo& info) { if (NULL == _ie.ptr ()) { XCAM_LOG_ERROR ("Please create inference engine"); return XCAM_RETURN_ERROR_ORDER; } OutputsDataMap outputs_info (_network.getOutputsInfo ()); if (info.numbers != outputs_info.size ()) { XCAM_LOG_ERROR ("Output size is not matched with model!"); return XCAM_RETURN_ERROR_PARAM; } int idx = 0; for (auto & out : outputs_info) { Precision precision = convert_precision_type (info.precision[idx]); out.second->setPrecision (precision); Layout layout = convert_layout_type (info.layout[idx]); out.second->setLayout (layout); idx++; } return XCAM_RETURN_NO_ERROR; } } // namespace XCam
[ "wei.zong@intel.com" ]
wei.zong@intel.com
71ea244320c918d4ba8022b399c3af2146bf0dc6
f5519b8523241414b255b6c98574ab46a98e63af
/Samples/Inventory/UE4/Source/Inventory/ViewModel.h
d72e202cc120343dbec819c605b0e5a0f763e830
[]
no_license
DaveCS1/Tutorials
05e42fc46fc728625d1ad19b2b3cca9e1e95ecf5
550db7c82510f474c7d7432aeee7f41ac58fbbff
refs/heads/master
2020-06-08T18:07:25.094374
2019-06-20T15:38:45
2019-06-20T15:38:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,181
h
//////////////////////////////////////////////////////////////////////////////////////////////////// // NoesisGUI - http://www.noesisengine.com // Copyright (c) 2013 Noesis Technologies S.L. All Rights Reserved. //////////////////////////////////////////////////////////////////////////////////////////////////// #ifndef __INVENTORY_VIEWMODEL_H__ #define __INVENTORY_VIEWMODEL_H__ #include <NsCore/Noesis.h> #include <NsCore/BaseComponent.h> #include <NsCore/String.h> #include <NsCore/ReflectionDeclare.h> #include <NsCore/ReflectionDeclareEnum.h> #include <NsGui/ObservableCollection.h> #include <NsGui/INotifyPropertyChanged.h> #include <NsDrawing/Rect.h> namespace Inventory { //////////////////////////////////////////////////////////////////////////////////////////////////// enum ItemCategory { ItemCategory_Head, ItemCategory_Chest, ItemCategory_Arms, ItemCategory_Legs, ItemCategory_Feet, ItemCategory_Hand, ItemCategory_Ring, ItemCategory_All }; //////////////////////////////////////////////////////////////////////////////////////////////////// struct Item final: public Noesis::BaseComponent { NsString name; NsString description; ItemCategory category; int life; int mana; int dps; int armor; Noesis::Rect icon; NS_DECLARE_REFLECTION(Item, BaseComponent) }; //////////////////////////////////////////////////////////////////////////////////////////////////// class NotifierBase: public Noesis::BaseComponent, public Noesis::INotifyPropertyChanged { public: Noesis::PropertyChangedEventHandler& PropertyChanged() final; NS_IMPLEMENT_INTERFACE_FIXUP protected: void OnPropertyChanged(const char* propertyName); private: Noesis::PropertyChangedEventHandler _changed; NS_DECLARE_REFLECTION(NotifierBase, BaseComponent) }; //////////////////////////////////////////////////////////////////////////////////////////////////// class Slot; typedef Noesis::Delegate<void (Slot* slot, Item* oldItem, Item* newItem)> SlotItemChangedHandler; //////////////////////////////////////////////////////////////////////////////////////////////////// class Slot: public NotifierBase { public: Slot(const char* name, ItemCategory allowedCategory); ItemCategory GetAllowedCategory() const; Item* GetItem() const; void SetItem(Item* item); SlotItemChangedHandler& ItemChanged(); bool GetIsDragOver() const; void SetIsDragOver(bool over); bool GetIsDropAllowed() const; void SetIsDropAllowed(bool dropAllowed); void UpdateIsDropAllowed(); bool GetIsSelected() const; void SetIsSelected(bool select); bool GetMoveFocus() const; void Focus(); private: void OnItemChanged(Item* oldItem, Item* newItem); bool IsItemAllowed(Item* item) const; private: NsString _name; ItemCategory _allowedCategory; Noesis::Ptr<Item> _item; bool _isDragOver; bool _isDropAllowed; bool _isSelected; bool _moveFocus; SlotItemChangedHandler _itemChanged; NS_DECLARE_REFLECTION(Slot, NotifierBase) }; //////////////////////////////////////////////////////////////////////////////////////////////////// class Player final: public NotifierBase { public: Player(const char* name, int life, int mana, int dps, int armor); int GetLife() const; void SetLife(int value); int GetMana() const; void SetMana(int value); int GetDps() const; void SetDps(int value); int GetArmor() const; void SetArmor(int value); Noesis::ObservableCollection<Slot>* GetSlots() const; private: void UpdateStats(Slot* slot, Item* oldItem, Item* newItem); private: NsString _name; int _life; int _mana; int _dps; int _armor; Noesis::Ptr<Noesis::ObservableCollection<Slot>> _slots; Noesis::PropertyChangedEventHandler _changed; NS_DECLARE_REFLECTION(Player, NotifierBase) }; //////////////////////////////////////////////////////////////////////////////////////////////////// class ViewModel final: public NotifierBase { public: ViewModel(); static ViewModel* Instance(); const char* GetPlatform() const; Player* GetPlayer() const; Noesis::ObservableCollection<Slot>* GetInventory() const; Noesis::ObservableCollection<Item>* GetItems() const; bool StartDragging(Slot* source, const Noesis::Point& position); void EndDragging(bool dropCancelled); Slot* GetDragSource() const; Item* GetDraggedItem() const; float GetDraggedItemX() const; void SetDraggedItemX(float x); float GetDraggedItemY() const; void SetDraggedItemY(float y); Slot* GetSelectedSlot() const; void SelectSlot(Slot* slot); private: void UpdateDropSlots(); private: Noesis::Ptr<Player> _player; Noesis::Ptr<Noesis::ObservableCollection<Slot>> _inventory; Noesis::Ptr<Noesis::ObservableCollection<Item>> _items; Noesis::Ptr<Slot> _selectedSlot; Noesis::Ptr<Slot> _dragSource; Noesis::Ptr<Item> _draggedItem; float _draggedItemX; float _draggedItemY; NS_DECLARE_REFLECTION(ViewModel, NotifierBase) }; } NS_DECLARE_REFLECTION_ENUM(Inventory::ItemCategory) #endif
[ "hcpizzi@hotmail.com" ]
hcpizzi@hotmail.com
ad5d7df245e7ad4ee5ee453b0fce868c457e5fff
4102a1ed8180b25f754de3720f12260c63a02409
/PlayFabSDK/Plugins/PlayFabProxy/Source/PlayFabProxy/Public/Proxy/Client/PFClientConsumeItem.h
3ef928f193d65eb0de0daad3294065e139ebf3db
[ "Apache-2.0" ]
permissive
MrBigDog/UnrealCppSdk
13203ecc4acf731032ee707def10a29e326056a4
ddb78658d517563c58139d46465748d11dfbc676
refs/heads/master
2020-03-22T05:47:50.189721
2018-06-18T22:26:16
2018-06-18T22:26:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,278
h
// This is automatically generated by PlayFab SDKGenerator. DO NOT modify this manually! #pragma once #include "CoreMinimal.h" #include "PlayFabProxyBaseModel.h" #include "Core/PlayFabClientAPI.h" #include "Core/PlayFabClientDataModels.h" #include "Proxy/PlayFabClientBPDataModels.h" #include "PFClientConsumeItem.generated.h" UCLASS(MinimalAPI) class UPFClientConsumeItem : public UPlayFabProxyBase { GENERATED_UCLASS_BODY() public: UPROPERTY(BlueprintAssignable) FBPClientConsumeItemResultDelegate OnSuccess; // Consume uses of a consumable item. When all uses are consumed, it will be removed from the player's inventory. UFUNCTION(BlueprintCallable, meta = (BlueprintInternalUseOnly = "true"), Category = "PlayFab|Client|Player Item Management") static UPFClientConsumeItem* ConsumeItem(class APlayerController* PlayerController, const FBPClientConsumeItemRequest& InConsumeItemRequest); // UOnlineBlueprintCallProxyBase interface virtual void Activate() override; // End of UOnlineBlueprintCallProxyBase interface private: FBPClientConsumeItemRequest Request; PlayFab::UPlayFabClientAPI::FConsumeItemDelegate SuccessDelegate; void OnSuccessCallback(const PlayFab::ClientModels::FConsumeItemResult& Result); };
[ "jenkins-bot@playfab.com" ]
jenkins-bot@playfab.com
0d0e3344dfbcce94cb34a60e6f38011e5a89690f
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_AlarmTrap_FPV_AnimBlueprint_functions.cpp
1f621046def75b413d03faf7a3d6cd16b3fa974c
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,126
cpp
// ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_AlarmTrap_FPV_AnimBlueprint_parameters.hpp" namespace sdk { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function AlarmTrap_FPV_AnimBlueprint.AlarmTrap_FPV_AnimBlueprint_C.ExecuteUbergraph_AlarmTrap_FPV_AnimBlueprint // () // Parameters: // int EntryPoint (Parm, ZeroConstructor, IsPlainOldData) void UAlarmTrap_FPV_AnimBlueprint_C::ExecuteUbergraph_AlarmTrap_FPV_AnimBlueprint(int EntryPoint) { static auto fn = UObject::FindObject<UFunction>("Function AlarmTrap_FPV_AnimBlueprint.AlarmTrap_FPV_AnimBlueprint_C.ExecuteUbergraph_AlarmTrap_FPV_AnimBlueprint"); UAlarmTrap_FPV_AnimBlueprint_C_ExecuteUbergraph_AlarmTrap_FPV_AnimBlueprint_Params params; params.EntryPoint = EntryPoint; auto flags = fn->FunctionFlags; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
77493e4fe554e9401cd4a28406ac6af7042bd12d
44db3d731b7bc01e9e12235e40134d56806fb368
/Zalgorithm.cpp
7efe16c004408059742433fae05a577cdafc47aa
[]
no_license
rpg49/String-algorithm
53b29d86d91ec6fe5c44ce8e5ab7344330226a9f
b1f5275eac7c20e4b32027a2d6da65e205966983
refs/heads/master
2022-12-28T18:11:27.177566
2020-10-11T10:41:17
2020-10-11T10:41:17
303,046,567
1
0
null
2020-10-11T10:41:18
2020-10-11T05:07:35
C++
UTF-8
C++
false
false
2,036
cpp
// implementation of Z algorithm for pattern searching in C++ #include<iostream> using namespace std; void getZarr(string str, int Z[]); // prints all occurrences of pattern in text using Z algo void search(string text, string pattern) { // Create concatenated string "P$T" string concat = pattern + "$" + text; int l = concat.length(); // Construct Z array int Z[l]; getZarr(concat, Z); // now looping through Z array for matching condition for (int i = 0; i < l; ++i) { // if Z[i] (matched region) is equal to pattern // length we got the pattern if (Z[i] == pattern.length()) cout << "Pattern found at index " << i - pattern.length() -1 << endl; } } // Fills Z array for given string str[] void getZarr(string str, int Z[]) { int n = str.length(); int L, R, k; // [L,R] make a window which matches with prefix of s L = R = 0; for (int i = 1; i < n; ++i) { // if i>R nothing matches so we will calculate. // Z[i] using naive way. if (i > R) { L = R = i; // R-L = 0 in starting, so it will start // checking from 0'th index. For example, // for "ababab" and i = 1, the value of R // remains 0 and Z[i] becomes 0. For string // "aaaaaa" and i = 1, Z[i] and R become 5 while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } else { // k = i-L so k corresponds to number which // matches in [L,R] interval. k = i-L; // if Z[k] is less than remaining interval // then Z[i] will be equal to Z[k]. // For example, str = "ababab", i = 3, R = 5 // and L = 2 if (Z[k] < R-i+1) Z[i] = Z[k]; // For example str = "aaaaaa" and i = 2, R is 5, // L is 0 else { // else start from R and check manually L = i; while (R<n && str[R-L] == str[R]) R++; Z[i] = R-L; R--; } } } } // Driver program int main() { string text ; getline(cin,text); string pattern ; getline(cin,pattern); search(text, pattern); return 0; }
[ "pandey.rpg49@gmail.com" ]
pandey.rpg49@gmail.com
083dc2d05bc84105f7a738f9f7c2632358c09bd2
7084f9a97a27a2387ad4dd86d942a0ae4ef6314a
/42.cpp
6e0f17dce7eb2fdf60be2dda38cb3c97c1cf80c6
[]
no_license
silviosanto6605/Compiti-informatica-vacanze-2021
2c37ff86aa4002afdcacecc780c68e7951984f34
8294d606fedfd63f5341a9e29e52159dcce64647
refs/heads/master
2023-06-24T10:20:11.904661
2021-07-25T18:58:14
2021-07-25T18:58:14
380,819,509
0
0
null
null
null
null
UTF-8
C++
false
false
387
cpp
#include <iostream> #include "src/funzioni.h" using namespace std; int main(int argc, char const *argv[]) { int number, base; cout << "Inserisci un numero: "; cin >> number; cout << "Inserisci la base, compresa tra 2 e 16: "; cin >> base; cout<<"base = "<<base<<"\tnum = "<<number<<" => "<<convertToAnyBase(number,base)<<" in base"<<base<<endl; return 0; }
[ "silviosanto6605@gmail.com" ]
silviosanto6605@gmail.com
8dc9dc46added867e3972c8ab493fcce1c9fdff5
a6205d92ce9e063d6ee185e5f39ced26e3c3d3d2
/todo/tuts/masm64/Include/hnetcfg.inc
839d0c18c3c9d18f8336e21d2c0d34c206d325d8
[]
no_license
wyrover/masm32-package-vs2015
9cd3bbcd1aaeb79fc33d924f1f1fdb4ed0f6eb26
855707ef7b9e9cbc6dc69bd24a635014c61fcfed
refs/heads/master
2020-12-30T22:31:42.391236
2016-05-24T17:22:27
2016-05-24T17:22:27
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,573
inc
extern __imp_HNetDeleteRasConnection:PANYARGS HNetDeleteRasConnection TEXTEQU <__imp_HNetDeleteRasConnection> extern __imp_HNetFreeSharingServicesPage:PANYARGS HNetFreeSharingServicesPage TEXTEQU <__imp_HNetFreeSharingServicesPage> extern __imp_HNetGetSharingServicesPage:PANYARGS HNetGetSharingServicesPage TEXTEQU <__imp_HNetGetSharingServicesPage> extern __imp_WinBomConfigureWindowsFirewall:PANYARGS WinBomConfigureWindowsFirewall TEXTEQU <__imp_WinBomConfigureWindowsFirewall> extern __imp_DllCanUnloadNow:PANYARGS DllCanUnloadNow TEXTEQU <__imp_DllCanUnloadNow> extern __imp_DllGetClassObject:PANYARGS DllGetClassObject TEXTEQU <__imp_DllGetClassObject> extern __imp_DllRegisterServer:PANYARGS DllRegisterServer TEXTEQU <__imp_DllRegisterServer> extern __imp_DllUnregisterServer:PANYARGS DllUnregisterServer TEXTEQU <__imp_DllUnregisterServer> extern __imp_HNetFreeFirewallLoggingSettings:PANYARGS HNetFreeFirewallLoggingSettings TEXTEQU <__imp_HNetFreeFirewallLoggingSettings> extern __imp_HNetGetFirewallSettingsPage:PANYARGS HNetGetFirewallSettingsPage TEXTEQU <__imp_HNetGetFirewallSettingsPage> extern __imp_HNetGetShareAndBridgeSettings:PANYARGS HNetGetShareAndBridgeSettings TEXTEQU <__imp_HNetGetShareAndBridgeSettings> extern __imp_HNetSetShareAndBridgeSettings:PANYARGS HNetSetShareAndBridgeSettings TEXTEQU <__imp_HNetSetShareAndBridgeSettings> extern __imp_HNetSharedAccessSettingsDlg:PANYARGS HNetSharedAccessSettingsDlg TEXTEQU <__imp_HNetSharedAccessSettingsDlg> extern __imp_HNetSharingAndFirewallSettingsDlg:PANYARGS HNetSharingAndFirewallSettingsDlg TEXTEQU <__imp_HNetSharingAndFirewallSettingsDlg> extern __imp_IcfChangeNotificationCreate:PANYARGS IcfChangeNotificationCreate TEXTEQU <__imp_IcfChangeNotificationCreate> extern __imp_IcfChangeNotificationDestroy:PANYARGS IcfChangeNotificationDestroy TEXTEQU <__imp_IcfChangeNotificationDestroy> extern __imp_IcfCheckAppAuthorization:PANYARGS IcfCheckAppAuthorization TEXTEQU <__imp_IcfCheckAppAuthorization> extern __imp_IcfCloseDynamicFwPort:PANYARGS IcfCloseDynamicFwPort TEXTEQU <__imp_IcfCloseDynamicFwPort> extern __imp_IcfConnect:PANYARGS IcfConnect TEXTEQU <__imp_IcfConnect> extern __imp_IcfDisconnect:PANYARGS IcfDisconnect TEXTEQU <__imp_IcfDisconnect> extern __imp_IcfFreeAdapters:PANYARGS IcfFreeAdapters TEXTEQU <__imp_IcfFreeAdapters> extern __imp_IcfFreeDynamicFwPorts:PANYARGS IcfFreeDynamicFwPorts TEXTEQU <__imp_IcfFreeDynamicFwPorts> extern __imp_IcfFreeProfile:PANYARGS IcfFreeProfile TEXTEQU <__imp_IcfFreeProfile> extern __imp_IcfFreeString:PANYARGS IcfFreeString TEXTEQU <__imp_IcfFreeString> extern __imp_IcfFreeTickets:PANYARGS IcfFreeTickets TEXTEQU <__imp_IcfFreeTickets> extern __imp_IcfGetAdapters:PANYARGS IcfGetAdapters TEXTEQU <__imp_IcfGetAdapters> extern __imp_IcfGetCurrentProfileType:PANYARGS IcfGetCurrentProfileType TEXTEQU <__imp_IcfGetCurrentProfileType> extern __imp_IcfGetDynamicFwPorts:PANYARGS IcfGetDynamicFwPorts TEXTEQU <__imp_IcfGetDynamicFwPorts> extern __imp_IcfGetOperationalMode:PANYARGS IcfGetOperationalMode TEXTEQU <__imp_IcfGetOperationalMode> extern __imp_IcfGetProfile:PANYARGS IcfGetProfile TEXTEQU <__imp_IcfGetProfile> extern __imp_IcfGetTickets:PANYARGS IcfGetTickets TEXTEQU <__imp_IcfGetTickets> extern __imp_IcfIsIcmpTypeAllowed:PANYARGS IcfIsIcmpTypeAllowed TEXTEQU <__imp_IcfIsIcmpTypeAllowed> extern __imp_IcfIsPortAllowed:PANYARGS IcfIsPortAllowed TEXTEQU <__imp_IcfIsPortAllowed> extern __imp_IcfOpenDynamicFwPort:PANYARGS IcfOpenDynamicFwPort TEXTEQU <__imp_IcfOpenDynamicFwPort> extern __imp_IcfOpenDynamicFwPortWithoutSocket:PANYARGS IcfOpenDynamicFwPortWithoutSocket TEXTEQU <__imp_IcfOpenDynamicFwPortWithoutSocket> extern __imp_IcfOpenFileSharingPorts:PANYARGS IcfOpenFileSharingPorts TEXTEQU <__imp_IcfOpenFileSharingPorts> extern __imp_IcfRefreshPolicy:PANYARGS IcfRefreshPolicy TEXTEQU <__imp_IcfRefreshPolicy> extern __imp_IcfRemoveDisabledAuthorizedApp:PANYARGS IcfRemoveDisabledAuthorizedApp TEXTEQU <__imp_IcfRemoveDisabledAuthorizedApp> extern __imp_IcfSetProfile:PANYARGS IcfSetProfile TEXTEQU <__imp_IcfSetProfile> extern __imp_IcfSetServicePermission:PANYARGS IcfSetServicePermission TEXTEQU <__imp_IcfSetServicePermission> extern __imp_IcfSubNetsGetScope:PANYARGS IcfSubNetsGetScope TEXTEQU <__imp_IcfSubNetsGetScope> extern __imp_IcfSubNetsIsStringValid:PANYARGS IcfSubNetsIsStringValid TEXTEQU <__imp_IcfSubNetsIsStringValid> extern __imp_IcfSubNetsToString:PANYARGS IcfSubNetsToString TEXTEQU <__imp_IcfSubNetsToString>
[ "admin@agguro.be" ]
admin@agguro.be
c563af312b39d43508826901d7aa1bcf6725e53c
7d4ff4ea6b306a07fc13a8fa3d120fb62df94726
/ir_remote/IRRemote.cpp
391f10e1b6d9b77431287a87e0183c0b2e4185a6
[]
no_license
oshurmamadov/ArduinoSamples
af34e14f88b3c807146fc652d2ee5304891e5a0d
0b1a8bdf6241b886e0cba0b37f5ca4c1f5635b2e
refs/heads/master
2023-04-21T15:29:07.466356
2021-05-05T07:36:48
2021-05-05T07:36:48
356,362,023
0
0
null
null
null
null
UTF-8
C++
false
false
416
cpp
/* * IRRemote.cpp * * Created on: 4 May 2021 * Author: parviz.oshurmamadov */ #include "IRremote.h" #include "Arduino.h" #include "MyIRRemote.h" int controlPin = 11; IRrecv IR(controlPin); decode_results cmd; void MyIRRemote::setup() { Serial.begin(28800); IR.enableIRIn(); } void MyIRRemote::loop() { while(IR.decode(&cmd) == 0) {} Serial.println(cmd.value, HEX); delay(1500); IR.resume(); }
[ "parviz0492@gmail.com" ]
parviz0492@gmail.com
6b2840bb09f76927534c56dcbdd4bc1e9b725cf2
2f93cbfcbbe90455ad4be6640b107c74932d386e
/library/twosat.hpp
e1873c2c955fdadb211018b942617b55eea7248d
[ "CC0-1.0" ]
permissive
reud/clion-sport-programming
9c88cc3f41a081a8731f1706e9e2c43b0ea0964e
0b8bfdc051c5003e24b35319ac1f4ce450a87c25
refs/heads/master
2023-03-09T12:14:38.697597
2021-02-24T15:36:50
2021-02-24T15:36:50
336,164,942
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
hpp
#ifndef ATCODER_TWOSAT_HPP #define ATCODER_TWOSAT_HPP 1 #include "./internal_scc" #include <cassert> #include <vector> namespace atcoder { // Reference: // B. Aspvall, M. Plass, and R. Tarjan, // A Linear-Time Algorithm for Testing the Truth of Certain Quantified Boolean // Formulas struct two_sat { public: two_sat() : _n(0), scc(0) {} two_sat(int n) : _n(n), _answer(n), scc(2 * n) {} void add_clause(int i, bool f, int j, bool g) { assert(0 <= i && i < _n); assert(0 <= j && j < _n); scc.add_edge(2 * i + (f ? 0 : 1), 2 * j + (g ? 1 : 0)); scc.add_edge(2 * j + (g ? 0 : 1), 2 * i + (f ? 1 : 0)); } bool satisfiable() { auto id = scc.scc_ids().second; for (int i = 0; i < _n; i++) { if (id[2 * i] == id[2 * i + 1]) return false; _answer[i] = id[2 * i] < id[2 * i + 1]; } return true; } std::vector<bool> answer() { return _answer; } private: int _n; std::vector<bool> _answer; internal::scc_graph scc; }; } // namespace atcoder #endif // ATCODER_TWOSAT_HPP
[ "reiji.kobayashi.9n@stu.hosei.ac.jp" ]
reiji.kobayashi.9n@stu.hosei.ac.jp
c0b90c4a28149bfe5a33854117f6850bff5f5cd4
d0e974bfe06745a508fbf1a8b213acc6ccdcf185
/DP_easy_learn/Longest_Increasing_Subsequence.cpp
680e5b19931fa218974134e144d56bbf88e131ba
[]
no_license
sahilrawat001/PEPCO
8f0cc3959a8c318bb09165ecb523057003134e1f
3e78fa02d086808735e14471952c83bc2d99750e
refs/heads/master
2023-08-24T13:51:47.137493
2021-10-26T17:00:18
2021-10-26T17:00:18
null
0
0
null
null
null
null
UTF-8
C++
false
false
909
cpp
//class Solution { //public: #include <bits/stdc++.h> using namespace std; int lcs(vector<int>x,vector<int>y,int n,int m) { int t[n+1][m+1]; for (int i = 0; i <= n; i++) for (int j = 0; j <= m; j++) if (i == 0 || j == 0) t[i][j] = 0; for(int i=1;i<n+1;i++) { for(int j=1;j<m+1;j++) { if(x[i-1]==y[j-1]) { t[i][j]=1+t[i-1][j-1]; } else { t[i][j]=max(t[i][j-1],t[i-1][j]); } } } return t[n][m]; } int lengthOfLIS(vector<int>& nums) { int n=nums.size(); vector<int>inc; inc=nums; sort(inc.begin(),inc.end()); inc.erase(unique(inc.begin(),inc.end()),inc.end()); return lcs(nums,inc,n,inc.size()); } int main() { vector<int> nums={10,9,2,5,3,7,101,18}; cout<<lengthOfLIS(nums); }
[ "divyanshnigam1612@gmail.com" ]
divyanshnigam1612@gmail.com
e55993d3dd35f67c2c69dcf5c7701b47039b0ff6
c5fdd2ed179efe5e6b2ac82d4553b2367bcb7ee5
/flightgoggles_ros_bridge/src/Common/jsonMessageSpec.hpp
a9f947c2a498670023de539981776f6a206d1415
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
SASLabStevens/FlightGoggles
80fa245cf6b68a36aa4b0475cc57b28b6d92bd0e
ad28590e19c8b74171f65e973331e70bdd5358da
refs/heads/master
2020-09-23T05:49:41.242678
2019-11-27T18:25:28
2019-11-27T18:25:28
225,420,600
1
0
NOASSERTION
2019-12-02T16:31:50
2019-12-02T16:31:50
null
UTF-8
C++
false
false
4,594
hpp
#ifndef UNITYMESSAGESPEC_H #define UNITYMESSAGESPEC_H /** * @file jsonMessageSpec.hpp * @author Winter Guerra * @brief Defines the json structure of messages going to and from Unity. */ // Message/state struct definition #include <iostream> #include <string> #include <vector> #include <opencv2/opencv.hpp> #include "json.hpp" using json = nlohmann::json; namespace unity_outgoing { struct Camera_t { std::string ID; // Position and rotation use Unity left-handed coordinates. // Z North, X East, Y up. // E.G. East, Up, North. std::vector<double> position; std::vector<double> rotation; // Metadata int channels; bool isDepth; int outputIndex; // Should this camera collision check or check for visibility? bool hasCollisionCheck = true; bool doesLandmarkVisCheck = false; }; // Window class for decoding the ZMQ messages. struct Object_t { std::string ID; std::string prefabID; std::vector<double> position; std::vector<double> rotation; // Metadata std::vector<double> size; }; struct StateMessage_t { // Scene/Render settings bool sceneIsInternal = true; // Scene choices in v1.4.1 // std::string sceneFilename = "Hazelwood_Loft_Full_Night"; // std::string sceneFilename = "Hazelwood_Loft_Full_Day"; // std::string sceneFilename = "Butterfly_World"; // std::string sceneFilename = "NYC_Subway"; // std::string sceneFilename = "Museum_Day"; std::string sceneFilename = "Museum_Day_Small"; // Frame Metadata int64_t ntime; int camWidth = 1024; int camHeight = 768; float camFOV = 70.0f; double camDepthScale = 0.20; // 0.xx corresponds to xx cm resolution // Object state update std::vector<Camera_t> cameras; std::vector<Object_t> objects; // std::vector<Landmark_t> landmarks; }; // Json constructors // StateMessage_t inline void to_json(json &j, const StateMessage_t &o) { j = json{// Initializers // {"maxFramerate", o.maxFramerate}, {"sceneIsInternal", o.sceneIsInternal}, {"sceneFilename", o.sceneFilename}, // Frame Metadata {"ntime", o.ntime}, {"camWidth", o.camWidth}, {"camHeight", o.camHeight}, {"camFOV", o.camFOV}, {"camDepthScale", o.camDepthScale}, // Object state update {"cameras", o.cameras}, {"objects", o.objects} }; } // Camera_t inline void to_json(json &j, const Camera_t &o) { j = json{{"ID", o.ID}, {"position", o.position}, {"rotation", o.rotation}, {"channels", o.channels}, {"isDepth", o.isDepth}, {"outputIndex", o.outputIndex}, {"hasCollisionCheck", o.hasCollisionCheck}, {"doesLandmarkVisCheck", o.doesLandmarkVisCheck} }; } // Object_t inline void to_json(json &j, const Object_t &o) { j = json{ {"ID", o.ID}, {"prefabID", o.prefabID}, {"position", o.position}, {"rotation", o.rotation}, {"size", o.size} }; } } // Struct for returning metadata from Unity. namespace unity_incoming { // Points in the world that should be checked for visibility from some camera. struct Landmark_t { std::string ID; std::vector<double> position; }; struct RenderMetadata_t { // Metadata int64_t ntime; int camWidth; int camHeight; double camDepthScale; // Object state update std::vector<std::string> cameraIDs; std::vector<int> channels; // Status update from collision detectors and raycasters. bool hasCameraCollision; std::vector<Landmark_t> landmarksInView; float lidarReturn; }; // Json Parsers // Landmark_t inline void from_json(const json &j, Landmark_t &o) { o.ID = j.at("ID").get<std::string>(); o.position = j.at("position").get<std::vector<double>>(); } // RenderMetadata_t inline void from_json(const json &j, RenderMetadata_t &o) { o.ntime = j.at("ntime").get<int64_t>(); o.camWidth = j.at("camWidth").get<int>(); o.camHeight = j.at("camHeight").get<int>(); o.camDepthScale = j.at("camDepthScale").get<double>(); o.cameraIDs = j.at("cameraIDs").get<std::vector<std::string>>(); o.channels = j.at("channels").get<std::vector<int>>(); o.hasCameraCollision = j.at("hasCameraCollision").get<bool>(); o.landmarksInView = j.at("landmarksInView").get<std::vector<Landmark_t>>(); o.lidarReturn = j.at("lidarReturn").get<float>(); } // Struct for outputting parsed received messages to handler functions struct RenderOutput_t { RenderMetadata_t renderMetadata; std::vector<cv::Mat> images; }; } #endif
[ "winterg@mit.edu" ]
winterg@mit.edu
5b45fb58e4ae0f666d90e22234e018ff924b398d
d06120aaff28e4e90f891201a9278fc339566a8d
/monopoly/Classes/Item/RidHospital.h
53bfca4fadfbbd17d02fecac9980ecceb67607b7
[ "MIT" ]
permissive
li-letian/Monopoly
7b8d9372bb1fe1ad6565205ce9014b67b468e9d1
6427672842ed94bb4dad585206ec08ec9a5f7a4d
refs/heads/master
2022-11-13T03:44:57.776063
2020-06-21T14:21:18
2020-06-21T14:21:18
261,958,000
4
3
MIT
2020-06-13T15:54:52
2020-05-07T05:30:03
C++
UTF-8
C++
false
false
260
h
#ifndef _RID_HOSPITAL_H_ #define _RID_HOSPITAL_H_ class Character; #include "Item.h" #include "Common/CommonMethod.h" class RidHospital :public Item { public: virtual void worked(Character* player); CREATE_FUNC(RidHospital); virtual bool init(); }; #endif
[ "liletian@tongji.edu.cn" ]
liletian@tongji.edu.cn
22d18b0d0114ee44e7fc44f066ad78a261736757
d926904d5081c2ced7346a6a317222b40c876c9e
/guilib/src/ExportCloudsDialog.h
7448806ebcd691fa52c4d02b473756751ec9c4f7
[]
no_license
lifunudt/pq
28371d74583e1adfd59e93553ebdaf84425f239a
ab8a6e146c9ca621f333a124493827ad247c1cb8
refs/heads/master
2016-09-13T07:20:59.665487
2016-05-14T03:25:26
2016-05-14T03:25:26
58,785,273
0
1
null
null
null
null
UTF-8
C++
false
false
4,681
h
/* Copyright (c) 2010-2014, Mathieu Labbe - IntRoLab - Universite de Sherbrooke All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Universite de Sherbrooke nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef EXPORTCLOUDSDIALOG_H_ #define EXPORTCLOUDSDIALOG_H_ #include <QDialog> #include <QMap> #include <QtCore/QSettings> #include <rtabmap/core/Signature.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/PolygonMesh.h> #include <pcl/TextureMesh.h> #include <pcl/pcl_base.h> class Ui_ExportCloudsDialog; class QAbstractButton; namespace rtabmap { class ProgressDialog; class ExportCloudsDialog : public QDialog { Q_OBJECT public: ExportCloudsDialog(QWidget *parent = 0); virtual ~ExportCloudsDialog(); void saveSettings(QSettings & settings, const QString & group = "") const; void loadSettings(QSettings & settings, const QString & group = ""); void exportClouds( const std::map<int, Transform> & poses, const std::map<int, int> & mapIds, const QMap<int, Signature> & cachedSignatures, const std::map<int, std::pair<pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr, pcl::IndicesPtr> > & createdClouds, const QString & workingDirectory); void viewClouds( const std::map<int, Transform> & poses, const std::map<int, int> & mapIds, const QMap<int, Signature> & cachedSignatures, const std::map<int, std::pair<pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr, pcl::IndicesPtr> > & createdClouds, const QString & workingDirectory); signals: void configChanged(); public slots: void restoreDefaults(); private slots: void updateReconstructionFlavor(); void updateMLSGrpVisibility(); private: std::map<int, std::pair<pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr, pcl::IndicesPtr> > getClouds( const std::map<int, Transform> & poses, const QMap<int, Signature> & cachedSignatures, const std::map<int, std::pair<pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr, pcl::IndicesPtr> > & createdClouds) const; bool getExportedClouds( const std::map<int, Transform> & poses, const std::map<int, int> & mapIds, const QMap<int, Signature> & cachedSignatures, const std::map<int, std::pair<pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr, pcl::IndicesPtr> > & createdClouds, const QString & workingDirectory, std::map<int, pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr> & clouds, std::map<int, pcl::PolygonMesh::Ptr> & meshes, std::map<int, pcl::TextureMesh::Ptr> & textureMeshes); void saveClouds(const QString & workingDirectory, const std::map<int, Transform> & poses, const std::map<int, pcl::PointCloud<pcl::PointXYZRGBNormal>::Ptr> & clouds, bool binaryMode = true); void saveMeshes(const QString & workingDirectory, const std::map<int, Transform> & poses, const std::map<int, pcl::PolygonMesh::Ptr> & meshes, bool binaryMode = true); void saveTextureMeshes(const QString & workingDirectory, const std::map<int, Transform> & poses, const std::map<int, pcl::TextureMesh::Ptr> & meshes); void setSaveButton(); void setOkButton(); void enableRegeneration(bool enabled); private: Ui_ExportCloudsDialog * _ui; ProgressDialog * _progressDialog; }; } #endif /* EXPORTCLOUDSDIALOG_H_ */
[ "lifunudt@163.com" ]
lifunudt@163.com
601a7932d5c159ceaa4c4d9b37d9b9b6b13a6713
5770c0f7227140b1421b89c609933cc5769f1b7c
/Command_Undo/Receiver.h
09ec7ba3bfc4166615ee4bac58d31576c52ca966
[]
no_license
cnyzgkn/DesignPattern
5190de10123363b9db376c5d7536ed867bea337d
9266b57604fff30520e617cf7c1fed0606ac30f6
refs/heads/master
2021-01-20T15:58:12.413133
2019-09-03T11:32:29
2019-09-03T11:32:29
65,065,540
0
0
null
null
null
null
UTF-8
C++
false
false
556
h
#ifndef RECEIVER_H #define RECEIVER_H #include <iostream> #include <math.h> class IReceiver { public: IReceiver(int val) : m_val(val) {}; void Increment() { m_val++; std::cout << "Increment m_val == " << m_val << std::endl; } void Decrement() { m_val--; std::cout << "Decrement m_val == " << m_val << std::endl; } void Square() { m_val *= m_val; std::cout << "Sqrt m_val == " << m_val << std::endl; } void Sqrt() { m_val = sqrt(m_val); std::cout << "Square m_val == " << m_val << std::endl; } private: int m_val; }; #endif
[ "cnyzgkn@gmail.com" ]
cnyzgkn@gmail.com
355ad15d10d6c95239c5047a6b6ad55217f586b8
5d29e57602700d59a079145ff22e6df945189fc3
/Graph/getpathBFS.cpp
f6d87469a75b74ee3d61b1057c26841e5998aa7e
[]
no_license
Saifu0/CP
be1e4f27fdbe74ff5b90c5f1875d26cb3017c6ba
3dcaad23ef21b7ea861a7ba4b35cfee913328037
refs/heads/master
2021-05-23T17:07:24.776476
2020-04-06T04:27:30
2020-04-06T04:27:30
253,394,047
0
0
null
null
null
null
UTF-8
C++
false
false
1,484
cpp
#include<bits/stdc++.h> using namespace std; vector<int> print(int **edge,int V, bool *visit,int x,int y) { // int start=x; int flag=0; queue<int>q; q.push(x); visit[x]=true; map<int ,int>m; //cout<<start; while(!q.empty()) { int start=q.front(); for(int i=0;i<V;i++) { if(edge[start][i]==1 && visit[i]==false) { q.push(i); visit[i]=true; m[i]=start; if (i == y) { flag = 1; break; } } //cout<<start<<" "; } q.pop(); } if(flag==0) return vector<int>(); vector<int>v; v.push_back(y); int t=y; while(t!=x) { v.push_back(m.at(t)); t=m.at(t); } return v; } int main() { int V, E; cin >> V >> E; int x,y; int **edge= new int*[V]; for(int i=0;i<V;i++) { edge[i]=new int[V]; for(int j=0;j<V;j++) { edge[i][j]=0; } } for(int i=0;i<E;i++) { int s,f; cin>>s>>f; edge[s][f]=1; edge[f][s]=1; } cin>>x>>y; bool *visit=new bool[V]; for(int i=0;i<V;i++) visit[i]=false; vector<int>v=print(edge,V,visit,x,y); for(int i=0;i<v.size();i++) { cout<<v[i]<<" "; } }
[ "saifurrahmankhankhan@gmail.com" ]
saifurrahmankhankhan@gmail.com
cf9fe5b06f41a4cc431155bd688d021952bcccde
02df46b70d7755cbb54bf716823941366a03e138
/src/client/src/HumanPlayer.cpp
6d9f24148d0ab43971c809fba285aa9093973711
[]
no_license
abbyAlbum/reversi
49eb49d2eba99d16b116c383aefcd06c54a7aec9
495896af38594cab24550474b0d89ee7e923a8de
refs/heads/master
2022-11-10T22:22:21.833685
2018-01-21T11:25:24
2018-01-21T11:25:24
275,802,832
1
0
null
null
null
null
UTF-8
C++
false
false
2,386
cpp
// // Created by eyal moskowitz 314074303 on 10/11/17. // #include "../include/HumanPlayer.h" /** * constructor for HumanPlayer. * @param symbol */ HumanPlayer::HumanPlayer(char symbol) { symbol_ = symbol; } /** * c'tor for HumanPlayer * @param color */ HumanPlayer::HumanPlayer(int color) { if (color == BLACK) symbol_ = 'X'; if (color == WHITE) symbol_ = 'O'; } /** * lets the player to make a move * @param moves possible moves for the player * @return the player's choice */ Point HumanPlayer::makeMove(vector<Point> &moves) { playerMove(moves); if (moves.empty()) { cout << "You have no possible moves, other player's turn." << endl; return Point(-1, -1); } Point p; cout << "Please enter row and column (separated with space):" << endl; while (true) { p = getValidInput(); bool isInMoves = false; for (int i = 0; i < moves.size(); ++i) { if (p == moves[i]) { isInMoves = true; break; } else isInMoves = false; } if (isInMoves) break; else { cout << "Your choice is illegal, please try again:" << endl; } } return p; } /** * makes sure that we get only numbers * @return the player's choice */ Point HumanPlayer::getValidInput() { int row, col; while (true) { cin >> row >> col; if (!cin.fail()) { cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); return Point(row, col); } // user didn't input row and column cout << "Please enter numbers only." << endl; cin.clear(); // reset failbit cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); } } /** * gets the player's symbol * @return symbol */ char HumanPlayer::getSymbol() const { return symbol_; } /** * prints the player's turn flow * @param moves */ void HumanPlayer::playerMove(vector<Point> &moves) { cout << symbol_ << ": It's your turn." << endl; printOptions(moves); } /** * prints the possible moves * @param moves vector */ void HumanPlayer::printOptions(vector<Point> &moves) { for (int i = 0; i < moves.size(); ++i) { if (i == moves.size() - 1) moves[i].print(); else { moves[i].print(); cout << ","; } } cout << endl; }
[ "eyal.moskowitz@gmail.com" ]
eyal.moskowitz@gmail.com
2d91bd96200c9f94eb2732d72b6d46dac88fc420
e3099f75c6dc4c50bc2291818311440f7e0047b0
/Math/Vector3.h
3fcf39e41df1b1d5ba4a361cccf468e0eb0d5884
[ "MIT" ]
permissive
API-Beast/libColorProcess
b60d01aa84a2d25b152d884cb1a0c5c1250be351
1f36ab7db7a666c91327ebd1284f0beb23a79222
refs/heads/master
2023-07-06T06:31:23.080085
2021-07-07T09:48:04
2021-07-07T09:48:04
299,062,760
0
0
null
null
null
null
UTF-8
C++
false
false
362
h
#pragma once #include "Vector3Macro.h" template<typename T> struct Vector3 { T x = T(0); T y = T(0); T z = T(0); VECTOR3_CONSTRUCTORS(Vector3, x, y, z); VECTOR3_MEMBER_FUNCTIONS(Vector3<T>, x, y, z); }; VECTOR3_OPERATORS_T(Vector3<T>, x, y, z, template<typename T>); using Vec3f = Vector3<float>; using Vec3u8 = Vector3<unsigned char>;
[ "api.beast@gmail.com" ]
api.beast@gmail.com
801ed6cf9d4bf750df02b6da93f06784bfcf7584
c0c591dc28c5fecce1df17c7929d89cf9c155c39
/STM32F415APP/Application/Application.cpp
8467f0b55ad62f0849e1960d86170450d04106ae
[]
no_license
KiraSokolov/devboy
027ec65c33c7fd4de7c6c730d98cbfdaadc86096
e06bf2d8e4df28f5fb6d97f187dfed0f594480f4
refs/heads/master
2020-03-29T03:56:43.005602
2018-09-01T05:56:38
2018-09-01T05:56:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
18,849
cpp
//****************************************************************************** // @file Application.cpp // @author Nicolai Shlapunov // // @details Application: User Application Class, implementation // // @copyright Copyright (c) 2016, Devtronic & Nicolai Shlapunov // All rights reserved. // // @section SUPPORT // // Devtronic invests time and resources providing this open source code, // please support Devtronic and open-source hardware/software by // donations and/or purchasing products from Devtronic. // //****************************************************************************** // ***************************************************************************** // *** Includes ************************************************************ // ***************************************************************************** #include "Application.h" #include "Tetris.h" #include "Pong.h" #include "Gario.h" #include "Calc.h" #include "GraphDemo.h" #include "InputTest.h" #include "fatfs.h" #include "usbd_cdc.h" // ***************************************************************************** // *** Get Instance ******************************************************** // ***************************************************************************** Application& Application::GetInstance(void) { static Application application; return application; } // ***************************************************************************** // *** Test get function *************************************************** // ***************************************************************************** char* Application::GetMenuStr(void* ptr, char* buf, uint32_t n, uint32_t add_param) { // Application* app = (Application*)ptr; snprintf(buf, n, "%lu", add_param); return buf; } // ***************************************************************************** // *** Application Loop **************************************************** // ***************************************************************************** Result Application::Loop() { // Sound control on the touchscreen SoundControlBox snd_box(0, 0); snd_box.Move(display_drv.GetScreenW() - snd_box.GetWidth(), display_drv.GetScreenH() - snd_box.GetHeight()); snd_box.Show(32768); // *** Menu Items ******************************************************** UiMenu::MenuItem main_menu_items[] = {{"Tetris", nullptr, &Application::GetMenuStr, this, 1}, {"Pong", nullptr, &Application::GetMenuStr, this, 2}, {"Gario", nullptr, &Application::GetMenuStr, this, 3}, {"Calc", nullptr, &Application::GetMenuStr, this, 4}, {"Graphic demo", nullptr, &Application::GetMenuStr, this, 5}, {"Input test", nullptr, &Application::GetMenuStr, this, 6}, {"SD write test", nullptr, &Application::GetMenuStr, this, 7}, {"USB test", nullptr, &Application::GetMenuStr, this, 8}, {"Servo test", nullptr, &Application::GetMenuStr, this, 9}, {"Touch calibrate", nullptr, &Application::GetMenuStr, this, 10}}; // Create menu object UiMenu menu("Main Menu", main_menu_items, NumberOf(main_menu_items)); // Main cycle while(1) { // Call menu main function if(menu.Run()) { switch(menu.GetCurrentPosition()) { // Tetris Application case 0: Tetris::GetInstance().Loop(); break; // Pong Application case 1: Pong::GetInstance().Loop(); break; case 2: // Gario Application Gario::GetInstance().Loop(); break; // Calc Application case 3: Calc::GetInstance().Loop(); break; // GraphDemo Application case 4: GraphDemo::GetInstance().Loop(); break; // InputTest Application case 5: InputTest::GetInstance().Loop(); break; // SD write test case 6: { // Mount SD FRESULT fres = f_mount(&SDFatFS, (TCHAR const*)SDPath, 0); // Open file if(fres == FR_OK) { fres = f_open(&SDFile, "STM32.TXT", FA_CREATE_ALWAYS | FA_WRITE); } // Write data to file if(fres == FR_OK) { // File write counts UINT wbytes; // File write buffer char wtext[128]; snprintf(wtext, NumberOf(wtext), "SD write test. Timestamp: %lu\r\n", HAL_GetTick()); for(uint32_t i = 0U; i < 10U; i++) { fres = f_write(&SDFile, wtext, strlen(wtext), &wbytes); if(fres != FR_OK) break; } } // Close file if(fres == FR_OK) { fres = f_close(&SDFile); } // Show result if(fres == FR_OK) { UiMsgBox msg_box("File written successfully", "Success"); msg_box.Run(3000U); } else { UiMsgBox msg_box("File write error", "Error"); msg_box.Run(3000U); } break; } // USB CDC test case 7: { uint8_t str[64]; // Create string snprintf((char*)str, sizeof(str), "USB test. Timestamp: %lu\r\n", HAL_GetTick()); // Send to USB if(USBD_CDC_SetTxBuffer(&hUsbDeviceFS, str, strlen((char*)str)) == USBD_OK) { USBD_CDC_TransmitPacket(&hUsbDeviceFS); // Wait until transmission finished while((hUsbDeviceFS.pClassData != nullptr) && (((USBD_CDC_HandleTypeDef*)hUsbDeviceFS.pClassData)->TxState == 1)) { RtosTick::DelayTicks(1U); } } break; } // Servo test case 8: { // Configure GPIO pin : PB12 GPIO_InitTypeDef GPIO_InitStruct; GPIO_InitStruct.Pin = GPIO_PIN_12; GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); for(uint32_t n = 0U; n < 100U; n++) { HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_SET); RtosTick::DelayTicks(1U); for(volatile uint32_t i = 0U; i < 1000U; i++); HAL_GPIO_WritePin(GPIOB, GPIO_PIN_12, GPIO_PIN_RESET); RtosTick::DelayTicks(18U); } } break; // Touchscreen Calibration case 9: display_drv.TouchCalibrate(); break; default: break; } } } // Always run return Result::RESULT_OK; } // ***************************************************************************** // ***************************************************************************** // *** SoundControlBox ***************************************************** // ***************************************************************************** // ***************************************************************************** const uint8_t mute_off_img[] = { 0xD7, 0xD7, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xD7, 0xD7, 0xD7, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xD7, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x62, 0x68, 0x68, 0x62, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x68, 0x93, 0x93, 0x69, 0x93, 0x93, 0x93, 0x68, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x31, 0x93, 0x68, 0x99, 0xC4, 0xCA, 0xC4, 0x99, 0x68, 0x69, 0x68, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x31, 0x93, 0x93, 0xCB, 0xFB, 0xCA, 0xCA, 0xCA, 0xFB, 0xFB, 0x99, 0x68, 0x68, 0x62, 0x37, 0x68, 0x62, 0x68, 0x31, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x93, 0x99, 0xFB, 0xC4, 0x93, 0x68, 0x93, 0x93, 0x99, 0xCA, 0xFB, 0xC4, 0x68, 0x68, 0x62, 0x62, 0x93, 0x68, 0x99, 0x62, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x38, 0x93, 0xFB, 0x99, 0x68, 0x93, 0x99, 0x99, 0x99, 0x99, 0x99, 0xC4, 0xFB, 0xC4, 0x68, 0x68, 0x31, 0x99, 0x93, 0x68, 0x99, 0x31, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x68, 0xCA, 0xC4, 0x68, 0x93, 0x99, 0x99, 0x99, 0x9A, 0xC4, 0xC4, 0x99, 0xCA, 0xFB, 0x93, 0x68, 0x62, 0x62, 0x99, 0x68, 0x99, 0x93, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x31, 0x93, 0xF5, 0x68, 0x93, 0x99, 0x99, 0x99, 0xC4, 0xC4, 0xC4, 0xCA, 0x99, 0x68, 0xCA, 0xCA, 0x62, 0x68, 0x31, 0x99, 0x93, 0x93, 0x99, 0x31, 0x00, 0xFB, 0xFB, 0x00, 0x62, 0x99, 0xC4, 0x69, 0x93, 0x99, 0x99, 0xC4, 0xC4, 0xCA, 0xCA, 0x99, 0x93, 0x93, 0x99, 0xFB, 0x93, 0x68, 0x37, 0x99, 0xC4, 0x68, 0xC4, 0x37, 0x00, 0xFB, 0xFB, 0x00, 0x62, 0xCA, 0x93, 0x93, 0x99, 0x99, 0xC4, 0xC4, 0xCA, 0xCA, 0xCA, 0x99, 0xC4, 0xC4, 0x68, 0xFB, 0x9A, 0x62, 0x62, 0x68, 0xC4, 0x62, 0x93, 0x37, 0x00, 0xFB, 0xFB, 0x00, 0x68, 0xFB, 0x68, 0x93, 0x99, 0x99, 0x99, 0xC4, 0xCA, 0xCA, 0x99, 0x93, 0xC4, 0x99, 0x62, 0xCA, 0xCA, 0x99, 0x93, 0x38, 0x68, 0x38, 0x68, 0x31, 0x00, 0xFB, 0xFB, 0x00, 0x68, 0xFB, 0x68, 0x93, 0x93, 0x99, 0x99, 0x99, 0xC4, 0xCA, 0x99, 0x37, 0x68, 0x99, 0xCA, 0x94, 0x64, 0x64, 0x6A, 0xC5, 0xC4, 0x38, 0x62, 0x31, 0x00, 0xFB, 0xFB, 0x00, 0x62, 0xF5, 0x68, 0x93, 0x93, 0x93, 0x99, 0xC4, 0xCA, 0xCA, 0xCA, 0x31, 0x99, 0x9B, 0x34, 0x34, 0x3A, 0x3A, 0x3A, 0x34, 0x64, 0xCA, 0x62, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x62, 0xCA, 0x93, 0x93, 0x93, 0x99, 0xC4, 0xCA, 0xCA, 0xCA, 0xFB, 0xCA, 0x9B, 0x34, 0x3A, 0x3A, 0x3A, 0x3A, 0x3A, 0x64, 0x3A, 0x3A, 0x9A, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x37, 0x99, 0x99, 0x93, 0x99, 0x99, 0x99, 0x99, 0x99, 0xCA, 0xCB, 0xF5, 0x34, 0x64, 0xF5, 0xF5, 0x3B, 0x3B, 0x9B, 0xFB, 0x95, 0x34, 0x95, 0x31, 0x00, 0xFB, 0xFB, 0x00, 0x31, 0x93, 0xCA, 0x69, 0x93, 0x99, 0x99, 0x99, 0xC4, 0xCA, 0xCA, 0x9B, 0x3A, 0x3B, 0xF5, 0xFB, 0xF5, 0x9B, 0xFB, 0xFB, 0x6A, 0x3A, 0x3A, 0x93, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x62, 0xCA, 0x93, 0x93, 0x93, 0x93, 0x99, 0xC4, 0xCA, 0xCA, 0x65, 0x3B, 0x3B, 0x3B, 0xCB, 0xFB, 0xFB, 0xFB, 0x6A, 0x35, 0x3B, 0x35, 0xC4, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x37, 0x93, 0xCA, 0x68, 0x93, 0x93, 0x99, 0xC4, 0xC4, 0xCA, 0x65, 0x3B, 0x11, 0x0B, 0x9B, 0xFB, 0xFB, 0xFB, 0x0B, 0x0B, 0x3B, 0x35, 0xC4, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x62, 0xC4, 0x99, 0x92, 0x93, 0x99, 0x99, 0x99, 0xCA, 0x6B, 0x3B, 0x0B, 0x71, 0xFB, 0xFB, 0xFB, 0xFB, 0xCB, 0x11, 0x0B, 0x35, 0x9A, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x31, 0x62, 0xC4, 0x99, 0x68, 0x93, 0x99, 0x99, 0x99, 0xCB, 0x0B, 0x3B, 0xFB, 0xFB, 0x6A, 0x11, 0xCB, 0xFB, 0x9B, 0x0B, 0x65, 0x62, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x37, 0x62, 0x99, 0xCA, 0x99, 0x93, 0x93, 0x99, 0xFB, 0x3B, 0x0B, 0x6B, 0x6A, 0x11, 0x11, 0x11, 0x9B, 0x0A, 0x0B, 0xCB, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x62, 0x62, 0x99, 0xCA, 0xCA, 0xCA, 0x99, 0xCB, 0x3B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x0B, 0x9B, 0x31, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x62, 0x62, 0x37, 0x37, 0x37, 0x38, 0x62, 0xCA, 0x9B, 0x3B, 0x0B, 0x0B, 0x0B, 0x6B, 0xCB, 0x31, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x31, 0x31, 0x31, 0x31, 0x06, 0x00, 0x31, 0x99, 0xCA, 0xCA, 0x9A, 0x62, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xD7, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xD7, 0xD7, 0xD7, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xD7, 0xD7}; const uint8_t mute_on_img[] = { 0xD7, 0xD7, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xD7, 0xD7, 0xD7, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xD7, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x62, 0x68, 0x68, 0x62, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x68, 0x93, 0x93, 0x69, 0x93, 0x93, 0x93, 0x68, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x31, 0x93, 0x68, 0x99, 0xC4, 0xCA, 0xC4, 0x99, 0x68, 0x69, 0x68, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x31, 0x93, 0x93, 0xCB, 0xFB, 0xCA, 0xCA, 0xCA, 0xFB, 0xFB, 0x99, 0x68, 0x68, 0x62, 0x37, 0x68, 0x62, 0x68, 0x31, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x93, 0x99, 0xFB, 0xC4, 0x93, 0x68, 0x93, 0x93, 0x99, 0xCA, 0xFB, 0xC4, 0x68, 0x68, 0x62, 0x62, 0x93, 0x68, 0x99, 0x62, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x38, 0x93, 0xFB, 0x99, 0x68, 0x93, 0x99, 0x99, 0x99, 0x99, 0x99, 0xC4, 0xFB, 0xC4, 0x68, 0x68, 0x31, 0x99, 0x93, 0x68, 0x99, 0x31, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x68, 0xCA, 0xC4, 0x68, 0x93, 0x99, 0x99, 0x99, 0x9A, 0xC4, 0xC4, 0x99, 0xCA, 0xFB, 0x93, 0x68, 0x62, 0x62, 0x99, 0x68, 0x99, 0x93, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x31, 0x93, 0xF5, 0x68, 0x93, 0x99, 0x99, 0x99, 0xC4, 0xC4, 0xC4, 0xCA, 0x99, 0x68, 0xCA, 0xCA, 0x62, 0x68, 0x31, 0x99, 0x93, 0x93, 0x99, 0x31, 0x00, 0xFB, 0xFB, 0x00, 0x62, 0x99, 0xC4, 0x69, 0x93, 0x99, 0x99, 0xC4, 0xC4, 0xCA, 0xCA, 0x99, 0x93, 0x93, 0x99, 0xFB, 0x93, 0x68, 0x37, 0x99, 0xC4, 0x68, 0xC4, 0x37, 0x00, 0xFB, 0xFB, 0x00, 0x62, 0xCA, 0x93, 0x93, 0x99, 0x99, 0xC4, 0xC4, 0xCA, 0xCA, 0xCA, 0x99, 0xC4, 0xC4, 0x68, 0xFB, 0x9A, 0x62, 0x62, 0x68, 0xC4, 0x62, 0x93, 0x37, 0x00, 0xFB, 0xFB, 0x00, 0x68, 0xFB, 0x68, 0x93, 0x99, 0x99, 0x99, 0xC4, 0xCA, 0xCA, 0x99, 0x93, 0xC4, 0x99, 0x62, 0xCA, 0xCA, 0x62, 0x62, 0x31, 0x68, 0x38, 0x68, 0x31, 0x00, 0xFB, 0xFB, 0x00, 0x68, 0xFB, 0x68, 0x93, 0x93, 0x99, 0x99, 0x99, 0xC4, 0xCA, 0x99, 0x37, 0x68, 0x62, 0x31, 0x99, 0xFB, 0x62, 0x62, 0x31, 0x62, 0x37, 0x62, 0x31, 0x00, 0xFB, 0xFB, 0x00, 0x62, 0xF5, 0x68, 0x93, 0x93, 0x93, 0x99, 0xC4, 0xCA, 0xCA, 0xCA, 0x31, 0x31, 0x31, 0x31, 0x93, 0xFB, 0x62, 0x62, 0x31, 0x62, 0x31, 0x62, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x62, 0xCA, 0x93, 0x93, 0x93, 0x99, 0xC4, 0xCA, 0xCA, 0xCA, 0xFB, 0x99, 0x31, 0x31, 0x31, 0x93, 0xFB, 0x62, 0x62, 0x31, 0x38, 0x31, 0x31, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x37, 0x99, 0x99, 0x93, 0x99, 0x99, 0x99, 0x99, 0x99, 0xCA, 0xCB, 0xF5, 0xCA, 0x69, 0x68, 0x99, 0xF5, 0x62, 0x62, 0x31, 0x31, 0x31, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x31, 0x93, 0xCA, 0x69, 0x93, 0x99, 0x99, 0x99, 0xC4, 0xCA, 0xCA, 0xCA, 0xCA, 0xCA, 0xCA, 0xCA, 0xC4, 0x62, 0x37, 0x31, 0x06, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x62, 0xCA, 0x93, 0x93, 0x93, 0x93, 0x99, 0xC4, 0xCA, 0xCA, 0xCA, 0xCA, 0xCA, 0x99, 0xFB, 0x93, 0x62, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x37, 0x93, 0xCA, 0x68, 0x93, 0x93, 0x99, 0xC4, 0xC4, 0xC4, 0xC4, 0xC4, 0xC4, 0xC4, 0xF5, 0x62, 0x62, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x62, 0xC4, 0x99, 0x92, 0x93, 0x99, 0x99, 0x99, 0x99, 0xC4, 0x99, 0x99, 0xF5, 0x93, 0x62, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x31, 0x62, 0xC4, 0x99, 0x68, 0x93, 0x99, 0x99, 0x99, 0x99, 0x99, 0xCA, 0x99, 0x37, 0x37, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x37, 0x62, 0x99, 0xCA, 0x99, 0x93, 0x93, 0x99, 0xC4, 0xF5, 0x99, 0x37, 0x37, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x37, 0x62, 0x62, 0x99, 0xCA, 0xCA, 0xCA, 0x99, 0x62, 0x37, 0x37, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x31, 0x62, 0x62, 0x37, 0x37, 0x37, 0x38, 0x37, 0x31, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, 0x31, 0x31, 0x31, 0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xD7, 0xFB, 0xFB, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFB, 0xFB, 0xD7, 0xD7, 0xD7, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xFB, 0xD7, 0xD7}; const ImageDesc mute_img[] = { {28, 28, 8, {.img8 = mute_off_img}, PALETTE_676, PALETTE_676[0xD7]}, {28, 28, 8, {.img8 = mute_on_img}, PALETTE_676, PALETTE_676[0xD7]}}; // ***************************************************************************** // *** Constructor ********************************************************* // ***************************************************************************** SoundControlBox::SoundControlBox(int32_t x, int32_t y, bool mute_flag) : Image(x, y, mute_img[0]) { // Store mute flag mute = mute_flag; // If mute is false - update image if(mute == false) { SetImage(mute_img[0]); } sound_drv.Mute(mute); // This object is active active = true; } // ***************************************************************************** // *** Action ************************************************************** // ***************************************************************************** void SoundControlBox::Action(VisObject::ActionType action, int32_t tx, int32_t ty) { // Switch for process action switch(action) { // Touch action case VisObject::ACT_TOUCH: // Change checked state mute = !mute; // Update image if(mute == true) { SetImage(mute_img[0], true); // Don't take semaphore - already taken } else { SetImage(mute_img[1], true); // Don't take semaphore - already taken } // Mute control sound_drv.Mute(mute); break; // Untouch action case VisObject::ACT_UNTOUCH: break; default: break; } }
[ "nicolai.shlapunov@gmail.com" ]
nicolai.shlapunov@gmail.com
9dbf5e93ae8dc636f6501051b9aebce7e4d2da32
c7d3981d3250c1df0ea0afb15a17aec2a3dfcbdc
/src/MainAgents/TargetingAgent.cpp
67a8db7aa7048e3b4f319f5401803b850cf5b630
[ "MIT" ]
permissive
kvakvs/RazeAndPlunder
5af4921c69b3e724f4b9bde76ed1828bef040dc9
f75980a979ecc0f04a9dce5724c54eec9f989348
refs/heads/master
2020-05-24T23:10:39.895635
2017-04-06T22:37:19
2017-04-06T22:37:19
84,888,368
5
1
null
null
null
null
UTF-8
C++
false
false
5,948
cpp
#include "TargetingAgent.h" #include <iso646.h> using namespace BWAPI; bool TargetingAgent::can_attack(UnitType type) { if (type.isBuilding()) { if (type.canAttack()) return true; return false; } if (type.isAddon()) { return false; } if (type.isWorker()) { return false; } return true; } int TargetingAgent::get_no_attackers(const BaseAgent* agent) { int cnt = 0; for (auto& u : Broodwar->enemy()->getUnits()) { if (can_attack(u->getType())) { int enemyMSD = 0; if (agent->unit_type().isFlyer()) { enemyMSD = u->getType().airWeapon().maxRange(); } else { enemyMSD = u->getType().groundWeapon().maxRange(); } double d = agent->get_unit()->getPosition().getDistance(u->getPosition()); if (d <= enemyMSD) { cnt++; } } } return cnt; } bool TargetingAgent::check_target(const BaseAgent* agent) { if (not agent->get_unit()->isIdle() && not agent->get_unit()->isMoving()) return false; Unit pTarget = find_target(agent); if (pTarget != nullptr && pTarget->getPlayer()->isEnemy(Broodwar->self())) { bool ok = agent->get_unit()->attack(pTarget, true); if (not ok) { //Broodwar << "Switch target failed: " << Broodwar->getLastError() << endl; } return ok; } return false; } bool TargetingAgent::is_highprio_target(UnitType type) { if (type.getID() == UnitTypes::Terran_Bunker.getID()) return true; if (type.getID() == UnitTypes::Terran_Battlecruiser.getID()) return true; if (type.getID() == UnitTypes::Terran_Missile_Turret.getID()) return true; if (type.getID() == UnitTypes::Protoss_Carrier.getID()) return true; if (type.getID() == UnitTypes::Protoss_Photon_Cannon.getID()) return true; if (type.getID() == UnitTypes::Protoss_Archon.getID()) return true; if (type.getID() == UnitTypes::Zerg_Sunken_Colony.getID()) return true; if (type.getID() == UnitTypes::Zerg_Spore_Colony.getID()) return true; if (type.getID() == UnitTypes::Zerg_Ultralisk.getID()) return true; return false; } Unit TargetingAgent::find_highprio_target(const BaseAgent* agent, int maxDist, bool targetsAir, bool targetsGround) { Unit target = nullptr; Position cPos = agent->get_unit()->getPosition(); int bestTargetScore = -10000; for (auto& u : Broodwar->enemy()->getUnits()) { if (u->exists()) { UnitType t = u->getType(); bool targets = is_highprio_target(t); if (t.isFlyer() && not targetsAir) targets = false; if (not t.isFlyer() && not targetsGround) targets = false; if (targets) { double dist = cPos.getDistance(u->getPosition()); if (dist <= (double)maxDist) { if (t.destroyScore() > bestTargetScore) { target = u; bestTargetScore = t.destroyScore(); } } } } } return target; } Unit TargetingAgent::find_target(const BaseAgent* agent) { //Check if the agent targets ground and/or air bool targetsGround = agent->can_target_ground(); bool targetsAir = agent->can_target_air(); //Iterate through enemies to select a target int bestTargetScore = -10000; Unit target = nullptr; for (auto& u : Broodwar->enemy()->getUnits()) { UnitType t = u->getType(); bool canAttack = false; if (not t.isFlyer() && targetsGround) canAttack = true; if ((t.isFlyer() || u->isLifted()) && targetsAir) canAttack = true; if (u->isCloaked() && not u->isDetected()) { canAttack = false; handle_cloaked_unit(u); } if (u->isBurrowed() && not u->isDetected()) { canAttack = false; handle_cloaked_unit(u); } int maxRange = 600; if (agent->get_unit()->isSieged() || agent->get_unit()->isBurrowed() || agent->get_unit()->isLoaded()) maxRange = agent->unit_type().groundWeapon().maxRange(); if (canAttack && agent->get_unit()->getPosition().getDistance(u->getPosition()) <= maxRange) { double mod = get_target_modifier(agent->get_unit()->getType(), t); int cScore = (int)((double)t.destroyScore() * mod); if (u->getHitPoints() < u->getInitialHitPoints()) { //Prioritize damaged targets cScore++; } if (cScore > bestTargetScore) { bestTargetScore = cScore; target = u; } } } return target; } double TargetingAgent::get_target_modifier(UnitType attacker, UnitType target) { //Non-attacking buildings if (target.isBuilding() && not target.canAttack() && not target.getID() == UnitTypes::Terran_Bunker.getID()) { return 0.05; } //Terran Goliath prefer air targets if (attacker.getID() == UnitTypes::Terran_Goliath.getID()) { if (target.isFlyer()) return 2; } //Siege Tanks prefer to take out enemy defense buildings if (attacker.getID() == UnitTypes::Terran_Siege_Tank_Siege_Mode.getID()) { if (target.isBuilding() && target.canAttack()) return 1.5; if (target.getID() == UnitTypes::Terran_Bunker.getID()) return 1.5; } //Siege Tanks are nasty and have high prio to be killed. if (target.getID() == UnitTypes::Terran_Siege_Tank_Siege_Mode.getID()) { return 1.5; } //Prio to take out detectors when having cloaking units if (is_cloaking_unit(attacker) && target.isDetector()) { return 2; } if (attacker.isFlyer() && not target.airWeapon().targetsAir()) { //Target cannot attack back. Set to low prio return 0.1; } if (not attacker.isFlyer() && not target.groundWeapon().targetsGround()) { //Target cannot attack back. Set to low prio return 0.1; } if (target.isWorker()) { //Workers are important but very weak units return 3; } return 1; //Default: No modifier } void TargetingAgent::handle_cloaked_unit(Unit unit) { //Terran: Cloaked units are handled by ComSat agent //Add code for handling cloaked units here. } bool TargetingAgent::is_cloaking_unit(UnitType type) { if (type.isCloakable()) return true; return false; }
[ "dmytro.lytovchenko@gmail.com" ]
dmytro.lytovchenko@gmail.com
227f4a0e1f20915139e90fce0d5cdd828c2f3477
dee3d3d6e50bcbf444b4069922dac356698c3782
/src/qt/walletmodel.h
fca36026c7b1701b15ce89a1e93384604914c6fe
[ "MIT" ]
permissive
darknetpay/darknet
68cc0a9fa9e580cb0fa3b5bfbe0890888dcf94df
cb84a55d87c7f0b4b37fbd85d7b1baa58b9b743f
refs/heads/master
2020-03-22T07:11:26.139198
2018-07-04T08:29:11
2018-07-04T08:29:11
139,684,124
0
0
MIT
2018-07-04T08:29:12
2018-07-04T07:20:52
C++
UTF-8
C++
false
false
10,033
h
// Copyright (c) 2011-2014 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_WALLETMODEL_H #define BITCOIN_QT_WALLETMODEL_H #include "paymentrequestplus.h" #include "walletmodeltransaction.h" #include "allocators.h" /* for SecureString */ #include "swifttx.h" #include "wallet.h" #include <map> #include <vector> #include <QObject> class AddressTableModel; class OptionsModel; class RecentRequestsTableModel; class TransactionTableModel; class WalletModelTransaction; class CCoinControl; class CKeyID; class COutPoint; class COutput; class CPubKey; class CWallet; class uint256; QT_BEGIN_NAMESPACE class QTimer; QT_END_NAMESPACE class SendCoinsRecipient { public: explicit SendCoinsRecipient() : amount(0), nVersion(SendCoinsRecipient::CURRENT_VERSION) { } explicit SendCoinsRecipient(const QString &addr, const QString &label, const CAmount& amount, const QString &message): address(addr), label(label), amount(amount), message(message), nVersion(SendCoinsRecipient::CURRENT_VERSION) {} // If from an insecure payment request, this is used for storing // the addresses, e.g. address-A<br />address-B<br />address-C. // Info: As we don't need to process addresses in here when using // payment requests, we can abuse it for displaying an address list. // Todo: This is a hack, should be replaced with a cleaner solution! QString address; QString label; AvailableCoinsType inputType; bool useSwiftTX; CAmount amount; // If from a payment request, this is used for storing the memo QString message; // If from a payment request, paymentRequest.IsInitialized() will be true PaymentRequestPlus paymentRequest; // Empty if no authentication or invalid signature/cert/etc. QString authenticatedMerchant; static const int CURRENT_VERSION = 1; int nVersion; ADD_SERIALIZE_METHODS; template <typename Stream, typename Operation> inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { std::string sAddress = address.toStdString(); std::string sLabel = label.toStdString(); std::string sMessage = message.toStdString(); std::string sPaymentRequest; if (!ser_action.ForRead() && paymentRequest.IsInitialized()) paymentRequest.SerializeToString(&sPaymentRequest); std::string sAuthenticatedMerchant = authenticatedMerchant.toStdString(); READWRITE(this->nVersion); nVersion = this->nVersion; READWRITE(sAddress); READWRITE(sLabel); READWRITE(amount); READWRITE(sMessage); READWRITE(sPaymentRequest); READWRITE(sAuthenticatedMerchant); if (ser_action.ForRead()) { address = QString::fromStdString(sAddress); label = QString::fromStdString(sLabel); message = QString::fromStdString(sMessage); if (!sPaymentRequest.empty()) paymentRequest.parse(QByteArray::fromRawData(sPaymentRequest.data(), sPaymentRequest.size())); authenticatedMerchant = QString::fromStdString(sAuthenticatedMerchant); } } }; /** Interface to Bitcoin wallet from Qt view code. */ class WalletModel : public QObject { Q_OBJECT public: explicit WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent = 0); ~WalletModel(); enum StatusCode // Returned by sendCoins { OK, InvalidAmount, InvalidAddress, AmountExceedsBalance, AmountWithFeeExceedsBalance, DuplicateAddress, TransactionCreationFailed, // Error returned when wallet is still locked TransactionCommitFailed, AnonymizeOnlyUnlocked, InsaneFee }; enum EncryptionStatus { Unencrypted, // !wallet->IsCrypted() Locked, // wallet->IsCrypted() && wallet->IsLocked() Unlocked, // wallet->IsCrypted() && !wallet->IsLocked() UnlockedForAnonymizationOnly // wallet->IsCrypted() && !wallet->IsLocked() && wallet->fWalletUnlockAnonymizeOnly }; OptionsModel *getOptionsModel(); AddressTableModel *getAddressTableModel(); TransactionTableModel *getTransactionTableModel(); RecentRequestsTableModel *getRecentRequestsTableModel(); CAmount getBalance(const CCoinControl *coinControl = NULL) const; CAmount getUnconfirmedBalance() const; CAmount getImmatureBalance() const; CAmount getAnonymizedBalance() const; bool haveWatchOnly() const; CAmount getWatchBalance() const; CAmount getWatchUnconfirmedBalance() const; CAmount getWatchImmatureBalance() const; EncryptionStatus getEncryptionStatus() const; // Check address for validity bool validateAddress(const QString &address); // Return status record for SendCoins, contains error id + information struct SendCoinsReturn { SendCoinsReturn(StatusCode status = OK): status(status) {} StatusCode status; }; // prepare transaction for getting txfee before sending coins SendCoinsReturn prepareTransaction(WalletModelTransaction &transaction, const CCoinControl *coinControl = NULL); // Send coins to a list of recipients SendCoinsReturn sendCoins(WalletModelTransaction &transaction); // Wallet encryption bool setWalletEncrypted(bool encrypted, const SecureString &passphrase); // Passphrase only needed when unlocking bool setWalletLocked(bool locked, const SecureString &passPhrase=SecureString(), bool anonymizeOnly=false); bool changePassphrase(const SecureString &oldPass, const SecureString &newPass); // Is wallet unlocked for anonymization only? bool isAnonymizeOnlyUnlocked(); // Wallet backup bool backupWallet(const QString &filename); // RAI object for unlocking wallet, returned by requestUnlock() class UnlockContext { public: UnlockContext(WalletModel *wallet, bool valid, bool relock); ~UnlockContext(); bool isValid() const { return valid; } // Copy operator and constructor transfer the context UnlockContext(const UnlockContext& obj) { CopyFrom(obj); } UnlockContext& operator=(const UnlockContext& rhs) { CopyFrom(rhs); return *this; } private: WalletModel *wallet; bool valid; mutable bool relock; // mutable, as it can be set to false by copying void CopyFrom(const UnlockContext& rhs); }; UnlockContext requestUnlock(bool relock); bool getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const; void getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs); bool isSpent(const COutPoint& outpoint) const; void listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const; bool isLockedCoin(uint256 hash, unsigned int n) const; void lockCoin(COutPoint& output); void unlockCoin(COutPoint& output); void listLockedCoins(std::vector<COutPoint>& vOutpts); void loadReceiveRequests(std::vector<std::string>& vReceiveRequests); bool saveReceiveRequest(const std::string &sAddress, const int64_t nId, const std::string &sRequest); private: CWallet *wallet; bool fHaveWatchOnly; bool fForceCheckBalanceChanged; // Wallet has an options model for wallet-specific options // (transaction fee, for example) OptionsModel *optionsModel; AddressTableModel *addressTableModel; TransactionTableModel *transactionTableModel; RecentRequestsTableModel *recentRequestsTableModel; // Cache some values to be able to detect changes CAmount cachedBalance; CAmount cachedUnconfirmedBalance; CAmount cachedImmatureBalance; CAmount cachedAnonymizedBalance; CAmount cachedWatchOnlyBalance; CAmount cachedWatchUnconfBalance; CAmount cachedWatchImmatureBalance; EncryptionStatus cachedEncryptionStatus; int cachedNumBlocks; int cachedTxLocks; int cachedObfuscateRounds; QTimer *pollTimer; void subscribeToCoreSignals(); void unsubscribeFromCoreSignals(); void checkBalanceChanged(); signals: // Signal that balance in wallet changed void balanceChanged(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance, const CAmount& anonymizedBalance, const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance); // Encryption status of wallet changed void encryptionStatusChanged(int status); // Signal emitted when wallet needs to be unlocked // It is valid behaviour for listeners to keep the wallet locked after this signal; // this means that the unlocking failed or was cancelled. void requireUnlock(); // Fired when a message should be reported to the user void message(const QString &title, const QString &message, unsigned int style); // Coins sent: from wallet, to recipient, in (serialized) transaction: void coinsSent(CWallet* wallet, SendCoinsRecipient recipient, QByteArray transaction); // Show progress dialog e.g. for rescan void showProgress(const QString &title, int nProgress); // Watch-only address added void notifyWatchonlyChanged(bool fHaveWatchonly); public slots: /* Wallet status might have changed */ void updateStatus(); /* New transaction, or transaction changed status */ void updateTransaction(); /* New, updated or removed address book entry */ void updateAddressBook(const QString &address, const QString &label, bool isMine, const QString &purpose, int status); /* Watch-only added */ void updateWatchOnlyFlag(bool fHaveWatchonly); /* Current, immature or unconfirmed balance might have changed - emit 'balanceChanged' if so */ void pollBalanceChanged(); }; #endif // BITCOIN_QT_WALLETMODEL_H
[ "sano.86@inbox.ru" ]
sano.86@inbox.ru
c2e758e3534e70310d1b28dd87bdbd16ff4f52b7
842777e5789c4501718e8288bd6f5e121325f100
/des/DES/GAME2.cpp
8f7aebadf557b3fe9dda797dc478bdc613f3a79f
[]
no_license
ShadowDL/project
611db2f14739b934f0a25a0af182d2439728781f
a5b7b5673efbdfad5990a8c08003d413e9e786c1
refs/heads/master
2021-01-01T04:12:22.790188
2016-05-07T10:32:29
2016-05-07T10:32:29
56,066,668
0
0
null
null
null
null
GB18030
C++
false
false
2,546
cpp
// GAME2.cpp : implementation file // #include "stdafx.h" #include "DES.h" #include "GAME2.h" #include "GAME3.h" #include "GAME.h" #include "ORRECT.h" #include "ERR1.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // GAME2 dialog GAME2::GAME2(CWnd* pParent /*=NULL*/) : CDialog(GAME2::IDD, pParent) , Num(0) { //{{AFX_DATA_INIT(GAME2) // NOTE: the ClassWizard will add member initialization here //}}AFX_DATA_INIT m_edit1 = _T(""); m_edit2 = _T(""); m_edit3 = _T(""); } void GAME2::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(GAME2) // NOTE: the ClassWizard will add DDX and DDV calls here //}}AFX_DATA_MAP DDX_Text(pDX, IDC_EDIT1, m_edit1); DDX_Text(pDX, IDC_EDIT2, m_edit2); DDX_Text(pDX, IDC_EDIT3, m_edit3); } BEGIN_MESSAGE_MAP(GAME2, CDialog) //{{AFX_MSG_MAP(GAME2) ON_BN_CLICKED(IDC_BUTTON1, OnButton1) //}}AFX_MSG_MAP ON_BN_CLICKED(IDC_BUTTON3, &GAME2::OnBnClickedButton3) ON_EN_CHANGE(IDC_EDIT1, &GAME2::OnEnChangeEdit1) ON_EN_CHANGE(IDC_EDIT2, &GAME2::OnEnChangeEdit2) ON_EN_CHANGE(IDC_EDIT3, &GAME2::OnEnChangeEdit3) ON_BN_CLICKED(IDC_BUTTON2, &GAME2::OnBnClickedButton2) ON_WM_CTLCOLOR() END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // GAME2 message handlers void GAME2::OnButton1() { EndDialog(IDCANCEL); GAME dlg; dlg.DoModal(); // TODO: Add your control notification handler code here } void GAME2::OnBnClickedButton3() { EndDialog(IDCANCEL); GAME3 dlg; dlg.DoModal(); // TODO: 在此添加控件通知处理程序代码 } void GAME2::OnEnChangeEdit1() { GetDlgItemText(IDC_EDIT1,m_edit1); } void GAME2::OnEnChangeEdit2() { GetDlgItemText(IDC_EDIT2,m_edit2); } void GAME2::OnEnChangeEdit3() { GetDlgItemText(IDC_EDIT3,m_edit3); } void GAME2::OnBnClickedButton2() { if(m_edit1=="16" && m_edit2 =="9" && m_edit3 =="19" ) { CORRECT dlg; dlg.DoModal(); } else { ERR1 dlg; dlg.DoModal(); } // TODO: 在此添加控件通知处理程序代码 } HBRUSH GAME2::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor); if( nCtlColor == CTLCOLOR_STATIC) { pDC->SetBkMode(TRANSPARENT); return HBRUSH(GetStockObject(HOLLOW_BRUSH)); } // TODO: 在此更改 DC 的任何特性 // TODO: 如果默认的不是所需画笔,则返回另一个画笔 return hbr; }
[ "smile005400@163.com" ]
smile005400@163.com
4436fa59e045c680efebde49e3fd34e6376bf30e
cb77dcbbce6c480f68c3dcb8610743f027bee95c
/android/art/test/ti-agent/jvmti_helper.cc
bceaa6b64ba399909b27fc5776cd0085c699ff08
[ "Apache-2.0", "NCSA", "MIT" ]
permissive
fengjixuchui/deoptfuscator
c888b93361d837ef619b9eb95ffd4b01a4bef51a
dec8fbf2b59f8dddf2dbd10868726b255364e1c5
refs/heads/master
2023-03-17T11:49:00.988260
2023-03-09T02:01:47
2023-03-09T02:01:47
333,074,914
0
0
MIT
2023-03-09T02:01:48
2021-01-26T12:16:31
null
UTF-8
C++
false
false
9,167
cc
/* * Copyright (C) 2017 The Android Open Source Project * * 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 "jvmti_helper.h" #include "test_env.h" #include <dlfcn.h> #include <algorithm> #include <cstdio> #include <cstring> #include <sstream> #include "android-base/logging.h" #include "scoped_local_ref.h" namespace art { void CheckJvmtiError(jvmtiEnv* env, jvmtiError error) { if (error != JVMTI_ERROR_NONE) { char* error_name; jvmtiError name_error = env->GetErrorName(error, &error_name); if (name_error != JVMTI_ERROR_NONE) { LOG(FATAL) << "Unable to get error name for " << error; } LOG(FATAL) << "Unexpected error: " << error_name; } } // These are a set of capabilities we will enable in all situations. These are chosen since they // will not affect the runtime in any significant way if they are enabled. static const jvmtiCapabilities standard_caps = { .can_tag_objects = 1, .can_generate_field_modification_events = 1, .can_generate_field_access_events = 1, .can_get_bytecodes = 1, .can_get_synthetic_attribute = 1, .can_get_owned_monitor_info = 0, .can_get_current_contended_monitor = 1, .can_get_monitor_info = 1, .can_pop_frame = 0, .can_redefine_classes = 1, .can_signal_thread = 1, .can_get_source_file_name = 1, .can_get_line_numbers = 1, .can_get_source_debug_extension = 1, .can_access_local_variables = 0, .can_maintain_original_method_order = 1, .can_generate_single_step_events = 1, .can_generate_exception_events = 0, .can_generate_frame_pop_events = 0, .can_generate_breakpoint_events = 1, .can_suspend = 1, .can_redefine_any_class = 0, .can_get_current_thread_cpu_time = 0, .can_get_thread_cpu_time = 0, .can_generate_method_entry_events = 1, .can_generate_method_exit_events = 1, .can_generate_all_class_hook_events = 0, .can_generate_compiled_method_load_events = 0, .can_generate_monitor_events = 0, .can_generate_vm_object_alloc_events = 1, .can_generate_native_method_bind_events = 1, .can_generate_garbage_collection_events = 1, .can_generate_object_free_events = 1, .can_force_early_return = 0, .can_get_owned_monitor_stack_depth_info = 0, .can_get_constant_pool = 0, .can_set_native_method_prefix = 0, .can_retransform_classes = 1, .can_retransform_any_class = 0, .can_generate_resource_exhaustion_heap_events = 0, .can_generate_resource_exhaustion_threads_events = 0, }; jvmtiCapabilities GetStandardCapabilities() { return standard_caps; } void SetStandardCapabilities(jvmtiEnv* env) { if (IsJVM()) { // RI is more strict about adding capabilities at runtime then ART so just give it everything. SetAllCapabilities(env); return; } jvmtiCapabilities caps = GetStandardCapabilities(); CheckJvmtiError(env, env->AddCapabilities(&caps)); } void SetAllCapabilities(jvmtiEnv* env) { jvmtiCapabilities caps; CheckJvmtiError(env, env->GetPotentialCapabilities(&caps)); CheckJvmtiError(env, env->AddCapabilities(&caps)); } bool JvmtiErrorToException(JNIEnv* env, jvmtiEnv* jvmtienv, jvmtiError error) { if (error == JVMTI_ERROR_NONE) { return false; } ScopedLocalRef<jclass> rt_exception(env, env->FindClass("java/lang/RuntimeException")); if (rt_exception.get() == nullptr) { // CNFE should be pending. return true; } char* err; CheckJvmtiError(jvmtienv, jvmtienv->GetErrorName(error, &err)); env->ThrowNew(rt_exception.get(), err); Deallocate(jvmtienv, err); return true; } std::ostream& operator<<(std::ostream& os, const jvmtiError& rhs) { switch (rhs) { case JVMTI_ERROR_NONE: return os << "NONE"; case JVMTI_ERROR_INVALID_THREAD: return os << "INVALID_THREAD"; case JVMTI_ERROR_INVALID_THREAD_GROUP: return os << "INVALID_THREAD_GROUP"; case JVMTI_ERROR_INVALID_PRIORITY: return os << "INVALID_PRIORITY"; case JVMTI_ERROR_THREAD_NOT_SUSPENDED: return os << "THREAD_NOT_SUSPENDED"; case JVMTI_ERROR_THREAD_SUSPENDED: return os << "THREAD_SUSPENDED"; case JVMTI_ERROR_THREAD_NOT_ALIVE: return os << "THREAD_NOT_ALIVE"; case JVMTI_ERROR_INVALID_OBJECT: return os << "INVALID_OBJECT"; case JVMTI_ERROR_INVALID_CLASS: return os << "INVALID_CLASS"; case JVMTI_ERROR_CLASS_NOT_PREPARED: return os << "CLASS_NOT_PREPARED"; case JVMTI_ERROR_INVALID_METHODID: return os << "INVALID_METHODID"; case JVMTI_ERROR_INVALID_LOCATION: return os << "INVALID_LOCATION"; case JVMTI_ERROR_INVALID_FIELDID: return os << "INVALID_FIELDID"; case JVMTI_ERROR_NO_MORE_FRAMES: return os << "NO_MORE_FRAMES"; case JVMTI_ERROR_OPAQUE_FRAME: return os << "OPAQUE_FRAME"; case JVMTI_ERROR_TYPE_MISMATCH: return os << "TYPE_MISMATCH"; case JVMTI_ERROR_INVALID_SLOT: return os << "INVALID_SLOT"; case JVMTI_ERROR_DUPLICATE: return os << "DUPLICATE"; case JVMTI_ERROR_NOT_FOUND: return os << "NOT_FOUND"; case JVMTI_ERROR_INVALID_MONITOR: return os << "INVALID_MONITOR"; case JVMTI_ERROR_NOT_MONITOR_OWNER: return os << "NOT_MONITOR_OWNER"; case JVMTI_ERROR_INTERRUPT: return os << "INTERRUPT"; case JVMTI_ERROR_INVALID_CLASS_FORMAT: return os << "INVALID_CLASS_FORMAT"; case JVMTI_ERROR_CIRCULAR_CLASS_DEFINITION: return os << "CIRCULAR_CLASS_DEFINITION"; case JVMTI_ERROR_FAILS_VERIFICATION: return os << "FAILS_VERIFICATION"; case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_ADDED: return os << "UNSUPPORTED_REDEFINITION_METHOD_ADDED"; case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED: return os << "UNSUPPORTED_REDEFINITION_SCHEMA_CHANGED"; case JVMTI_ERROR_INVALID_TYPESTATE: return os << "INVALID_TYPESTATE"; case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED: return os << "UNSUPPORTED_REDEFINITION_HIERARCHY_CHANGED"; case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_DELETED: return os << "UNSUPPORTED_REDEFINITION_METHOD_DELETED"; case JVMTI_ERROR_UNSUPPORTED_VERSION: return os << "UNSUPPORTED_VERSION"; case JVMTI_ERROR_NAMES_DONT_MATCH: return os << "NAMES_DONT_MATCH"; case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED: return os << "UNSUPPORTED_REDEFINITION_CLASS_MODIFIERS_CHANGED"; case JVMTI_ERROR_UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED: return os << "UNSUPPORTED_REDEFINITION_METHOD_MODIFIERS_CHANGED"; case JVMTI_ERROR_UNMODIFIABLE_CLASS: return os << "JVMTI_ERROR_UNMODIFIABLE_CLASS"; case JVMTI_ERROR_NOT_AVAILABLE: return os << "NOT_AVAILABLE"; case JVMTI_ERROR_MUST_POSSESS_CAPABILITY: return os << "MUST_POSSESS_CAPABILITY"; case JVMTI_ERROR_NULL_POINTER: return os << "NULL_POINTER"; case JVMTI_ERROR_ABSENT_INFORMATION: return os << "ABSENT_INFORMATION"; case JVMTI_ERROR_INVALID_EVENT_TYPE: return os << "INVALID_EVENT_TYPE"; case JVMTI_ERROR_ILLEGAL_ARGUMENT: return os << "ILLEGAL_ARGUMENT"; case JVMTI_ERROR_NATIVE_METHOD: return os << "NATIVE_METHOD"; case JVMTI_ERROR_CLASS_LOADER_UNSUPPORTED: return os << "CLASS_LOADER_UNSUPPORTED"; case JVMTI_ERROR_OUT_OF_MEMORY: return os << "OUT_OF_MEMORY"; case JVMTI_ERROR_ACCESS_DENIED: return os << "ACCESS_DENIED"; case JVMTI_ERROR_WRONG_PHASE: return os << "WRONG_PHASE"; case JVMTI_ERROR_INTERNAL: return os << "INTERNAL"; case JVMTI_ERROR_UNATTACHED_THREAD: return os << "UNATTACHED_THREAD"; case JVMTI_ERROR_INVALID_ENVIRONMENT: return os << "INVALID_ENVIRONMENT"; } LOG(FATAL) << "Unexpected error type " << static_cast<int>(rhs); __builtin_unreachable(); } } // namespace art
[ "gyoonus@gmail.com" ]
gyoonus@gmail.com
7ccd491c7768a422751ffbae943a07235616424d
186c9244be7d49b01ff630faa7005ba1b0191446
/3rdparty/WebRTC/android/include/webrtc/out/Release/arm64/gen/sdk/android/generated_peerconnection_jni/RtpParameters_jni.h
378f27ce3752e3f3ecfec96bdf51094f5926d162
[ "BSD-3-Clause" ]
permissive
SergeySeroshtan/virgil-webrtc-qt-demo
a7fb9079ed2f98ea39b507445788b37066d38ae1
1c9ebe3893629ad396be6e187657df870b06322b
refs/heads/master
2023-03-15T19:30:57.461814
2020-09-10T17:10:26
2020-09-10T17:10:26
null
0
0
null
null
null
null
UTF-8
C++
false
false
33,947
h
// Copyright 2014 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. // This file is autogenerated by // base/android/jni_generator/jni_generator.py // For // org/webrtc/RtpParameters #ifndef org_webrtc_RtpParameters_JNI #define org_webrtc_RtpParameters_JNI #include <jni.h> #include "../../../../../../../sdk/android/src/jni/jni_generator_helper.h" // Step 1: Forward declarations. JNI_REGISTRATION_EXPORT extern const char kClassPath_org_webrtc_RtpParameters[]; const char kClassPath_org_webrtc_RtpParameters[] = "org/webrtc/RtpParameters"; JNI_REGISTRATION_EXPORT extern const char kClassPath_org_webrtc_RtpParameters_00024DegradationPreference[]; const char kClassPath_org_webrtc_RtpParameters_00024DegradationPreference[] = "org/webrtc/RtpParameters$DegradationPreference"; JNI_REGISTRATION_EXPORT extern const char kClassPath_org_webrtc_RtpParameters_00024Encoding[]; const char kClassPath_org_webrtc_RtpParameters_00024Encoding[] = "org/webrtc/RtpParameters$Encoding"; JNI_REGISTRATION_EXPORT extern const char kClassPath_org_webrtc_RtpParameters_00024Codec[]; const char kClassPath_org_webrtc_RtpParameters_00024Codec[] = "org/webrtc/RtpParameters$Codec"; JNI_REGISTRATION_EXPORT extern const char kClassPath_org_webrtc_RtpParameters_00024Rtcp[]; const char kClassPath_org_webrtc_RtpParameters_00024Rtcp[] = "org/webrtc/RtpParameters$Rtcp"; JNI_REGISTRATION_EXPORT extern const char kClassPath_org_webrtc_RtpParameters_00024HeaderExtension[]; const char kClassPath_org_webrtc_RtpParameters_00024HeaderExtension[] = "org/webrtc/RtpParameters$HeaderExtension"; // Leaking this jclass as we cannot use LazyInstance from some threads. JNI_REGISTRATION_EXPORT std::atomic<jclass> g_org_webrtc_RtpParameters_clazz(nullptr); #ifndef org_webrtc_RtpParameters_clazz_defined #define org_webrtc_RtpParameters_clazz_defined inline jclass org_webrtc_RtpParameters_clazz(JNIEnv* env) { return base::android::LazyGetClass(env, kClassPath_org_webrtc_RtpParameters, &g_org_webrtc_RtpParameters_clazz); } #endif // Leaking this jclass as we cannot use LazyInstance from some threads. JNI_REGISTRATION_EXPORT std::atomic<jclass> g_org_webrtc_RtpParameters_00024DegradationPreference_clazz(nullptr); #ifndef org_webrtc_RtpParameters_00024DegradationPreference_clazz_defined #define org_webrtc_RtpParameters_00024DegradationPreference_clazz_defined inline jclass org_webrtc_RtpParameters_00024DegradationPreference_clazz(JNIEnv* env) { return base::android::LazyGetClass(env, kClassPath_org_webrtc_RtpParameters_00024DegradationPreference, &g_org_webrtc_RtpParameters_00024DegradationPreference_clazz); } #endif // Leaking this jclass as we cannot use LazyInstance from some threads. JNI_REGISTRATION_EXPORT std::atomic<jclass> g_org_webrtc_RtpParameters_00024Encoding_clazz(nullptr); #ifndef org_webrtc_RtpParameters_00024Encoding_clazz_defined #define org_webrtc_RtpParameters_00024Encoding_clazz_defined inline jclass org_webrtc_RtpParameters_00024Encoding_clazz(JNIEnv* env) { return base::android::LazyGetClass(env, kClassPath_org_webrtc_RtpParameters_00024Encoding, &g_org_webrtc_RtpParameters_00024Encoding_clazz); } #endif // Leaking this jclass as we cannot use LazyInstance from some threads. JNI_REGISTRATION_EXPORT std::atomic<jclass> g_org_webrtc_RtpParameters_00024Codec_clazz(nullptr); #ifndef org_webrtc_RtpParameters_00024Codec_clazz_defined #define org_webrtc_RtpParameters_00024Codec_clazz_defined inline jclass org_webrtc_RtpParameters_00024Codec_clazz(JNIEnv* env) { return base::android::LazyGetClass(env, kClassPath_org_webrtc_RtpParameters_00024Codec, &g_org_webrtc_RtpParameters_00024Codec_clazz); } #endif // Leaking this jclass as we cannot use LazyInstance from some threads. JNI_REGISTRATION_EXPORT std::atomic<jclass> g_org_webrtc_RtpParameters_00024Rtcp_clazz(nullptr); #ifndef org_webrtc_RtpParameters_00024Rtcp_clazz_defined #define org_webrtc_RtpParameters_00024Rtcp_clazz_defined inline jclass org_webrtc_RtpParameters_00024Rtcp_clazz(JNIEnv* env) { return base::android::LazyGetClass(env, kClassPath_org_webrtc_RtpParameters_00024Rtcp, &g_org_webrtc_RtpParameters_00024Rtcp_clazz); } #endif // Leaking this jclass as we cannot use LazyInstance from some threads. JNI_REGISTRATION_EXPORT std::atomic<jclass> g_org_webrtc_RtpParameters_00024HeaderExtension_clazz(nullptr); #ifndef org_webrtc_RtpParameters_00024HeaderExtension_clazz_defined #define org_webrtc_RtpParameters_00024HeaderExtension_clazz_defined inline jclass org_webrtc_RtpParameters_00024HeaderExtension_clazz(JNIEnv* env) { return base::android::LazyGetClass(env, kClassPath_org_webrtc_RtpParameters_00024HeaderExtension, &g_org_webrtc_RtpParameters_00024HeaderExtension_clazz); } #endif // Step 2: Constants (optional). // Step 3: Method stubs. namespace webrtc { namespace jni { static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024DegradationPreference_fromNativeIndex(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_DegradationPreference_fromNativeIndex(JNIEnv* env, JniIntWrapper nativeIndex) { jclass clazz = org_webrtc_RtpParameters_00024DegradationPreference_clazz(env); CHECK_CLAZZ(env, clazz, org_webrtc_RtpParameters_00024DegradationPreference_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_STATIC>( env, clazz, "fromNativeIndex", "(I)Lorg/webrtc/RtpParameters$DegradationPreference;", &g_org_webrtc_RtpParameters_00024DegradationPreference_fromNativeIndex); jobject ret = env->CallStaticObjectMethod(clazz, call_context.base.method_id, as_jint(nativeIndex)); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_Constructor(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Encoding_Constructor(JNIEnv* env, const base::android::JavaRef<jstring>& rid, jboolean active, jdouble bitratePriority, JniIntWrapper networkPriority, const base::android::JavaRef<jobject>& maxBitrateBps, const base::android::JavaRef<jobject>& minBitrateBps, const base::android::JavaRef<jobject>& maxFramerate, const base::android::JavaRef<jobject>& numTemporalLayers, const base::android::JavaRef<jobject>& scaleResolutionDownBy, const base::android::JavaRef<jobject>& ssrc) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, clazz, org_webrtc_RtpParameters_00024Encoding_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "<init>", "(Ljava/lang/String;ZDILjava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/lang/Double;Ljava/lang/Long;)V", &g_org_webrtc_RtpParameters_00024Encoding_Constructor); jobject ret = env->NewObject(clazz, call_context.base.method_id, rid.obj(), active, bitratePriority, as_jint(networkPriority), maxBitrateBps.obj(), minBitrateBps.obj(), maxFramerate.obj(), numTemporalLayers.obj(), scaleResolutionDownBy.obj(), ssrc.obj()); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getRid(nullptr); static base::android::ScopedJavaLocalRef<jstring> Java_Encoding_getRid(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getRid", "()Ljava/lang/String;", &g_org_webrtc_RtpParameters_00024Encoding_getRid); jstring ret = static_cast<jstring>(env->CallObjectMethod(obj.obj(), call_context.base.method_id)); return base::android::ScopedJavaLocalRef<jstring>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getActive(nullptr); static jboolean Java_Encoding_getActive(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), false); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getActive", "()Z", &g_org_webrtc_RtpParameters_00024Encoding_getActive); jboolean ret = env->CallBooleanMethod(obj.obj(), call_context.base.method_id); return ret; } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getBitratePriority(nullptr); static jdouble Java_Encoding_getBitratePriority(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), 0); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getBitratePriority", "()D", &g_org_webrtc_RtpParameters_00024Encoding_getBitratePriority); jdouble ret = env->CallDoubleMethod(obj.obj(), call_context.base.method_id); return ret; } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getNetworkPriority(nullptr); static jint Java_Encoding_getNetworkPriority(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), 0); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getNetworkPriority", "()I", &g_org_webrtc_RtpParameters_00024Encoding_getNetworkPriority); jint ret = env->CallIntMethod(obj.obj(), call_context.base.method_id); return ret; } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getMaxBitrateBps(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Encoding_getMaxBitrateBps(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getMaxBitrateBps", "()Ljava/lang/Integer;", &g_org_webrtc_RtpParameters_00024Encoding_getMaxBitrateBps); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getMinBitrateBps(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Encoding_getMinBitrateBps(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getMinBitrateBps", "()Ljava/lang/Integer;", &g_org_webrtc_RtpParameters_00024Encoding_getMinBitrateBps); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getMaxFramerate(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Encoding_getMaxFramerate(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getMaxFramerate", "()Ljava/lang/Integer;", &g_org_webrtc_RtpParameters_00024Encoding_getMaxFramerate); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getNumTemporalLayers(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Encoding_getNumTemporalLayers(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getNumTemporalLayers", "()Ljava/lang/Integer;", &g_org_webrtc_RtpParameters_00024Encoding_getNumTemporalLayers); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getScaleResolutionDownBy(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Encoding_getScaleResolutionDownBy(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getScaleResolutionDownBy", "()Ljava/lang/Double;", &g_org_webrtc_RtpParameters_00024Encoding_getScaleResolutionDownBy); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Encoding_getSsrc(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Encoding_getSsrc(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Encoding_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Encoding_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getSsrc", "()Ljava/lang/Long;", &g_org_webrtc_RtpParameters_00024Encoding_getSsrc); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Codec_Constructor(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Codec_Constructor(JNIEnv* env, JniIntWrapper payloadType, const base::android::JavaRef<jstring>& name, const base::android::JavaRef<jobject>& kind, const base::android::JavaRef<jobject>& clockRate, const base::android::JavaRef<jobject>& numChannels, const base::android::JavaRef<jobject>& parameters) { jclass clazz = org_webrtc_RtpParameters_00024Codec_clazz(env); CHECK_CLAZZ(env, clazz, org_webrtc_RtpParameters_00024Codec_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "<init>", "(ILjava/lang/String;Lorg/webrtc/MediaStreamTrack$MediaType;Ljava/lang/Integer;Ljava/lang/Integer;Ljava/util/Map;)V", &g_org_webrtc_RtpParameters_00024Codec_Constructor); jobject ret = env->NewObject(clazz, call_context.base.method_id, as_jint(payloadType), name.obj(), kind.obj(), clockRate.obj(), numChannels.obj(), parameters.obj()); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Codec_getPayloadType(nullptr); static jint Java_Codec_getPayloadType(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Codec_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Codec_clazz(env), 0); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getPayloadType", "()I", &g_org_webrtc_RtpParameters_00024Codec_getPayloadType); jint ret = env->CallIntMethod(obj.obj(), call_context.base.method_id); return ret; } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Codec_getName(nullptr); static base::android::ScopedJavaLocalRef<jstring> Java_Codec_getName(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Codec_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Codec_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getName", "()Ljava/lang/String;", &g_org_webrtc_RtpParameters_00024Codec_getName); jstring ret = static_cast<jstring>(env->CallObjectMethod(obj.obj(), call_context.base.method_id)); return base::android::ScopedJavaLocalRef<jstring>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Codec_getKind(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Codec_getKind(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Codec_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Codec_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getKind", "()Lorg/webrtc/MediaStreamTrack$MediaType;", &g_org_webrtc_RtpParameters_00024Codec_getKind); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Codec_getClockRate(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Codec_getClockRate(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Codec_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Codec_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getClockRate", "()Ljava/lang/Integer;", &g_org_webrtc_RtpParameters_00024Codec_getClockRate); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Codec_getNumChannels(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Codec_getNumChannels(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Codec_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Codec_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getNumChannels", "()Ljava/lang/Integer;", &g_org_webrtc_RtpParameters_00024Codec_getNumChannels); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Codec_getParameters(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Codec_getParameters(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Codec_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Codec_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getParameters", "()Ljava/util/Map;", &g_org_webrtc_RtpParameters_00024Codec_getParameters); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Rtcp_Constructor(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_Rtcp_Constructor(JNIEnv* env, const base::android::JavaRef<jstring>& cname, jboolean reducedSize) { jclass clazz = org_webrtc_RtpParameters_00024Rtcp_clazz(env); CHECK_CLAZZ(env, clazz, org_webrtc_RtpParameters_00024Rtcp_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "<init>", "(Ljava/lang/String;Z)V", &g_org_webrtc_RtpParameters_00024Rtcp_Constructor); jobject ret = env->NewObject(clazz, call_context.base.method_id, cname.obj(), reducedSize); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Rtcp_getCname(nullptr); static base::android::ScopedJavaLocalRef<jstring> Java_Rtcp_getCname(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Rtcp_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Rtcp_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getCname", "()Ljava/lang/String;", &g_org_webrtc_RtpParameters_00024Rtcp_getCname); jstring ret = static_cast<jstring>(env->CallObjectMethod(obj.obj(), call_context.base.method_id)); return base::android::ScopedJavaLocalRef<jstring>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024Rtcp_getReducedSize(nullptr); static jboolean Java_Rtcp_getReducedSize(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024Rtcp_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024Rtcp_clazz(env), false); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getReducedSize", "()Z", &g_org_webrtc_RtpParameters_00024Rtcp_getReducedSize); jboolean ret = env->CallBooleanMethod(obj.obj(), call_context.base.method_id); return ret; } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024HeaderExtension_Constructor(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_HeaderExtension_Constructor(JNIEnv* env, const base::android::JavaRef<jstring>& uri, JniIntWrapper id, jboolean encrypted) { jclass clazz = org_webrtc_RtpParameters_00024HeaderExtension_clazz(env); CHECK_CLAZZ(env, clazz, org_webrtc_RtpParameters_00024HeaderExtension_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "<init>", "(Ljava/lang/String;IZ)V", &g_org_webrtc_RtpParameters_00024HeaderExtension_Constructor); jobject ret = env->NewObject(clazz, call_context.base.method_id, uri.obj(), as_jint(id), encrypted); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024HeaderExtension_getUri(nullptr); static base::android::ScopedJavaLocalRef<jstring> Java_HeaderExtension_getUri(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024HeaderExtension_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024HeaderExtension_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getUri", "()Ljava/lang/String;", &g_org_webrtc_RtpParameters_00024HeaderExtension_getUri); jstring ret = static_cast<jstring>(env->CallObjectMethod(obj.obj(), call_context.base.method_id)); return base::android::ScopedJavaLocalRef<jstring>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024HeaderExtension_getId(nullptr); static jint Java_HeaderExtension_getId(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024HeaderExtension_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024HeaderExtension_clazz(env), 0); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getId", "()I", &g_org_webrtc_RtpParameters_00024HeaderExtension_getId); jint ret = env->CallIntMethod(obj.obj(), call_context.base.method_id); return ret; } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_00024HeaderExtension_getEncrypted(nullptr); static jboolean Java_HeaderExtension_getEncrypted(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_00024HeaderExtension_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_00024HeaderExtension_clazz(env), false); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getEncrypted", "()Z", &g_org_webrtc_RtpParameters_00024HeaderExtension_getEncrypted); jboolean ret = env->CallBooleanMethod(obj.obj(), call_context.base.method_id); return ret; } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_Constructor(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_RtpParameters_Constructor(JNIEnv* env, const base::android::JavaRef<jstring>& transactionId, const base::android::JavaRef<jobject>& degradationPreference, const base::android::JavaRef<jobject>& rtcp, const base::android::JavaRef<jobject>& headerExtensions, const base::android::JavaRef<jobject>& encodings, const base::android::JavaRef<jobject>& codecs) { jclass clazz = org_webrtc_RtpParameters_clazz(env); CHECK_CLAZZ(env, clazz, org_webrtc_RtpParameters_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "<init>", "(Ljava/lang/String;Lorg/webrtc/RtpParameters$DegradationPreference;Lorg/webrtc/RtpParameters$Rtcp;Ljava/util/List;Ljava/util/List;Ljava/util/List;)V", &g_org_webrtc_RtpParameters_Constructor); jobject ret = env->NewObject(clazz, call_context.base.method_id, transactionId.obj(), degradationPreference.obj(), rtcp.obj(), headerExtensions.obj(), encodings.obj(), codecs.obj()); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_getTransactionId(nullptr); static base::android::ScopedJavaLocalRef<jstring> Java_RtpParameters_getTransactionId(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getTransactionId", "()Ljava/lang/String;", &g_org_webrtc_RtpParameters_getTransactionId); jstring ret = static_cast<jstring>(env->CallObjectMethod(obj.obj(), call_context.base.method_id)); return base::android::ScopedJavaLocalRef<jstring>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_getDegradationPreference(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_RtpParameters_getDegradationPreference(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getDegradationPreference", "()Lorg/webrtc/RtpParameters$DegradationPreference;", &g_org_webrtc_RtpParameters_getDegradationPreference); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_getRtcp(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_RtpParameters_getRtcp(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getRtcp", "()Lorg/webrtc/RtpParameters$Rtcp;", &g_org_webrtc_RtpParameters_getRtcp); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_getHeaderExtensions(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_RtpParameters_getHeaderExtensions(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getHeaderExtensions", "()Ljava/util/List;", &g_org_webrtc_RtpParameters_getHeaderExtensions); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_getEncodings(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_RtpParameters_getEncodings(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getEncodings", "()Ljava/util/List;", &g_org_webrtc_RtpParameters_getEncodings); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } static std::atomic<jmethodID> g_org_webrtc_RtpParameters_getCodecs(nullptr); static base::android::ScopedJavaLocalRef<jobject> Java_RtpParameters_getCodecs(JNIEnv* env, const base::android::JavaRef<jobject>& obj) { jclass clazz = org_webrtc_RtpParameters_clazz(env); CHECK_CLAZZ(env, obj.obj(), org_webrtc_RtpParameters_clazz(env), NULL); jni_generator::JniJavaCallContextChecked call_context; call_context.Init< base::android::MethodID::TYPE_INSTANCE>( env, clazz, "getCodecs", "()Ljava/util/List;", &g_org_webrtc_RtpParameters_getCodecs); jobject ret = env->CallObjectMethod(obj.obj(), call_context.base.method_id); return base::android::ScopedJavaLocalRef<jobject>(env, ret); } } // namespace jni } // namespace webrtc // Step 4: Generated test functions (optional). #endif // org_webrtc_RtpParameters_JNI
[ "sergey.seroshtan@gmail.com" ]
sergey.seroshtan@gmail.com
d527ff2707b261c52ae14b53972c1fe1fb89fc40
eee5fc5e9e1bd9ababc9cf8ccb8add19c9219ca3
/ABC/051/c.cpp
69539d5775cb5b525096052953c205962b866e92
[]
no_license
matatabinoneko/Atcoder
31aa0114bde28ab1cf528feb86d1e70d54622d84
07cc54894b5bcf9bcb43e57a67f2a0cbb2714867
refs/heads/master
2021-11-13T04:39:13.824438
2021-10-31T01:42:52
2021-10-31T01:42:52
196,823,857
0
0
null
null
null
null
UTF-8
C++
false
false
290
cpp
#include<bits/stdc++.h> using namespace std; #define ll long long int main(void){ int sx,sy,tx,ty; cin >> sx >> sy >> tx >> ty; string u(ty-sy,'U'),r(tx-sx,'R'),d(ty-sy,'D'),l(tx-sx,'L'); string s = u+r+d+l+'L'+u+'U'+r+"RDR"+d+'D'+l+"LU"; cout << s << endl; return 0; }
[ "matatabinoneko0721@gmail.com" ]
matatabinoneko0721@gmail.com
164180e324416649e8e218a8b430a83803e3a28f
ebaaaffb2a7ff5991441e9ce2110f40c36185798
/C++/adapter/ducks/Turkey.h
06d4939b2c57e68fc01b30ed1632f6930783f97f
[]
no_license
iMageChans/DesignModel
6fa0e9322992f0003951e564c1e84449b4b76d33
c4c59770b356db606e38f2c1bba278d8627cbac5
refs/heads/master
2020-12-28T01:39:44.541684
2020-02-18T00:02:57
2020-02-18T00:02:57
238,139,157
0
0
null
null
null
null
UTF-8
C++
false
false
199
h
// // Created by Chans on 2020/2/7. // #ifndef DUCKS_TURKEY_H #define DUCKS_TURKEY_H class Turkey { public: virtual void gobble() = 0; virtual void fly() = 0; }; #endif //DUCKS_TURKEY_H
[ "imagechans@gmail.com" ]
imagechans@gmail.com
12f6e6c4cf465c0d67904d196438f9229643b8e4
f7c2e7038e94181a130086182562c93194e89cca
/Codechef/G3.cpp
f2e57505d97a114a953dac97a18b102a20c7dec4
[]
no_license
PrajwalaTM/accepted
d836749488fe0089c6519c89462df667d85f3d01
0d305186950c6bb3a56b99e6c08a6cc039d4824d
refs/heads/master
2021-06-18T20:22:23.916516
2017-05-05T15:43:44
2017-05-05T15:43:44
null
0
0
null
null
null
null
UTF-8
C++
false
false
986
cpp
#include <bits/stdc++.h> using namespace std; #define ll long long #define l long #define MAX 100003 #define MOD 1000000007 #define fin(i,a,n) for(i=a;i<=n;i++) #define fde(i,a,n) for(i=n;i>=a;i--) #define sd(a) scanf("%d",&a) #define sld(a) scanf("%ld",&a) #define slld(a) scanf("%lld",&a) #define slf(a) scanf("%lf",&a) #define sllf(a) scanf("%llf",&a) #define pd(a) printf("%d",a) #define pld(a) printf("%ld",a) #define plld(a) printf("%lld",a) #define plf(a) printf("%lf",a) #define pllf(a) printf("%llf",a) #define pn printf("\n") #define ps printf(" ") #define mp make_pair #define pb push_back int main() { ll t; slld(t); while(t--) { ll n; slld(n); ll a[n+1]; ll pos,ans=0; for(ll i=1;i<=n;i++) { slld(a[i]); ans=ans^(a[i]-i); } if(!ans) printf("Johnny wins"); else { printf("Mary wins\n");} } }
[ "prajwala.tm@gmail.com" ]
prajwala.tm@gmail.com
3a0dca931deeeb0137a5006a69ff8c04c715ae26
4785ba6c5fe01795caf080b2eb2ac9705c6e814c
/Zjazd2-MiNI-GfxEditor/EditorGui/DrawingArea.h
fbcec5d085201e30dd381d011887f85cf4d31cf6
[]
no_license
Venthe/Warsaw-University-of-Technology-Projects
99d2e13526479578db6848c5d2eee147e86ed48f
bda29284e3652e9cd4d2b79e86c88344f274c045
refs/heads/master
2023-03-08T02:34:20.693264
2019-11-23T23:10:05
2019-11-23T23:10:05
192,820,115
0
0
null
2023-03-03T06:55:42
2019-06-20T00:07:26
C++
UTF-8
C++
false
false
1,219
h
#pragma once #include <QWidget> // NOLINT #include "ControlPoint.h" class DrawingArea : public QWidget { Q_OBJECT public: DrawingArea(QWidget* parent = Q_NULLPTR); ~DrawingArea() final; QSize minimumSizeHint() const override; QSize sizeHint() const override; void paintEvent(QPaintEvent* event) override; void mouseMoveEvent(QMouseEvent* event) override; void mousePressEvent(QMouseEvent* event) override; signals: void mousePositionChanged(QPoint point); void controlPointListChanged(); public slots: void controlPointListUpdated(); private: std::vector<esl::ControlPoint>* controlPointList; double* controlPointWeight; int canvasMinX, canvasMinY, canvasMaxX, canvasMaxY; void drawBackgroundBox(QPainter& painter); void drawPath(QPainter& painter, std::vector<QPoint> points); // TODO: Split into helper methods? std::vector<QPoint> toQPoints( std::vector<esl::ControlPoint> controlPointList); QPoint toQPoint(esl::ControlPoint point); esl::ControlPoint toControlPoint(QPoint point); public: void setControlPointListReference( std::vector<esl::ControlPoint>* controlPointList); void setControlPointWeightReference(double* controlPointWeight); };
[ "jacek.b.lipiec@gmail.com" ]
jacek.b.lipiec@gmail.com
636505648fdc304d4ec066b2ba711d5343fefd36
79eb83cc3e7f4324ad3f7e56f094384ee494a7a9
/Manager/ActionFlowManager.h
ad174fe6191cd56e03487b6253153e9a4bf3f42c
[]
no_license
JiaoMing/Blackcat
4a32ab2ec1abc356a4494ec9177ad0b3128d575b
95fa6f74429ead752741cbff3debca8bb0cbdb6e
refs/heads/master
2020-04-15T11:08:28.111536
2014-11-13T08:40:57
2014-11-13T08:40:57
30,082,134
0
4
null
2015-01-30T17:10:54
2015-01-30T17:10:53
null
UTF-8
C++
false
false
910
h
// // ActionFlowManager.h // Blackcat // // Created by haojunhua on 14-1-13. // // #ifndef Blackcat_ActionFlowManager_h #define Blackcat_ActionFlowManager_h #include "cocos2d.h" using namespace cocos2d; #include "AudioManager.h" class ActionFlow:public CCObject{ public: ActionFlow(){ m_actionArray=CCArray::create(); m_actionArray->retain(); m_audioArray=CCArray::create(); m_audioArray->retain(); } ~ActionFlow(){CC_SAFE_RELEASE(m_actionArray);CC_SAFE_RELEASE(m_audioArray);} CC_SYNTHESIZE(CCArray*, m_actionArray, ActionArray); CC_SYNTHESIZE(CCArray*, m_audioArray, AudioArray); }; class ActionFlowManager { public: static ActionFlowManager* sharedActionFlowManager(); ActionFlowManager(); ~ActionFlowManager(); public: ActionFlow* getActionFlowWithKey(const char* key); private: CCDictionary* m_audioFlowDict; }; #endif
[ "380050803@qq.com" ]
380050803@qq.com
c6be207cd850358090e8f487a60f1159c0605622
5a97be73f3c6e2987480194a791675259f8d7edf
/BZOJ/2815/source/sj/catas.cpp
260185754f6bf80f1fd9f15a2cfc5853f031c7c5
[ "MIT" ]
permissive
sjj118/OI-Code
1d33d2a7a6eeba2ed16692d663e1b81cdc1341fd
964ea6e799d14010f305c7e4aee269d860a781f7
refs/heads/master
2022-02-21T17:54:14.764880
2019-09-05T07:16:27
2019-09-05T07:16:27
65,370,460
0
0
null
null
null
null
UTF-8
C++
false
false
1,476
cpp
#include<iostream> #include<cstdio> #define rg register #define rep(i,x,y) for(rg int i=(x);i<=(y);++i) #define per(i,x,y) for(rg int i=(x);i>=(y);--i) using namespace std; const int maxn=7e4,maxm=2e6; int n; struct Tree{ int pa[maxn][16],tot,head[maxn],to[maxm],next[maxm],dep[maxn],size[maxn]; void ins(int a,int b){ dep[a]=dep[b]+1;pa[a][0]=b; to[++tot]=a;next[tot]=head[b];head[b]=tot; rep(i,1,15)pa[a][i]=pa[pa[a][i-1]][i-1]; } int lca(int a,int b){ if(dep[a]>dep[b])swap(a,b); per(i,15,0)if(dep[pa[b][i]]>=dep[a])b=pa[b][i]; if(a==b)return a; per(i,15,0)if(pa[a][i]!=pa[b][i])a=pa[a][i],b=pa[b][i]; return pa[a][0]; } void dfs(int k){ size[k]=1; for(int p=head[k];p;p=next[p])dfs(to[p]),size[k]+=size[to[p]]; } }T; struct Graph{ int tot,head[maxn],to[maxm],next[maxm],indegree[maxn],pa[maxn]; void ins(int a,int b){to[++tot]=b;next[tot]=head[a];head[a]=tot;++indegree[b];} int q[maxn],ql,qr; void topsort(){ ql=1;qr=0;T.dep[n+1]=1; rep(i,1,n)if(indegree[i]==0)q[++qr]=i,pa[i]=n+1; while(ql<=qr){ int k=q[ql++];T.ins(k,pa[k]); for(int p=head[k];p;p=next[p]){ --indegree[to[p]]; if(pa[to[p]]==0)pa[to[p]]=k;else pa[to[p]]=T.lca(pa[to[p]],k); if(indegree[to[p]]==0)q[++qr]=to[p]; } } } }G; int main(){ scanf("%d",&n); rep(i,1,n){ int x;while(scanf("%d",&x)&&x)G.ins(x,i); } G.topsort(); T.dfs(n+1); rep(i,1,n)printf("%d\n",T.size[i]-1); return 0; }
[ "sjj118@sjj118.com" ]
sjj118@sjj118.com
4e5b4eee7f3e2318961b191e025e62d0a23e4df0
c5f736326dd996a75a4b1e37e45a34e7e349c38f
/Speed.hpp
033ca91928af901e550dedffd05428f2f5a3f517
[]
no_license
briansoule/ERADICATE2
5aaf2f67e2bdf09d2f90f75da573a920c551f09f
41b8c8e4517ebc6801f38efc2d113cd57f42f6e9
refs/heads/master
2023-03-16T14:22:20.190093
2020-05-27T19:03:03
2020-05-27T19:03:03
null
0
0
null
null
null
null
UTF-8
C++
false
false
956
hpp
#ifndef _HPP_SPEED #define _HPP_SPEED #include <chrono> #include <mutex> #include <list> #include <map> class Speed { public: typedef std::pair<long long, size_t> samplePair; typedef std::list<samplePair> sampleList; public: Speed(const unsigned int intervalPrintMs = 500, const unsigned int intervalSampleMs = 10000); ~Speed(); void update(const unsigned int numPoints, const unsigned int indexDevice); void print() const; double getSpeed() const; double getSpeed(const unsigned int indexDevice) const; private: double getSpeed(const sampleList & l) const; void updateList(const unsigned int & numPoints, const long long & ns, sampleList & l); private: const unsigned int m_intervalPrintMs; const unsigned int m_intervalSampleMs; long long m_lastPrint; mutable std::recursive_mutex m_mutex; sampleList m_lSamples; std::map<unsigned int, sampleList> m_mDeviceSamples; }; #endif /* _HPP_SPEED */
[ "johan@johgu.se" ]
johan@johgu.se
c3c1ab463f97e73e4fef49aa31cfca4bb21292ea
5a9fd26dd8d874cc338955bf1e2f99541669e88d
/tests/Coverage.cpp
90a84ab9b7942ed823c798d06d2c13bd240a0bd4
[]
no_license
buchanae/warren
0f8dd84031fda9659189e808d46b3da0e6912e5c
9044a8d24e35ef21672faf005372c39826568a4f
refs/heads/master
2021-05-29T14:14:29.069758
2012-08-07T01:03:41
2012-08-07T01:03:41
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,818
cpp
#include <sstream> #include <string> #include <vector> #include "gtest/gtest.h" #include "gmock/gmock.h" #include "warren/Alignment.h" #include "warren/Coverage.h" using testing::DoubleEq; using testing::ElementsAre; /* TEST(CoverageTest, diff_signals) { vector<double> a, b, diff; a.push_back(5.5); b.push_back(4.3); a.push_back(7.5); b.push_back(4.3); diff_signals(a, b, diff); EXPECT_THAT(diff, ElementsAre(DoubleEq(1.2), DoubleEq(3.2))); } */ TEST(CoverageTest, Coverage_setMinReferenceLength) { Coverage c; EXPECT_EQ(0, c.coverages.size()); c.setMinReferenceLength("foo", 10); EXPECT_EQ(1, c.coverages.size()); EXPECT_THAT(c.coverages.find("foo")->second, ElementsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); c.setMinReferenceLength("foo", 5); EXPECT_THAT(c.coverages.find("foo")->second, ElementsAre(0, 0, 0, 0, 0, 0, 0, 0, 0, 0)); } TEST(CoverageTest, Coverage_add) { Coverage c; c.add("foo", 2, 3); EXPECT_THAT(c.coverages.find("foo")->second, ElementsAre(0, 1, 1, 1)); c.add("foo", 2, 2); EXPECT_THAT(c.coverages.find("foo")->second, ElementsAre(0, 2, 2, 1)); c.add("foo", 6, 2); EXPECT_THAT(c.coverages.find("foo")->second, ElementsAre(0, 2, 2, 1, 0, 1, 1)); c.setMinReferenceLength("foo", 10); EXPECT_THAT(c.coverages.find("foo")->second, ElementsAre(0, 2, 2, 1, 0, 1, 1, 0, 0, 0)); } TEST(CoverageTest, Coverage_add_alignment) { Alignment a; a.RefName = "foo"; a.position(3); CigarOp op; a.CigarData.clear(); op.Type = 'M'; op.Length = 2; a.CigarData.push_back(op); op.Type = 'N'; op.Length = 3; a.CigarData.push_back(op); op.Type = 'M'; op.Length = 2; a.CigarData.push_back(op); Coverage c; c.add(a); EXPECT_THAT(c.coverages.find("foo")->second, ElementsAre(0, 0, 1, 1, 0, 0, 0, 1, 1)); } TEST(CoverageTest, load) { Coverage c; std::stringstream coverage_str("bar\t6\n1\n1\n1\n0\n0\n0\nfoo\t5\n0\n0\n1\n1\n0\n"); c.load(coverage_str); EXPECT_THAT(c.coverages.find("bar")->second, ElementsAre(1, 1, 1, 0, 0, 0)); EXPECT_THAT(c.coverages.find("foo")->second, ElementsAre(0, 0, 1, 1, 0)); } TEST(CoverageTest, toString) { // Note that references are output in sorted order on reference name Coverage c; c.setMinReferenceLength("foo", 5); c.setMinReferenceLength("bar", 6); c.add("foo", 3, 2); c.add("bar", 1, 3); std::string expected = "bar\t6\n1\n1\n1\n0\n0\n0\nfoo\t5\n0\n0\n1\n1\n0\n"; std::stringstream out; c.toOutputStream(out); EXPECT_EQ(expected, out.str()); std::string out_string; c.toString(out_string); EXPECT_EQ(expected, out_string); }
[ "buchanae@gmail.com" ]
buchanae@gmail.com
c77928f79c7af3dbe882f849a5ea5182003c04b2
3e02f49f1b19e3245fbe4032f5761567823dd9cf
/game_2048.h
6ebd664a834622f6b7e34eb2629af3c108ba108a
[]
no_license
satyamsammi/game_2048_using_CPP
c57b7350f3d056fa20e64a98b32d3ccbfc4c53b8
d59fec0e381eb906bbc973d0ea6bfe2509cc57c1
refs/heads/master
2021-01-01T03:54:17.980901
2016-05-05T05:40:16
2016-05-05T05:40:16
58,107,164
0
0
null
null
null
null
UTF-8
C++
false
false
9,999
h
#ifndef GAME_H #define GAME_H 1 #include<math.h> #include <cstdlib> #include<iostream> using namespace std; class game{ int arr[4][4]; int score=0; int high_score=0; void number_generator() { int i=rand()%4; int j=rand()%4; while(arr[i][j]!=0) { i=rand()%4; j=rand()%4; } int k=rand()%20; if(k>15) { arr[i][j]=4; } else arr[i][j]=2; return; } void display() { system("cls"); for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { cout<<arr[i][j]<<" "; } cout<<endl; } cout<<score<<endl; } void move_right() { if(is_gameover()) { cout<<"game over"<<endl; return; } for(int i=0;i<4;i++) { for(int j=3;j>=0;j--) { if(arr[i][j]==0) { int k=j-1; int count=1; while(k>-1 && arr[i][k]==0) { k--; count++; } for(int l=j;l>=count;l--) { arr[i][l]=arr[i][l-count]; } for(int m=0;m<count;m++) { arr[i][m]=0; } } } } for(int i=0;i<4;i++) { for(int j=3;j>0;) { if(arr[i][j]==arr[i][j-1]) { arr[i][j]*=2; score+=arr[i][j]; arr[i][j-1]=0; j=j-2; } else j--; } } for(int i=0;i<4;i++) { for(int j=3;j>=0;j--) { if(arr[i][j]==0) { int k=j-1; int count=1; while(k>-1 && arr[i][k]==0) { k--; count++; } for(int l=j;l>=count;l--) { arr[i][l]=arr[i][l-count]; } for(int m=0;m<count;m++) { arr[i][m]=0; } } } } number_generator(); display(); return; } void move_left() { if(is_gameover()) { cout<<"game over"<<endl; return; } for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(arr[i][j]==0) { int k=j+1; int count=1; while(k<4 && arr[i][k]==0) { k++; count++; } for(int l=j;l< 4-count;l++) { arr[i][l]=arr[i][l+count]; } for(int m=3;m>=4-count;m--) { arr[i][m]=0; } } } } for(int i=0;i<4;i++) { for(int j=0;j<4;) { if(arr[i][j]==arr[i][j+1]) { arr[i][j]*=2; score+=arr[i][j]; arr[i][j+1]=0; j=j+2; } else j++; } } for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { if(arr[i][j]==0) { int k=j+1; int count=1; while(k<4 && arr[i][k]==0) { k++; count++; } for(int l=j;l< 4-count;l++) { arr[i][l]=arr[i][l+count]; } for(int m=3;m>=4-count;m--) { arr[i][m]=0; } } } } number_generator(); display(); return; } void move_up() { if(is_gameover()) { cout<<"game over"<<endl; return; } for(int j=0;j<4;j++) { for(int i=0;i<4;i++) { if(arr[i][j]==0) { int k=i+1; int count=1; while(k<4 && arr[k][j]==0) { k++; count++; } for(int l=i;l< 4-count;l++) { arr[l][j]=arr[l+count][j]; } for(int m=3;m>=4-count;m--) { arr[m][j]=0; } } } } for(int j=0;j<4;j++) { for(int i=0;i<3;) { if(arr[i][j]==arr[i+1][j]) { arr[i][j]*=2; score+=arr[i][j]; arr[i+1][j]=0; i=i+2; } else i++; } } for(int j=0;j<4;j++) { for(int i=0;i<4;i++) { if(arr[i][j]==0) { int k=i+1; int count=1; while(k<4 && arr[k][j]==0) { k++; count++; } for(int l=i;l< 4-count;l++) { arr[l][j]=arr[l+count][j]; } for(int m=3;m>=4-count;m--) { arr[m][j]=0; } } } } number_generator(); display(); return; } void move_down() { if(is_gameover()) { cout<<"game over"<<endl; return; } for(int j=0;j<4;j++) { for(int i=3;i>=0;i--) { if(arr[i][j]==0) { int k=i-1; int count=1; while(k>-1 && arr[k][j]==0) { k--; count++; } for(int l=i;l>=count;l--) { arr[l][j]=arr[l-count][j]; } for(int m=0;m<count;m++) { arr[m][j]=0; } } } } for(int j=0;j<4;j++) { for(int i=3;i>0;) { if(arr[i][j]==arr[i-1][j]) { arr[i][j]*=2; score+=arr[i][j]; arr[i-1][j]=0; i=i-2; } else i--; } } for(int j=0;j<4;j++) { for(int i=3;i>=0;i--) { if(arr[i][j]==0) { int k=i-1; int count=1; while(k>-1 && arr[k][j]==0) { k--; count++; } for(int l=i;l>=count;l--) { arr[l][j]=arr[l-count][j]; } for(int m=0;m<count;m++) { arr[m][j]=0; } } } } number_generator(); display(); return; } public: game() { for(int i=0;i<4;i++) { for(int j=0;j<4;j++) { arr[i][j]=0; } } score=0; number_generator(); number_generator(); display(); } bool is_gameover() { int flag=0; for(int i=0;i<4;i++) { for(int j=0;j<3;j++) { if(arr[i][j]==arr[i][j+1] || arr[i][j]==0 || arr[i][j+1]==0 ) { flag=1; return false; } } } for(int j=0;j<4;j++) { for(int i=0;i<3;j++) { if(arr[i][j]==arr[i+1][j]) { flag=1; return false; } } } if(flag==0) return true; } void pub_move_right() { move_right(); return; } void pub_move_left() { move_left(); return; } void pub_move_up() { move_up(); return; } void pub_move_down() { move_down(); return; } }; #endif // GAME_H
[ "satyamsammi@gmail.com" ]
satyamsammi@gmail.com
b08fec0133c7f7fbca5ff05fb400a70c5af6a3dd
221c01443908442de88838a76f2bf36597a6b428
/uri/1759.cpp
468e5858d5c5b9972f4cc1ef19079f7e5fede37f
[]
no_license
mansurul-hasan-masud/my-all-code
71335ad0230fbf15db89b111fac8217a77a5acd8
9a959b295e11c48003cd934107cfaeec35bb1b14
refs/heads/master
2021-05-20T03:32:21.292527
2020-06-24T15:43:26
2020-06-24T15:43:26
252,167,503
0
0
null
null
null
null
UTF-8
C++
false
false
141
cpp
#include <stdio.h> int main() { int n, i; scanf("%d", &n); for(i = 1; i < n; i++) { printf("Ho "); } printf("Ho!\n"); return 0; }
[ "mhmasud006@gmail.com" ]
mhmasud006@gmail.com
2fb6b230700a39014e657c004dc702a6c08e56d1
8de2b4f0749e94bd04f19c0b7bdc0fd5bff8efc1
/src/fcst/source/solvers/newton_w_line_search.cc
68b33e99ca03a400252e0313dcc14571715461ff
[ "MIT", "DOC" ]
permissive
LeimingHu/OpenFCST_v0.2
c4c3368e3ec90e147d7c873339d413a0ee957d70
770a0d9b145cd39c3a065b653a53b5082dc5d85c
refs/heads/master
2021-05-28T17:34:40.945643
2015-04-08T22:26:17
2015-04-08T22:26:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,990
cc
//--------------------------------------------------------------------------- // // FCST: Fuel Cell Simulation Toolbox // // Copyright (C) 2009-13 by Energy Systems Design Laboratory, University of Alberta // // This software is distributed under the MIT License. // For more information, see the README file in /doc/LICENSE // // - Class: newton_w_line_search.cc // - Description: Variant of the Newton-Raphson solver // - Developers: Marc Secanell // - $Id: newton_w_line_search.cc 2605 2014-08-15 03:36:44Z secanell $ // //--------------------------------------------------------------------------- #include <newton_w_line_search.h> //If I put it in appframe #include<appframe/newton_w_line_search.h> #include <base/parameter_handler.h> #include <base/data_out_base.h> #include <lac/block_vector.h> #include <iostream> #include <iomanip> #include <fstream> #include <string> #include <sstream> #include <cmath> #include <iomanip> using namespace FuelCell::ApplicationCore; //--------------------------------------------------------------------------- const Event NewtonLineSearch::bad_derivative = Event::assign("Newton"); //--------------------------------------------------------------------------- NewtonLineSearch::NewtonLineSearch(ApplicationBase& app) : newtonBase(app) { FcstUtilities::log << "->NewtonLineSearch"; } //--------------------------------------------------------------------------- void NewtonLineSearch::declare_parameters(ParameterHandler& param) { param.enter_subsection("Newton"); { param.declare_entry("Line search","false", Patterns::Bool()); param.declare_entry("Initial Overrelaxation", "1.", Patterns::Double()); param.declare_entry("Number of iterations with overrelaxation","1",Patterns::Integer()); } param.leave_subsection(); newtonBase::declare_parameters(param); } //--------------------------------------------------------------------------- void NewtonLineSearch::_initialize (ParameterHandler& param) { param.enter_subsection("Newton"); line_search = param.get_bool("Line search"); overrelax = param.get_double("Initial Overrelaxation"); overrelax_steps = param.get_integer("Number of iterations with overrelaxation"); param.leave_subsection (); } //--------------------------------------------------------------------------- void NewtonLineSearch::initialize (ParameterHandler& param) { newtonBase::initialize(param); _initialize(param); } //--------------------------------------------------------------------------- void NewtonLineSearch::solve (FuelCell::ApplicationCore::FEVector& u, const FuelCell::ApplicationCore::FEVectors& in_vectors) { this->step = 0; FcstUtilities::log.push ("Newton"); if (debug>2) FcstUtilities::log << "u: " << u.l2_norm() << std::endl; FEVector* Du = get_data()->block_vector_pool.alloc(); FEVector* res = get_data()->block_vector_pool.alloc(); res->reinit(u); Du->reinit(u); FEVectors src1; FEVectors src2; src1.add_vector(u, "Newton iterate"); src1.merge(in_vectors); src2.add_vector(*res, "Newton residual"); src2.merge(src1); // fill res with (f(u), v) double residual = app->residual(*res, src1); double old_residual = residual; // Output the solution at the Newton iteration if residual debug is on this->debug_output(u, *Du, *res); // while (control.check(this->step++, residual) == SolverControl::iterate) { // assemble (Df(u), v) if (residual/old_residual >= assemble_threshold) app->notify (bad_derivative);//app->assemble_reason (reason_nonlinear); //Changed after Guido's changes: app->assemble (src1); Du->reinit(u); try { app->solve (*Du, src2); } catch (SolverControl::NoConvergence& e) { FcstUtilities::log << "Inner iteration failed after " << e.last_step << " steps with residual " << e.last_residual << std::endl; } //////////////////////////////////////////////////////////// //-- Step size control //////////////////////////////////////////////////////////// if (line_search) { FcstUtilities::log << "Line Search" << std::endl; // -- Use a line search to increase robustness double min_residual = residual; double opt_alpha = -0.25; unsigned int num_points = 1; const double* ref = get_data()->scalar("Refinement"); if (this->step < 10 && *ref < 1) num_points = 20; else if ((this->step >=10 && this->step < 20) && *ref < 1) num_points = 10; else num_points = 5; // ------------ GEOMETRIC LINE SEARCH // Scale: I will look at 2^0, 2^-1, 2^-2, ..., 2^{-num_points} double scale = 2; for (unsigned int alpha = 1; alpha < num_points + 1; ++alpha) { // scale u u.add(-pow(scale,-double(alpha-1)), *Du); residual = app->residual(*res, src1); if (residual < min_residual && !std::isnan(residual)) { opt_alpha = -pow(scale,-double(alpha-1)); min_residual = residual; } // FcstUtilities::log<<"Residual for "<<pow(scale,-double(alpha-1))<<" is: "<<residual<<std::endl; // unscale u u.add(pow(scale,-double(alpha-1)), *Du); } /* // ------ LINEAR LINE SEARCH (Not tested) ------------- for (unsigned int alpha = 1; alpha < num_points; ++alpha) { u.add(-1.0/num_points, *Du); residual = app->residual(*res, u); if (residual < min_residual && !std::isnan(residual)) { opt_alpha = alpha*(1.0/num_points); min_residual = residual; } } // unscale u u.add(1.0, *Du); */ //FcstUtilities::log<<"Norm of change in solution: "<<Du->l2_norm()<<std::endl; //FcstUtilities::log<<"Line search with "<<num_points<<" number of points. Optimal alpha: "<<opt_alpha<<std::endl; FcstUtilities::log << "Step size = " << -opt_alpha << std::endl; u.add(opt_alpha, *Du); residual = app->residual(*res, src1); } else // No line search { //////////////////////////////////////////////////////////// // a) First, use overrelaxation during the initial // iterations because Newton's algorithm tends to overshoot: double alpha = 1.0; const double* ref = get_data()->scalar("Refinement"); if (this->step < overrelax_steps && *ref < 1) { alpha = overrelax*this->step; alpha = (alpha <= 1) ? alpha : 1; FcstUtilities::log << "Step size = " << alpha << std::endl; } // Update solution u.add(-alpha,*Du); // Update residual old_residual = residual; residual = app->residual(*res, src1); // b) Next, make sure that the chosen step reduces the residual // overwise reduce the residual further: unsigned int step_size = 0; while (residual >= old_residual || std::isnan(residual)) { ++step_size; if (control.log_history()) FcstUtilities::log << "Step size: 2^{-" << step_size << "}" << std::endl; if (step_size > 20) { if (control.log_history()) FcstUtilities::log << "Step size too small!" << std::endl; break; } u.add(pow(2,-double(step_size)), *Du); residual = app->residual(*res, src1); } } // Output the global residual and the equation specific residual: FcstUtilities::log << "Overall residual "<<"at iteration "<<this->step<<" = " << residual << std::endl; for (unsigned int i = 0; i<res->n_blocks(); i++) FcstUtilities::log << "Residual for equation "<<i<<" is: "<<res->block(i).l2_norm() << std::endl; // Debug output options: this->debug_output(u, *Du, *res); } get_data()->block_vector_pool.free(Du); get_data()->block_vector_pool.free(res); FcstUtilities::log.pop(); // in case of failure: throw // exception if (control.last_check() != SolverControl::success) throw SolverControl::NoConvergence (control.last_step(), control.last_value()); // otherwise exit as normal }
[ "secanell@ualberta.ca" ]
secanell@ualberta.ca
55e89797dd08555473d5390dd5de26a62e67cceb
f88d76cd4962f2986de087592126e36634f7e910
/include/sead/ray.h
891047046e31e6c9465466492f9836854adf8d05
[]
no_license
GRAnimated/Superstar
302f17bc9a662340f0514b20c1ae224c4e7d8794
d9565c2c6d4bf52500c7f732e60cb40af3902735
refs/heads/master
2021-01-02T01:21:38.548921
2020-02-25T23:04:48
2020-02-25T23:04:48
239,430,097
8
1
null
null
null
null
UTF-8
C++
false
false
150
h
/** * @file ray.h * @brief Severely basic Ray template class. */ #pragma once namespace sead { template<typename T> class Ray { }; };
[ "devin@nhscan.com" ]
devin@nhscan.com
ea1be306eae7d4579c6752d2f3d6f8414c3be19b
6ac0d7ffef9586660667b6a8900e2d3e90528ae1
/src/lib/CovMatrix.hpp
9306784a68e9fb89a2864621d0936b63a32d919a
[]
no_license
vlanore/new_bayescode
6d2e6bd5ed9a0e5cbcd76f1082a505237f9d864a
969d71d244b14bbaab5bd0f243068f51cbe2a4a3
refs/heads/master
2022-09-02T03:45:03.074056
2022-07-18T19:27:34
2022-07-18T19:27:34
215,250,479
0
0
null
null
null
null
UTF-8
C++
false
false
9,127
hpp
#pragma once #include "linalg.hpp" #include "components/custom_tracer.hpp" class CovMatrix : public custom_tracer { public: CovMatrix(int indim) : value(indim, std::vector<double>(indim, 0)), invvalue(indim, std::vector<double>(indim, 0)), u(indim, std::vector<double>(indim, 0)), invu(indim, std::vector<double>(indim, 0)), v(indim,0), logv(indim,0), diagflag(false) { for (size_t i=0; i<size(); i++) { value[i][i] = 1.0; } } CovMatrix(const CovMatrix& from) : value(from.value), invvalue(from.invvalue), u(from.u), invu(from.invu), v(from.v), logv(from.logv), diagflag(false) { } virtual ~CovMatrix() {} size_t size() const { return value.size(); } const std::vector<double>& operator[](size_t i) const {return value.at(i);} double operator()(int i, int j) const { return value.at(i).at(j); } void to_stream_header(std::string name, std::ostream& os) const override { for (size_t i=0; i<size(); i++) { for (size_t j=i+1; j<size(); j++) { os << name << "[" << i << "][" << j << "]" << '\t'; } } for (size_t i=0; i<size(); i++) { os << name << "[" << i << "][" << i << "]"; if (i<size()-1) { os << '\t'; } } } void to_stream(std::ostream& os) const override { for (size_t i=0; i<size(); i++) { for (size_t j=i+1; j<size(); j++) { os << value[i][j] << '\t'; } } for (size_t i=0; i<size(); i++) { os << value[i][i]; if (i<size()-1) { os << '\t'; } } } void from_stream(std::istream& is) override { for (size_t i=0; i<size(); i++) { for (size_t j=i+1; j<size(); j++) { is >> value[i][j]; value[j][i] = value[i][j]; } } for (size_t i=0; i<size(); i++) { is >> value[i][i]; } CorruptDiag(); } void setval(int i, int j, double val) { value[i][j] = val; diagflag = false; } void add(int i, int j, double val) { value[i][j] += val; diagflag = false; } CovMatrix& operator*=(double scal) { for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { value[i][j] *= scal; std::cerr << value[i][j] << '\t'; } std::cerr << '\n'; } diagflag = false; return *this; } virtual void MultivariateNormalSample(std::vector<double>& vec, bool inverse=false) const { std::vector<double> principalcomp(size(), 0); for (size_t i=0; i<size(); i++) { if (inverse) { principalcomp[i] = Random::sNormal() * sqrt(GetEigenVal()[i]); } else { principalcomp[i] = Random::sNormal() / sqrt(GetEigenVal()[i]); } } for (size_t i=0; i<size(); i++) { vec[i]=0; } for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { vec[j] += principalcomp[i] * GetEigenVect()[j][i]; } } } double logMultivariateNormalDensity(const std::vector<double>& dval) const { double tXSX = 0; for (size_t i=0; i<size(); i++) { tXSX += GetInvMatrix()[i][i] * dval[i] * dval[i]; for (size_t j=0; j<i ; j++) { tXSX += 2 * GetInvMatrix()[i][j] * dval[j] * dval[i]; } } return -0.5 * (GetLogDeterminant() + tXSX); } const std::vector<double>& GetEigenVal() const { if (! diagflag) Diagonalise(); return v; } const std::vector<double>& GetLogEigenVal() const { if (! diagflag) Diagonalise(); return logv; } const std::vector<std::vector<double>>& GetEigenVect() const { if (! diagflag) { Diagonalise(); } return u; } double GetLogDeterminant() const { double ret = 0; for (size_t i=0; i<size(); i++) { ret += GetLogEigenVal()[i]; } return ret; } const std::vector<std::vector<double>>& GetInvEigenVect() const { if (! diagflag) Diagonalise(); return invu; } void SetToZero() { for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { value[i][j] = 0; } } diagflag = false; } void SetToIdentity() { for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { value[i][j] = 0; } } for (size_t i=0; i<size(); i++) { value[i][i] = 1; } diagflag = false; } /* void Project(int index, double** m) { int k = 0; for (size_t i=0; i<size(); i++) { if (i != index) { size_t l = 0; for (size_t j=0; j<size(); j++) { if (j != index) { m[k][l] = value[i][j] - value[i][index] * value[j][index] / value[index][index]; l++; } } k++; } } } */ const std::vector<std::vector<double>>& GetInvMatrix() const { if (! diagflag) Diagonalise(); return invvalue; } bool isPositive() const { if (! diagflag) Diagonalise(); bool r = true; for (size_t i=0; i<size(); i++) { if(GetEigenVal()[i] <= 1e-6){ r = false; } } return r; } void CorruptDiag() const { diagflag = false; } double GetMax() const { double max = 0; for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { double tmp = fabs(value.at(i).at(j)); if (max < tmp) { max = tmp; } } } return max; } //Set the matrix to it s inverse //loook si diagflag int Invert() { std::vector<std::vector<double>> a(size(), std::vector<double>(size(), 0)); // copy value into a : for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { a[i][j] = value[i][j]; } } double logdet = LinAlg::Gauss(a,size(), value); diagflag = false; if (std::isinf(logdet)) { std::cerr << "error in cov matrix: non invertible\n"; return 1; exit(1); } return 0; } double CheckInverse() const { double max = 0; for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { double tot = 0; for (size_t k=0; k<size(); k++) { tot += value.at(i).at(k) * GetInvMatrix()[k][j]; } if (i == j) { tot --; } if (max < fabs(tot)) { max = fabs(tot); } } } return max; } int Diagonalise() const { int nmax = 1000; double epsilon = 1e-10; int n = LinAlg::DiagonalizeSymmetricMatrix(value,size(),nmax,epsilon,v,u); bool failed = (n == nmax); if (failed) { std::cerr << "diag failed\n"; std::cerr << n << '\n'; for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { std::cerr << value.at(i).at(j) << '\t'; } std::cerr << '\n'; } exit(1); } // normalise u for (size_t i=0; i<size(); i++) { double total = 0; for (size_t j=0; j<size(); j++) { total += u[j][i] * u[j][i]; } } // u-1 = tu for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { invu[j][i] = u[i][j]; } } for (size_t i=0; i<size(); i++) { logv[i] = log(v[i]); } LinAlg::Gauss(value,size(),invvalue); diagflag = true; double tmp = CheckDiag(); if (tmp > 1e-6) { std::cerr << "diag error in cov matrix\n"; std::cerr << tmp << '\n'; exit(1); } return failed; } double CheckDiag() const { std::vector<std::vector<double>> a(size(), std::vector<double>(size(), 0)); std::vector<std::vector<double>> b(size(), std::vector<double>(size(), 0)); for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { double tot = 0; for (size_t k=0; k<size(); k++) { tot += invu[i][k] * value.at(k).at(j); } a[i][j] = tot; } } double max = 0; for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { double tot = 0; for (size_t k=0; k<size(); k++) { tot += a[i][k] * u[k][j]; } b[i][j] = tot; if (i != j) { if (max < fabs(tot)) { max = fabs(tot); } } } } return max; } void SetToScatterMatrix(const std::vector<std::vector<double>>& invals) { int df = invals.size(); for (size_t i=0; i<size(); i++) { for (size_t j=0; j<size(); j++) { value[i][j] = 0; for (int l=0; l<df; l++) { value[i][j] += invals[l][i] * invals[l][j]; } } } diagflag = false; } private: std::vector<std::vector<double>> value; // inverse mutable std::vector<std::vector<double>> invvalue; // eigenvect mutable std::vector<std::vector<double>> u; // inv eigenvect mutable std::vector<std::vector<double>> invu; // eigenval mutable std::vector<double> v; // log eigenval mutable std::vector<double> logv; mutable bool diagflag; };
[ "nicolas.lartillot@gmail.com" ]
nicolas.lartillot@gmail.com
3d579f5b9f935846fc46e581fd8c78833780c498
51c0442c62be96c47a5702e46a8962143c5ed303
/Union Find/UnionFind.h
7698da0e4231b320c93cc7d6eac4a4e4599efe3a
[]
no_license
KamilB00/algorithms-time-analysis
2e6faaa780e7a22c76e3b8033fc332d01ed9ea53
c8a17393026f6b419816b1bdf3c3c8f592b066b8
refs/heads/master
2023-06-03T22:37:21.470396
2021-06-16T20:23:40
2021-06-16T20:23:40
371,028,889
0
0
null
2021-06-16T20:23:40
2021-05-26T12:38:37
C++
UTF-8
C++
false
false
350
h
#include "../Data Structures/Priority Queue/Queue.cpp" struct UnionNode{ int up; int rank; }; class UnionFind{ private: UnionNode *set; int numOfVer; public: UnionFind(int n); ~UnionFind(); void makeSet(int v); int findSet(int v); bool isOneSet(); void printSet(); void unionSets(Edge_Element edge); };
[ "bonkowski.kamil@icloud.com" ]
bonkowski.kamil@icloud.com
e27175e4e677261e8eab72d81f2a952b6c4023a9
0c6d1094ebd14895c6b3337fedfe1f0b369ebc73
/2021/Codeforces/1493B.cpp
7b50ca61b297e35a6f5a1b857d484838e98c82f5
[]
no_license
imran43h/Coding
51ab117e1ff2ba16b375fc289dc4553d8cabd87d
11e74e400e70abb845b8607a500015ed672b5aab
refs/heads/master
2023-03-29T22:01:50.357010
2021-04-08T12:37:25
2021-04-08T12:37:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,504
cpp
#include<bits/stdc++.h> #define Fast ios::sync_with_stdio(0);cin.tie(0);cout.tie(0); #define Freed freopen ("0in.txt","r",stdin); #define Fout freopen ("0out.txt","w",stdout); #define ll long long int #define pb push_back #define mp make_pair #define pi acos(-1.0) #define Mod 1000000007 #define limit 1000008 using namespace std; bool vis[12]; void solve(int t) { ll i,j,n=5,m,k,h; string s; cin >> h >> m ; cin >> s; int g1,g2,p1,p2,h1,h2,m1,m2; g1 = h/10; g2 = h%10; p1 = m/10; p2 = m%10; h1 = s[0]-'0'; h1 = h1*10+s[1]-'0'; m1 = (s[3]-'0')*10+s[4]-'0'; while(1) { if(m1>=m) { h1++; m1 = 0; } if(vis[m1/10] && vis[m1%10]) break; m1++; } while(1) { if(h1>=h) { cout <<"00:00\n"; return; } if(vis[h1/10] && vis[h1%10]) break; h1++; } cout <<h1/10<<h1%10<<":"<<m1/10<<m1%10<<endl; return ; while(vis[m2]==0 || m2==p2) { if(m2>=9) { m1++; m2 = 0; } else m2++; } while(vis[m1]==0) { if(m1>=p1) { h2++; m1 = 0; break; } else m1++; } while(vis[h2]==0 || h2==g2) { if(h2==9) { h1++; h2 = m1 = m2 = 0; } else h2++; } while(vis[h1]==0) { if(h1>=g1) { h1++; h2 = m1 = m2 = 0; break; } else h1++; } if(h1>=g1) { cout <<"00:00\n"; return ; } cout <<h1<<h2<<":"<<m1<<m2<<endl; return ; if(h1==3 || h1==4) { h1 = 5; h2= m1 = m2 = 0; } if(h1==6 || h1==7) { h1 = 8; h2= m1 = m2 = 0; } if(h2==3 || h2==4) { h1 = 5; m1 = m2 = 0; } if(h2==6 || h2==7) { h1 = 8; m1 = m2 = 0; } if(m1==3 || m1==4) { m1 = 5; m2 = 0; } if(m1==6 || m1==7) { m1 = 8; m2 = 0; } if(m2==3 || m2==4) { m2 = 5; } if(m1==6 || m1==7) { m1 = 8; } return ; } int main() { // Fast // Freed // Fout vis[0] = vis[1] = vis[2] = vis[5] = vis[8] = 1; int t,tt=1; cin >> tt; for(t=1; t<=tt; t++) solve(t); return 0; }
[ "md.naeem.al.imran@gmail.com" ]
md.naeem.al.imran@gmail.com
44cb44d896eac372e8769c08a9d618cd42cecef0
99315747ff1b821d3dfc6edccbb9d359bdb3289b
/PurpleUI/PurpleUI/SurfaceSystem/ViewRect.cpp
8432af7c3261eced37a0a451d17809ad8f131034
[]
no_license
gitQqqHs/PurpleUI
235371b2817ec9810cfefa9d91be15f542becdf0
f7b2b45494507ddaeba00d97d1916367aa4d485c
refs/heads/master
2020-08-09T12:45:28.394588
2019-06-10T14:00:04
2019-06-10T14:00:04
null
0
0
null
null
null
null
WINDOWS-1252
C++
false
false
1,011
cpp
#include "ViewRect.h" ViewRect::~ViewRect() { Clear(); } void ViewRect::SetViewRect(int w, int h, char ch) { m_viewData = new char[(w + 1)*h]; //ÉèÖÃViewÇøÓò m_srcRect.x = m_srcRect.y = 0; m_srcRect.h = h; m_srcRect.w = w; m_cutRect = m_srcRect; m_isSrcData = true; ResetSrcView(ch); } void ViewRect::SetViewRect(const ViewRect & src) { m_viewData = src.m_viewData; m_srcRect = src.m_srcRect; m_cutRect = src.m_cutRect; m_isSrcData = false; } void ViewRect::SetViewRect(const ViewRect &src, const Rect & cut) { SetViewRect(src); m_cutRect.x = src.m_cutRect.x + cut.x >= 0 ? cut.x : 0; m_cutRect.y = src.m_cutRect.y + cut.y >= 0 ? cut.y : 0; m_cutRect.w = cut.w > src.m_cutRect.w ? src.m_cutRect.w : cut.w; m_cutRect.h = cut.h > src.m_cutRect.h ? src.m_cutRect.h : cut.h; } void ViewRect::SetViewRect(ViewRect && src) { m_viewData = src.m_viewData; m_isSrcData = src.m_isSrcData ? true : false; m_srcRect = src.m_srcRect; m_cutRect = src.m_cutRect; src.m_isSrcData = false; }
[ "wpq2225232027@163.com" ]
wpq2225232027@163.com
5d05f0b25e1efe512488486c98aeae61f4a6cef7
47a329f97802a17a418425125dba7155d574c8e5
/Kratos/DlgSettingsForCurvers.cpp
11d9d0e2edff2fc025b0ba3d9f25b6f825344fd6
[]
no_license
Alexepus/Kratos
17ff64c4483d1655e8be051536cfbcddf250691e
cee428532308938d0a0aa80c9f6778817413deb7
refs/heads/master
2021-01-19T10:59:37.823686
2019-08-25T17:18:50
2019-08-25T17:18:50
15,020,259
0
0
null
null
null
null
UTF-8
C++
false
false
16,202
cpp
// DlgSettingsForCurvers.cpp : implementation file // #include "stdafx.h" #include "Main.h" //#include "ProgNew.h" //#include "DlgSettingsForCurvers.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CDlgSettingsForCurvers dialog //class CMainFrame; CDlgSettingsForCurvers::CDlgSettingsForCurvers(CWnd* pParent /*=NULL*/) : CDialog(CDlgSettingsForCurvers::IDD, pParent) { /* //{{AFX_DATA_INIT(CDlgSettingsForCurvers) m_CheckCurrLine = FALSE; m_CheckCurrPoints = FALSE; m_CheckResLine = FALSE; m_CheckResPoints = FALSE; m_CheckGrid = FALSE; m_CheckGuideLines = FALSE; //}}AFX_DATA_INIT // m_CurrSizePoints = 2; */ /* m_CheckCurrLine = m_pMainFrame->m_Doc.m_Graph.m_LineShort; m_CheckCurrPoints = m_pMainFrame->m_Doc.m_Graph.m_PointsShort; m_SizePointsCurr = m_pMainFrame->m_Doc.m_Graph.m_SizePointsShort; m_CheckResLine = m_pMainFrame->m_Doc.m_Graph.m_LineAll; m_CheckResPoints = m_pMainFrame->m_Doc.m_Graph.m_PointsAll; m_SizePointsRes = m_pMainFrame->m_Doc.m_Graph.m_SizePointsAll; */ //m_CheckGrid = TRUE; //if(m_CheckCurrLine) AfxMessageBox("m_CheckCurrLine==TRUE"); //else AfxMessageBox("m_CheckCurrLine==FALSE"); } void CDlgSettingsForCurvers::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(CDlgSettingsForCurvers) DDX_Check(pDX, IDC_CHECK_CURR_LINE, m_CheckCurrLine); DDX_Check(pDX, IDC_CHECK_CURR_POINTS, m_CheckCurrPoints); DDX_Check(pDX, IDC_CHECK_RES_LINE, m_CheckResLine); DDX_Check(pDX, IDC_CHECK_RES_POINTS, m_CheckResPoints); DDX_Check(pDX, IDC_CHECK_GRID, m_CheckGrid); DDX_Check(pDX, IDC_CHECK_GUIDE_LINES, m_CheckGuideLines); //}}AFX_DATA_MAP } BEGIN_MESSAGE_MAP(CDlgSettingsForCurvers, CDialog) //{{AFX_MSG_MAP(CDlgSettingsForCurvers) ON_BN_CLICKED(IDC_CHECK_CURR_LINE, OnCheckCurrLine) ON_BN_CLICKED(IDC_BUTTON_CURR_COLOR, OnButtonCurrColor) ON_BN_CLICKED(IDC_CHECK_CURR_POINTS, OnCheckCurrPoints) ON_WM_PAINT() ON_CBN_SELENDOK(IDC_COMBO_SIZE_CURR, OnSelEndOkComboSizeCurr) ON_BN_CLICKED(IDC_BUTTON_RES_COLOR, OnButtonResColor) ON_BN_CLICKED(IDC_CHECK_RES_LINE, OnCheckResLine) ON_BN_CLICKED(IDC_CHECK_RES_POINTS, OnCheckResPoints) ON_CBN_SELENDOK(IDC_COMBO_SIZE_RES, OnSelEndOkComboSizeRes) ON_BN_CLICKED(IDC_CHECK_GRID, OnCheckGrid) ON_BN_CLICKED(IDC_BUTTON_GRID_COLOR, OnButtonGridColor) ON_BN_CLICKED(IDC_CHECK_GUIDE_LINES, OnCheckGuideLines) //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CDlgSettingsForCurvers message handlers BOOL CDlgSettingsForCurvers::OnInitDialog() { CDialog::OnInitDialog(); // TODO: Add extra initialization here m_ColorCurr = m_pMainFrame->m_Doc.m_Graph.m_DataShortColor; m_ColorRes = m_pMainFrame->m_Doc.m_Graph.m_DataAllColor; m_ColorGrid = m_pMainFrame->m_Doc.m_Graph.m_GridColor; m_CheckCurrLine = m_pMainFrame->m_Doc.m_Graph.m_LineShort; m_CheckCurrPoints = m_pMainFrame->m_Doc.m_Graph.m_PointsShort; m_SizePointsCurr = m_pMainFrame->m_Doc.m_Graph.m_SizePointsShort; m_CheckResLine = m_pMainFrame->m_Doc.m_Graph.m_LineAll; m_CheckResPoints = m_pMainFrame->m_Doc.m_Graph.m_PointsAll; m_SizePointsRes = m_pMainFrame->m_Doc.m_Graph.m_SizePointsAll; m_CheckGrid = m_pMainFrame->m_Doc.m_Graph.m_Grid; m_CheckGuideLines = m_pMainFrame->m_Doc.m_Graph.m_GuideLines; HWND hWndChild = ::GetDlgItem(this->m_hWnd, IDC_CHECK_CURR_LINE); if(m_CheckCurrLine) ::SendMessage(hWndChild, BM_SETCHECK, 1, 0); else ::SendMessage(hWndChild, BM_SETCHECK, 0, 0); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_CHECK_CURR_POINTS); if(m_CheckCurrPoints) ::SendMessage(hWndChild, BM_SETCHECK, 1, 0); else ::SendMessage(hWndChild, BM_SETCHECK, 0, 0); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_CHECK_RES_LINE); if(m_CheckResLine) ::SendMessage(hWndChild, BM_SETCHECK, 1, 0); else ::SendMessage(hWndChild, BM_SETCHECK, 0, 0); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_CHECK_RES_POINTS); if(m_CheckResPoints) ::SendMessage(hWndChild, BM_SETCHECK, 1, 0); else ::SendMessage(hWndChild, BM_SETCHECK, 0, 0); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_CHECK_GRID); if(m_CheckGrid) ::SendMessage(hWndChild, BM_SETCHECK, 1, 0); else ::SendMessage(hWndChild, BM_SETCHECK, 0, 0); int i; char strCombo[16]; //m_CheckCurrLine = TRUE; // CURRENT CURVE hWndChild = ::GetDlgItem(this->m_hWnd, IDC_EDIT_CURR_SAMPLE); RECT r; ::GetClientRect(hWndChild, &r); m_hWndSimpleCurr = ::CreateWindow(m_pMainFrame->m_Doc.m_Graph.m_cl_name_for_curve, NULL, WS_CHILD|WS_CLIPCHILDREN|WS_VISIBLE,//|WS_HSCROLL|WS_VSCROLL, 0, 0, r.right, r.bottom, hWndChild, NULL, AfxGetInstanceHandle(),0); UpdateWndSimpleCurr(); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_CURR); for(i=0; i<19; ++i) { sprintf(strCombo, "%i", 2+i); ::SendMessage(hWndChild, CB_ADDSTRING, 0, (LPARAM) strCombo); } ::SendMessage(hWndChild, CB_SETCURSEL , (WPARAM) (m_SizePointsCurr-2), 0); //::SendMessage(hWndChild, CB_SETITEMHEIGHT , 0, 100); // RESULT CURVE hWndChild = ::GetDlgItem(this->m_hWnd, IDC_EDIT_RES_SAMPLE); ::GetClientRect(hWndChild, &r); m_hWndSimpleRes = ::CreateWindow(m_pMainFrame->m_Doc.m_Graph.m_cl_name_for_curve, NULL, WS_CHILD|WS_CLIPCHILDREN|WS_VISIBLE,//|WS_HSCROLL|WS_VSCROLL, 0, 0, r.right, r.bottom, hWndChild, NULL, AfxGetInstanceHandle(),0); UpdateWndSimpleRes(); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_RES); for(i=0; i<19; ++i) { sprintf(strCombo, "%i", 2+i); ::SendMessage(hWndChild, CB_ADDSTRING, 0, (LPARAM) strCombo); } ::SendMessage(hWndChild, CB_SETCURSEL , (WPARAM) (m_SizePointsRes-2), 0); // GRID hWndChild = ::GetDlgItem(this->m_hWnd, IDC_EDIT_GRID_SAMPLE); // RECT r; ::GetClientRect(hWndChild, &r); m_hWndSimpleGrid = ::CreateWindow(m_pMainFrame->m_Doc.m_Graph.m_cl_name_for_curve, NULL, WS_CHILD|WS_CLIPCHILDREN|WS_VISIBLE,//|WS_HSCROLL|WS_VSCROLL, 0, 0, r.right, r.bottom, hWndChild, NULL, AfxGetInstanceHandle(),0); UpdateWndSimpleGrid(); //GUIDE LINES hWndChild = ::GetDlgItem(this->m_hWnd, IDC_EDIT_CURSOR_SAMPLE); ::GetClientRect(hWndChild, &r); m_hWndSimpleGuideLines = ::CreateWindow(m_pMainFrame->m_Doc.m_Graph.m_cl_name_for_curve, NULL, WS_CHILD|WS_CLIPCHILDREN|WS_VISIBLE,//|WS_HSCROLL|WS_VSCROLL, 0, 0, r.right, r.bottom, hWndChild, NULL, AfxGetInstanceHandle(),0); UpdateWndSimpleGuideLines(); UpdateData(FALSE); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CDlgSettingsForCurvers::OnCheckCurrLine() { // TODO: Add your control notification handler code here if(m_CheckCurrLine) m_CheckCurrLine = FALSE; else m_CheckCurrLine = TRUE; UpdateWndSimpleCurr(); } //========= void CDlgSettingsForCurvers::OnCheckResLine() { // TODO: Add your control notification handler code here if(m_CheckResLine) m_CheckResLine = FALSE; else m_CheckResLine = TRUE; UpdateWndSimpleRes(); } //======== void CDlgSettingsForCurvers::OnCheckCurrPoints() { // TODO: Add your control notification handler code here //HWND hWndChild;// = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_CURR); if(m_CheckCurrPoints) m_CheckCurrPoints = FALSE; else m_CheckCurrPoints = TRUE; UpdateWndSimpleCurr(); } //========= void CDlgSettingsForCurvers::OnCheckResPoints() { // TODO: Add your control notification handler code here if(m_CheckResPoints) m_CheckResPoints = FALSE; else m_CheckResPoints = TRUE; UpdateWndSimpleRes(); } //========= void CDlgSettingsForCurvers::OnSelEndOkComboSizeCurr() { // TODO: Add your control notification handler code here //AfxMessageBox("OnSelEndOkComboSizeCurr() "); UINT res; HWND hWndChild = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_CURR); res = (UINT) ::SendMessage(hWndChild, CB_GETCURSEL , 0, 0); if(res!=CB_ERR) m_SizePointsCurr = res+2; UpdateWndSimpleCurr(); } //=========== void CDlgSettingsForCurvers::OnSelEndOkComboSizeRes() { // TODO: Add your control notification handler code here UINT res; HWND hWndChild = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_RES); res = (UINT) ::SendMessage(hWndChild, CB_GETCURSEL , 0, 0); if(res!=CB_ERR) m_SizePointsRes = res+2; UpdateWndSimpleRes(); } //=========== void CDlgSettingsForCurvers::UpdateWndSimpleCurr() { HWND hWndChild; HDC DC; DC = ::GetDC(m_hWndSimpleCurr); RECT r; ::GetClientRect(m_hWndSimpleCurr, &r); //LOGBRUSH LogBrush = {BS_SOLID, m_pMainFrame->m_Doc.m_Graph.m_DataShortColor,0}; LOGBRUSH LogBrush = {BS_SOLID, m_ColorCurr, 0}; HPEN NewPen = ::ExtCreatePen( PS_COSMETIC | PS_SOLID, 1, &LogBrush,0,0); HPEN OldPen = (HPEN) ::SelectObject(DC, NewPen); HBRUSH NewBrush = ::CreateBrushIndirect(&LogBrush); HBRUSH OldBrush = (HBRUSH) ::SelectObject(DC, NewBrush); //::SetBkColor(DC, m_ColorCurr); ::InvalidateRect(m_hWndSimpleCurr, &r, TRUE); ::UpdateWindow(m_hWndSimpleCurr); if(m_CheckCurrLine) { ::MoveToEx(DC, 0, r.bottom, NULL); ::LineTo(DC, r.right, 0); } if(m_CheckCurrPoints) ::Ellipse(DC, r.right/2-m_SizePointsCurr/2, r.bottom/2-m_SizePointsCurr/2, (int)(r.right/2+m_SizePointsCurr/2.+0.5), (int)(r.bottom/2+m_SizePointsCurr/2.+0.5) ); ::SelectObject(DC, OldBrush); ::SelectObject(DC, OldPen); ::DeleteObject(NewBrush); ::DeleteObject(NewPen); ::ReleaseDC(m_hWndSimpleCurr, DC); if(!m_CheckCurrPoints) { hWndChild = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_CURR); ::EnableWindow(hWndChild, FALSE); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_STATIC_CURR); ::EnableWindow(hWndChild, FALSE); } else { hWndChild = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_CURR); ::EnableWindow(hWndChild, TRUE); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_STATIC_CURR); ::EnableWindow(hWndChild, TRUE); } hWndChild = ::GetDlgItem(this->m_hWnd, IDC_BUTTON_CURR_COLOR); if(!m_CheckCurrPoints && !m_CheckCurrLine) ::EnableWindow(hWndChild, FALSE); else ::EnableWindow(hWndChild, TRUE); } COLORREF CDlgSettingsForCurvers::WndColorSet(COLORREF rgb) { COLORREF CustColor[16]; CHOOSECOLOR cc; CWinApp* App = AfxGetApp(); //rgb = (COLORREF) App->GetProfileInt("COLOR","FirstColor",0xff0000); char* str[] = {"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16"}; //rgb=RGB(0,0,255); int i; for(i=0; i<16; ++i) CustColor[i]=(COLORREF) App->GetProfileInt("COLOR",str[i],0xffffff); memset(&cc, 0, sizeof(CHOOSECOLOR)); cc.lStructSize=sizeof(CHOOSECOLOR); cc.hwndOwner=m_hWnd; // cc.hInstance=AfxGetInstanceHandle(); cc.lpCustColors=CustColor; cc.Flags=CC_RGBINIT|CC_FULLOPEN; cc.rgbResult=rgb; if(::ChooseColor(&cc)) rgb=cc.rgbResult; //App->WriteProfileInt("COLOR","FirstColor",(int) rgb); for(i=0; i<16; ++i) App->WriteProfileInt("COLOR",str[i],cc.lpCustColors[i]); /* m_Doc.m_Graph.m_DataAllColor = (COLORREF) App->GetProfileInt("COLOR","1",0xff0000); m_Doc.m_Graph.m_DataShortColor = (COLORREF) App->GetProfileInt("COLOR","2",0xff0000); m_Doc.m_Graph.m_GridColor = (COLORREF) App->GetProfileInt("COLOR","3",0xff0000); //REDRAW m_Doc.m_Graph.ReDrawAll(); */ return rgb; } //========== void CDlgSettingsForCurvers::OnButtonCurrColor() { // TODO: Add your control notification handler code here m_ColorCurr = WndColorSet(m_ColorCurr); UpdateWndSimpleCurr(); } //========== void CDlgSettingsForCurvers::OnButtonResColor() { // TODO: Add your control notification handler code here m_ColorRes = WndColorSet(m_ColorRes); UpdateWndSimpleRes(); } void CDlgSettingsForCurvers::OnPaint() { CPaintDC dc(this); // device context for painting // TODO: Add your message handler code here UpdateWndSimpleCurr(); UpdateWndSimpleRes(); UpdateWndSimpleGrid(); UpdateWndSimpleGuideLines(); // Do not call CDialog::OnPaint() for painting messages } void CDlgSettingsForCurvers::UpdateWndSimpleRes() { HWND hWndChild; HDC DC; DC = ::GetDC(m_hWndSimpleRes); RECT r; ::GetClientRect(m_hWndSimpleRes, &r); //LOGBRUSH LogBrush = {BS_SOLID, m_pMainFrame->m_Doc.m_Graph.m_DataShortColor,0}; LOGBRUSH LogBrush = {BS_SOLID, m_ColorRes, 0}; HPEN NewPen = ::ExtCreatePen( PS_COSMETIC | PS_SOLID, 1, &LogBrush,0,0); HPEN OldPen = (HPEN) ::SelectObject(DC, NewPen); HBRUSH NewBrush = ::CreateBrushIndirect(&LogBrush); HBRUSH OldBrush = (HBRUSH) ::SelectObject(DC, NewBrush); //::SetBkColor(DC, m_ColorCurr); ::InvalidateRect(m_hWndSimpleRes, &r, TRUE); ::UpdateWindow(m_hWndSimpleRes); if(m_CheckResLine) { ::MoveToEx(DC, 0, r.bottom, NULL); ::LineTo(DC, r.right, 0); } if(m_CheckResPoints) ::Ellipse(DC, r.right/2-m_SizePointsRes/2, r.bottom/2-m_SizePointsRes/2, (int)(r.right/2+m_SizePointsRes/2.+0.5), (int)(r.bottom/2+m_SizePointsRes/2.+0.5) ); ::SelectObject(DC, OldBrush); ::SelectObject(DC, OldPen); ::DeleteObject(NewBrush); ::DeleteObject(NewPen); ::ReleaseDC(m_hWndSimpleRes, DC); if(!m_CheckResPoints) { hWndChild = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_RES); ::EnableWindow(hWndChild, FALSE); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_STATIC_RES); ::EnableWindow(hWndChild, FALSE); } else { hWndChild = ::GetDlgItem(this->m_hWnd, IDC_COMBO_SIZE_RES); ::EnableWindow(hWndChild, TRUE); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_STATIC_RES); ::EnableWindow(hWndChild, TRUE); } hWndChild = ::GetDlgItem(this->m_hWnd, IDC_BUTTON_RES_COLOR); if(!m_CheckResPoints && !m_CheckResLine) ::EnableWindow(hWndChild, FALSE); else ::EnableWindow(hWndChild, TRUE); } void CDlgSettingsForCurvers::OnCheckGrid() { // TODO: Add your control notification handler code here if(m_CheckGrid) m_CheckGrid = FALSE; else m_CheckGrid = TRUE; UpdateWndSimpleGrid(); } void CDlgSettingsForCurvers::UpdateWndSimpleGrid() { HWND hWndChild; HDC DC; DC = ::GetDC(m_hWndSimpleGrid); RECT r; ::GetClientRect(m_hWndSimpleGrid, &r); //LOGBRUSH LogBrush = {BS_SOLID, m_pMainFrame->m_Doc.m_Graph.m_DataShortColor,0}; LOGBRUSH LogBrush = {BS_SOLID, m_ColorGrid, 0}; HPEN NewPen = ::ExtCreatePen( PS_GEOMETRIC | PS_DOT, 1, &LogBrush,0,0); HPEN OldPen = (HPEN) ::SelectObject(DC, NewPen); //HBRUSH NewBrush = ::CreateBrushIndirect(&LogBrush); //HBRUSH OldBrush = (HBRUSH) ::SelectObject(DC, NewBrush); ::SetBkColor(DC, m_ColorGrid); ::InvalidateRect(m_hWndSimpleGrid, &r, TRUE); ::UpdateWindow(m_hWndSimpleGrid); if(m_CheckGrid) { ::MoveToEx(DC, 0, r.bottom/3, NULL); ::LineTo(DC, r.right, r.bottom/3); ::MoveToEx(DC, 0, 2*r.bottom/3, NULL); ::LineTo(DC, r.right, 2*r.bottom/3); ::MoveToEx(DC, r.right/3, 0, NULL); ::LineTo(DC, r.right/3, r.bottom); ::MoveToEx(DC, 2*r.right/3, 0, NULL); ::LineTo(DC, 2*r.right/3, r.bottom); } ::SelectObject(DC, OldPen); //::DeleteObject(NewBrush); ::DeleteObject(NewPen); ::ReleaseDC(m_hWndSimpleGrid, DC); hWndChild = ::GetDlgItem(this->m_hWnd, IDC_BUTTON_GRID_COLOR); if(!m_CheckGrid) ::EnableWindow(hWndChild, FALSE); else ::EnableWindow(hWndChild, TRUE); } void CDlgSettingsForCurvers::OnButtonGridColor() { // TODO: Add your control notification handler code here m_ColorGrid = WndColorSet(m_ColorGrid); UpdateWndSimpleGrid(); } void CDlgSettingsForCurvers::OnCheckGuideLines() { UpdateData(); UpdateWndSimpleGuideLines(); } void CDlgSettingsForCurvers::UpdateWndSimpleGuideLines() { HDC DC; DC = ::GetDC(m_hWndSimpleGuideLines); RECT r; ::GetClientRect(m_hWndSimpleGuideLines, &r); LOGBRUSH LogBrush = {BS_SOLID, m_ColorGrid, 0}; HPEN NewPen; HPEN OldPen; ::SetBkColor(DC, (COLORREF) RGB(0,0,0)); ::SetROP2(DC, R2_NOT); ::InvalidateRect(m_hWndSimpleGuideLines, &r, TRUE); ::UpdateWindow(m_hWndSimpleGuideLines); if(m_CheckGuideLines) { NewPen = ::ExtCreatePen(PS_COSMETIC | PS_DOT, 1, &LogBrush, 0, 0); OldPen = (HPEN) ::SelectObject(DC, NewPen); ::MoveToEx(DC, 0, r.bottom/2, NULL); ::LineTo(DC, r.right, r.bottom/2); ::MoveToEx(DC, r.right/2, 0, NULL); ::LineTo(DC, r.right/2, r.bottom); } else { NewPen = ::ExtCreatePen( PS_GEOMETRIC , 1, &LogBrush,0,0); OldPen = (HPEN) ::SelectObject(DC, NewPen); ::MoveToEx(DC, r.right/2-8, r.bottom/2, NULL); ::LineTo(DC, r.right/2+8, r.bottom/2); ::MoveToEx(DC, r.right/2, r.bottom/2-8, NULL); ::LineTo(DC, r.right/2, r.bottom/2+8); } ::SelectObject(DC, OldPen); ::DeleteObject(NewPen); ::ReleaseDC(m_hWndSimpleGrid, DC); }
[ "alexpopov@mail.ru" ]
alexpopov@mail.ru
ee0a375b5c2ab0595549ad33f253e16f010d2d4d
41ab6b8bbeb03958c59350ae6da2887a4bf8e144
/third_party/v8/src/assembler.cc
2037a0ec8fbcdf9d5dee4c70e0b80437e5c24b41
[ "Apache-2.0", "SunPro", "BSD-3-Clause", "bzip2-1.0.6" ]
permissive
ofrobots/no-bazel
6472b0bb1b3309d8613ee97c6526a3fa46060eab
f7eb147044dc35aac86df8bd9bec2cc55863ce17
refs/heads/master
2020-04-07T14:21:40.305137
2018-12-08T00:53:07
2018-12-08T00:53:07
158,443,929
4
0
Apache-2.0
2018-12-13T01:54:59
2018-11-20T19:56:42
C++
UTF-8
C++
false
false
15,983
cc
// Copyright (c) 1994-2006 Sun Microsystems 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. // // - Redistribution 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 Sun Microsystems or the names of 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. // The original source code covered by the above license above has been // modified significantly by Google Inc. // Copyright 2012 the V8 project authors. All rights reserved. #include "src/assembler.h" #include "src/assembler-inl.h" #include "src/code-stubs.h" #include "src/deoptimizer.h" #include "src/disassembler.h" #include "src/instruction-stream.h" #include "src/isolate.h" #include "src/ostreams.h" #include "src/simulator.h" // For flushing instruction cache. #include "src/snapshot/serializer-common.h" #include "src/snapshot/snapshot.h" #include "src/string-constants.h" namespace v8 { namespace internal { AssemblerOptions AssemblerOptions::EnableV8AgnosticCode() const { AssemblerOptions options = *this; options.v8_agnostic_code = true; options.record_reloc_info_for_serialization = false; options.enable_root_array_delta_access = false; // Inherit |enable_simulator_code| value. options.isolate_independent_code = false; options.inline_offheap_trampolines = false; // Inherit |code_range_start| value. // Inherit |use_pc_relative_calls_and_jumps| value. return options; } AssemblerOptions AssemblerOptions::Default( Isolate* isolate, bool explicitly_support_serialization) { AssemblerOptions options; bool serializer = isolate->serializer_enabled() || explicitly_support_serialization; options.record_reloc_info_for_serialization = serializer; options.enable_root_array_delta_access = !serializer; #ifdef USE_SIMULATOR // Don't generate simulator specific code if we are building a snapshot, which // might be run on real hardware. options.enable_simulator_code = !serializer; #endif options.inline_offheap_trampolines = !serializer; #if V8_TARGET_ARCH_X64 || V8_TARGET_ARCH_ARM64 const base::AddressRegion& code_range = isolate->heap()->memory_allocator()->code_range(); DCHECK_IMPLIES(code_range.begin() != kNullAddress, !code_range.is_empty()); options.code_range_start = code_range.begin(); #endif return options; } // ----------------------------------------------------------------------------- // Implementation of AssemblerBase AssemblerBase::AssemblerBase(const AssemblerOptions& options, void* buffer, int buffer_size) : options_(options), enabled_cpu_features_(0), emit_debug_code_(FLAG_debug_code), predictable_code_size_(false), constant_pool_available_(false), jump_optimization_info_(nullptr) { own_buffer_ = buffer == nullptr; if (buffer_size == 0) buffer_size = kMinimalBufferSize; DCHECK_GT(buffer_size, 0); if (own_buffer_) buffer = NewArray<byte>(buffer_size); buffer_ = static_cast<byte*>(buffer); buffer_size_ = buffer_size; pc_ = buffer_; } AssemblerBase::~AssemblerBase() { if (own_buffer_) DeleteArray(buffer_); } void AssemblerBase::FlushICache(void* start, size_t size) { if (size == 0) return; #if defined(USE_SIMULATOR) base::LockGuard<base::Mutex> lock_guard(Simulator::i_cache_mutex()); Simulator::FlushICache(Simulator::i_cache(), start, size); #else CpuFeatures::FlushICache(start, size); #endif // USE_SIMULATOR } void AssemblerBase::Print(Isolate* isolate) { StdoutStream os; v8::internal::Disassembler::Decode(isolate, &os, buffer_, pc_); } // ----------------------------------------------------------------------------- // Implementation of PredictableCodeSizeScope PredictableCodeSizeScope::PredictableCodeSizeScope(AssemblerBase* assembler, int expected_size) : assembler_(assembler), expected_size_(expected_size), start_offset_(assembler->pc_offset()), old_value_(assembler->predictable_code_size()) { assembler_->set_predictable_code_size(true); } PredictableCodeSizeScope::~PredictableCodeSizeScope() { CHECK_EQ(expected_size_, assembler_->pc_offset() - start_offset_); assembler_->set_predictable_code_size(old_value_); } // ----------------------------------------------------------------------------- // Implementation of CpuFeatureScope #ifdef DEBUG CpuFeatureScope::CpuFeatureScope(AssemblerBase* assembler, CpuFeature f, CheckPolicy check) : assembler_(assembler) { DCHECK_IMPLIES(check == kCheckSupported, CpuFeatures::IsSupported(f)); old_enabled_ = assembler_->enabled_cpu_features(); assembler_->EnableCpuFeature(f); } CpuFeatureScope::~CpuFeatureScope() { assembler_->set_enabled_cpu_features(old_enabled_); } #endif bool CpuFeatures::initialized_ = false; unsigned CpuFeatures::supported_ = 0; unsigned CpuFeatures::icache_line_size_ = 0; unsigned CpuFeatures::dcache_line_size_ = 0; ConstantPoolBuilder::ConstantPoolBuilder(int ptr_reach_bits, int double_reach_bits) { info_[ConstantPoolEntry::INTPTR].entries.reserve(64); info_[ConstantPoolEntry::INTPTR].regular_reach_bits = ptr_reach_bits; info_[ConstantPoolEntry::DOUBLE].regular_reach_bits = double_reach_bits; } ConstantPoolEntry::Access ConstantPoolBuilder::NextAccess( ConstantPoolEntry::Type type) const { const PerTypeEntryInfo& info = info_[type]; if (info.overflow()) return ConstantPoolEntry::OVERFLOWED; int dbl_count = info_[ConstantPoolEntry::DOUBLE].regular_count; int dbl_offset = dbl_count * kDoubleSize; int ptr_count = info_[ConstantPoolEntry::INTPTR].regular_count; int ptr_offset = ptr_count * kPointerSize + dbl_offset; if (type == ConstantPoolEntry::DOUBLE) { // Double overflow detection must take into account the reach for both types int ptr_reach_bits = info_[ConstantPoolEntry::INTPTR].regular_reach_bits; if (!is_uintn(dbl_offset, info.regular_reach_bits) || (ptr_count > 0 && !is_uintn(ptr_offset + kDoubleSize - kPointerSize, ptr_reach_bits))) { return ConstantPoolEntry::OVERFLOWED; } } else { DCHECK(type == ConstantPoolEntry::INTPTR); if (!is_uintn(ptr_offset, info.regular_reach_bits)) { return ConstantPoolEntry::OVERFLOWED; } } return ConstantPoolEntry::REGULAR; } ConstantPoolEntry::Access ConstantPoolBuilder::AddEntry( ConstantPoolEntry& entry, ConstantPoolEntry::Type type) { DCHECK(!emitted_label_.is_bound()); PerTypeEntryInfo& info = info_[type]; const int entry_size = ConstantPoolEntry::size(type); bool merged = false; if (entry.sharing_ok()) { // Try to merge entries std::vector<ConstantPoolEntry>::iterator it = info.shared_entries.begin(); int end = static_cast<int>(info.shared_entries.size()); for (int i = 0; i < end; i++, it++) { if ((entry_size == kPointerSize) ? entry.value() == it->value() : entry.value64() == it->value64()) { // Merge with found entry. entry.set_merged_index(i); merged = true; break; } } } // By definition, merged entries have regular access. DCHECK(!merged || entry.merged_index() < info.regular_count); ConstantPoolEntry::Access access = (merged ? ConstantPoolEntry::REGULAR : NextAccess(type)); // Enforce an upper bound on search time by limiting the search to // unique sharable entries which fit in the regular section. if (entry.sharing_ok() && !merged && access == ConstantPoolEntry::REGULAR) { info.shared_entries.push_back(entry); } else { info.entries.push_back(entry); } // We're done if we found a match or have already triggered the // overflow state. if (merged || info.overflow()) return access; if (access == ConstantPoolEntry::REGULAR) { info.regular_count++; } else { info.overflow_start = static_cast<int>(info.entries.size()) - 1; } return access; } void ConstantPoolBuilder::EmitSharedEntries(Assembler* assm, ConstantPoolEntry::Type type) { PerTypeEntryInfo& info = info_[type]; std::vector<ConstantPoolEntry>& shared_entries = info.shared_entries; const int entry_size = ConstantPoolEntry::size(type); int base = emitted_label_.pos(); DCHECK_GT(base, 0); int shared_end = static_cast<int>(shared_entries.size()); std::vector<ConstantPoolEntry>::iterator shared_it = shared_entries.begin(); for (int i = 0; i < shared_end; i++, shared_it++) { int offset = assm->pc_offset() - base; shared_it->set_offset(offset); // Save offset for merged entries. if (entry_size == kPointerSize) { assm->dp(shared_it->value()); } else { assm->dq(shared_it->value64()); } DCHECK(is_uintn(offset, info.regular_reach_bits)); // Patch load sequence with correct offset. assm->PatchConstantPoolAccessInstruction(shared_it->position(), offset, ConstantPoolEntry::REGULAR, type); } } void ConstantPoolBuilder::EmitGroup(Assembler* assm, ConstantPoolEntry::Access access, ConstantPoolEntry::Type type) { PerTypeEntryInfo& info = info_[type]; const bool overflow = info.overflow(); std::vector<ConstantPoolEntry>& entries = info.entries; std::vector<ConstantPoolEntry>& shared_entries = info.shared_entries; const int entry_size = ConstantPoolEntry::size(type); int base = emitted_label_.pos(); DCHECK_GT(base, 0); int begin; int end; if (access == ConstantPoolEntry::REGULAR) { // Emit any shared entries first EmitSharedEntries(assm, type); } if (access == ConstantPoolEntry::REGULAR) { begin = 0; end = overflow ? info.overflow_start : static_cast<int>(entries.size()); } else { DCHECK(access == ConstantPoolEntry::OVERFLOWED); if (!overflow) return; begin = info.overflow_start; end = static_cast<int>(entries.size()); } std::vector<ConstantPoolEntry>::iterator it = entries.begin(); if (begin > 0) std::advance(it, begin); for (int i = begin; i < end; i++, it++) { // Update constant pool if necessary and get the entry's offset. int offset; ConstantPoolEntry::Access entry_access; if (!it->is_merged()) { // Emit new entry offset = assm->pc_offset() - base; entry_access = access; if (entry_size == kPointerSize) { assm->dp(it->value()); } else { assm->dq(it->value64()); } } else { // Retrieve offset from shared entry. offset = shared_entries[it->merged_index()].offset(); entry_access = ConstantPoolEntry::REGULAR; } DCHECK(entry_access == ConstantPoolEntry::OVERFLOWED || is_uintn(offset, info.regular_reach_bits)); // Patch load sequence with correct offset. assm->PatchConstantPoolAccessInstruction(it->position(), offset, entry_access, type); } } // Emit and return position of pool. Zero implies no constant pool. int ConstantPoolBuilder::Emit(Assembler* assm) { bool emitted = emitted_label_.is_bound(); bool empty = IsEmpty(); if (!emitted) { // Mark start of constant pool. Align if necessary. if (!empty) assm->DataAlign(kDoubleSize); assm->bind(&emitted_label_); if (!empty) { // Emit in groups based on access and type. // Emit doubles first for alignment purposes. EmitGroup(assm, ConstantPoolEntry::REGULAR, ConstantPoolEntry::DOUBLE); EmitGroup(assm, ConstantPoolEntry::REGULAR, ConstantPoolEntry::INTPTR); if (info_[ConstantPoolEntry::DOUBLE].overflow()) { assm->DataAlign(kDoubleSize); EmitGroup(assm, ConstantPoolEntry::OVERFLOWED, ConstantPoolEntry::DOUBLE); } if (info_[ConstantPoolEntry::INTPTR].overflow()) { EmitGroup(assm, ConstantPoolEntry::OVERFLOWED, ConstantPoolEntry::INTPTR); } } } return !empty ? emitted_label_.pos() : 0; } HeapObjectRequest::HeapObjectRequest(double heap_number, int offset) : kind_(kHeapNumber), offset_(offset) { value_.heap_number = heap_number; DCHECK(!IsSmiDouble(value_.heap_number)); } HeapObjectRequest::HeapObjectRequest(CodeStub* code_stub, int offset) : kind_(kCodeStub), offset_(offset) { value_.code_stub = code_stub; DCHECK_NOT_NULL(value_.code_stub); } HeapObjectRequest::HeapObjectRequest(const StringConstantBase* string, int offset) : kind_(kStringConstant), offset_(offset) { value_.string = string; DCHECK_NOT_NULL(value_.string); } // Platform specific but identical code for all the platforms. void Assembler::RecordDeoptReason(DeoptimizeReason reason, SourcePosition position, int id) { EnsureSpace ensure_space(this); RecordRelocInfo(RelocInfo::DEOPT_SCRIPT_OFFSET, position.ScriptOffset()); RecordRelocInfo(RelocInfo::DEOPT_INLINING_ID, position.InliningId()); RecordRelocInfo(RelocInfo::DEOPT_REASON, static_cast<int>(reason)); RecordRelocInfo(RelocInfo::DEOPT_ID, id); } void Assembler::RecordComment(const char* msg) { if (FLAG_code_comments) { EnsureSpace ensure_space(this); RecordRelocInfo(RelocInfo::COMMENT, reinterpret_cast<intptr_t>(msg)); } } void Assembler::DataAlign(int m) { DCHECK(m >= 2 && base::bits::IsPowerOfTwo(m)); while ((pc_offset() & (m - 1)) != 0) { db(0); } } void AssemblerBase::RequestHeapObject(HeapObjectRequest request) { DCHECK(!options().v8_agnostic_code); request.set_offset(pc_offset()); heap_object_requests_.push_front(request); } int AssemblerBase::AddCodeTarget(Handle<Code> target) { DCHECK(!options().v8_agnostic_code); int current = static_cast<int>(code_targets_.size()); if (current > 0 && !target.is_null() && code_targets_.back().address() == target.address()) { // Optimization if we keep jumping to the same code target. return current - 1; } else { code_targets_.push_back(target); return current; } } Handle<Code> AssemblerBase::GetCodeTarget(intptr_t code_target_index) const { DCHECK(!options().v8_agnostic_code); DCHECK_LE(0, code_target_index); DCHECK_LT(code_target_index, code_targets_.size()); return code_targets_[code_target_index]; } void AssemblerBase::UpdateCodeTarget(intptr_t code_target_index, Handle<Code> code) { DCHECK(!options().v8_agnostic_code); DCHECK_LE(0, code_target_index); DCHECK_LT(code_target_index, code_targets_.size()); code_targets_[code_target_index] = code; } } // namespace internal } // namespace v8
[ "ofrobots@google.com" ]
ofrobots@google.com
c6fe8b3048d638692115a7017a9009524efc840c
647ae6cac947d9a1a6d6ea698e6df88704654deb
/include/grid.h
18957cd038b890d643d3f28b59688479f411b845
[]
no_license
caymard/turmite
869356786f130a31c4ed48baa9f6fd45f9d260b7
1a9b01878d1f9cd7a1d6f99b7891f8b1bcb9d9a0
refs/heads/master
2021-01-01T16:55:20.984106
2015-05-04T14:13:04
2015-05-04T14:13:04
23,578,378
0
0
null
null
null
null
UTF-8
C++
false
false
1,779
h
/* Grid class A grid is composed of cells which all have a color. */ #ifndef GRID_H #define GRID_H #include <vector> #include <list> #include <utility> #include <iostream> #include <SDL.h> using std::vector; using std::list; using std::pair; class Grid { private: int m_width; // Width of the grid int m_height; // Height of the grid vector<vector<int>> m_cells; // Cells matrix vector<Uint32> m_color_table; // Color table to link color index & hexadecimal code list<pair<int, int>> m_update_cells; // List for the rendering optimization public: /* Main constructor @param width the width of the grid (in cells) @param height the height of the grid (in cells) @param color_table the color table */ Grid(int width, int height, vector<Uint32> color_table); /* Default constructor */ Grid() { }; /* Get the width of the grid @return the width of the grid */ int width() { return m_width; } /* Get the height of the grid @return the height of the grid */ int height() { return m_height; } /* Get the color of a cell @param x horizontal position of the cell @param y vertical position of the cell @return the color of the cell */ int get_color(int x, int y); /* Set the color of a cell @param x horizontal position of the cell @param y vertical position of the cell @param color the color */ void set_color(int x, int y, int color); /* Fill a SDL Surface with the whole grid @param surface pointer to the SDL surface */ void fill_surface(SDL_Surface* surface); /* Update a SDL Surface with points stocked in the update list It allows to gain some time for rendering @param surface pointer to the SDL Surface */ void update_surface(SDL_Surface* surface); }; #endif // !GRID_H
[ "blog.clm@gmail.com" ]
blog.clm@gmail.com
1446e0e0bc4070d502cdbc4dc45aab6f85f5eb8e
5fc464fc61feec5b956a3b023942414d4dce20aa
/SPRINT 4/Position.cpp
00b2b0f4daf4f8ed09b5cf4976f9bebb66bcdd2b
[]
no_license
Ombrelin/dut1-sda
ac7960cf15877f8464032973237bccb5c86f294a
61bc1cfc42ae57a9e65c2481fdfae354138b6ff5
refs/heads/master
2023-01-24T22:56:48.191208
2020-11-24T22:36:29
2020-11-24T22:36:29
292,926,006
0
0
null
null
null
null
ISO-8859-1
C++
false
false
686
cpp
/** * @file Position.cpp * Projet sem04-tp-Cpp3 * @author l'équipe pédagogique * @version 1 19/12/05 * @brief Composant de positions sur une grille * Structures de données et algorithmes - DUT1 Paris 5 */ #include <iostream> #include <cassert> using namespace std; #include "Position.h" /** * @brief Saisie d'une position valide * @return la position saisie */ Position saisir() { Position p; cout << "Position (abscisse? ordonnee?) ? "; cin >> p.abscisse >> p.ordonnee; return p; } /** * @brief Affichage d'une position * @param[in] p : la position à afficher */ void afficher(const Position& p) { cout << "[" << p.abscisse << ", " << p.ordonnee << "] "; }
[ "arsene@lapostolet.fr" ]
arsene@lapostolet.fr