hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
439bba9e6cab6ea730b8ec6fa894d9b85b83fffd | 8,293 | cpp | C++ | cachelib/navy/scheduler/tests/OrderedThreadPoolJobSchedulerTest.cpp | GerHobbelt/CacheLib | 580bf6950aad89cf86dbc153f12dada79b71eaf7 | [
"Apache-2.0"
] | 578 | 2021-09-01T14:19:55.000Z | 2022-03-29T12:22:46.000Z | cachelib/navy/scheduler/tests/OrderedThreadPoolJobSchedulerTest.cpp | igchor/Cachelib | 7db2c643d49fd0a4ec6c492d94a400cbe0515a70 | [
"Apache-2.0"
] | 61 | 2021-09-02T18:48:06.000Z | 2022-03-31T01:56:00.000Z | cachelib/navy/scheduler/tests/OrderedThreadPoolJobSchedulerTest.cpp | igchor/Cachelib | 7db2c643d49fd0a4ec6c492d94a400cbe0515a70 | [
"Apache-2.0"
] | 88 | 2021-09-02T21:22:19.000Z | 2022-03-27T07:40:27.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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 <folly/Random.h>
#include <gtest/gtest.h>
#include <set>
#include <thread>
#include "cachelib/navy/scheduler/ThreadPoolJobScheduler.h"
#include "cachelib/navy/testing/SeqPoints.h"
namespace facebook {
namespace cachelib {
namespace navy {
namespace tests {
// order jobs with same type and ensure that they are executed in the
// enqueued order.
TEST(OrderedThreadPoolJobScheduler, OrderedEnqueueSameType) {
uint64_t key = 5;
SeqPoints sp;
std::vector<int> order;
int seq = 0;
OrderedThreadPoolJobScheduler scheduler{1, 2, 2};
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(1);
return JobExitCode::Done;
},
"", JobType::Write, key);
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(2);
return JobExitCode::Done;
},
"", JobType::Write, key);
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(3);
return JobExitCode::Done;
},
"", JobType::Write, key);
EXPECT_EQ(2, scheduler.getTotalSpooled());
sp.reached(0);
sp.wait(1);
sp.wait(2);
sp.wait(3);
for (int i = 1; i <= seq; i++) {
EXPECT_EQ(i, order[i - 1]);
}
}
// enqueue jobs with different job types for the same key. Ensure that the
// ordering is maintained.
TEST(OrderedThreadPoolJobScheduler, OrderedEnqueueDiffType) {
std::array<JobType, 2> jobTypes = {JobType::Read, JobType::Write};
uint64_t key = 5;
SeqPoints sp;
std::vector<int> order;
int seq = 0;
OrderedThreadPoolJobScheduler scheduler{1, 2, 2};
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(1);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(2);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&sp, &order, n = ++seq]() {
sp.wait(0);
order.push_back(n);
sp.reached(3);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
EXPECT_EQ(2, scheduler.getTotalSpooled());
sp.reached(0);
sp.wait(1);
sp.wait(2);
sp.wait(3);
for (int i = 1; i <= seq; i++) {
EXPECT_EQ(i, order[i - 1]);
}
}
// enqueue three jobs, check that two of them are spooled and calling finish
// should handle the draining of all the jobs, even with rescheduling.
TEST(OrderedThreadPoolJobScheduler, SpoolAndFinish) {
std::array<JobType, 2> jobTypes = {JobType::Read, JobType::Write};
uint64_t key = 5;
SeqPoints sp;
OrderedThreadPoolJobScheduler scheduler{1, 2, 2};
scheduler.enqueueWithKey(
[&sp]() {
sp.wait(0);
sp.reached(1);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&sp]() {
sp.wait(0);
sp.reached(2);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&sp, i = 0]() mutable {
sp.wait(0);
if (i < 2) {
i++;
return JobExitCode::Reschedule;
}
sp.reached(3);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
EXPECT_EQ(2, scheduler.getTotalSpooled());
sp.reached(0);
scheduler.finish();
sp.wait(1);
sp.wait(2);
sp.wait(3);
}
// ensure that the ordering is maintained with the rescheduling of the jobs.
// We enqueue three jobs for same key that can reschedule and ensure that
// after reschedule, the order is maintained as well.
TEST(OrderedThreadPoolJobScheduler, JobWithRetry) {
std::array<JobType, 3> jobTypes = {JobType::Read, JobType::Write,
JobType::Reclaim};
uint64_t key = 5;
SeqPoints sp;
std::atomic<uint64_t> numReschedules{0};
OrderedThreadPoolJobScheduler scheduler{1, 2, 2};
scheduler.enqueueWithKey(
[&, i = 0]() mutable {
sp.wait(0);
if (i < 2) {
i++;
numReschedules++;
return JobExitCode::Reschedule;
}
sp.reached(1);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&, i = 0]() mutable {
sp.wait(0);
if (i < 2) {
i++;
numReschedules++;
return JobExitCode::Reschedule;
}
sp.reached(2);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
scheduler.enqueueWithKey(
[&, i = 0]() mutable {
sp.wait(0);
if (i < 2) {
i++;
numReschedules++;
return JobExitCode::Reschedule;
}
sp.reached(3);
return JobExitCode::Done;
},
"", jobTypes[folly::Random::rand32() % jobTypes.size()], key);
EXPECT_EQ(2, scheduler.getTotalSpooled());
EXPECT_EQ(0, numReschedules);
sp.reached(0);
sp.wait(1);
EXPECT_GE(numReschedules, 2);
sp.wait(2);
EXPECT_GE(numReschedules, 4);
sp.wait(3);
EXPECT_EQ(6, numReschedules);
}
TEST(OrderedThreadPoolJobScheduler, OrderedEnqueueAndFinish) {
unsigned int numKeys = 10000;
std::atomic<int> numCompleted{0};
{
OrderedThreadPoolJobScheduler scheduler{3, 32, 10};
for (unsigned int i = 0; i < numKeys; i++) {
scheduler.enqueueWithKey(
[&]() {
++numCompleted;
return JobExitCode::Done;
},
"", JobType::Write, folly::Random::rand32());
}
scheduler.finish();
}
EXPECT_EQ(numCompleted, numKeys);
}
// enqueue a certain number of jobs and validate the stats for spooling are
// reflective of the behavior expected.
TEST(OrderedThreadPoolJobScheduler, OrderedEnqueueMaxLen) {
unsigned int numKeys = 10000;
std::atomic<int> numCompleted{0};
SeqPoints sp;
sp.setName(0, "all enqueued");
unsigned int numQueues = 4;
OrderedThreadPoolJobScheduler scheduler{numQueues, 1, 10};
for (unsigned int i = 0; i < numKeys; i++) {
scheduler.enqueueWithKey(
[&]() {
sp.wait(0);
++numCompleted;
return JobExitCode::Done;
},
"", JobType::Read, folly::Random::rand32());
}
uint64_t numSpooled = 0;
uint64_t maxQueueLen = 0;
uint64_t pendingJobs = 0;
scheduler.getCounters([&](folly::StringPiece name, double stat) {
if (name == "navy_reader_max_queue_len") {
maxQueueLen = static_cast<uint64_t>(stat);
} else if (name == "navy_req_order_curr_spool_size") {
numSpooled = static_cast<uint64_t>(stat);
} else if (name == "navy_max_reader_pool_pending_jobs") {
pendingJobs = static_cast<uint64_t>(stat);
}
});
EXPECT_GE(numSpooled, 0);
uint64_t numQueued = numKeys - numSpooled;
EXPECT_LE(maxQueueLen, numQueued);
// we could have at most one job executing per Queue. So the total of
// pending jobs must not be off by more than numQueue when compared with
// total enqueued.
EXPECT_LE(numQueued - pendingJobs, numQueues);
sp.reached(0);
scheduler.finish();
EXPECT_EQ(numCompleted, numKeys);
}
} // namespace tests
} // namespace navy
} // namespace cachelib
} // namespace facebook
| 27.460265 | 76 | 0.615218 | [
"vector"
] |
43a2bc8e4bd2bfdbdd7511262574e6492faeb65b | 73,529 | hpp | C++ | thirdparty/vectormath/include/sse/vectormath.hpp | catid/xrcap | d3c5900c44861e618fd28b4256387725646b85c7 | [
"BSD-3-Clause"
] | 62 | 2019-12-21T23:48:28.000Z | 2021-11-25T14:29:28.000Z | thirdparty/vectormath/include/sse/vectormath.hpp | catid/xrcap | d3c5900c44861e618fd28b4256387725646b85c7 | [
"BSD-3-Clause"
] | 5 | 2020-01-06T19:55:41.000Z | 2020-06-19T23:13:24.000Z | thirdparty/vectormath/include/sse/vectormath.hpp | catid/xrcap | d3c5900c44861e618fd28b4256387725646b85c7 | [
"BSD-3-Clause"
] | 10 | 2019-12-22T15:53:10.000Z | 2021-07-18T09:12:06.000Z | /*
Copyright (C) 2006, 2007 Sony Computer Entertainment Inc.
All rights reserved.
Redistribution and use in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the Sony Computer Entertainment Inc nor the names
of its contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef VECTORMATH_SSE_VECTORMATH_HPP
#define VECTORMATH_SSE_VECTORMATH_HPP
#include <cmath>
#include <xmmintrin.h>
#include <emmintrin.h>
#ifdef VECTORMATH_DEBUG
#include <cstdio>
#endif // VECTORMATH_DEBUG
#if defined(_MSC_VER)
// Visual Studio (MS compiler)
#define VECTORMATH_ALIGNED(type) __declspec(align(16)) type
#define VECTORMATH_ALIGNED_TYPE_PRE __declspec(align(16))
#define VECTORMATH_ALIGNED_TYPE_POST /* nothing */
#elif defined(__GNUC__)
// GCC or Clang
#define VECTORMATH_ALIGNED(type) type __attribute__((aligned(16)))
#define VECTORMATH_ALIGNED_TYPE_PRE /* nothing */
#define VECTORMATH_ALIGNED_TYPE_POST __attribute__((aligned(16)))
#else
// Unknown compiler
#error "Define VECTORMATH_ALIGNED for your compiler or platform!"
#endif
#include "internal.hpp"
#include "floatinvec.hpp"
#include "boolinvec.hpp"
#include "vecidx.hpp"
namespace Vectormath
{
namespace SSE
{
// ========================================================
// Forward Declarations
// ========================================================
class Vector3;
class Vector4;
class Point3;
class Quat;
class Matrix3;
class Matrix4;
class Transform3;
// ========================================================
// A 3-D vector in array-of-structures format
// ========================================================
VECTORMATH_ALIGNED_TYPE_PRE class Vector3
{
__m128 mVec128;
public:
// Default constructor; does no initialization
//
inline Vector3() { }
// Construct a 3-D vector from x, y, and z elements
//
inline Vector3(float x, float y, float z);
// Construct a 3-D vector from x, y, and z elements (scalar data contained in vector data type)
//
inline Vector3(const FloatInVec & x, const FloatInVec & y, const FloatInVec & z);
// Copy elements from a 3-D point into a 3-D vector
//
explicit inline Vector3(const Point3 & pnt);
// Set all elements of a 3-D vector to the same scalar value
//
explicit inline Vector3(float scalar);
// Set all elements of a 3-D vector to the same scalar value (scalar data contained in vector data type)
//
explicit inline Vector3(const FloatInVec & scalar);
// Set vector float data in a 3-D vector
//
explicit inline Vector3(__m128 vf4);
// Get vector float data from a 3-D vector
//
inline __m128 get128() const;
// Assign one 3-D vector to another
//
inline Vector3 & operator = (const Vector3 & vec);
// Set the x element of a 3-D vector
//
inline Vector3 & setX(float x);
// Set the y element of a 3-D vector
//
inline Vector3 & setY(float y);
// Set the z element of a 3-D vector
//
inline Vector3 & setZ(float z);
// Set the w element of a padded 3-D vector
// NOTE:
// You are free to use the additional w component - if never set, it's value is undefined.
//
inline Vector3 & setW(float w);
// Set the x element of a 3-D vector (scalar data contained in vector data type)
//
inline Vector3 & setX(const FloatInVec & x);
// Set the y element of a 3-D vector (scalar data contained in vector data type)
//
inline Vector3 & setY(const FloatInVec & y);
// Set the z element of a 3-D vector (scalar data contained in vector data type)
//
inline Vector3 & setZ(const FloatInVec & z);
// Set the w element of a padded 3-D vector
// NOTE:
// You are free to use the additional w component - if never set, it's value is undefined.
//
inline Vector3 & setW(const FloatInVec & w);
// Get the x element of a 3-D vector
//
inline const FloatInVec getX() const;
// Get the y element of a 3-D vector
//
inline const FloatInVec getY() const;
// Get the z element of a 3-D vector
//
inline const FloatInVec getZ() const;
// Get the w element of a padded 3-D vector
// NOTE:
// You are free to use the additional w component - if never set, it's value is undefined.
//
inline const FloatInVec getW() const;
// Set an x, y, or z element of a 3-D vector by index
//
inline Vector3 & setElem(int idx, float value);
// Set an x, y, or z element of a 3-D vector by index (scalar data contained in vector data type)
//
inline Vector3 & setElem(int idx, const FloatInVec & value);
// Get an x, y, or z element of a 3-D vector by index
//
inline const FloatInVec getElem(int idx) const;
// Subscripting operator to set or get an element
//
inline VecIdx operator[](int idx);
// Subscripting operator to get an element
//
inline const FloatInVec operator[](int idx) const;
// Add two 3-D vectors
//
inline const Vector3 operator + (const Vector3 & vec) const;
// Subtract a 3-D vector from another 3-D vector
//
inline const Vector3 operator - (const Vector3 & vec) const;
// Add a 3-D vector to a 3-D point
//
inline const Point3 operator + (const Point3 & pnt) const;
// Multiply a 3-D vector by a scalar
//
inline const Vector3 operator * (float scalar) const;
// Divide a 3-D vector by a scalar
//
inline const Vector3 operator / (float scalar) const;
// Multiply a 3-D vector by a scalar (scalar data contained in vector data type)
//
inline const Vector3 operator * (const FloatInVec & scalar) const;
// Divide a 3-D vector by a scalar (scalar data contained in vector data type)
//
inline const Vector3 operator / (const FloatInVec & scalar) const;
// Perform compound assignment and addition with a 3-D vector
//
inline Vector3 & operator += (const Vector3 & vec);
// Perform compound assignment and subtraction by a 3-D vector
//
inline Vector3 & operator -= (const Vector3 & vec);
// Perform compound assignment and multiplication by a scalar
//
inline Vector3 & operator *= (float scalar);
// Perform compound assignment and division by a scalar
//
inline Vector3 & operator /= (float scalar);
// Perform compound assignment and multiplication by a scalar (scalar data contained in vector data type)
//
inline Vector3 & operator *= (const FloatInVec & scalar);
// Perform compound assignment and division by a scalar (scalar data contained in vector data type)
//
inline Vector3 & operator /= (const FloatInVec & scalar);
// Negate all elements of a 3-D vector
//
inline const Vector3 operator - () const;
// Construct x axis
//
static inline const Vector3 xAxis();
// Construct y axis
//
static inline const Vector3 yAxis();
// Construct z axis
//
static inline const Vector3 zAxis();
} VECTORMATH_ALIGNED_TYPE_POST;
// Multiply a 3-D vector by a scalar
//
inline const Vector3 operator * (float scalar, const Vector3 & vec);
// Multiply a 3-D vector by a scalar (scalar data contained in vector data type)
//
inline const Vector3 operator * (const FloatInVec & scalar, const Vector3 & vec);
// Multiply two 3-D vectors per element
//
inline const Vector3 mulPerElem(const Vector3 & vec0, const Vector3 & vec1);
// Divide two 3-D vectors per element
// NOTE:
// Floating-point behavior matches standard library function divf4.
//
inline const Vector3 divPerElem(const Vector3 & vec0, const Vector3 & vec1);
// Compute the reciprocal of a 3-D vector per element
// NOTE:
// Floating-point behavior matches standard library function recipf4.
//
inline const Vector3 recipPerElem(const Vector3 & vec);
// Compute the absolute value of a 3-D vector per element
//
inline const Vector3 absPerElem(const Vector3 & vec);
// Copy sign from one 3-D vector to another, per element
//
inline const Vector3 copySignPerElem(const Vector3 & vec0, const Vector3 & vec1);
// Maximum of two 3-D vectors per element
//
inline const Vector3 maxPerElem(const Vector3 & vec0, const Vector3 & vec1);
// Minimum of two 3-D vectors per element
//
inline const Vector3 minPerElem(const Vector3 & vec0, const Vector3 & vec1);
// Maximum element of a 3-D vector
//
inline const FloatInVec maxElem(const Vector3 & vec);
// Minimum element of a 3-D vector
//
inline const FloatInVec minElem(const Vector3 & vec);
// Compute the sum of all elements of a 3-D vector
//
inline const FloatInVec sum(const Vector3 & vec);
// Compute the dot product of two 3-D vectors
//
inline const FloatInVec dot(const Vector3 & vec0, const Vector3 & vec1);
// Compute the square of the length of a 3-D vector
//
inline const FloatInVec lengthSqr(const Vector3 & vec);
// Compute the length of a 3-D vector
//
inline const FloatInVec length(const Vector3 & vec);
// Normalize a 3-D vector
// NOTE:
// The result is unpredictable when all elements of vec are at or near zero.
//
inline const Vector3 normalize(const Vector3 & vec);
// Compute cross product of two 3-D vectors
//
inline const Vector3 cross(const Vector3 & vec0, const Vector3 & vec1);
// Outer product of two 3-D vectors
//
inline const Matrix3 outer(const Vector3 & vec0, const Vector3 & vec1);
// Pre-multiply a row vector by a 3x3 matrix
// NOTE:
// Slower than column post-multiply.
//
inline const Vector3 rowMul(const Vector3 & vec, const Matrix3 & mat);
// Cross-product matrix of a 3-D vector
//
inline const Matrix3 crossMatrix(const Vector3 & vec);
// Create cross-product matrix and multiply
// NOTE:
// Faster than separately creating a cross-product matrix and multiplying.
//
inline const Matrix3 crossMatrixMul(const Vector3 & vec, const Matrix3 & mat);
// Linear interpolation between two 3-D vectors
// NOTE:
// Does not clamp t between 0 and 1.
//
inline const Vector3 lerp(float t, const Vector3 & vec0, const Vector3 & vec1);
// Linear interpolation between two 3-D vectors (scalar data contained in vector data type)
// NOTE:
// Does not clamp t between 0 and 1.
//
inline const Vector3 lerp(const FloatInVec & t, const Vector3 & vec0, const Vector3 & vec1);
// Spherical linear interpolation between two 3-D vectors
// NOTE:
// The result is unpredictable if the vectors point in opposite directions.
// Does not clamp t between 0 and 1.
//
inline const Vector3 slerp(float t, const Vector3 & unitVec0, const Vector3 & unitVec1);
// Spherical linear interpolation between two 3-D vectors (scalar data contained in vector data type)
// NOTE:
// The result is unpredictable if the vectors point in opposite directions.
// Does not clamp t between 0 and 1.
//
inline const Vector3 slerp(const FloatInVec & t, const Vector3 & unitVec0, const Vector3 & unitVec1);
// Conditionally select between two 3-D vectors
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
// However, the transfer of select1 to a VMX register may use more processing time than a branch.
// Use the BoolInVec version for better performance.
//
inline const Vector3 select(const Vector3 & vec0, const Vector3 & vec1, bool select1);
// Conditionally select between two 3-D vectors (scalar data contained in vector data type)
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
//
inline const Vector3 select(const Vector3 & vec0, const Vector3 & vec1, const BoolInVec & select1);
// Store x, y, and z elements of 3-D vector in first three words of a quadword, preserving fourth word
//
inline void storeXYZ(const Vector3 & vec, __m128 * quad);
// Load four three-float 3-D vectors, stored in three quadwords
//
inline void loadXYZArray(Vector3 & vec0, Vector3 & vec1, Vector3 & vec2, Vector3 & vec3, const __m128 * threeQuads);
// Store four 3-D vectors in three quadwords
//
inline void storeXYZArray(const Vector3 & vec0, const Vector3 & vec1, const Vector3 & vec2, const Vector3 & vec3, __m128 * threeQuads);
#ifdef VECTORMATH_DEBUG
// Print a 3-D vector
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Vector3 & vec);
// Print a 3-D vector and an associated string identifier
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Vector3 & vec, const char * name);
#endif // VECTORMATH_DEBUG
// ========================================================
// A 4-D vector in array-of-structures format
// ========================================================
VECTORMATH_ALIGNED_TYPE_PRE class Vector4
{
__m128 mVec128;
public:
// Default constructor; does no initialization
//
inline Vector4() { }
// Construct a 4-D vector from x, y, z, and w elements
//
inline Vector4(float x, float y, float z, float w);
// Construct a 4-D vector from x, y, z, and w elements (scalar data contained in vector data type)
//
inline Vector4(const FloatInVec & x, const FloatInVec & y, const FloatInVec & z, const FloatInVec & w);
// Construct a 4-D vector from a 3-D vector and a scalar
//
inline Vector4(const Vector3 & xyz, float w);
// Construct a 4-D vector from a 3-D vector and a scalar (scalar data contained in vector data type)
//
inline Vector4(const Vector3 & xyz, const FloatInVec & w);
// Copy x, y, and z from a 3-D vector into a 4-D vector, and set w to 0
//
explicit inline Vector4(const Vector3 & vec);
// Copy x, y, and z from a 3-D point into a 4-D vector, and set w to 1
//
explicit inline Vector4(const Point3 & pnt);
// Copy elements from a quaternion into a 4-D vector
//
explicit inline Vector4(const Quat & quat);
// Set all elements of a 4-D vector to the same scalar value
//
explicit inline Vector4(float scalar);
// Set all elements of a 4-D vector to the same scalar value (scalar data contained in vector data type)
//
explicit inline Vector4(const FloatInVec & scalar);
// Set vector float data in a 4-D vector
//
explicit inline Vector4(__m128 vf4);
// Get pointer to first float
inline float* GetPtr()
{
return &mVec128.m128_f32[0];
}
// Get vector float data from a 4-D vector
//
inline __m128 get128() const;
// Assign one 4-D vector to another
//
inline Vector4 & operator = (const Vector4 & vec);
// Set the x, y, and z elements of a 4-D vector
// NOTE:
// This function does not change the w element.
//
inline Vector4 & setXYZ(const Vector3 & vec);
// Get the x, y, and z elements of a 4-D vector
//
inline const Vector3 getXYZ() const;
// Set the x element of a 4-D vector
//
inline Vector4 & setX(float x);
// Set the y element of a 4-D vector
//
inline Vector4 & setY(float y);
// Set the z element of a 4-D vector
//
inline Vector4 & setZ(float z);
// Set the w element of a 4-D vector
//
inline Vector4 & setW(float w);
// Set the x element of a 4-D vector (scalar data contained in vector data type)
//
inline Vector4 & setX(const FloatInVec & x);
// Set the y element of a 4-D vector (scalar data contained in vector data type)
//
inline Vector4 & setY(const FloatInVec & y);
// Set the z element of a 4-D vector (scalar data contained in vector data type)
//
inline Vector4 & setZ(const FloatInVec & z);
// Set the w element of a 4-D vector (scalar data contained in vector data type)
//
inline Vector4 & setW(const FloatInVec & w);
// Get the x element of a 4-D vector
//
inline const FloatInVec getX() const;
// Get the y element of a 4-D vector
//
inline const FloatInVec getY() const;
// Get the z element of a 4-D vector
//
inline const FloatInVec getZ() const;
// Get the w element of a 4-D vector
//
inline const FloatInVec getW() const;
// Set an x, y, z, or w element of a 4-D vector by index
//
inline Vector4 & setElem(int idx, float value);
// Set an x, y, z, or w element of a 4-D vector by index (scalar data contained in vector data type)
//
inline Vector4 & setElem(int idx, const FloatInVec & value);
// Get an x, y, z, or w element of a 4-D vector by index
//
inline const FloatInVec getElem(int idx) const;
// Subscripting operator to set or get an element
//
inline VecIdx operator[](int idx);
// Subscripting operator to get an element
//
inline const FloatInVec operator[](int idx) const;
// Add two 4-D vectors
//
inline const Vector4 operator + (const Vector4 & vec) const;
// Subtract a 4-D vector from another 4-D vector
//
inline const Vector4 operator - (const Vector4 & vec) const;
// Multiply a 4-D vector by a scalar
//
inline const Vector4 operator * (float scalar) const;
// Divide a 4-D vector by a scalar
//
inline const Vector4 operator / (float scalar) const;
// Multiply a 4-D vector by a scalar (scalar data contained in vector data type)
//
inline const Vector4 operator * (const FloatInVec & scalar) const;
// Divide a 4-D vector by a scalar (scalar data contained in vector data type)
//
inline const Vector4 operator / (const FloatInVec & scalar) const;
// Perform compound assignment and addition with a 4-D vector
//
inline Vector4 & operator += (const Vector4 & vec);
// Perform compound assignment and subtraction by a 4-D vector
//
inline Vector4 & operator -= (const Vector4 & vec);
// Perform compound assignment and multiplication by a scalar
//
inline Vector4 & operator *= (float scalar);
// Perform compound assignment and division by a scalar
//
inline Vector4 & operator /= (float scalar);
// Perform compound assignment and multiplication by a scalar (scalar data contained in vector data type)
//
inline Vector4 & operator *= (const FloatInVec & scalar);
// Perform compound assignment and division by a scalar (scalar data contained in vector data type)
//
inline Vector4 & operator /= (const FloatInVec & scalar);
// Negate all elements of a 4-D vector
//
inline const Vector4 operator - () const;
// Construct x axis
//
static inline const Vector4 xAxis();
// Construct y axis
//
static inline const Vector4 yAxis();
// Construct z axis
//
static inline const Vector4 zAxis();
// Construct w axis
//
static inline const Vector4 wAxis();
} VECTORMATH_ALIGNED_TYPE_POST;
// Multiply a 4-D vector by a scalar
//
inline const Vector4 operator * (float scalar, const Vector4 & vec);
// Multiply a 4-D vector by a scalar (scalar data contained in vector data type)
//
inline const Vector4 operator * (const FloatInVec & scalar, const Vector4 & vec);
// Multiply two 4-D vectors per element
//
inline const Vector4 mulPerElem(const Vector4 & vec0, const Vector4 & vec1);
// Divide two 4-D vectors per element
// NOTE:
// Floating-point behavior matches standard library function divf4.
//
inline const Vector4 divPerElem(const Vector4 & vec0, const Vector4 & vec1);
// Compute the reciprocal of a 4-D vector per element
// NOTE:
// Floating-point behavior matches standard library function recipf4.
//
inline const Vector4 recipPerElem(const Vector4 & vec);
// Compute the absolute value of a 4-D vector per element
//
inline const Vector4 absPerElem(const Vector4 & vec);
// Copy sign from one 4-D vector to another, per element
//
inline const Vector4 copySignPerElem(const Vector4 & vec0, const Vector4 & vec1);
// Maximum of two 4-D vectors per element
//
inline const Vector4 maxPerElem(const Vector4 & vec0, const Vector4 & vec1);
// Minimum of two 4-D vectors per element
//
inline const Vector4 minPerElem(const Vector4 & vec0, const Vector4 & vec1);
// Maximum element of a 4-D vector
//
inline const FloatInVec maxElem(const Vector4 & vec);
// Minimum element of a 4-D vector
//
inline const FloatInVec minElem(const Vector4 & vec);
// Compute the sum of all elements of a 4-D vector
//
inline const FloatInVec sum(const Vector4 & vec);
// Compute the dot product of two 4-D vectors
//
inline const FloatInVec dot(const Vector4 & vec0, const Vector4 & vec1);
// Compute the square of the length of a 4-D vector
//
inline const FloatInVec lengthSqr(const Vector4 & vec);
// Compute the length of a 4-D vector
//
inline const FloatInVec length(const Vector4 & vec);
// Normalize a 4-D vector
// NOTE:
// The result is unpredictable when all elements of vec are at or near zero.
//
inline const Vector4 normalize(const Vector4 & vec);
// Outer product of two 4-D vectors
//
inline const Matrix4 outer(const Vector4 & vec0, const Vector4 & vec1);
// Linear interpolation between two 4-D vectors
// NOTE:
// Does not clamp t between 0 and 1.
//
inline const Vector4 lerp(float t, const Vector4 & vec0, const Vector4 & vec1);
// Linear interpolation between two 4-D vectors (scalar data contained in vector data type)
// NOTE:
// Does not clamp t between 0 and 1.
//
inline const Vector4 lerp(const FloatInVec & t, const Vector4 & vec0, const Vector4 & vec1);
// Spherical linear interpolation between two 4-D vectors
// NOTE:
// The result is unpredictable if the vectors point in opposite directions.
// Does not clamp t between 0 and 1.
//
inline const Vector4 slerp(float t, const Vector4 & unitVec0, const Vector4 & unitVec1);
// Spherical linear interpolation between two 4-D vectors (scalar data contained in vector data type)
// NOTE:
// The result is unpredictable if the vectors point in opposite directions.
// Does not clamp t between 0 and 1.
//
inline const Vector4 slerp(const FloatInVec & t, const Vector4 & unitVec0, const Vector4 & unitVec1);
// Conditionally select between two 4-D vectors
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
// However, the transfer of select1 to a VMX register may use more processing time than a branch.
// Use the BoolInVec version for better performance.
//
inline const Vector4 select(const Vector4 & vec0, const Vector4 & vec1, bool select1);
// Conditionally select between two 4-D vectors (scalar data contained in vector data type)
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
//
inline const Vector4 select(const Vector4 & vec0, const Vector4 & vec1, const BoolInVec & select1);
#ifdef VECTORMATH_DEBUG
// Print a 4-D vector
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Vector4 & vec);
// Print a 4-D vector and an associated string identifier
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Vector4 & vec, const char * name);
#endif // VECTORMATH_DEBUG
// ========================================================
// A 3-D point in array-of-structures format
// ========================================================
VECTORMATH_ALIGNED_TYPE_PRE class Point3
{
__m128 mVec128;
public:
// Default constructor; does no initialization
//
inline Point3() { }
// Construct a 3-D point from x, y, and z elements
//
inline Point3(float x, float y, float z);
// Construct a 3-D point from x, y, and z elements (scalar data contained in vector data type)
//
inline Point3(const FloatInVec & x, const FloatInVec & y, const FloatInVec & z);
// Copy elements from a 3-D vector into a 3-D point
//
explicit inline Point3(const Vector3 & vec);
// Set all elements of a 3-D point to the same scalar value
//
explicit inline Point3(float scalar);
// Set all elements of a 3-D point to the same scalar value (scalar data contained in vector data type)
//
explicit inline Point3(const FloatInVec & scalar);
// Set vector float data in a 3-D point
//
explicit inline Point3(__m128 vf4);
// Get vector float data from a 3-D point
//
inline __m128 get128() const;
// Assign one 3-D point to another
//
inline Point3 & operator = (const Point3 & pnt);
// Set the x element of a 3-D point
//
inline Point3 & setX(float x);
// Set the y element of a 3-D point
//
inline Point3 & setY(float y);
// Set the z element of a 3-D point
//
inline Point3 & setZ(float z);
// Set the w element of a padded 3-D point
// NOTE:
// You are free to use the additional w component - if never set, it's value is undefined.
//
inline Point3 & setW(float w);
// Set the x element of a 3-D point (scalar data contained in vector data type)
//
inline Point3 & setX(const FloatInVec & x);
// Set the y element of a 3-D point (scalar data contained in vector data type)
//
inline Point3 & setY(const FloatInVec & y);
// Set the z element of a 3-D point (scalar data contained in vector data type)
//
inline Point3 & setZ(const FloatInVec & z);
// Set the w element of a padded 3-D point
// NOTE:
// You are free to use the additional w component - if never set, it's value is undefined.
//
inline Point3 & setW(const FloatInVec & w);
// Get the x element of a 3-D point
//
inline const FloatInVec getX() const;
// Get the y element of a 3-D point
//
inline const FloatInVec getY() const;
// Get the z element of a 3-D point
//
inline const FloatInVec getZ() const;
// Get the w element of a padded 3-D point
// NOTE:
// You are free to use the additional w component - if never set, it's value is undefined.
//
inline const FloatInVec getW() const;
// Set an x, y, or z element of a 3-D point by index
//
inline Point3 & setElem(int idx, float value);
// Set an x, y, or z element of a 3-D point by index (scalar data contained in vector data type)
//
inline Point3 & setElem(int idx, const FloatInVec & value);
// Get an x, y, or z element of a 3-D point by index
//
inline const FloatInVec getElem(int idx) const;
// Subscripting operator to set or get an element
//
inline VecIdx operator[](int idx);
// Subscripting operator to get an element
//
inline const FloatInVec operator[](int idx) const;
// Subtract a 3-D point from another 3-D point
//
inline const Vector3 operator - (const Point3 & pnt) const;
// Add a 3-D point to a 3-D vector
//
inline const Point3 operator + (const Vector3 & vec) const;
// Subtract a 3-D vector from a 3-D point
//
inline const Point3 operator - (const Vector3 & vec) const;
// Perform compound assignment and addition with a 3-D vector
//
inline Point3 & operator += (const Vector3 & vec);
// Perform compound assignment and subtraction by a 3-D vector
//
inline Point3 & operator -= (const Vector3 & vec);
} VECTORMATH_ALIGNED_TYPE_POST;
// Multiply two 3-D points per element
//
inline const Point3 mulPerElem(const Point3 & pnt0, const Point3 & pnt1);
// Divide two 3-D points per element
// NOTE:
// Floating-point behavior matches standard library function divf4.
//
inline const Point3 divPerElem(const Point3 & pnt0, const Point3 & pnt1);
// Compute the reciprocal of a 3-D point per element
// NOTE:
// Floating-point behavior matches standard library function recipf4.
//
inline const Point3 recipPerElem(const Point3 & pnt);
// Compute the absolute value of a 3-D point per element
//
inline const Point3 absPerElem(const Point3 & pnt);
// Copy sign from one 3-D point to another, per element
//
inline const Point3 copySignPerElem(const Point3 & pnt0, const Point3 & pnt1);
// Maximum of two 3-D points per element
//
inline const Point3 maxPerElem(const Point3 & pnt0, const Point3 & pnt1);
// Minimum of two 3-D points per element
//
inline const Point3 minPerElem(const Point3 & pnt0, const Point3 & pnt1);
// Maximum element of a 3-D point
//
inline const FloatInVec maxElem(const Point3 & pnt);
// Minimum element of a 3-D point
//
inline const FloatInVec minElem(const Point3 & pnt);
// Compute the sum of all elements of a 3-D point
//
inline const FloatInVec sum(const Point3 & pnt);
// Apply uniform scale to a 3-D point
//
inline const Point3 scale(const Point3 & pnt, float scaleVal);
// Apply uniform scale to a 3-D point (scalar data contained in vector data type)
//
inline const Point3 scale(const Point3 & pnt, const FloatInVec & scaleVal);
// Apply non-uniform scale to a 3-D point
//
inline const Point3 scale(const Point3 & pnt, const Vector3 & scaleVec);
// Scalar projection of a 3-D point on a unit-length 3-D vector
//
inline const FloatInVec projection(const Point3 & pnt, const Vector3 & unitVec);
// Compute the square of the distance of a 3-D point from the coordinate-system origin
//
inline const FloatInVec distSqrFromOrigin(const Point3 & pnt);
// Compute the distance of a 3-D point from the coordinate-system origin
//
inline const FloatInVec distFromOrigin(const Point3 & pnt);
// Compute the square of the distance between two 3-D points
//
inline const FloatInVec distSqr(const Point3 & pnt0, const Point3 & pnt1);
// Compute the distance between two 3-D points
//
inline const FloatInVec dist(const Point3 & pnt0, const Point3 & pnt1);
// Linear interpolation between two 3-D points
// NOTE:
// Does not clamp t between 0 and 1.
//
inline const Point3 lerp(float t, const Point3 & pnt0, const Point3 & pnt1);
// Linear interpolation between two 3-D points (scalar data contained in vector data type)
// NOTE:
// Does not clamp t between 0 and 1.
//
inline const Point3 lerp(const FloatInVec & t, const Point3 & pnt0, const Point3 & pnt1);
// Conditionally select between two 3-D points
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
// However, the transfer of select1 to a VMX register may use more processing time than a branch.
// Use the BoolInVec version for better performance.
//
inline const Point3 select(const Point3 & pnt0, const Point3 & pnt1, bool select1);
// Conditionally select between two 3-D points (scalar data contained in vector data type)
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
//
inline const Point3 select(const Point3 & pnt0, const Point3 & pnt1, const BoolInVec & select1);
// Store x, y, and z elements of 3-D point in first three words of a quadword, preserving fourth word
//
inline void storeXYZ(const Point3 & pnt, __m128 * quad);
// Load four three-float 3-D points, stored in three quadwords
//
inline void loadXYZArray(Point3 & pnt0, Point3 & pnt1, Point3 & pnt2, Point3 & pnt3, const __m128 * threeQuads);
// Store four 3-D points in three quadwords
//
inline void storeXYZArray(const Point3 & pnt0, const Point3 & pnt1, const Point3 & pnt2, const Point3 & pnt3, __m128 * threeQuads);
#ifdef VECTORMATH_DEBUG
// Print a 3-D point
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Point3 & pnt);
// Print a 3-D point and an associated string identifier
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Point3 & pnt, const char * name);
#endif // VECTORMATH_DEBUG
// ========================================================
// A quaternion in array-of-structures format
// ========================================================
VECTORMATH_ALIGNED_TYPE_PRE class Quat
{
__m128 mVec128;
public:
// Default constructor; does no initialization
//
inline Quat() { }
// Construct a quaternion from x, y, z, and w elements
//
inline Quat(float x, float y, float z, float w);
// Construct a quaternion from x, y, z, and w elements (scalar data contained in vector data type)
//
inline Quat(const FloatInVec & x, const FloatInVec & y, const FloatInVec & z, const FloatInVec & w);
// Construct a quaternion from a 3-D vector and a scalar
//
inline Quat(const Vector3 & xyz, float w);
// Construct a quaternion from a 3-D vector and a scalar (scalar data contained in vector data type)
//
inline Quat(const Vector3 & xyz, const FloatInVec & w);
// Copy elements from a 4-D vector into a quaternion
//
explicit inline Quat(const Vector4 & vec);
// Convert a rotation matrix to a unit-length quaternion
//
explicit inline Quat(const Matrix3 & rotMat);
// Set all elements of a quaternion to the same scalar value
//
explicit inline Quat(float scalar);
// Set all elements of a quaternion to the same scalar value (scalar data contained in vector data type)
//
explicit inline Quat(const FloatInVec & scalar);
// Set vector float data in a quaternion
//
explicit inline Quat(__m128 vf4);
// Get vector float data from a quaternion
//
inline __m128 get128() const;
// Assign one quaternion to another
//
inline Quat & operator = (const Quat & quat);
// Set the x, y, and z elements of a quaternion
// NOTE:
// This function does not change the w element.
//
inline Quat & setXYZ(const Vector3 & vec);
// Get the x, y, and z elements of a quaternion
//
inline const Vector3 getXYZ() const;
// Set the x element of a quaternion
//
inline Quat & setX(float x);
// Set the y element of a quaternion
//
inline Quat & setY(float y);
// Set the z element of a quaternion
//
inline Quat & setZ(float z);
// Set the w element of a quaternion
//
inline Quat & setW(float w);
// Set the x element of a quaternion (scalar data contained in vector data type)
//
inline Quat & setX(const FloatInVec & x);
// Set the y element of a quaternion (scalar data contained in vector data type)
//
inline Quat & setY(const FloatInVec & y);
// Set the z element of a quaternion (scalar data contained in vector data type)
//
inline Quat & setZ(const FloatInVec & z);
// Set the w element of a quaternion (scalar data contained in vector data type)
//
inline Quat & setW(const FloatInVec & w);
// Get the x element of a quaternion
//
inline const FloatInVec getX() const;
// Get the y element of a quaternion
//
inline const FloatInVec getY() const;
// Get the z element of a quaternion
//
inline const FloatInVec getZ() const;
// Get the w element of a quaternion
//
inline const FloatInVec getW() const;
// Set an x, y, z, or w element of a quaternion by index
//
inline Quat & setElem(int idx, float value);
// Set an x, y, z, or w element of a quaternion by index (scalar data contained in vector data type)
//
inline Quat & setElem(int idx, const FloatInVec & value);
// Get an x, y, z, or w element of a quaternion by index
//
inline const FloatInVec getElem(int idx) const;
// Subscripting operator to set or get an element
//
inline VecIdx operator[](int idx);
// Subscripting operator to get an element
//
inline const FloatInVec operator[](int idx) const;
// Add two quaternions
//
inline const Quat operator + (const Quat & quat) const;
// Subtract a quaternion from another quaternion
//
inline const Quat operator - (const Quat & quat) const;
// Multiply two quaternions
//
inline const Quat operator * (const Quat & quat) const;
// Multiply a quaternion by a scalar
//
inline const Quat operator * (float scalar) const;
// Divide a quaternion by a scalar
//
inline const Quat operator / (float scalar) const;
// Multiply a quaternion by a scalar (scalar data contained in vector data type)
//
inline const Quat operator * (const FloatInVec & scalar) const;
// Divide a quaternion by a scalar (scalar data contained in vector data type)
//
inline const Quat operator / (const FloatInVec & scalar) const;
// Perform compound assignment and addition with a quaternion
//
inline Quat & operator += (const Quat & quat);
// Perform compound assignment and subtraction by a quaternion
//
inline Quat & operator -= (const Quat & quat);
// Perform compound assignment and multiplication by a quaternion
//
inline Quat & operator *= (const Quat & quat);
// Perform compound assignment and multiplication by a scalar
//
inline Quat & operator *= (float scalar);
// Perform compound assignment and division by a scalar
//
inline Quat & operator /= (float scalar);
// Perform compound assignment and multiplication by a scalar (scalar data contained in vector data type)
//
inline Quat & operator *= (const FloatInVec & scalar);
// Perform compound assignment and division by a scalar (scalar data contained in vector data type)
//
inline Quat & operator /= (const FloatInVec & scalar);
// Negate all elements of a quaternion
//
inline const Quat operator - () const;
// Construct an identity quaternion
//
static inline const Quat identity();
// Construct a quaternion to rotate between two unit-length 3-D vectors
// NOTE:
// The result is unpredictable if unitVec0 and unitVec1 point in opposite directions.
//
static inline const Quat rotation(const Vector3 & unitVec0, const Vector3 & unitVec1);
// Construct a quaternion to rotate around a unit-length 3-D vector
//
static inline const Quat rotation(float radians, const Vector3 & unitVec);
// Construct a quaternion to rotate around a unit-length 3-D vector (scalar data contained in vector data type)
//
static inline const Quat rotation(const FloatInVec & radians, const Vector3 & unitVec);
// Construct a quaternion to rotate around the x axis
//
static inline const Quat rotationX(float radians);
// Construct a quaternion to rotate around the y axis
//
static inline const Quat rotationY(float radians);
// Construct a quaternion to rotate around the z axis
//
static inline const Quat rotationZ(float radians);
// Construct a quaternion to rotate around the x axis (scalar data contained in vector data type)
//
static inline const Quat rotationX(const FloatInVec & radians);
// Construct a quaternion to rotate around the y axis (scalar data contained in vector data type)
//
static inline const Quat rotationY(const FloatInVec & radians);
// Construct a quaternion to rotate around the z axis (scalar data contained in vector data type)
//
static inline const Quat rotationZ(const FloatInVec & radians);
} VECTORMATH_ALIGNED_TYPE_POST;
// Multiply a quaternion by a scalar
//
inline const Quat operator * (float scalar, const Quat & quat);
// Multiply a quaternion by a scalar (scalar data contained in vector data type)
//
inline const Quat operator * (const FloatInVec & scalar, const Quat & quat);
// Compute the conjugate of a quaternion
//
inline const Quat conj(const Quat & quat);
// Use a unit-length quaternion to rotate a 3-D vector
//
inline const Vector3 rotate(const Quat & unitQuat, const Vector3 & vec);
// Compute the dot product of two quaternions
//
inline const FloatInVec dot(const Quat & quat0, const Quat & quat1);
// Compute the norm of a quaternion
//
inline const FloatInVec norm(const Quat & quat);
// Compute the length of a quaternion
//
inline const FloatInVec length(const Quat & quat);
// Normalize a quaternion
// NOTE:
// The result is unpredictable when all elements of quat are at or near zero.
//
inline const Quat normalize(const Quat & quat);
// Linear interpolation between two quaternions
// NOTE:
// Does not clamp t between 0 and 1.
//
inline const Quat lerp(float t, const Quat & quat0, const Quat & quat1);
// Linear interpolation between two quaternions (scalar data contained in vector data type)
// NOTE:
// Does not clamp t between 0 and 1.
//
inline const Quat lerp(const FloatInVec & t, const Quat & quat0, const Quat & quat1);
// Spherical linear interpolation between two quaternions
// NOTE:
// Interpolates along the shortest path between orientations.
// Does not clamp t between 0 and 1.
//
inline const Quat slerp(float t, const Quat & unitQuat0, const Quat & unitQuat1);
// Spherical linear interpolation between two quaternions (scalar data contained in vector data type)
// NOTE:
// Interpolates along the shortest path between orientations.
// Does not clamp t between 0 and 1.
//
inline const Quat slerp(const FloatInVec & t, const Quat & unitQuat0, const Quat & unitQuat1);
// Spherical quadrangle interpolation
//
inline const Quat squad(float t, const Quat & unitQuat0, const Quat & unitQuat1, const Quat & unitQuat2, const Quat & unitQuat3);
// Spherical quadrangle interpolation (scalar data contained in vector data type)
//
inline const Quat squad(const FloatInVec & t, const Quat & unitQuat0, const Quat & unitQuat1, const Quat & unitQuat2, const Quat & unitQuat3);
// Conditionally select between two quaternions
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
// However, the transfer of select1 to a VMX register may use more processing time than a branch.
// Use the BoolInVec version for better performance.
//
inline const Quat select(const Quat & quat0, const Quat & quat1, bool select1);
// Conditionally select between two quaternions (scalar data contained in vector data type)
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
//
inline const Quat select(const Quat & quat0, const Quat & quat1, const BoolInVec & select1);
#ifdef VECTORMATH_DEBUG
// Print a quaternion
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Quat & quat);
// Print a quaternion and an associated string identifier
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Quat & quat, const char * name);
#endif // VECTORMATH_DEBUG
// ========================================================
// A 3x3 matrix in array-of-structures format
// ========================================================
VECTORMATH_ALIGNED_TYPE_PRE class Matrix3
{
Vector3 mCol0;
Vector3 mCol1;
Vector3 mCol2;
public:
// Default constructor; does no initialization
//
inline Matrix3() { }
// Copy a 3x3 matrix
//
inline Matrix3(const Matrix3 & mat);
// Construct a 3x3 matrix containing the specified columns
//
inline Matrix3(const Vector3 & col0, const Vector3 & col1, const Vector3 & col2);
// Construct a 3x3 rotation matrix from a unit-length quaternion
//
explicit inline Matrix3(const Quat & unitQuat);
// Set all elements of a 3x3 matrix to the same scalar value
//
explicit inline Matrix3(float scalar);
// Set all elements of a 3x3 matrix to the same scalar value (scalar data contained in vector data type)
//
explicit inline Matrix3(const FloatInVec & scalar);
// Assign one 3x3 matrix to another
//
inline Matrix3 & operator = (const Matrix3 & mat);
// Set column 0 of a 3x3 matrix
//
inline Matrix3 & setCol0(const Vector3 & col0);
// Set column 1 of a 3x3 matrix
//
inline Matrix3 & setCol1(const Vector3 & col1);
// Set column 2 of a 3x3 matrix
//
inline Matrix3 & setCol2(const Vector3 & col2);
// Get column 0 of a 3x3 matrix
//
inline const Vector3 getCol0() const;
// Get column 1 of a 3x3 matrix
//
inline const Vector3 getCol1() const;
// Get column 2 of a 3x3 matrix
//
inline const Vector3 getCol2() const;
// Set the column of a 3x3 matrix referred to by the specified index
//
inline Matrix3 & setCol(int col, const Vector3 & vec);
// Set the row of a 3x3 matrix referred to by the specified index
//
inline Matrix3 & setRow(int row, const Vector3 & vec);
// Get the column of a 3x3 matrix referred to by the specified index
//
inline const Vector3 getCol(int col) const;
// Get the row of a 3x3 matrix referred to by the specified index
//
inline const Vector3 getRow(int row) const;
// Subscripting operator to set or get a column
//
inline Vector3 & operator[](int col);
// Subscripting operator to get a column
//
inline const Vector3 operator[](int col) const;
// Set the element of a 3x3 matrix referred to by column and row indices
//
inline Matrix3 & setElem(int col, int row, float val);
// Set the element of a 3x3 matrix referred to by column and row indices (scalar data contained in vector data type)
//
inline Matrix3 & setElem(int col, int row, const FloatInVec & val);
// Get the element of a 3x3 matrix referred to by column and row indices
//
inline const FloatInVec getElem(int col, int row) const;
// Add two 3x3 matrices
//
inline const Matrix3 operator + (const Matrix3 & mat) const;
// Subtract a 3x3 matrix from another 3x3 matrix
//
inline const Matrix3 operator - (const Matrix3 & mat) const;
// Negate all elements of a 3x3 matrix
//
inline const Matrix3 operator - () const;
// Multiply a 3x3 matrix by a scalar
//
inline const Matrix3 operator * (float scalar) const;
// Multiply a 3x3 matrix by a scalar (scalar data contained in vector data type)
//
inline const Matrix3 operator * (const FloatInVec & scalar) const;
// Multiply a 3x3 matrix by a 3-D vector
//
inline const Vector3 operator * (const Vector3 & vec) const;
// Multiply two 3x3 matrices
//
inline const Matrix3 operator * (const Matrix3 & mat) const;
// Perform compound assignment and addition with a 3x3 matrix
//
inline Matrix3 & operator += (const Matrix3 & mat);
// Perform compound assignment and subtraction by a 3x3 matrix
//
inline Matrix3 & operator -= (const Matrix3 & mat);
// Perform compound assignment and multiplication by a scalar
//
inline Matrix3 & operator *= (float scalar);
// Perform compound assignment and multiplication by a scalar (scalar data contained in vector data type)
//
inline Matrix3 & operator *= (const FloatInVec & scalar);
// Perform compound assignment and multiplication by a 3x3 matrix
//
inline Matrix3 & operator *= (const Matrix3 & mat);
// Construct an identity 3x3 matrix
//
static inline const Matrix3 identity();
// Construct a 3x3 matrix to rotate around the x axis
//
static inline const Matrix3 rotationX(float radians);
// Construct a 3x3 matrix to rotate around the y axis
//
static inline const Matrix3 rotationY(float radians);
// Construct a 3x3 matrix to rotate around the z axis
//
static inline const Matrix3 rotationZ(float radians);
// Construct a 3x3 matrix to rotate around the x axis (scalar data contained in vector data type)
//
static inline const Matrix3 rotationX(const FloatInVec & radians);
// Construct a 3x3 matrix to rotate around the y axis (scalar data contained in vector data type)
//
static inline const Matrix3 rotationY(const FloatInVec & radians);
// Construct a 3x3 matrix to rotate around the z axis (scalar data contained in vector data type)
//
static inline const Matrix3 rotationZ(const FloatInVec & radians);
// Construct a 3x3 matrix to rotate around the x, y, and z axes
//
static inline const Matrix3 rotationZYX(const Vector3 & radiansXYZ);
// Construct a 3x3 matrix to rotate around a unit-length 3-D vector
//
static inline const Matrix3 rotation(float radians, const Vector3 & unitVec);
// Construct a 3x3 matrix to rotate around a unit-length 3-D vector (scalar data contained in vector data type)
//
static inline const Matrix3 rotation(const FloatInVec & radians, const Vector3 & unitVec);
// Construct a rotation matrix from a unit-length quaternion
//
static inline const Matrix3 rotation(const Quat & unitQuat);
// Construct a 3x3 matrix to perform scaling
//
static inline const Matrix3 scale(const Vector3 & scaleVec);
} VECTORMATH_ALIGNED_TYPE_POST;
// Multiply a 3x3 matrix by a scalar
//
inline const Matrix3 operator * (float scalar, const Matrix3 & mat);
// Multiply a 3x3 matrix by a scalar (scalar data contained in vector data type)
//
inline const Matrix3 operator * (const FloatInVec & scalar, const Matrix3 & mat);
// Append (post-multiply) a scale transformation to a 3x3 matrix
// NOTE:
// Faster than creating and multiplying a scale transformation matrix.
//
inline const Matrix3 appendScale(const Matrix3 & mat, const Vector3 & scaleVec);
// Prepend (pre-multiply) a scale transformation to a 3x3 matrix
// NOTE:
// Faster than creating and multiplying a scale transformation matrix.
//
inline const Matrix3 prependScale(const Vector3 & scaleVec, const Matrix3 & mat);
// Multiply two 3x3 matrices per element
//
inline const Matrix3 mulPerElem(const Matrix3 & mat0, const Matrix3 & mat1);
// Compute the absolute value of a 3x3 matrix per element
//
inline const Matrix3 absPerElem(const Matrix3 & mat);
// Transpose of a 3x3 matrix
//
inline const Matrix3 transpose(const Matrix3 & mat);
// Compute the inverse of a 3x3 matrix
// NOTE:
// Result is unpredictable when the determinant of mat is equal to or near 0.
//
inline const Matrix3 inverse(const Matrix3 & mat);
// Determinant of a 3x3 matrix
//
inline const FloatInVec determinant(const Matrix3 & mat);
// Conditionally select between two 3x3 matrices
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
// However, the transfer of select1 to a VMX register may use more processing time than a branch.
// Use the BoolInVec version for better performance.
//
inline const Matrix3 select(const Matrix3 & mat0, const Matrix3 & mat1, bool select1);
// Conditionally select between two 3x3 matrices (scalar data contained in vector data type)
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
//
inline const Matrix3 select(const Matrix3 & mat0, const Matrix3 & mat1, const BoolInVec & select1);
#ifdef VECTORMATH_DEBUG
// Print a 3x3 matrix
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Matrix3 & mat);
// Print a 3x3 matrix and an associated string identifier
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Matrix3 & mat, const char * name);
#endif // VECTORMATH_DEBUG
// ========================================================
// A 4x4 matrix in array-of-structures format
// ========================================================
VECTORMATH_ALIGNED_TYPE_PRE class Matrix4
{
Vector4 mCol0;
Vector4 mCol1;
Vector4 mCol2;
Vector4 mCol3;
public:
// Default constructor; does no initialization
//
inline Matrix4() { }
// Copy a 4x4 matrix
//
inline Matrix4(const Matrix4 & mat);
// Construct a 4x4 matrix containing the specified columns
//
inline Matrix4(const Vector4 & col0, const Vector4 & col1, const Vector4 & col2, const Vector4 & col3);
// Construct a 4x4 matrix from a 3x4 transformation matrix
//
explicit inline Matrix4(const Transform3 & mat);
// Construct a 4x4 matrix from a 3x3 matrix and a 3-D vector
//
inline Matrix4(const Matrix3 & mat, const Vector3 & translateVec);
// Construct a 4x4 matrix from a unit-length quaternion and a 3-D vector
//
inline Matrix4(const Quat & unitQuat, const Vector3 & translateVec);
// Set all elements of a 4x4 matrix to the same scalar value
//
explicit inline Matrix4(float scalar);
// Set all elements of a 4x4 matrix to the same scalar value (scalar data contained in vector data type)
//
explicit inline Matrix4(const FloatInVec & scalar);
// Get pointer to first float
inline float* GetPtr()
{
return mCol0.GetPtr();
}
// Assign one 4x4 matrix to another
//
inline Matrix4 & operator = (const Matrix4 & mat);
// Set the upper-left 3x3 submatrix
// NOTE:
// This function does not change the bottom row elements.
//
inline Matrix4 & setUpper3x3(const Matrix3 & mat3);
// Get the upper-left 3x3 submatrix of a 4x4 matrix
//
inline const Matrix3 getUpper3x3() const;
// Set translation component
// NOTE:
// This function does not change the bottom row elements.
//
inline Matrix4 & setTranslation(const Vector3 & translateVec);
// Get the translation component of a 4x4 matrix
//
inline const Vector3 getTranslation() const;
// Set column 0 of a 4x4 matrix
//
inline Matrix4 & setCol0(const Vector4 & col0);
// Set column 1 of a 4x4 matrix
//
inline Matrix4 & setCol1(const Vector4 & col1);
// Set column 2 of a 4x4 matrix
//
inline Matrix4 & setCol2(const Vector4 & col2);
// Set column 3 of a 4x4 matrix
//
inline Matrix4 & setCol3(const Vector4 & col3);
// Get column 0 of a 4x4 matrix
//
inline const Vector4 getCol0() const;
// Get column 1 of a 4x4 matrix
//
inline const Vector4 getCol1() const;
// Get column 2 of a 4x4 matrix
//
inline const Vector4 getCol2() const;
// Get column 3 of a 4x4 matrix
//
inline const Vector4 getCol3() const;
// Set the column of a 4x4 matrix referred to by the specified index
//
inline Matrix4 & setCol(int col, const Vector4 & vec);
// Set the row of a 4x4 matrix referred to by the specified index
//
inline Matrix4 & setRow(int row, const Vector4 & vec);
// Get the column of a 4x4 matrix referred to by the specified index
//
inline const Vector4 getCol(int col) const;
// Get the row of a 4x4 matrix referred to by the specified index
//
inline const Vector4 getRow(int row) const;
// Subscripting operator to set or get a column
//
inline Vector4 & operator[](int col);
// Subscripting operator to get a column
//
inline const Vector4 operator[](int col) const;
// Set the element of a 4x4 matrix referred to by column and row indices
//
inline Matrix4 & setElem(int col, int row, float val);
// Set the element of a 4x4 matrix referred to by column and row indices (scalar data contained in vector data type)
//
inline Matrix4 & setElem(int col, int row, const FloatInVec & val);
// Get the element of a 4x4 matrix referred to by column and row indices
//
inline const FloatInVec getElem(int col, int row) const;
// Add two 4x4 matrices
//
inline const Matrix4 operator + (const Matrix4 & mat) const;
// Subtract a 4x4 matrix from another 4x4 matrix
//
inline const Matrix4 operator - (const Matrix4 & mat) const;
// Negate all elements of a 4x4 matrix
//
inline const Matrix4 operator - () const;
// Multiply a 4x4 matrix by a scalar
//
inline const Matrix4 operator * (float scalar) const;
// Multiply a 4x4 matrix by a scalar (scalar data contained in vector data type)
//
inline const Matrix4 operator * (const FloatInVec & scalar) const;
// Multiply a 4x4 matrix by a 4-D vector
//
inline const Vector4 operator * (const Vector4 & vec) const;
// Multiply a 4x4 matrix by a 3-D vector
//
inline const Vector4 operator * (const Vector3 & vec) const;
// Multiply a 4x4 matrix by a 3-D point
//
inline const Vector4 operator * (const Point3 & pnt) const;
// Multiply two 4x4 matrices
//
inline const Matrix4 operator * (const Matrix4 & mat) const;
// Multiply a 4x4 matrix by a 3x4 transformation matrix
//
inline const Matrix4 operator * (const Transform3 & tfrm) const;
// Perform compound assignment and addition with a 4x4 matrix
//
inline Matrix4 & operator += (const Matrix4 & mat);
// Perform compound assignment and subtraction by a 4x4 matrix
//
inline Matrix4 & operator -= (const Matrix4 & mat);
// Perform compound assignment and multiplication by a scalar
//
inline Matrix4 & operator *= (float scalar);
// Perform compound assignment and multiplication by a scalar (scalar data contained in vector data type)
//
inline Matrix4 & operator *= (const FloatInVec & scalar);
// Perform compound assignment and multiplication by a 4x4 matrix
//
inline Matrix4 & operator *= (const Matrix4 & mat);
// Perform compound assignment and multiplication by a 3x4 transformation matrix
//
inline Matrix4 & operator *= (const Transform3 & tfrm);
// Construct an identity 4x4 matrix
//
static inline const Matrix4 identity();
// Construct a 4x4 matrix to rotate around the x axis
//
static inline const Matrix4 rotationX(float radians);
// Construct a 4x4 matrix to rotate around the y axis
//
static inline const Matrix4 rotationY(float radians);
// Construct a 4x4 matrix to rotate around the z axis
//
static inline const Matrix4 rotationZ(float radians);
// Construct a 4x4 matrix to rotate around the x axis (scalar data contained in vector data type)
//
static inline const Matrix4 rotationX(const FloatInVec & radians);
// Construct a 4x4 matrix to rotate around the y axis (scalar data contained in vector data type)
//
static inline const Matrix4 rotationY(const FloatInVec & radians);
// Construct a 4x4 matrix to rotate around the z axis (scalar data contained in vector data type)
//
static inline const Matrix4 rotationZ(const FloatInVec & radians);
// Construct a 4x4 matrix to rotate around the x, y, and z axes
//
static inline const Matrix4 rotationZYX(const Vector3 & radiansXYZ);
// Construct a 4x4 matrix to rotate around a unit-length 3-D vector
//
static inline const Matrix4 rotation(float radians, const Vector3 & unitVec);
// Construct a 4x4 matrix to rotate around a unit-length 3-D vector (scalar data contained in vector data type)
//
static inline const Matrix4 rotation(const FloatInVec & radians, const Vector3 & unitVec);
// Construct a rotation matrix from a unit-length quaternion
//
static inline const Matrix4 rotation(const Quat & unitQuat);
// Construct a 4x4 matrix to perform scaling
//
static inline const Matrix4 scale(const Vector3 & scaleVec);
// Construct a 4x4 matrix to perform translation
//
static inline const Matrix4 translation(const Vector3 & translateVec);
// Construct viewing matrix based on eye, position looked at, and up direction
//
static inline const Matrix4 lookAt(const Point3 & eyePos, const Point3 & lookAtPos, const Vector3 & upVec);
// Construct a perspective projection matrix
//
static inline const Matrix4 perspective(float fovyRadians, float aspect, float zNear, float zFar);
// Construct a perspective projection matrix based on frustum
//
static inline const Matrix4 frustum(float left, float right, float bottom, float top, float zNear, float zFar);
// Construct an orthographic projection matrix
//
static inline const Matrix4 orthographic(float left, float right, float bottom, float top, float zNear, float zFar);
} VECTORMATH_ALIGNED_TYPE_POST;
// Multiply a 4x4 matrix by a scalar
//
inline const Matrix4 operator * (float scalar, const Matrix4 & mat);
// Multiply a 4x4 matrix by a scalar (scalar data contained in vector data type)
//
inline const Matrix4 operator * (const FloatInVec & scalar, const Matrix4 & mat);
// Append (post-multiply) a scale transformation to a 4x4 matrix
// NOTE:
// Faster than creating and multiplying a scale transformation matrix.
//
inline const Matrix4 appendScale(const Matrix4 & mat, const Vector3 & scaleVec);
// Prepend (pre-multiply) a scale transformation to a 4x4 matrix
// NOTE:
// Faster than creating and multiplying a scale transformation matrix.
//
inline const Matrix4 prependScale(const Vector3 & scaleVec, const Matrix4 & mat);
// Multiply two 4x4 matrices per element
//
inline const Matrix4 mulPerElem(const Matrix4 & mat0, const Matrix4 & mat1);
// Compute the absolute value of a 4x4 matrix per element
//
inline const Matrix4 absPerElem(const Matrix4 & mat);
// Transpose of a 4x4 matrix
//
inline const Matrix4 transpose(const Matrix4 & mat);
// Compute the inverse of a 4x4 matrix
// NOTE:
// Result is unpredictable when the determinant of mat is equal to or near 0.
//
inline const Matrix4 inverse(const Matrix4 & mat);
// Compute the inverse of a 4x4 matrix, which is expected to be an affine matrix
// NOTE:
// This can be used to achieve better performance than a general inverse when the specified 4x4 matrix meets the given restrictions.
// The result is unpredictable when the determinant of mat is equal to or near 0.
//
inline const Matrix4 affineInverse(const Matrix4 & mat);
// Compute the inverse of a 4x4 matrix, which is expected to be an affine matrix with an orthogonal upper-left 3x3 submatrix
// NOTE:
// This can be used to achieve better performance than a general inverse when the specified 4x4 matrix meets the given restrictions.
//
inline const Matrix4 orthoInverse(const Matrix4 & mat);
// Determinant of a 4x4 matrix
//
inline const FloatInVec determinant(const Matrix4 & mat);
// Conditionally select between two 4x4 matrices
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
// However, the transfer of select1 to a VMX register may use more processing time than a branch.
// Use the BoolInVec version for better performance.
//
inline const Matrix4 select(const Matrix4 & mat0, const Matrix4 & mat1, bool select1);
// Conditionally select between two 4x4 matrices (scalar data contained in vector data type)
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
//
inline const Matrix4 select(const Matrix4 & mat0, const Matrix4 & mat1, const BoolInVec & select1);
#ifdef VECTORMATH_DEBUG
// Print a 4x4 matrix
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Matrix4 & mat);
// Print a 4x4 matrix and an associated string identifier
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Matrix4 & mat, const char * name);
#endif // VECTORMATH_DEBUG
// ========================================================
// A 3x4 transformation matrix in array-of-structs format
// ========================================================
VECTORMATH_ALIGNED_TYPE_PRE class Transform3
{
Vector3 mCol0;
Vector3 mCol1;
Vector3 mCol2;
Vector3 mCol3;
public:
// Default constructor; does no initialization
//
inline Transform3() { }
// Copy a 3x4 transformation matrix
//
inline Transform3(const Transform3 & tfrm);
// Construct a 3x4 transformation matrix containing the specified columns
//
inline Transform3(const Vector3 & col0, const Vector3 & col1, const Vector3 & col2, const Vector3 & col3);
// Construct a 3x4 transformation matrix from a 3x3 matrix and a 3-D vector
//
inline Transform3(const Matrix3 & tfrm, const Vector3 & translateVec);
// Construct a 3x4 transformation matrix from a unit-length quaternion and a 3-D vector
//
inline Transform3(const Quat & unitQuat, const Vector3 & translateVec);
// Set all elements of a 3x4 transformation matrix to the same scalar value
//
explicit inline Transform3(float scalar);
// Set all elements of a 3x4 transformation matrix to the same scalar value (scalar data contained in vector data type)
//
explicit inline Transform3(const FloatInVec & scalar);
// Assign one 3x4 transformation matrix to another
//
inline Transform3 & operator = (const Transform3 & tfrm);
// Set the upper-left 3x3 submatrix
//
inline Transform3 & setUpper3x3(const Matrix3 & mat3);
// Get the upper-left 3x3 submatrix of a 3x4 transformation matrix
//
inline const Matrix3 getUpper3x3() const;
// Set translation component
//
inline Transform3 & setTranslation(const Vector3 & translateVec);
// Get the translation component of a 3x4 transformation matrix
//
inline const Vector3 getTranslation() const;
// Set column 0 of a 3x4 transformation matrix
//
inline Transform3 & setCol0(const Vector3 & col0);
// Set column 1 of a 3x4 transformation matrix
//
inline Transform3 & setCol1(const Vector3 & col1);
// Set column 2 of a 3x4 transformation matrix
//
inline Transform3 & setCol2(const Vector3 & col2);
// Set column 3 of a 3x4 transformation matrix
//
inline Transform3 & setCol3(const Vector3 & col3);
// Get column 0 of a 3x4 transformation matrix
//
inline const Vector3 getCol0() const;
// Get column 1 of a 3x4 transformation matrix
//
inline const Vector3 getCol1() const;
// Get column 2 of a 3x4 transformation matrix
//
inline const Vector3 getCol2() const;
// Get column 3 of a 3x4 transformation matrix
//
inline const Vector3 getCol3() const;
// Set the column of a 3x4 transformation matrix referred to by the specified index
//
inline Transform3 & setCol(int col, const Vector3 & vec);
// Set the row of a 3x4 transformation matrix referred to by the specified index
//
inline Transform3 & setRow(int row, const Vector4 & vec);
// Get the column of a 3x4 transformation matrix referred to by the specified index
//
inline const Vector3 getCol(int col) const;
// Get the row of a 3x4 transformation matrix referred to by the specified index
//
inline const Vector4 getRow(int row) const;
// Subscripting operator to set or get a column
//
inline Vector3 & operator[](int col);
// Subscripting operator to get a column
//
inline const Vector3 operator[](int col) const;
// Set the element of a 3x4 transformation matrix referred to by column and row indices
//
inline Transform3 & setElem(int col, int row, float val);
// Set the element of a 3x4 transformation matrix referred to by column and row indices (scalar data contained in vector data type)
//
inline Transform3 & setElem(int col, int row, const FloatInVec & val);
// Get the element of a 3x4 transformation matrix referred to by column and row indices
//
inline const FloatInVec getElem(int col, int row) const;
// Multiply a 3x4 transformation matrix by a 3-D vector
//
inline const Vector3 operator * (const Vector3 & vec) const;
// Multiply a 3x4 transformation matrix by a 3-D point
//
inline const Point3 operator * (const Point3 & pnt) const;
// Multiply two 3x4 transformation matrices
//
inline const Transform3 operator * (const Transform3 & tfrm) const;
// Perform compound assignment and multiplication by a 3x4 transformation matrix
//
inline Transform3 & operator *= (const Transform3 & tfrm);
// Construct an identity 3x4 transformation matrix
//
static inline const Transform3 identity();
// Construct a 3x4 transformation matrix to rotate around the x axis
//
static inline const Transform3 rotationX(float radians);
// Construct a 3x4 transformation matrix to rotate around the y axis
//
static inline const Transform3 rotationY(float radians);
// Construct a 3x4 transformation matrix to rotate around the z axis
//
static inline const Transform3 rotationZ(float radians);
// Construct a 3x4 transformation matrix to rotate around the x axis (scalar data contained in vector data type)
//
static inline const Transform3 rotationX(const FloatInVec & radians);
// Construct a 3x4 transformation matrix to rotate around the y axis (scalar data contained in vector data type)
//
static inline const Transform3 rotationY(const FloatInVec & radians);
// Construct a 3x4 transformation matrix to rotate around the z axis (scalar data contained in vector data type)
//
static inline const Transform3 rotationZ(const FloatInVec & radians);
// Construct a 3x4 transformation matrix to rotate around the x, y, and z axes
//
static inline const Transform3 rotationZYX(const Vector3 & radiansXYZ);
// Construct a 3x4 transformation matrix to rotate around a unit-length 3-D vector
//
static inline const Transform3 rotation(float radians, const Vector3 & unitVec);
// Construct a 3x4 transformation matrix to rotate around a unit-length 3-D vector (scalar data contained in vector data type)
//
static inline const Transform3 rotation(const FloatInVec & radians, const Vector3 & unitVec);
// Construct a rotation matrix from a unit-length quaternion
//
static inline const Transform3 rotation(const Quat & unitQuat);
// Construct a 3x4 transformation matrix to perform scaling
//
static inline const Transform3 scale(const Vector3 & scaleVec);
// Construct a 3x4 transformation matrix to perform translation
//
static inline const Transform3 translation(const Vector3 & translateVec);
} VECTORMATH_ALIGNED_TYPE_POST;
// Append (post-multiply) a scale transformation to a 3x4 transformation matrix
// NOTE:
// Faster than creating and multiplying a scale transformation matrix.
//
inline const Transform3 appendScale(const Transform3 & tfrm, const Vector3 & scaleVec);
// Prepend (pre-multiply) a scale transformation to a 3x4 transformation matrix
// NOTE:
// Faster than creating and multiplying a scale transformation matrix.
//
inline const Transform3 prependScale(const Vector3 & scaleVec, const Transform3 & tfrm);
// Multiply two 3x4 transformation matrices per element
//
inline const Transform3 mulPerElem(const Transform3 & tfrm0, const Transform3 & tfrm1);
// Compute the absolute value of a 3x4 transformation matrix per element
//
inline const Transform3 absPerElem(const Transform3 & tfrm);
// Inverse of a 3x4 transformation matrix
// NOTE:
// Result is unpredictable when the determinant of the left 3x3 submatrix is equal to or near 0.
//
inline const Transform3 inverse(const Transform3 & tfrm);
// Compute the inverse of a 3x4 transformation matrix, expected to have an orthogonal upper-left 3x3 submatrix
// NOTE:
// This can be used to achieve better performance than a general inverse when the specified 3x4 transformation matrix meets the given restrictions.
//
inline const Transform3 orthoInverse(const Transform3 & tfrm);
// Conditionally select between two 3x4 transformation matrices
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
// However, the transfer of select1 to a VMX register may use more processing time than a branch.
// Use the BoolInVec version for better performance.
//
inline const Transform3 select(const Transform3 & tfrm0, const Transform3 & tfrm1, bool select1);
// Conditionally select between two 3x4 transformation matrices (scalar data contained in vector data type)
// NOTE:
// This function uses a conditional select instruction to avoid a branch.
//
inline const Transform3 select(const Transform3 & tfrm0, const Transform3 & tfrm1, const BoolInVec & select1);
#ifdef VECTORMATH_DEBUG
// Print a 3x4 transformation matrix
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Transform3 & tfrm);
// Print a 3x4 transformation matrix and an associated string identifier
// NOTE:
// Function is only defined when VECTORMATH_DEBUG is defined.
//
inline void print(const Transform3 & tfrm, const char * name);
#endif // VECTORMATH_DEBUG
} // namespace SSE
} // namespace Vectormath
// Inline implementations:
#include "vector.hpp"
#include "quaternion.hpp"
#include "matrix.hpp"
#endif // VECTORMATH_SSE_VECTORMATH_HPP
| 32.136801 | 147 | 0.690394 | [
"vector"
] |
43a9f8c7ed3e7d948e6d2e8a2b0e16bec9a43d3c | 7,078 | cpp | C++ | test/unittest/rtps/persistence/PersistenceTests.cpp | pbleyer/Fast-DDS | 1963bd8ccbe0bc6c93267fb1977565d32ef56188 | [
"Apache-2.0"
] | null | null | null | test/unittest/rtps/persistence/PersistenceTests.cpp | pbleyer/Fast-DDS | 1963bd8ccbe0bc6c93267fb1977565d32ef56188 | [
"Apache-2.0"
] | null | null | null | test/unittest/rtps/persistence/PersistenceTests.cpp | pbleyer/Fast-DDS | 1963bd8ccbe0bc6c93267fb1977565d32ef56188 | [
"Apache-2.0"
] | null | null | null | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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 <fastdds/rtps/attributes/PropertyPolicy.h>
#include <rtps/history/CacheChangePool.h>
#include <rtps/persistence/PersistenceService.h>
#include <climits>
#include <gtest/gtest.h>
using namespace eprosima::fastrtps::rtps;
class NoOpPayloadPool : public IPayloadPool
{
virtual bool get_payload(
uint32_t,
CacheChange_t&) override
{
return true;
}
virtual bool get_payload(
SerializedPayload_t&,
IPayloadPool*&,
CacheChange_t&) override
{
return true;
}
virtual bool release_payload(
CacheChange_t&) override
{
return true;
}
};
class PersistenceTest : public ::testing::Test
{
protected:
IPersistenceService* service = nullptr;
std::shared_ptr<NoOpPayloadPool> payload_pool_ = std::make_shared<NoOpPayloadPool>();
virtual void SetUp()
{
std::remove("test.db");
}
virtual void TearDown()
{
if (service != nullptr)
{
delete service;
}
std::remove("test.db");
}
};
/*!
* @fn TEST_F(PersistenceTest, Writer)
* @brief This test checks the writer persistence interface of the persistence service.
*/
TEST_F(PersistenceTest, Writer)
{
const std::string persist_guid("TEST_WRITER");
PropertyPolicy policy;
policy.properties().emplace_back("dds.persistence.plugin", "builtin.SQLITE3");
policy.properties().emplace_back("dds.persistence.sqlite3.filename", "test.db");
// Get service from factory
service = PersistenceFactory::create_persistence_service(policy);
ASSERT_NE(service, nullptr);
auto init_cache = [](CacheChange_t* item)
{
item->serializedPayload.reserve(128);
};
PoolConfig cfg{ MemoryManagementPolicy_t::PREALLOCATED_MEMORY_MODE, 0, 10, 0 };
auto pool = std::make_shared<CacheChangePool>(cfg, init_cache);
SequenceNumber_t max_seq;
CacheChange_t change;
GUID_t guid(GuidPrefix_t::unknown(), 1U);
std::vector<CacheChange_t*> changes;
change.kind = ALIVE;
change.writerGUID = guid;
change.serializedPayload.length = 0;
// Initial load should return empty vector
changes.clear();
ASSERT_TRUE(service->load_writer_from_storage(persist_guid, guid, changes, pool, payload_pool_, max_seq));
ASSERT_EQ(changes.size(), 0u);
// Add two changes
change.sequenceNumber.low = 1;
ASSERT_TRUE(service->add_writer_change_to_storage(persist_guid, change));
change.sequenceNumber.low = 2;
ASSERT_TRUE(service->add_writer_change_to_storage(persist_guid, change));
// Should not be able to add same sequence again
change.sequenceNumber.low = 1;
ASSERT_FALSE(service->add_writer_change_to_storage(persist_guid, change));
change.sequenceNumber.low = 2;
ASSERT_FALSE(service->add_writer_change_to_storage(persist_guid, change));
// Loading should return two changes (seqs = 1, 2)
changes.clear();
ASSERT_TRUE(service->load_writer_from_storage(persist_guid, guid, changes, pool, payload_pool_, max_seq));
ASSERT_EQ(changes.size(), 2u);
uint32_t i = 0;
for (auto it : changes)
{
++i;
ASSERT_EQ(it->sequenceNumber, SequenceNumber_t(0, i));
}
// Remove seq = 1, and test it can be safely removed twice
change.sequenceNumber.low = 1;
ASSERT_TRUE(service->remove_writer_change_from_storage(persist_guid, change));
ASSERT_TRUE(service->remove_writer_change_from_storage(persist_guid, change));
// Loading should return one change (seq = 2)
changes.clear();
ASSERT_TRUE(service->load_writer_from_storage(persist_guid, guid, changes, pool, payload_pool_, max_seq));
ASSERT_EQ(changes.size(), 1u);
ASSERT_EQ((*changes.begin())->sequenceNumber, SequenceNumber_t(0, 2));
// Remove seq = 2, and check that load returns empty vector
changes.clear();
change.sequenceNumber.low = 2;
ASSERT_TRUE(service->remove_writer_change_from_storage(persist_guid, change));
ASSERT_TRUE(service->load_writer_from_storage(persist_guid, guid, changes, pool, payload_pool_, max_seq));
ASSERT_EQ(changes.size(), 0u);
}
/*!
* @fn TEST_F(PersistenceTest, Reader)
* @brief This test checks the reader persistence interface of the persistence service.
*/
TEST_F(PersistenceTest, Reader)
{
const std::string persist_guid("TEST_READER");
PropertyPolicy policy;
policy.properties().emplace_back("dds.persistence.plugin", "builtin.SQLITE3");
policy.properties().emplace_back("dds.persistence.sqlite3.filename", "test.db");
// Get service from factory
service = PersistenceFactory::create_persistence_service(policy);
ASSERT_NE(service, nullptr);
IPersistenceService::map_allocator_t pool(128, 1024);
foonathan::memory::map<GUID_t, SequenceNumber_t, IPersistenceService::map_allocator_t> seq_map(pool);
foonathan::memory::map<GUID_t, SequenceNumber_t, IPersistenceService::map_allocator_t> seq_map_loaded(pool);
GUID_t guid_1(GuidPrefix_t::unknown(), 1U);
SequenceNumber_t seq_1(0, 1);
GUID_t guid_2(GuidPrefix_t::unknown(), 2U);
SequenceNumber_t seq_2(0, 1);
// Initial load should return empty map
seq_map_loaded.clear();
ASSERT_TRUE(service->load_reader_from_storage(persist_guid, seq_map_loaded));
ASSERT_EQ(seq_map_loaded.size(), 0u);
// Add two changes
seq_map[guid_1] = seq_1;
ASSERT_TRUE(service->update_writer_seq_on_storage(persist_guid, guid_1, seq_1));
seq_map[guid_2] = seq_2;
ASSERT_TRUE(service->update_writer_seq_on_storage(persist_guid, guid_2, seq_2));
// Loading should return local map
seq_map_loaded.clear();
ASSERT_TRUE(service->load_reader_from_storage(persist_guid, seq_map_loaded));
ASSERT_EQ(seq_map_loaded, seq_map);
// Update previously added changes
seq_1.low = 100;
seq_map[guid_1] = seq_1;
ASSERT_TRUE(service->update_writer_seq_on_storage(persist_guid, guid_1, seq_1));
seq_2.low = 200;
seq_map[guid_2] = seq_2;
ASSERT_TRUE(service->update_writer_seq_on_storage(persist_guid, guid_2, seq_2));
// Loading should return local map
seq_map_loaded.clear();
ASSERT_TRUE(service->load_reader_from_storage(persist_guid, seq_map_loaded));
ASSERT_EQ(seq_map_loaded, seq_map);
}
int main(
int argc,
char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 33.230047 | 112 | 0.708392 | [
"vector"
] |
43aa360d11825ebd325d6a65b01d00d38265291c | 13,083 | cpp | C++ | Tools/DumpRenderTree/win/AccessibilityControllerWin.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | Tools/DumpRenderTree/win/AccessibilityControllerWin.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | Tools/DumpRenderTree/win/AccessibilityControllerWin.cpp | jacadcaps/webkitty | 9aebd2081349f9a7b5d168673c6f676a1450a66d | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (C) 2008, 2009, 2010, 2013 Apple 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "AccessibilityController.h"
#include "AccessibilityUIElement.h"
#include "DumpRenderTree.h"
#include "FrameLoadDelegate.h"
#include "TestRunner.h"
#include <JavaScriptCore/JSRetainPtr.h>
#include <JavaScriptCore/JSStringRef.h>
#include <JavaScriptCore/JSStringRefBSTR.h>
#include <WebCore/AccessibilityObjectWrapperWin.h>
#include <WebCore/COMPtr.h>
#include <WebKitLegacy/WebKit.h>
#include <comutil.h>
#include <oleacc.h>
#include <string>
#include <wtf/Assertions.h>
#include <wtf/text/AtomString.h>
AccessibilityController::AccessibilityController() = default;
AccessibilityController::~AccessibilityController()
{
setLogFocusEvents(false);
setLogAccessibilityEvents(false);
setLogValueChangeEvents(false);
if (m_notificationsEventHook)
UnhookWinEvent(m_notificationsEventHook);
for (auto& listener : m_notificationListeners.values())
JSValueUnprotect(frame->globalContext(), listener);
}
AccessibilityUIElement AccessibilityController::elementAtPoint(int x, int y)
{
// FIXME: implement
return { nullptr };
}
static COMPtr<IAccessibleComparable> comparableObject(const COMPtr<IServiceProvider>& serviceProvider)
{
COMPtr<IAccessibleComparable> comparable;
serviceProvider->QueryService(SID_AccessibleComparable, __uuidof(IAccessibleComparable), reinterpret_cast<void**>(&comparable));
return comparable;
}
static COMPtr<IAccessible> findAccessibleObjectById(AccessibilityUIElement parentObject, BSTR idAttribute)
{
COMPtr<IAccessible> parentIAccessible = parentObject.platformUIElement();
COMPtr<IServiceProvider> serviceProvider(Query, parentIAccessible);
if (!serviceProvider)
return 0;
COMPtr<IAccessibleComparable> comparable = comparableObject(serviceProvider);
if (!comparable)
return 0;
_variant_t value;
_bstr_t elementIdAttributeKey(L"AXDRTElementIdAttribute");
if (SUCCEEDED(comparable->get_attribute(elementIdAttributeKey, &value.GetVARIANT()))) {
ASSERT(V_VT(&value) == VT_BSTR);
if (VARCMP_EQ == ::VarBstrCmp(value.bstrVal, idAttribute, LOCALE_USER_DEFAULT, 0))
return parentIAccessible;
}
long childCount = parentObject.childrenCount();
if (!childCount)
return nullptr;
COMPtr<IAccessible> result;
for (long i = 0; i < childCount; ++i) {
AccessibilityUIElement childAtIndex = parentObject.getChildAtIndex(i);
result = findAccessibleObjectById(childAtIndex, idAttribute);
if (result)
return result;
}
return nullptr;
}
AccessibilityUIElement AccessibilityController::accessibleElementById(JSStringRef id)
{
AccessibilityUIElement rootAccessibilityUIElement = rootElement();
_bstr_t idAttribute(JSStringCopyBSTR(id), false);
COMPtr<IAccessible> result = findAccessibleObjectById(rootAccessibilityUIElement, idAttribute);
if (result)
return AccessibilityUIElement(result);
return { nullptr };
}
AccessibilityUIElement AccessibilityController::focusedElement()
{
COMPtr<IAccessible> rootAccessible = rootElement().platformUIElement();
_variant_t vFocus;
if (FAILED(rootAccessible->get_accFocus(&vFocus.GetVARIANT())))
return { nullptr };
if (V_VT(&vFocus) == VT_I4) {
ASSERT(V_I4(&vFocus) == CHILDID_SELF);
// The root accessible object is the focused object.
return rootAccessible;
}
ASSERT(V_VT(&vFocus) == VT_DISPATCH);
// We have an IDispatch; query for IAccessible.
return COMPtr<IAccessible>(Query, V_DISPATCH(&vFocus));
}
AccessibilityUIElement AccessibilityController::rootElement()
{
COMPtr<IWebView> view;
if (FAILED(frame->webView(&view)))
return { nullptr };
COMPtr<IWebViewPrivate2> viewPrivate(Query, view);
if (!viewPrivate)
return { nullptr };
HWND webViewWindow;
if (FAILED(viewPrivate->viewWindow(&webViewWindow)))
return { nullptr };
// Make sure the layout is up to date, so we can find all accessible elements.
COMPtr<IWebFramePrivate> framePrivate(Query, frame);
if (framePrivate)
framePrivate->layout();
// Get the root accessible object by querying for the accessible object for the
// WebView's window.
COMPtr<IAccessible> rootAccessible;
if (FAILED(AccessibleObjectFromWindow(webViewWindow, static_cast<DWORD>(OBJID_CLIENT), __uuidof(IAccessible), reinterpret_cast<void**>(&rootAccessible))))
return { nullptr };
return rootAccessible;
}
static void CALLBACK logEventProc(HWINEVENTHOOK, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD)
{
// Get the accessible object for this event.
COMPtr<IAccessible> parentObject;
_variant_t vChild;
HRESULT hr = AccessibleObjectFromEvent(hwnd, idObject, idChild, &parentObject, &vChild.GetVARIANT());
ASSERT(SUCCEEDED(hr));
// Get the name of the focused element, and log it to stdout.
_bstr_t nameBSTR;
hr = parentObject->get_accName(vChild, &nameBSTR.GetBSTR());
ASSERT(SUCCEEDED(hr));
std::wstring name(nameBSTR, nameBSTR.length());
switch (event) {
case EVENT_OBJECT_FOCUS:
fprintf(testResult, "Received focus event for object '%S'.\n", name.c_str());
break;
case EVENT_OBJECT_SELECTION:
fprintf(testResult, "Received selection event for object '%S'.\n", name.c_str());
break;
case EVENT_OBJECT_VALUECHANGE: {
_bstr_t valueBSTR;
hr = parentObject->get_accValue(vChild, &valueBSTR.GetBSTR());
ASSERT(SUCCEEDED(hr));
std::wstring value(valueBSTR, valueBSTR.length());
fprintf(testResult, "Received value change event for object '%S', value '%S'.\n", name.c_str(), value.c_str());
break;
}
case EVENT_SYSTEM_SCROLLINGSTART:
fprintf(testResult, "Received scrolling start event for object '%S'.\n", name.c_str());
break;
default:
fprintf(testResult, "Received unknown event for object '%S'.\n", name.c_str());
break;
}
}
void AccessibilityController::setLogFocusEvents(bool logFocusEvents)
{
if (!!m_focusEventHook == logFocusEvents)
return;
if (!logFocusEvents) {
UnhookWinEvent(m_focusEventHook);
m_focusEventHook = 0;
return;
}
// Ensure that accessibility is initialized for the WebView by querying for
// the root accessible object.
rootElement();
m_focusEventHook = SetWinEventHook(EVENT_OBJECT_FOCUS, EVENT_OBJECT_FOCUS, GetModuleHandle(0), logEventProc, GetCurrentProcessId(), 0, WINEVENT_INCONTEXT);
ASSERT(m_focusEventHook);
}
void AccessibilityController::platformResetToConsistentState()
{
}
void AccessibilityController::setLogValueChangeEvents(bool logValueChangeEvents)
{
if (!!m_valueChangeEventHook == logValueChangeEvents)
return;
if (!logValueChangeEvents) {
UnhookWinEvent(m_valueChangeEventHook);
m_valueChangeEventHook = 0;
return;
}
// Ensure that accessibility is initialized for the WebView by querying for
// the root accessible object.
rootElement();
m_valueChangeEventHook = SetWinEventHook(EVENT_OBJECT_VALUECHANGE, EVENT_OBJECT_VALUECHANGE, GetModuleHandle(0), logEventProc, GetCurrentProcessId(), 0, WINEVENT_INCONTEXT);
ASSERT(m_valueChangeEventHook);
}
void AccessibilityController::setLogScrollingStartEvents(bool logScrollingStartEvents)
{
if (!!m_scrollingStartEventHook == logScrollingStartEvents)
return;
if (!logScrollingStartEvents) {
UnhookWinEvent(m_scrollingStartEventHook);
m_scrollingStartEventHook = 0;
return;
}
// Ensure that accessibility is initialized for the WebView by querying for
// the root accessible object.
rootElement();
m_scrollingStartEventHook = SetWinEventHook(EVENT_SYSTEM_SCROLLINGSTART, EVENT_SYSTEM_SCROLLINGSTART, GetModuleHandle(0), logEventProc, GetCurrentProcessId(), 0, WINEVENT_INCONTEXT);
ASSERT(m_scrollingStartEventHook);
}
void AccessibilityController::setLogAccessibilityEvents(bool logAccessibilityEvents)
{
if (!!m_allEventsHook == logAccessibilityEvents)
return;
if (!logAccessibilityEvents) {
UnhookWinEvent(m_allEventsHook);
m_allEventsHook = 0;
return;
}
// Ensure that accessibility is initialized for the WebView by querying for
// the root accessible object.
rootElement();
m_allEventsHook = SetWinEventHook(EVENT_MIN, EVENT_MAX, GetModuleHandle(0), logEventProc, GetCurrentProcessId(), 0, WINEVENT_INCONTEXT);
ASSERT(m_allEventsHook);
}
static std::string stringEvent(DWORD event)
{
switch(event) {
case EVENT_OBJECT_VALUECHANGE:
return "value change event";
default:
return "unknown event";
}
}
static void CALLBACK notificationListenerProc(HWINEVENTHOOK, DWORD event, HWND hwnd, LONG idObject, LONG idChild, DWORD, DWORD)
{
// Get the accessible object for this event.
COMPtr<IAccessible> parentObject;
_variant_t vChild;
HRESULT hr = AccessibleObjectFromEvent(hwnd, idObject, idChild, &parentObject, &vChild.GetVARIANT());
if (FAILED(hr) || !parentObject)
return;
COMPtr<IDispatch> childDispatch;
if (FAILED(parentObject->get_accChild(vChild, &childDispatch)))
return;
COMPtr<IAccessible> childAccessible(Query, childDispatch);
sharedFrameLoadDelegate->accessibilityController()->winNotificationReceived(childAccessible, stringEvent(event));
}
bool AccessibilityController::addNotificationListener(JSObjectRef functionCallback)
{
return false;
}
void AccessibilityController::removeNotificationListener()
{
}
void AccessibilityController::winNotificationReceived(PlatformUIElement element, const std::string& eventName)
{
for (auto& slot : m_notificationListeners) {
COMPtr<IServiceProvider> thisServiceProvider(Query, slot.key);
if (!thisServiceProvider)
continue;
COMPtr<IAccessibleComparable> thisComparable = comparableObject(thisServiceProvider);
if (!thisComparable)
continue;
COMPtr<IServiceProvider> elementServiceProvider(Query, element);
if (!elementServiceProvider)
continue;
COMPtr<IAccessibleComparable> elementComparable = comparableObject(elementServiceProvider);
if (!elementComparable)
continue;
BOOL isSame = FALSE;
thisComparable->isSameObject(elementComparable.get(), &isSame);
if (!isSame)
continue;
auto jsNotification = adopt(JSStringCreateWithUTF8CString(eventName.c_str()));
JSValueRef argument = JSValueMakeString(frame->globalContext(), jsNotification.get());
JSObjectCallAsFunction(frame->globalContext(), slot.value, 0, 1, &argument, 0);
}
}
void AccessibilityController::winAddNotificationListener(PlatformUIElement element, JSObjectRef functionCallback)
{
if (!m_notificationsEventHook)
m_notificationsEventHook = SetWinEventHook(EVENT_MIN, EVENT_MAX, GetModuleHandle(0), notificationListenerProc, GetCurrentProcessId(), 0, WINEVENT_INCONTEXT);
JSValueProtect(frame->globalContext(), functionCallback);
m_notificationListeners.add(element, functionCallback);
}
void AccessibilityController::enableEnhancedAccessibility(bool)
{
// FIXME: implement
}
bool AccessibilityController::enhancedAccessibilityEnabled()
{
// FIXME: implement
return false;
}
JSRetainPtr<JSStringRef> AccessibilityController::platformName() const
{
return adopt(JSStringCreateWithUTF8CString("win"));
}
| 33.632391 | 186 | 0.723381 | [
"object"
] |
43ab2b6f5e37929a851a1a026e59fdcf0467b02f | 16,064 | cpp | C++ | Engine/Source/GEOGL/Rendering/Renderer2D.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | Engine/Source/GEOGL/Rendering/Renderer2D.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | Engine/Source/GEOGL/Rendering/Renderer2D.cpp | Matthew-Krueger/GEOGL | aae6adbd3d9cfadb4fe65b961d018636e42ddecc | [
"Zlib"
] | null | null | null | /*******************************************************************************
* Copyright (c) 2020 Matthew Krueger *
* *
* This software is provided 'as-is', without any express or implied *
* warranty. In no event will the authors be held liable for any damages *
* arising from the use of this software. *
* *
* Permission is granted to anyone to use this software for any purpose, *
* including commercial applications, and to alter it and redistribute it *
* freely, subject to the following restrictions: *
* *
* 1. The origin of this software must not be misrepresented; you must not *
* claim that you wrote the original software. If you use this software *
* in a product, an acknowledgment in the product documentation would *
* be appreciated but is not required. *
* *
* 2. Altered source versions must be plainly marked as such, and must not *
* be misrepresented as being the original software. *
* *
* 3. This notice may not be removed or altered from any source *
* distribution. *
* *
*******************************************************************************/
#include "Renderer2D.hpp"
#include <GEOGL/Platform/OpenGL.hpp>
#include "RenderCommand.hpp"
namespace GEOGL{
struct QuadVertex{
glm::vec3 position;
glm::vec4 color;
glm::vec2 textureCoord;
float tilingFactor;
float textureIndex;
//TODO: color, texid
};
struct Renderer2DData{
const uint32_t maxQuads = 7500;
const uint32_t maxVertices = maxQuads * 4;
const uint32_t maxIndices = maxQuads * 6;
static const uint32_t maxTextureSlots = 32; //TODO: Get from RenderCaps
Ref<VertexArray> quadVertexArray;
Ref<VertexBuffer> quadVertexBuffer;
Ref<Shader> textureShader;
Ref<Texture2D> whiteTexture;
uint32_t quadIndexCount = 0;
QuadVertex* quadVertexBufferBase = nullptr;
QuadVertex* quadVertexBufferPtr = nullptr;
glm::vec4 quadVertexPositions[4] = {};
//TODO: GUID identifier
std::array<Ref<Texture2D>, maxTextureSlots> textureSlots;
uint32_t textureSlotIndex = 0;
Renderer2D::Statistics stats{};
bool wireframe = false;
};
static Renderer2DData s_Data;
static glm::mat4 s_IdentMatrix;
void GEOGL::Renderer2D::init(const std::string& applicationResourceDirectory) {
GEOGL_PROFILE_FUNCTION();
/* Store a blank identity matrix to save on compute */
s_IdentMatrix = glm::mat4(1.0f);
s_Data.quadVertexArray = VertexArray::create();
/* Create the quad vertex Buffer */
{
s_Data.quadVertexBuffer = VertexBuffer::create(s_Data.maxVertices * sizeof(QuadVertex));
{
s_Data.quadVertexBuffer->setLayout({
{ShaderDataType::FLOAT3, "a_Position"},
{ShaderDataType::FLOAT4, "a_Color"},
{ShaderDataType::FLOAT2, "a_TextureCoord"},
{ShaderDataType::FLOAT, "a_TilingFactor"},
{ShaderDataType::FLOAT, "a_TextureIndex"}
});
}
s_Data.quadVertexArray->addVertexBuffer(s_Data.quadVertexBuffer);
s_Data.quadVertexBufferBase = new QuadVertex[s_Data.maxVertices];
}
/* Create t he quad indices */
{
auto *quadIndices = new uint32_t[s_Data.maxIndices];
uint32_t offset = 0;
for (uint32_t i = 0; i < s_Data.maxIndices; i += 6) {
quadIndices[i + 0] = offset + 0;
quadIndices[i + 1] = offset + 1;
quadIndices[i + 2] = offset + 2;
quadIndices[i + 3] = offset + 2;
quadIndices[i + 4] = offset + 3;
quadIndices[i + 5] = offset + 0;
offset += 4;
}
auto quadIB = IndexBuffer::create(quadIndices, s_Data.maxIndices);
s_Data.quadVertexArray->setIndexBuffer(quadIB);
delete[] quadIndices;
}
/* Creat eh the white texture */
s_Data.whiteTexture = Texture2D::create(1,1);
uint32_t whiteTextureData = 0xFFFFFFFF;
auto whttxtr = s_Data.whiteTexture;
s_Data.whiteTexture->setData(&whiteTextureData, sizeof(whiteTextureData));
/* Create the shaders */
{
s_Data.textureShader = Shader::create(applicationResourceDirectory + "/Shaders/2DRenderer/Texture");
s_Data.textureShader->bind();
int32_t samplers[GEOGL::Renderer2DData::maxTextureSlots];
for(uint32_t i = 0; i<GEOGL::Renderer2DData::maxTextureSlots; ++i){
samplers[i] = (int32_t)i;
s_Data.textureShader->setInt(GEOGL_FORMAT("u_Textures[{}]", i).c_str(), i);
}
s_Data.textureShader->setIntArray("u_Textures", samplers, GEOGL::Renderer2DData::maxTextureSlots);
}
s_Data.quadVertexPositions[0] = {-0.5, -0.5, 0.0f, 1.0f};
s_Data.quadVertexPositions[1] = { 0.5, -0.5, 0.0f, 1.0f};
s_Data.quadVertexPositions[2] = { 0.5, 0.5, 0.0f, 1.0f};
s_Data.quadVertexPositions[3] = {-0.5, 0.5, 0.0f, 1.0f};
}
void GEOGL::Renderer2D::shutdown() {
GEOGL_PROFILE_FUNCTION();
if(s_Data.quadVertexBufferBase)
delete s_Data.quadVertexBufferBase;
s_Data.quadVertexBufferBase = nullptr;
s_Data.quadVertexBufferPtr = nullptr;
s_Data.quadVertexArray = nullptr;
s_Data.quadVertexBuffer = nullptr;
for(uint32_t i=0; i<GEOGL::Renderer2DData::maxTextureSlots; ++i){
s_Data.textureSlots[i] = nullptr;
}
s_Data.whiteTexture = nullptr;
s_Data.textureShader = nullptr;
}
void GEOGL::Renderer2D::beginScene(const OrthographicCamera &camera) {
GEOGL_PROFILE_FUNCTION();
auto projectionViewMatrix = camera.getProjectionViewMatrix();
s_Data.textureShader->bind();
s_Data.textureShader->setMat4("u_ProjectionViewMatrix", projectionViewMatrix);
s_Data.quadIndexCount = 0;
s_Data.quadVertexBufferPtr = s_Data.quadVertexBufferBase;
s_Data.textureSlotIndex = 0;
}
void GEOGL::Renderer2D::endScene() {
GEOGL_PROFILE_FUNCTION();
Renderer2D::flush();
if(s_Data.wireframe){
Renderer2D::renderWireframe(false);
}
}
void GEOGL::Renderer2D::flush(){
GEOGL_PROFILE_FUNCTION();
if(s_Data.quadVertexBufferPtr == s_Data.quadVertexBufferBase) return; /* Since there is no data to render, skip the remainder of the function */
s_Data.textureShader->bind();
s_Data.quadVertexArray->bind();
//s_Data.textureSlots[0]->bind(0);
//s_Data.textureSlots[1]->bind(1);
for(uint32_t i=0; i<s_Data.textureSlotIndex; ++i){
auto& texture = s_Data.textureSlots[i];
texture->bind(i);
}
uint32_t dataSize = (uint8_t*)s_Data.quadVertexBufferPtr - (uint8_t*)s_Data.quadVertexBufferBase;
s_Data.quadVertexBuffer->setData(s_Data.quadVertexBufferBase, dataSize);
RenderCommand::drawIndexed(s_Data.quadVertexArray, s_Data.quadIndexCount);
s_Data.stats.drawCalls++;
s_Data.quadIndexCount = 0;
s_Data.quadVertexBufferPtr = s_Data.quadVertexBufferBase;
s_Data.textureSlotIndex = 0;
}
void Renderer2D::renderWireframe(bool status) {
Renderer2D::flush();
RenderCommand::renderWireframe(&status);
s_Data.wireframe = status;
}
void GEOGL::Renderer2D::drawQuad(const QuadProperties& properties) {
drawQuad(properties, s_Data.whiteTexture);
}
void Renderer2D::drawQuad(const QuadProperties& properties, const Ref<Texture2D>& texture) {
GEOGL_RENDERER_PROFILE_FUNCTION();
/* guard against buffer overflow */
if(s_Data.quadIndexCount >= s_Data.maxIndices || s_Data.textureSlotIndex >= GEOGL::Renderer2DData::maxTextureSlots){
flush();
}
glm::mat4 transform = glm::translate(s_IdentMatrix, properties.position);
transform = glm::scale(transform, {properties.size.x, properties.size.y, 1.0f});
glm::vec3 position = properties.position;
float textureIndex = -1;
for(uint32_t i=0; i<s_Data.textureSlotIndex;++i){
if(*s_Data.textureSlots[i] == *texture){
textureIndex = (float)i;
break;
}
}
if(textureIndex==-1){
textureIndex = (float)s_Data.textureSlotIndex;
s_Data.textureSlots[s_Data.textureSlotIndex] = texture;
++s_Data.textureSlotIndex;
}
glm::vec2 textureCoords[] = {{0,0}, {1,0}, {1,1}, {0,1}};
for(int i=0; i<4; ++i){
s_Data.quadVertexBufferPtr->position = transform * s_Data.quadVertexPositions[i];
s_Data.quadVertexBufferPtr->color = properties.colorTint;
s_Data.quadVertexBufferPtr->textureCoord = textureCoords[i];
s_Data.quadVertexBufferPtr->tilingFactor = properties.tilingFactor;
s_Data.quadVertexBufferPtr->textureIndex = textureIndex;
s_Data.quadVertexBufferPtr++;
}
s_Data.quadIndexCount += 6;
++s_Data.stats.quadCount;
}
void Renderer2D::drawQuad(const Renderer2D::QuadProperties &properties, const Ref <SubTexture2D> &subTexture) {
GEOGL_RENDERER_PROFILE_FUNCTION();
auto texture = subTexture->getTexture();
/* guard against buffer overflow */
if(s_Data.quadIndexCount >= s_Data.maxIndices || s_Data.textureSlotIndex >= GEOGL::Renderer2DData::maxTextureSlots){
flush();
}
glm::mat4 transform = glm::translate(s_IdentMatrix, properties.position);
transform = glm::scale(transform, {properties.size.x, properties.size.y, 1.0f});
glm::vec3 position = properties.position;
float textureIndex = -1;
for(uint32_t i=0; i<s_Data.textureSlotIndex;++i){
if(*s_Data.textureSlots[i] == *texture){
textureIndex = (float)i;
break;
}
}
if(textureIndex==-1){
textureIndex = (float)s_Data.textureSlotIndex;
s_Data.textureSlots[s_Data.textureSlotIndex] = texture;
++s_Data.textureSlotIndex;
}
auto textureCoords = subTexture->getTextureCoords();
for(int i=0; i<4; ++i){
s_Data.quadVertexBufferPtr->position = transform * s_Data.quadVertexPositions[i];
s_Data.quadVertexBufferPtr->color = properties.colorTint;
s_Data.quadVertexBufferPtr->textureCoord = textureCoords[i];
s_Data.quadVertexBufferPtr->tilingFactor = properties.tilingFactor;
s_Data.quadVertexBufferPtr->textureIndex = textureIndex;
s_Data.quadVertexBufferPtr++;
}
s_Data.quadIndexCount += 6;
++s_Data.stats.quadCount;
}
void Renderer2D::drawRotatedQuad(const Renderer2D::QuadProperties &properties, float rotation) {
drawRotatedQuad(properties, s_Data.whiteTexture, rotation);
}
void Renderer2D::drawRotatedQuad(const Renderer2D::QuadProperties &properties, const Ref <Texture2D> &texture, float rotation) {
GEOGL_RENDERER_PROFILE_FUNCTION();
/* guard against buffer overflow */
if(s_Data.quadIndexCount >= s_Data.maxIndices || s_Data.textureSlotIndex >= GEOGL::Renderer2DData::maxTextureSlots){
flush();
}
glm::mat4 transform = glm::translate(s_IdentMatrix, properties.position);
transform = (rotation!=0) ? glm::rotate(transform, (rotation), {0,0,1}) : transform;
transform = glm::scale(transform, {properties.size.x, properties.size.y, 1.0f});
glm::vec3 position = properties.position;
float textureIndex = -1;
for(uint32_t i=0; i<s_Data.textureSlotIndex;++i){
if(*s_Data.textureSlots[i] == *texture){
textureIndex = (float)i;
break;
}
}
if(textureIndex==-1){
textureIndex = (float)s_Data.textureSlotIndex;
s_Data.textureSlots[s_Data.textureSlotIndex] = texture;
++s_Data.textureSlotIndex;
}
glm::vec2 textureCoords[] = {{0,0}, {1,0}, {1,1}, {0,1}};
for(int i=0; i<4; ++i){
s_Data.quadVertexBufferPtr->position = transform * s_Data.quadVertexPositions[i];
s_Data.quadVertexBufferPtr->color = properties.colorTint;
s_Data.quadVertexBufferPtr->textureCoord = textureCoords[i];
s_Data.quadVertexBufferPtr->tilingFactor = properties.tilingFactor;
s_Data.quadVertexBufferPtr->textureIndex = textureIndex;
s_Data.quadVertexBufferPtr++;
}
s_Data.quadIndexCount += 6;
++s_Data.stats.quadCount;
}
void Renderer2D::drawRotatedQuad(const Renderer2D::QuadProperties &properties, const Ref <SubTexture2D> &subTexture, float rotation) {
GEOGL_RENDERER_PROFILE_FUNCTION();
/* guard against buffer overflow */
if(s_Data.quadIndexCount >= s_Data.maxIndices || s_Data.textureSlotIndex >= GEOGL::Renderer2DData::maxTextureSlots){
flush();
}
auto texture = subTexture->getTexture();
glm::mat4 transform = glm::translate(s_IdentMatrix, properties.position);
transform = (rotation!=0) ? glm::rotate(transform, (rotation), {0,0,1}) : transform;
transform = glm::scale(transform, {properties.size.x, properties.size.y, 1.0f});
glm::vec3 position = properties.position;
float textureIndex = -1;
for(uint32_t i=0; i<s_Data.textureSlotIndex;++i){
if(*s_Data.textureSlots[i] == *texture){
textureIndex = (float)i;
break;
}
}
if(textureIndex==-1){
textureIndex = (float)s_Data.textureSlotIndex;
s_Data.textureSlots[s_Data.textureSlotIndex] = texture;
++s_Data.textureSlotIndex;
}
//glm::vec2 textureCoords[] = {{0,0}, {1,0}, {1,1}, {0,1}};
auto textureCoords = subTexture->getTextureCoords();
for(int i=0; i<4; ++i){
s_Data.quadVertexBufferPtr->position = transform * s_Data.quadVertexPositions[i];
s_Data.quadVertexBufferPtr->color = properties.colorTint;
s_Data.quadVertexBufferPtr->textureCoord = textureCoords[i];
s_Data.quadVertexBufferPtr->tilingFactor = properties.tilingFactor;
s_Data.quadVertexBufferPtr->textureIndex = textureIndex;
s_Data.quadVertexBufferPtr++;
}
s_Data.quadIndexCount += 6;
++s_Data.stats.quadCount;
}
void Renderer2D::resetStats() {
memset(&s_Data.stats, 0, sizeof(Statistics));
}
Renderer2D::Statistics Renderer2D::getStatistics() {
return s_Data.stats;
}
}
| 35.93736 | 152 | 0.577191 | [
"render",
"transform"
] |
43b40e99c712c69b4a8e694d6f476dca471f4544 | 22,941 | cc | C++ | DQM/HcalCommon/src/ContainerSingle2D.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | DQM/HcalCommon/src/ContainerSingle2D.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | DQM/HcalCommon/src/ContainerSingle2D.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "DQM/HcalCommon/interface/ContainerSingle2D.h"
#include "DQM/HcalCommon/interface/Utilities.h"
namespace hcaldqm {
using namespace constants;
using namespace quantity;
ContainerSingle2D::ContainerSingle2D() {
_qx = nullptr;
_qy = nullptr;
_qz = nullptr;
}
ContainerSingle2D::ContainerSingle2D(std::string const &folder, Quantity *qx, Quantity *qy, Quantity *qz)
: Container(folder, qz->name() + "vs" + qy->name() + "vs" + qx->name()), _qx(qx), _qy(qy), _qz(qz) {
_qx->setAxisType(quantity::fXAxis);
_qy->setAxisType(quantity::fYAxis);
_qz->setAxisType(quantity::fZAxis);
}
ContainerSingle2D::ContainerSingle2D(
std::string const &folder, std::string const &qname, Quantity *qx, Quantity *qy, Quantity *qz, int debug /*=0*/)
: Container(folder, qname), _qx(qx), _qy(qy), _qz(qz) {
_qx->setAxisType(quantity::fXAxis);
_qy->setAxisType(quantity::fYAxis);
_qz->setAxisType(quantity::fZAxis);
}
ContainerSingle2D::ContainerSingle2D(ContainerSingle2D const &c) : Container(c._folder, c._qname) {
_qx = c._qx->makeCopy();
_qy = c._qy->makeCopy();
_qz = c._qz->makeCopy();
}
ContainerSingle2D::~ContainerSingle2D() {
if (_qx != nullptr)
delete _qx;
if (_qy != nullptr)
delete _qy;
if (_qz != nullptr)
delete _qz;
_qx = nullptr;
_qy = nullptr;
_qz = nullptr;
}
/* virtual */ void ContainerSingle2D::initialize(
std::string const &folder, Quantity *qx, Quantity *qy, Quantity *qz, int debug /*=0*/) {
Container::initialize(folder, qz->name() + "vs" + qy->name() + "vs" + qx->name(), debug);
_qx = qx;
_qy = qy;
_qz = qz;
_qx->setAxisType(quantity::fXAxis);
_qy->setAxisType(quantity::fYAxis);
_qz->setAxisType(quantity::fZAxis);
}
/* virtual */ void ContainerSingle2D::initialize(
std::string const &folder, std::string const &qname, Quantity *qx, Quantity *qy, Quantity *qz, int debug /*=0*/) {
Container::initialize(folder, qname, debug);
_qx = qx;
_qy = qy;
_qz = qz;
_qx->setAxisType(quantity::fXAxis);
_qy->setAxisType(quantity::fYAxis);
_qz->setAxisType(quantity::fZAxis);
}
/* virtual */ void ContainerSingle2D::book(DQMStore::IBooker &ib, std::string subsystem, std::string aux) {
ib.setCurrentFolder(subsystem + "/" + _folder + "/" + _qname);
_me = ib.book2D(_qname + (aux.empty() ? aux : "_" + aux),
_qname + (aux.empty() ? aux : " " + aux),
_qx->nbins(),
_qx->min(),
_qx->max(),
_qy->nbins(),
_qy->min(),
_qy->max());
customize();
}
/* virtual */ void ContainerSingle2D::load(DQMStore::IGetter &ig, std::string subsystem, std::string aux) {
_me = ig.get(subsystem + "/" + _folder + "/" + _qname + "/" + _qname + (aux.empty() ? aux : "_" + aux));
}
/* virtual */ void ContainerSingle2D::customize() {
_me->setAxisTitle(_qx->name(), 1);
_me->setAxisTitle(_qy->name(), 2);
_me->setAxisTitle(_qz->name(), 3);
TH1 *h = _me->getTH1();
_qx->setBits(h);
_qy->setBits(h);
_qz->setBits(h);
std::vector<std::string> xlabels = _qx->getLabels();
std::vector<std::string> ylabels = _qy->getLabels();
for (unsigned int i = 0; i < xlabels.size(); i++) {
_me->setBinLabel(i + 1, xlabels[i], 1);
}
for (unsigned int i = 0; i < ylabels.size(); i++) {
_me->setBinLabel(i + 1, ylabels[i], 2);
}
}
/* virtual */ void ContainerSingle2D::fill(int x, int y) { _me->Fill(_qx->getValue(x), _qy->getValue(y)); }
/* virtual */ void ContainerSingle2D::fill(int x, double y) { _me->Fill(_qx->getValue(x), _qy->getValue(y)); }
/* virtual */ void ContainerSingle2D::fill(int x, double y, double z) {
_me->Fill(_qx->getValue(x), _qy->getValue(y), z);
}
/* virtual */ void ContainerSingle2D::fill(double x, int y) { _me->Fill(_qx->getValue(x), _qy->getValue(y)); }
/* virtual */ void ContainerSingle2D::fill(double x, double y) { _me->Fill(_qx->getValue(x), _qy->getValue(y)); }
/* virtual */ void ContainerSingle2D::fill(double x, double y, double z) {
_me->Fill(_qx->getValue(x), _qy->getValue(y), z);
}
/* virtual */ void ContainerSingle2D::fill(int x, int y, double z) {
_me->Fill(_qx->getValue(x), _qy->getValue(y), z);
}
/* virtual */ void ContainerSingle2D::fill(int x, int y, int z) { _me->Fill(_qx->getValue(x), _qy->getValue(y), z); }
/* virtual */ void ContainerSingle2D::fill(HcalDetId const &id) { _me->Fill(_qx->getValue(id), _qy->getValue(id)); }
/* virtual */ double ContainerSingle2D::getBinContent(int x, int y) {
return _me->getBinContent(_qx->getBin(x), _qy->getBin(y));
}
/* virtual */ double ContainerSingle2D::getBinContent(int x, double y) {
return _me->getBinContent(_qx->getBin(x), _qy->getBin(y));
}
/* virtual */ double ContainerSingle2D::getBinContent(double x, int y) {
return _me->getBinContent(_qx->getBin(x), _qy->getBin(y));
}
/* virtual */ double ContainerSingle2D::getBinContent(double x, double y) {
return _me->getBinContent(_qx->getBin(x), _qy->getBin(y));
}
/* virtual */ double ContainerSingle2D::getBinEntries(int x, int y) {
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(y));
}
/* virtual */ double ContainerSingle2D::getBinEntries(int x, double y) {
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(y));
}
/* virtual */ double ContainerSingle2D::getBinEntries(double x, int y) {
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(y));
}
/* virtual */ double ContainerSingle2D::getBinEntries(double x, double y) {
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(y));
}
/* virtual */ void ContainerSingle2D::setBinContent(int x, int y, int z) {
_me->setBinContent(_qx->getBin(x), _qy->getBin(y), z);
}
/* virtual */ void ContainerSingle2D::setBinContent(int x, double y, int z) {
_me->setBinContent(_qx->getBin(x), _qy->getBin(y), z);
}
/* virtual */ void ContainerSingle2D::setBinContent(double x, int y, int z) {
_me->setBinContent(_qx->getBin(x), _qy->getBin(y), z);
}
/* virtual */ void ContainerSingle2D::setBinContent(double x, double y, int z) {
_me->setBinContent(_qx->getBin(x), _qy->getBin(y), z);
}
/* virtual */ void ContainerSingle2D::setBinContent(int x, int y, double z) {
_me->setBinContent(_qx->getBin(x), _qy->getBin(y), z);
}
/* virtual */ void ContainerSingle2D::setBinContent(int x, double y, double z) {
_me->setBinContent(_qx->getBin(x), _qy->getBin(y), z);
}
/* virtual */ void ContainerSingle2D::setBinContent(double x, int y, double z) {
_me->setBinContent(_qx->getBin(x), _qy->getBin(y), z);
}
/* virtual */ void ContainerSingle2D::setBinContent(double x, double y, double z) {
_me->setBinContent(_qx->getBin(x), _qy->getBin(y), z);
}
/* virtual */ void ContainerSingle2D::fill(HcalDetId const &id, double x) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x));
else if (_qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id));
}
/* virtual */ void ContainerSingle2D::fill(HcalDetId const &id, int x) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x));
else if (_qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id));
}
/* virtual */ void ContainerSingle2D::fill(HcalDetId const &id, double x, double y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtual */ void ContainerSingle2D::fill(HcalDetId const &id, int x, int y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtual */ void ContainerSingle2D::fill(HcalDetId const &id, int x, double y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtula */ double ContainerSingle2D::getBinContent(HcalDetId const &id) {
return _me->getBinContent(_qx->getBin(id), _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinContent(HcalDetId const &id, int x) {
if (_qx->isCoordinate())
return _me->getBinContent(_qx->getBin(id), _qy->getBin(x));
else
return _me->getBinContent(_qx->getBin(x), _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinContent(HcalDetId const &id, double x) {
if (_qx->isCoordinate())
return _me->getBinContent(_qx->getBin(id), _qy->getBin(x));
else
return _me->getBinContent(_qx->getBin(x), _qy->getBin(id));
}
/* virtula */ double ContainerSingle2D::getBinEntries(HcalDetId const &id) {
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinEntries(HcalDetId const &id, int x) {
if (_qx->isCoordinate())
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(x));
else
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinEntries(HcalDetId const &id, double x) {
if (_qx->isCoordinate())
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(x));
else
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalDetId const &id, int x) {
_me->setBinContent(_qx->getBin(id), _qy->getBin(id), x);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalDetId const &id, double x) {
_me->setBinContent(_qx->getBin(id), _qy->getBin(id), x);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalDetId const &id, int x, int y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalDetId const &id, int x, double y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalDetId const &id, double x, int y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalDetId const &id, double x, double y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
// by ElectronicsId
/* virtual */ void ContainerSingle2D::fill(HcalElectronicsId const &id) {
_me->Fill(_qx->getValue(id), _qy->getValue(id));
}
/* virtual */ void ContainerSingle2D::fill(HcalElectronicsId const &id, double x) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x));
else if (_qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id));
}
/* virtual */ void ContainerSingle2D::fill(HcalElectronicsId const &id, int x) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x));
else if (_qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id));
}
/* virtual */ void ContainerSingle2D::fill(HcalElectronicsId const &id, double x, double y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtual */ void ContainerSingle2D::fill(HcalElectronicsId const &id, int x, int y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtual */ void ContainerSingle2D::fill(HcalElectronicsId const &id, int x, double y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtula */ double ContainerSingle2D::getBinContent(HcalElectronicsId const &id) {
return _me->getBinContent(_qx->getBin(id), _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinContent(HcalElectronicsId const &id, int x) {
if (_qx->isCoordinate())
return _me->getBinContent(_qx->getBin(id), _qy->getBin(x));
else
return _me->getBinContent(_qx->getBin(x), _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinContent(HcalElectronicsId const &id, double x) {
if (_qx->isCoordinate())
return _me->getBinContent(_qx->getBin(id), _qy->getBin(x));
else
return _me->getBinContent(_qx->getBin(x), _qy->getBin(id));
}
/* virtula */ double ContainerSingle2D::getBinEntries(HcalElectronicsId const &id) {
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinEntries(HcalElectronicsId const &id, int x) {
if (_qx->isCoordinate())
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(x));
else
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinEntries(HcalElectronicsId const &id, double x) {
if (_qx->isCoordinate())
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(x));
else
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalElectronicsId const &id, int x) {
_me->setBinContent(_qx->getBin(id), _qy->getBin(id), x);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalElectronicsId const &id, double x) {
_me->setBinContent(_qx->getBin(id), _qy->getBin(id), x);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalElectronicsId const &id, int x, int y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalElectronicsId const &id, int x, double y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalElectronicsId const &id, double x, int y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalElectronicsId const &id, double x, double y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
// by TrigTowerDetId
/* virtual */ void ContainerSingle2D::fill(HcalTrigTowerDetId const &id) {
_me->Fill(_qx->getValue(id), _qy->getValue(id));
}
/* virtual */ void ContainerSingle2D::fill(HcalTrigTowerDetId const &id, double x) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x));
else if (_qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id));
}
/* virtual */ void ContainerSingle2D::fill(HcalTrigTowerDetId const &id, int x) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x));
else if (_qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id));
}
/* virtual */ void ContainerSingle2D::fill(HcalTrigTowerDetId const &id, double x, double y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtual */ void ContainerSingle2D::fill(HcalTrigTowerDetId const &id, int x, int y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtual */ void ContainerSingle2D::fill(HcalTrigTowerDetId const &id, int x, double y) {
if (_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(id), x);
else if (_qx->isCoordinate() && !_qy->isCoordinate())
_me->Fill(_qx->getValue(id), _qy->getValue(x), y);
else if (!_qx->isCoordinate() && _qy->isCoordinate())
_me->Fill(_qx->getValue(x), _qy->getValue(id), y);
}
/* virtual */ void ContainerSingle2D::fill(HcalDetId const &did, HcalElectronicsId const &eid) {
if (_qx->type() == fDetectorQuantity)
_me->Fill(_qx->getValue(did), _qy->getValue(eid));
else
_me->Fill(_qx->getValue(eid), _qy->getValue(did));
}
/* virtual */ void ContainerSingle2D::fill(HcalDetId const &did, HcalElectronicsId const &eid, double x) {
if (_qx->type() == fDetectorQuantity)
_me->Fill(_qx->getValue(did), _qy->getValue(eid), x);
else
_me->Fill(_qx->getValue(eid), _qy->getValue(did), x);
}
/* virtula */ double ContainerSingle2D::getBinContent(HcalTrigTowerDetId const &id) {
return _me->getBinContent(_qx->getBin(id), _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinContent(HcalTrigTowerDetId const &id, int x) {
if (_qx->isCoordinate())
return _me->getBinContent(_qx->getBin(id), _qy->getBin(x));
else
return _me->getBinContent(_qx->getBin(x), _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinContent(HcalTrigTowerDetId const &id, double x) {
if (_qx->isCoordinate())
return _me->getBinContent(_qx->getBin(id), _qy->getBin(x));
else
return _me->getBinContent(_qx->getBin(x), _qy->getBin(id));
}
/* virtula */ double ContainerSingle2D::getBinEntries(HcalTrigTowerDetId const &id) {
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinEntries(HcalTrigTowerDetId const &id, int x) {
if (_qx->isCoordinate())
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(x));
else
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ double ContainerSingle2D::getBinEntries(HcalTrigTowerDetId const &id, double x) {
if (_qx->isCoordinate())
return _me->getBinEntries(_qx->getBin(id) + _qx->wofnbins() * _qy->getBin(x));
else
return _me->getBinEntries(_qx->getBin(x) + _qx->wofnbins() * _qy->getBin(id));
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalTrigTowerDetId const &id, int x) {
_me->setBinContent(_qx->getBin(id), _qy->getBin(id), x);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalTrigTowerDetId const &id, double x) {
_me->setBinContent(_qx->getBin(id), _qy->getBin(id), x);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalTrigTowerDetId const &id, int x, int y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalTrigTowerDetId const &id, int x, double y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalTrigTowerDetId const &id, double x, int y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::setBinContent(HcalTrigTowerDetId const &id, double x, double y) {
if (_qx->isCoordinate())
_me->setBinContent(_qx->getBin(id), _qy->getBin(x), y);
else
_me->setBinContent(_qx->getBin(x), _qy->getBin(id), y);
}
/* virtual */ void ContainerSingle2D::extendAxisRange(int l) {
if (l < _qx->nbins())
return;
int x = _qx->nbins();
while (l >= x) {
_me->getTH1()->LabelsInflate();
x *= 2;
_qx->setMax(x);
}
}
void ContainerSingle2D::showOverflowZ(bool showOverflow) { _qz->showOverflow(showOverflow); }
} // namespace hcaldqm
| 42.641264 | 120 | 0.635543 | [
"vector"
] |
43b41082b9bf27e3e6c11beef1e71fdf8bda6516 | 8,464 | cpp | C++ | test/regression_tests/HeavyTestNorm.cpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 3 | 2017-08-08T21:06:02.000Z | 2020-01-08T13:23:36.000Z | test/regression_tests/HeavyTestNorm.cpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 2 | 2016-12-17T00:18:56.000Z | 2019-08-09T15:29:25.000Z | test/regression_tests/HeavyTestNorm.cpp | jrood-nrel/percept | 363cdd0050443760d54162f140b2fb54ed9decf0 | [
"BSD-2-Clause"
] | 2 | 2017-11-30T07:02:41.000Z | 2019-08-05T17:07:04.000Z | // Copyright 2002 - 2008, 2010, 2011 National Technology Engineering
// Solutions of Sandia, LLC (NTESS). Under the terms of Contract
// DE-NA0003525 with NTESS, the U.S. Government retains certain rights
// in this software.
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include <stk_mesh/base/BulkData.hpp>
#include <stk_mesh/base/MetaData.hpp>
#include <percept/Percept.hpp>
#include <percept/function/StringFunction.hpp>
#include <percept/function/FieldFunction.hpp>
#include <percept/function/FunctionOperator.hpp>
#include <percept/function/ConstantFunction.hpp>
#include <percept/Util.hpp>
#include <percept/norm/Norm.hpp>
#include <percept/norm/H1Norm.hpp>
#include <percept/math/Math.hpp>
#include <percept/PerceptMesh.hpp>
#include <percept/fixtures/Fixture.hpp>
#include <stk_util/environment/WallTime.hpp>
#include <stk_util/diag/PrintTable.hpp>
#include <stk_util/parallel/Parallel.hpp>
#include <gtest/gtest.h>
#include <Teuchos_ScalarTraits.hpp>
#include <stdexcept>
#include <sstream>
#include <vector>
#include <cmath>
#include <iostream>
#include <string>
#include <typeinfo>
#include <math.h>
namespace percept {
namespace heavy_tests {
#define EXTRA_PRINT 0
//=============================================================================
//=============================================================================
//=============================================================================
/// This test uses a back door to the function that passes in the element to avoid the lookup of the element when the
/// StringFunction contains references to FieldFunctions
void norm_string_function_turbo_timings(TurboOption turboOpt, const size_t nxyz = 4, bool only_turbo=false)
{
EXCEPTWATCH;
dw().m(LOG_NORM) << "norm.string_function " << stk::diag::dendl;
/// create a meta data/bulk data empty pair
PerceptMesh eMesh(3u);
if (1)
{
// Need a symmetric mesh around the origin for some of the tests below to work correctly (i.e. have analytic solutions)
const size_t num_x = nxyz;
const size_t num_y = nxyz;
const size_t num_z = nxyz;
std::string config_mesh =
Ioss::Utils::to_string(num_x) + "x" +
Ioss::Utils::to_string(num_y) + "x" +
Ioss::Utils::to_string(num_z) + "|bbox:-0.5,-0.5,-0.5,0.5,0.5,0.5";
eMesh.new_mesh(GMeshSpec(config_mesh));
eMesh.commit();
}
stk::mesh::MetaData& metaData = *eMesh.get_fem_meta_data();
stk::mesh::BulkData& bulkData = *eMesh.get_bulk_data();
/// the coordinates field is always created by the PerceptMesh read operation, here we just get the field
stk::mesh::FieldBase *coords_field = metaData.get_field(stk::topology::NODE_RANK, "coordinates");
/// create a field function from the existing coordinates field
FieldFunction ff_coords("ff_coords", coords_field, &bulkData,
Dimensions(3), Dimensions(3), FieldFunction::SIMPLE_SEARCH );
/// the function to be integrated: sqrt(Integral[x^2, dxdydz]) =?= sqrt(x^3/3 @ [-0.5, 0.5]) ==> sqrt(0.25/3)
StringFunction sfx("x", Name("sfx"), Dimensions(3), Dimensions(1) );
ff_coords.add_alias("mc");
//StringFunction sfcm("sqrt(mc[0]*mc[0]+mc[1]*mc[1]+mc[2]*mc[2])", Name("sfcm"), Dimensions(3), Dimensions(1));
StringFunction sfx_mc("mc[0]", Name("sfx_mc"), Dimensions(3), Dimensions(1) );
/// the function to be integrated: sqrt(Integral[x^2, dxdydz]) =?= sqrt(x^3/3 @ [-0.5, 0.5]) ==> sqrt(0.25/3)
/// A place to hold the result.
/// This is a "writable" function (we may want to make this explicit - StringFunctions are not writable; FieldFunctions are
/// since we interpolate values to them from other functions).
ConstantFunction sfx_res(0.0, "sfx_res");
ConstantFunction sfx_res_turbo(0.0, "sfx_res_turbo");
ConstantFunction sfx_res_slow(0.0, "sfx_res_slow");
ConstantFunction sfx_res_fast(0.0, "sfx_res_fast");
#define COL_SEP "|"
#define EXPR_CELL_WIDTH (80)
#define TIME_IT2(expr_none,expr_turbo,msg,topt) \
{ \
double TURBO_NONE_time = 0; \
double TURBO_ON_time = 0; \
TIME_IT(expr_none,TURBO_NONE_time); \
TIME_IT(expr_turbo,TURBO_ON_time); \
if (1) std::cout << msg << #topt << " for expression= " << QUOTE(expr_none) << " timings= " << std::endl; \
if (1) std::cout << "TURBO_NONE_time= " << TURBO_NONE_time << " " \
<< ( turboOpt==TURBO_ELEMENT?"TURBO_ELEMENT_time":"TURBO_BUCKET_time") <<"= " << TURBO_ON_time \
<< " ratio= " << TURBO_NONE_time/TURBO_ON_time << std::endl; \
}
int numIter = 1;
for (int iter = 0; iter < numIter; iter++)
{
/// Create the operator that will do the work
/// get the l2 norm
Norm<2> l2Norm (bulkData, &metaData.universal_part(), TURBO_NONE);
Norm<2> l2Norm_turbo(bulkData, &metaData.universal_part(), turboOpt);
TIME_IT2((only_turbo ? (void)0 : l2Norm(sfx, sfx_res)); , l2Norm_turbo(sfx, sfx_res_turbo);, "Should be the same turboOpt= ", turboOpt );
TIME_IT2((only_turbo ? (void)0 : l2Norm(sfx_mc, sfx_res_slow)); , l2Norm_turbo(sfx, sfx_res_fast); , "StringFunction with ref to FF, slow vs. fast" ,turboOpt );
double sfx_expect = std::sqrt(0.25/3.);
if (!only_turbo) EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res.getValue());
EXPECT_DOUBLE_EQ_APPROX_TOL( sfx_expect, sfx_res_turbo.getValue(), 1.e-8);
if (!only_turbo) EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res_slow.getValue());
EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res_fast.getValue());
/// the function to be integrated: (Integral[ abs(x), dxdydz]) =?= (2 * |x|^2/2 @ [0, 0.5]) ==> .25)
Norm<1> l1Norm(bulkData, &metaData.universal_part(), TURBO_NONE);
l1Norm(sfx, sfx_res);
Norm<1> l1Norm_turbo(bulkData, &metaData.universal_part(), TURBO_NONE);
l1Norm_turbo(sfx, sfx_res_turbo);
sfx_expect = 0.25;
if (!only_turbo) EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res.getValue());
EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res_turbo.getValue());
/// the function to be integrated: sqrt(Integral[(x*y*z)^2, dxdydz]) =?= (see unitTest1.py)
StringFunction sfxyz("x*y*z", Name("sfxyz"), Dimensions(3), Dimensions(1) );
TIME_IT2((only_turbo ? (void)0 : l2Norm(sfxyz, sfx_res)); , l2Norm_turbo(sfxyz, sfx_res_turbo); , "should be the same", turboOpt );
sfx_expect = 0.0240562612162344;
if (!only_turbo) EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res.getValue());
EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res_turbo.getValue());
/// the function to be integrated (but over a rotated domain): sqrt(Integral[(x*y*z)^2, dxdydz]) =?= (see unitTest2.py)
/// now rotate the mesh
Math::Matrix rmz = Math::rotationMatrix(2, 30);
Math::Matrix rm = rmz;
eMesh.transform_mesh(rm);
TIME_IT2((only_turbo ? (void)0 : l2Norm(sfxyz, sfx_res)); , l2Norm_turbo(sfxyz, sfx_res_turbo); , "should be the same", turboOpt );
sfx_expect = 0.0178406008037016;
// NOTE: we need extra quadrature accuracy to reproduce this result (cubDegree==4 in IntegratedOp almost gets it right)
// for now, we are satisfied with 3 digits
//EXPECT_DOUBLE_EQ_APPROX(sfx_res.getValue(), sfx_expect);
if (!only_turbo && std::fabs(sfx_res.getValue()-sfx_expect) > 0.01*sfx_expect)
{
EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res.getValue());
EXPECT_TRUE(false);
}
if (!only_turbo && std::fabs(sfx_res_turbo.getValue()-sfx_expect) > 0.01*sfx_expect)
{
EXPECT_DOUBLE_EQ_APPROX( sfx_expect, sfx_res_turbo.getValue());
EXPECT_TRUE(false);
}
}
}
//=============================================================================
//=============================================================================
//=============================================================================
TEST(heavy_norm, string_function_turbo_timings)
{
EXCEPTWATCH;
norm_string_function_turbo_timings(TURBO_ELEMENT);
}
TEST(heavy_norm, string_function_turbo_timings_bucket)
{
EXCEPTWATCH;
norm_string_function_turbo_timings(TURBO_BUCKET);
}
TEST(heavy_norm, string_function_turbo_timings_bucket_prof)
{
EXCEPTWATCH;
norm_string_function_turbo_timings(TURBO_BUCKET, 10, true);
}
}
}
| 41.287805 | 164 | 0.64095 | [
"mesh",
"vector"
] |
43b6099907b110b4501e32453e0d3106d8f21d5c | 11,938 | cpp | C++ | debugger/src/cpu_arm_plugin/cpu_arm7_func.cpp | mfkiwl/riscv_vhdl-64bit-fault-tolerant | 9c18c09c0f2ae664e6e95cf54d737203849a9253 | [
"Apache-2.0"
] | 432 | 2015-11-08T20:32:45.000Z | 2022-03-30T07:53:01.000Z | debugger/src/cpu_arm_plugin/cpu_arm7_func.cpp | mfkiwl/riscv_vhdl-64bit-fault-tolerant | 9c18c09c0f2ae664e6e95cf54d737203849a9253 | [
"Apache-2.0"
] | 37 | 2016-02-23T13:13:34.000Z | 2021-09-27T14:06:50.000Z | debugger/src/cpu_arm_plugin/cpu_arm7_func.cpp | mfkiwl/riscv_vhdl-64bit-fault-tolerant | 9c18c09c0f2ae664e6e95cf54d737203849a9253 | [
"Apache-2.0"
] | 99 | 2015-12-07T05:17:18.000Z | 2022-02-17T11:17:14.000Z | /*
* Copyright 2018 Sergey Khabarov, sergeykhbr@gmail.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 <api_core.h>
#include "cpu_arm7_func.h"
#include "srcproc/thumb_disasm.h"
namespace debugger {
CpuCortex_Functional::CpuCortex_Functional(const char *name) :
CpuGeneric(name) {
registerInterface(static_cast<ICpuArm *>(this));
registerAttribute("VectorTable", &vectorTable_);
registerAttribute("DefaultMode", &defaultMode_);
p_psr_ = reinterpret_cast<ProgramStatusRegsiterType *>(
&R[Reg_cpsr]);
PC_ = &R[Reg_pc]; // redefine location of PC register in bank
}
CpuCortex_Functional::~CpuCortex_Functional() {
}
void CpuCortex_Functional::postinitService() {
// Supported instruction sets:
for (int i = 0; i < INSTR_HASH_TABLE_SIZE; i++) {
listInstr_[i].make_list(0);
}
addArm7tmdiIsa();
addThumb2Isa();
CpuGeneric::postinitService();
pcmd_br_ = new CmdBrArm(itap_);
icmdexec_->registerCommand(static_cast<ICommand *>(pcmd_br_));
pcmd_reg_ = new CmdRegArm(itap_);
icmdexec_->registerCommand(static_cast<ICommand *>(pcmd_reg_));
pcmd_regs_ = new CmdRegsArm(itap_);
icmdexec_->registerCommand(static_cast<ICommand *>(pcmd_regs_));
if (defaultMode_.is_equal("Thumb")) {
setInstrMode(THUMB_mode);
}
}
void CpuCortex_Functional::predeleteService() {
CpuGeneric::predeleteService();
icmdexec_->unregisterCommand(static_cast<ICommand *>(pcmd_br_));
icmdexec_->unregisterCommand(static_cast<ICommand *>(pcmd_reg_));
icmdexec_->unregisterCommand(static_cast<ICommand *>(pcmd_regs_));
delete pcmd_br_;
delete pcmd_reg_;
delete pcmd_regs_;
}
/** HAP_ConfigDone */
void CpuCortex_Functional::hapTriggered(EHapType type,
uint64_t param,
const char *descr) {
AttributeType pwrlist;
IPower *ipwr;
RISCV_get_iface_list(IFACE_POWER, &pwrlist);
for (unsigned i = 0; i < pwrlist.size(); i++) {
ipwr = static_cast<IPower *>(pwrlist[i].to_iface());
ipwr->power(POWER_ON);
}
CpuGeneric::hapTriggered(type, param, descr);
}
unsigned CpuCortex_Functional::addSupportedInstruction(
ArmInstruction *instr) {
AttributeType tmp(instr);
listInstr_[instr->hash()].add_to_list(&tmp);
return 0;
}
void CpuCortex_Functional::handleTrap() {
// Check software before checking I-bit
if (interrupt_pending_[0] & (1ull << Interrupt_SoftwareIdx)) {
DsuMapType::udbg_type::debug_region_type::breakpoint_control_reg t1;
t1.val = br_control_.getValue().val;
if (t1.bits.trap_on_break == 0) {
sw_breakpoint_ = true;
interrupt_pending_[0] &= ~(1ull << Interrupt_SoftwareIdx);
setNPC(getPC());
halt(HaltSwBreakpoint, "SWI Breakpoint");
return;
}
}
if (getI() == 1) {
return;
}
if ((interrupt_pending_[0] | interrupt_pending_[1]) == 0) {
return;
}
if (InITBlock()) {
// To simplify psr control suppose interrupts outside of blocks
return;
}
int irq_idx;
for (int i = 0; i < 2; i++) {
if (interrupt_pending_[i] == 0) {
continue;
}
for (int n = 0; n < 64; n++) {
if ((interrupt_pending_[i] & (1ull << n)) == 0) {
continue;
}
irq_idx = 64*i + n;
if (irq_idx < 16) {
enterException(irq_idx);
} else {
RISCV_error("Interrupts from NVIC not supported %d", irq_idx);
}
}
interrupt_pending_[i] = 0;
}
interrupt_pending_[0] = 0;
}
void CpuCortex_Functional::enterException(int idx) {
// Save register into stack
trans_.addr = static_cast<uint32_t>(R[Reg_sp]);
trans_.action = MemAction_Write;
trans_.wstrb = 0xF;
trans_.xsize = 4;
trans_.addr -= 4;
trans_.wpayload.b32[0] = static_cast<uint32_t>(R[Reg_r0]);
dma_memop(&trans_);
trans_.addr -= 4;
trans_.wpayload.b32[0] = static_cast<uint32_t>(R[Reg_r1]);
dma_memop(&trans_);
trans_.addr -= 4;
trans_.wpayload.b32[0] = static_cast<uint32_t>(R[Reg_r2]);
dma_memop(&trans_);
trans_.addr -= 4;
trans_.wpayload.b32[0] = static_cast<uint32_t>(R[Reg_r3]);
dma_memop(&trans_);
trans_.addr -= 4;
trans_.wpayload.b32[0] = static_cast<uint32_t>(R[Reg_fe]);
dma_memop(&trans_);
trans_.addr -= 4;
trans_.wpayload.b32[0] = static_cast<uint32_t>(R[Reg_lr]);
dma_memop(&trans_);
trans_.addr -= 4;
trans_.wpayload.b32[0] =
static_cast<uint32_t>(getNPC() | 0x1);
dma_memop(&trans_);
trans_.addr -= 4;
trans_.wpayload.b32[0] = static_cast<uint32_t>(R[Reg_cpsr]);
dma_memop(&trans_);
setReg(Reg_sp, static_cast<uint32_t>(trans_.addr));
setReg(Reg_lr, 0xFFFFFFF9); // EXC_RETURN
// Load vector address:
trans_.action = MemAction_Read;
trans_.addr = 4*idx;
trans_.xsize = 4;
trans_.wstrb = 0;
dma_memop(&trans_);
uint32_t npc = trans_.rpayload.b32[0];
if (npc & 0x1) {
setInstrMode(THUMB_mode);
npc &= ~0x1ul;
} else {
setInstrMode(ARM_mode);
}
setNPC(npc);
}
void CpuCortex_Functional::exitException(uint32_t exc_return) {
trans_.action = MemAction_Read;
trans_.addr = R[Reg_sp];
trans_.xsize = 4;
trans_.wstrb = 0;
dma_memop(&trans_);
R[Reg_cpsr] = trans_.rpayload.b32[0];
trans_.addr += 4;
dma_memop(&trans_);
uint32_t npc = trans_.rpayload.b32[0] & ~0x1ul;
setReg(Reg_pc, npc);
setBranch(npc);
trans_.addr += 4;
dma_memop(&trans_);
setReg(Reg_lr, trans_.rpayload.b32[0]);
trans_.addr += 4;
dma_memop(&trans_);
setReg(Reg_fe, trans_.rpayload.b32[0]);
trans_.addr += 4;
dma_memop(&trans_);
setReg(Reg_r3, trans_.rpayload.b32[0]);
trans_.addr += 4;
dma_memop(&trans_);
setReg(Reg_r2, trans_.rpayload.b32[0]);
trans_.addr += 4;
dma_memop(&trans_);
setReg(Reg_r1, trans_.rpayload.b32[0]);
trans_.addr += 4;
dma_memop(&trans_);
setReg(Reg_r0, trans_.rpayload.b32[0]);
trans_.addr += 4;
setReg(Reg_sp, static_cast<uint32_t>(trans_.addr));
}
uint64_t CpuCortex_Functional::getResetAddress() {
Axi4TransactionType tr;
tr.action = MemAction_Read;
tr.addr = resetVector_.to_uint64() + 4;
tr.source_idx = sysBusMasterID_.to_int();
tr.xsize = 4;
dma_memop(&tr);
return tr.rpayload.b32[0] - 1;
}
void CpuCortex_Functional::reset(IFace *isource) {
Axi4TransactionType tr;
CpuGeneric::reset(isource);
ITBlockEnabled = false;
ITBlockBaseCond_ = 0;
ITBlockMask_ = 0;
ITBlockCondition_ = Cond_AL;
tr.action = MemAction_Read;
tr.addr = resetVector_.to_uint64();
tr.source_idx = sysBusMasterID_.to_int();
tr.xsize = 4;
dma_memop(&tr);
setReg(Reg_sp, tr.rpayload.b32[0]);
if (defaultMode_.is_equal("Thumb")) {
setInstrMode(THUMB_mode);
}
estate_ = CORE_Halted;
}
void CpuCortex_Functional::StartITBlock(uint32_t firstcond, uint32_t mask) {
// bf0c : ite eq => eq ne
// bf14 : ite ne => ne eq
// bf16 : itet ne => ne eq ne
ITBlockBaseCond_ = firstcond;
uint32_t base0 = firstcond & 0x1;
uint32_t m3 = (mask >> 3) & 0x1;
uint32_t m2 = (mask >> 2) & 0x1;
uint32_t m1 = (mask >> 1) & 0x1;
if ((mask & 0x7) == 0) {
// One instruction condition
ITBlockMask_ = (base0 << 4) | 0x8;
} else if ((mask & 0x3) == 0) {
// Two instructions condition
ITBlockMask_ = (base0 << 4) | (m3 << 3) | 0x4;
} else if ((mask & 0x1) == 0) {
// Three instructions condition
ITBlockMask_ = (base0 << 4) | (m3 << 3) | (m2 << 2) | 0x2;
} else {
// Four instructions condition
ITBlockMask_ = (base0 << 4) | (m3 << 3) | (m2 << 2) | (m1 << 2) | 0x1;
}
ITBlockCondition_ = firstcond;
ITBlockEnabled = true;
}
void CpuCortex_Functional::trackContextEnd() {
CpuGeneric::trackContextEnd();
if (ITBlockMask_ && !ITBlockEnabled) {
if (LastInITBlock()) {
// See table 2-1 shifting of IT execution stage
ITBlockMask_ = 0;
ITBlockCondition_ = Cond_AL;
} else {
ITBlockMask_ = ITBlockMask_ << 1; // 5 bits field
ITBlockCondition_ =
(ITBlockBaseCond_ & ~0x1) | ((ITBlockMask_ >> 4) & 1);
}
}
ITBlockEnabled = false; // Just to skip IT instruction
}
GenericInstruction *CpuCortex_Functional::decodeInstruction(Reg64Type *cache) {
GenericInstruction *instr = NULL;
uint32_t ti = cacheline_[0].buf32[0];
EIsaArmV7 etype;
if (getInstrMode() == THUMB_mode) {
uint32_t tio;
etype = decoder_thumb(ti, &tio, errmsg_, sizeof(errmsg_));
//cacheline_[0].buf32[0] = tio;
} else {
etype = decoder_arm(ti, errmsg_, sizeof(errmsg_));
}
if (etype < ARMV7_Total) {
instr = isaTableArmV7_[etype];
} else {
RISCV_error("ARM decoder error [%08" RV_PRI64 "x] %08x",
getPC(), ti);
}
portRegs_.getp()[Reg_pc].val = getPC();
return instr;
}
void CpuCortex_Functional::generateIllegalOpcode() {
//raiseSignal(EXCEPTION_InstrIllegal);
RISCV_error("Illegal instruction at 0x%08" RV_PRI64 "x", getPC());
}
void CpuCortex_Functional::traceOutput() {
char tstr[1024];
trace_action_type *pa;
disasm_thumb(trace_data_.pc,
trace_data_.instr,
trace_data_.disasm,
sizeof(trace_data_.disasm));
RISCV_sprintf(tstr, sizeof(tstr),
"%9" RV_PRI64 "d: %08" RV_PRI64 "x: %s \n",
trace_data_.step_cnt - 1,
trace_data_.pc,
trace_data_.disasm);
(*trace_file_) << tstr;
for (int i = 0; i < trace_data_.action_cnt; i++) {
pa = &trace_data_.action[i];
if (!pa->memop) {
RISCV_sprintf(tstr, sizeof(tstr),
"%21s %10s <= %08x\n",
"",
IREGS_NAMES[pa->waddr],
static_cast<uint32_t>(pa->wdata));
} else if (pa->memop_write) {
RISCV_sprintf(tstr, sizeof(tstr),
"%21s [%08" RV_PRI64 "x] <= %08x\n",
"",
pa->memop_addr,
pa->memop_data.buf32[0]);
} else {
RISCV_sprintf(tstr, sizeof(tstr),
"%21s [%08" RV_PRI64 "x] => %08x\n",
"",
pa->memop_addr,
pa->memop_data.buf32[0]);
}
(*trace_file_) << tstr;
}
trace_file_->flush();
}
void CpuCortex_Functional::raiseSignal(int idx) {
if (idx >= 128) {
RISCV_error("Raise unsupported signal %d", idx);
}
RISCV_debug("Request Interrupt %d", idx);
interrupt_pending_[idx >> 6] |= (1ull << (idx & 0x3F));
}
void CpuCortex_Functional::lowerSignal(int idx) {
interrupt_pending_[idx >> 6] &= ~(1ull << (idx & 0x3F));
RISCV_error("Lower unsupported signal %d", idx);
}
void CpuCortex_Functional::raiseSoftwareIrq() {
interrupt_pending_[0] |= (1ull << Interrupt_SoftwareIdx);
}
} // namespace debugger
| 29.188264 | 79 | 0.600184 | [
"vector"
] |
43b78b8479272ef60a968f4fab8dadf482bf4030 | 5,086 | hpp | C++ | sources/page.hpp | Unusual55/CPP_Ex2_B | 0d7989a3cd88a56e1b2b15d2f71a52a771f78718 | [
"MIT"
] | null | null | null | sources/page.hpp | Unusual55/CPP_Ex2_B | 0d7989a3cd88a56e1b2b15d2f71a52a771f78718 | [
"MIT"
] | null | null | null | sources/page.hpp | Unusual55/CPP_Ex2_B | 0d7989a3cd88a56e1b2b15d2f71a52a771f78718 | [
"MIT"
] | null | null | null | #ifndef PAGE_HPP
#define PAGE_HPP
#pragma once
#include <string>
#include "Direction.hpp"
#include <unordered_map>
#include <vector>
#include <iterator>
#include <string>
#include <iostream>
#define LEN 100
using namespace std;
class Page
{
unordered_map<int, char *> rows;
void printRow(int rowId)
{
for (int i = 0; i < LEN; i++)
{
cout << rows.at(rowId)[i];
}
cout << endl;
}
public:
Page()
{
;
}
~Page()
{
int key = -1;
for (auto it = rows.begin(); it != rows.end(); ++it)
{
key = it->first;
delete[] rows.at(key);
}
}
void validRow(int index)
{
if (index < 0)
{
std::__throw_invalid_argument("row index cannot be negative number.");
}
}
bool isRowExist(int index)
{
validRow(index);
int count = rows.count(index);
bool flag=false;
if(count>0){
flag=true;
}
return flag;
}
void addRow(int rowId, int startFrom, string const &str);
void addRow(int rowId);
void removeCharAt(int rowId, int colId)
{
validRow(rowId);
if (colId < 0 || colId >= LEN)
{
std::__throw_invalid_argument("column index is not within the bounds.");
}
if (isRowExist(rowId))
{
rows.at(rowId)[colId] = '~';
}
else
{
addRow(rowId);
rows.at(rowId)[colId] = '~';
}
}
void writeToRowHorizontal(int rowId, int colId, string const &str);
void eraseFromPageHorizontal(int rowId, int colId, int length);
void writeToRowVertical(int rowId, int colId, string const &str);
void eraseFromPageVertical(int rowId, int colId, int length);
void canWriteVertical(int rowId, int colId, string const &str);
static void validColStr(int startFrom, string const &str)
{
unsigned int i = 0;
int len = str.length();
if (startFrom < 0 || startFrom >= LEN)
{
std::__throw_invalid_argument("column is not within the range.");
}
if (startFrom + len >= LEN)
{
std::__throw_invalid_argument("cannot write out of bounds");
}
char c1 = '~';
char c2 = '\n';
char c3 = '\t';
char c4 = '\r';
char c = ' ';
for (i = 0; i < str.length(); i++)
{
c = str[i];
if (c == c1 || c == c2 || c == c3 || c == c4)
{
std::__throw_invalid_argument("The string contain invalid character: ~ or \n or \t or \r");
}
}
}
string readFromRowHorizontal(int rowId, int colId, int length);
string readFromColumnVertical(int rowId, int colId, int length);
string getEmptyRow()
{
string str = "";
for (int i = 0; i < LEN; i++)
{
str += "_";
}
return str + "\n";
}
string getEmptyRow(int startFrom, int endAt)
{
if (startFrom < 0 || startFrom >= LEN)
{
std::__throw_invalid_argument("invalid starting column.");
}
if (startFrom>endAt)
{
std::__throw_invalid_argument("The length cannot be a negative number.");
}
if (endAt> LEN || endAt<0)
{
std::__throw_invalid_argument("The inedex you entered is not withing the bounds of a row.");
}
string str = "";
for (int i = startFrom; i < endAt; i++)
{
str += "_";
}
return str;
}
int getMaximalRowId()
{
int maxRowId = -1;
int curr = -1;
for (auto kv : rows)
{
curr = kv.first;
maxRowId = max(curr, maxRowId);
}
return maxRowId;
}
void show()
{
int maxPage = getMaximalRowId();
int i;
for (i = 0; i <= maxPage; i++)
{
if (!isRowExist(i))
{
cout << getEmptyRow() << endl;
}
else
{
printRow(i);
}
}
}
string getRow(int rowId, int startFrom, int length)
{
validRow(rowId);
int i = 0;
if (startFrom < 0 || startFrom >= LEN)
{
std::__throw_invalid_argument("invalid starting column.");
}
if (length < 0)
{
std::__throw_invalid_argument("The length cannot be a negative number.");
}
if (startFrom + length > LEN)
{
std::__throw_invalid_argument("The inedex you entered is now withing the bounds of a row....");
}
string str;
if (isRowExist(rowId))
{
for (i = startFrom; i < startFrom + length; i++)
{
str += rows.at(rowId)[(unsigned)i];
}
}
else{
str+=getEmptyRow(startFrom, startFrom+length);
}
return str;
}
};
#endif | 24.68932 | 107 | 0.486433 | [
"vector"
] |
43b97d05a32233d7dd97a4bb8c3d8e2133fa56a6 | 2,220 | cpp | C++ | SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | SerialPrograms/Source/PokemonSwSh/Inference/PokemonSwSh_FishingDetector.cpp | BlizzardHero/Arduino-Source | bc4ce6433651b0feef488735098900f8bf4144f8 | [
"MIT"
] | null | null | null | /* Fishing Detector
*
* From: https://github.com/PokemonAutomation/Arduino-Source
*
*/
#include <QImage>
#include "Common/Compiler.h"
#include "CommonFramework/ImageTools/SolidColorTest.h"
#include "CommonFramework/Tools/VideoOverlaySet.h"
#include "CommonFramework/InferenceInfra/InferenceRoutines.h"
#include "PokemonSwSh_MarkFinder.h"
#include "PokemonSwSh_FishingDetector.h"
namespace PokemonAutomation{
namespace NintendoSwitch{
namespace PokemonSwSh{
FishingMissDetector::FishingMissDetector()
: VisualInferenceCallback("FishingMissDetector")
, m_hook_box(0.1, 0.15, 0.8, 0.4)
, m_miss_box(0.3, 0.9, 0.4, 0.05)
{}
void FishingMissDetector::make_overlays(VideoOverlaySet& items) const{
items.add(COLOR_RED, m_hook_box);
items.add(COLOR_RED, m_miss_box);
}
bool FishingMissDetector::detect(const QImage& frame){
QImage miss_image = extract_box(frame, m_miss_box);
ImageStats miss_stats = image_stats(miss_image);
if (!is_white(miss_stats)){
return false;
}
QImage hook_image = extract_box(frame, m_hook_box);
if (image_stddev(hook_image).sum() < 50){
return false;
}
return true;
}
bool FishingMissDetector::process_frame(
const QImage& frame,
std::chrono::system_clock::time_point timestamp
){
return detect(frame);
}
FishingHookDetector::FishingHookDetector(VideoOverlay& overlay)
: VisualInferenceCallback("FishingHookDetector")
, m_overlay(overlay)
, m_hook_box(0.1, 0.15, 0.8, 0.4)
{}
void FishingHookDetector::make_overlays(VideoOverlaySet& items) const{
items.add(COLOR_RED, m_hook_box);
}
bool FishingHookDetector::process_frame(
const QImage& frame,
std::chrono::system_clock::time_point timestamp
){
QImage hook_image = extract_box(frame, m_hook_box);
std::vector<ImagePixelBox> exclamation_marks = find_exclamation_marks(hook_image);
for (const ImagePixelBox& mark : exclamation_marks){
ImageFloatBox box = translate_to_parent(frame, m_hook_box, mark);
m_marks.emplace_back(m_overlay, box, COLOR_YELLOW);
}
return !exclamation_marks.empty();
}
}
}
}
| 25.227273 | 87 | 0.704054 | [
"vector"
] |
43c46c5d50c93190a0528375e068b51c891d9b32 | 19,693 | cpp | C++ | compiler/llvm/HexboxAnalysis.cpp | Ruide/ACES | cade77ad522a0a0df0af50940fff61871e7bc745 | [
"NCSA"
] | 16 | 2018-08-15T14:51:14.000Z | 2022-02-26T17:16:45.000Z | compiler/llvm/HexboxAnalysis.cpp | Ruide/ACES | cade77ad522a0a0df0af50940fff61871e7bc745 | [
"NCSA"
] | 1 | 2019-06-14T21:25:43.000Z | 2019-12-18T20:10:43.000Z | compiler/llvm/HexboxAnalysis.cpp | Ruide/ACES | cade77ad522a0a0df0af50940fff61871e7bc745 | [
"NCSA"
] | 12 | 2018-12-21T00:47:03.000Z | 2022-02-16T14:28:16.000Z | //===- HexboxAnalysis.cpp -------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file performs analysis of the application to generate data that can
// be used to create a HexBox policy
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/Statistic.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/CallSite.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Pass.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/Debug.h"
#include "llvm/Transforms/Instrumentation.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfoMetadata.h"
#include "json/json.h" //From https://github.com/open-source-parsers/jsoncpp
#include <fstream>
#include "llvm/IR/InstIterator.h"
using namespace llvm;
#define DEBUG_TYPE "hexbox"
STATISTIC(NumFunctions, "Num Functions");
static cl::opt<std::string> HexboxAnalysisResults("hexbox-analysis-results",
cl::desc("JSON File to write analysis results to"),
cl::init("-"),cl::value_desc("filename"));
namespace {
struct HexboxAnalysis : public FunctionPass {
static char ID;
HexboxAnalysis() : FunctionPass(ID) {
initializeHexboxAnalysisPass(*PassRegistry::getPassRegistry());
}
Json::Value OutputJsonRoot;
/******************************AddFunctionToJSON**************************
* Adds the function to the Root Json value, along with all callers and
* callees. Also initializes the Globals object under the function
*
*************************************************************************/
Json::Value & AddFunctionToJSON(Function & F){
std::string name = F.getName().str();
Json::Value *Fnode;
Json::Value *Attr;
std::string str;
raw_string_ostream type_name_stream(str);
F.getType()->print(type_name_stream);
Fnode = &OutputJsonRoot[name];
Attr = &(*Fnode)["Attr"];
(*Attr)["Type"]="Function";
(*Attr)["Address Taken"]= F.hasAddressTaken();
(*Attr)["LLVM_Type"] = type_name_stream.str();
DISubprogram * SP = F.getSubprogram();
if ( SP ){
std::string filename = SP->getFile()->getFilename().str();
(*Attr)["Filename"] = filename;
}
//Adds Callers
std::vector<Json::Value> Cons;
for (User * U: F.users()){
if (Instruction * Inst = dyn_cast<Instruction>(U)){
if (auto cs = CallSite(Inst)){
Function * caller = cs.getCaller();
add_connection(*Fnode,caller->getName().str(),"Caller");
}
}
}
//Adds Callees
for ( BasicBlock &BB : F ){
for ( Instruction & I : BB ){
if ( CallSite cs = CallSite(&I) ){
if (cs){
Function * callee = cs.getCalledFunction();
if ( callee ){
add_connection(*Fnode,callee->getName().str(),"Callee");
}else if ( InlineAsm * IA = dyn_cast_or_null<InlineAsm>(cs.getCalledValue()) ){
std::string str;
raw_string_ostream callee_name(str);
cs->print(callee_name);
add_connection(*Fnode,callee_name.str(),"Asm Callee");
}else if (ConstantExpr * ConstEx = dyn_cast_or_null<ConstantExpr>(cs.getCalledValue())){
Instruction * Inst = ConstEx->getAsInstruction();
if( CastInst * CI = dyn_cast_or_null<CastInst>(Inst) ){
if ( Function * c = dyn_cast<Function>(Inst->getOperand(0)) ){
add_connection(*Fnode,c->getName().str(),"Callee");
}else{
assert(false && "Unhandled Cast");
}
}else{
assert(false && "Unhandled Constant");
}
delete Inst;
}else{
add_indirect_calls(*Fnode, F, I, cs);
}
}
}
}
}
return (*Fnode);
}
void add_connection(Json::Value & Fnode, std::string name ,std::string type){
Json::Value *Connections;
Connections = &Fnode["Connections"][name];
(*Connections)["Type"] = type;
(*Connections)["Count"] = (*Connections)["Count"].asUInt64() + 1;
}
bool TypesEqual(Type *T1,Type *T2,unsigned depth = 0){
if ( T1 == T2 ){
return true;
}
if (depth > 10){
// If we haven't found a difference this deep just assume they are
// the same type. We need to overapproximate (i.e. say more things
// are equal than really are) so return true
return true;
}
if (PointerType *Pty1 = dyn_cast<PointerType>(T1) ){
if (PointerType *Pty2 = dyn_cast<PointerType>(T2)){
return TypesEqual(Pty1->getPointerElementType(),
Pty2->getPointerElementType(),depth+1);
}else{
return false;
}
}
if (FunctionType * FTy1 = dyn_cast<FunctionType>(T1)){
if (FunctionType * FTy2 = dyn_cast<FunctionType>(T2)){
if (FTy1->getNumParams() != FTy2->getNumParams()){
return false;
}
if (! TypesEqual(FTy1->getReturnType(),
FTy2->getReturnType(), depth+1)){
return false;
}
for (unsigned i=0; i<FTy1->getNumParams(); i++){
if (FTy1->getParamType(i) == FTy1 &&
FTy2->getParamType(i) == FTy2 ){
continue;
}else if (FTy1->getParamType(i) != FTy1 &&
FTy2->getParamType(i) != FTy2 ){
FTy1->getParamType(i)->dump();
FTy2->getParamType(i)->dump();
if( !TypesEqual(FTy1->getParamType(i),
FTy2->getParamType(i), depth+1)){
return false;
}
}else{
return false;
}
}
return true;
}else{
return false;
}
}
if (StructType *STy1 = dyn_cast<StructType>(T1)){
if (StructType *STy2 = dyn_cast<StructType>(T2)){
if(STy2->getNumElements() != STy1->getNumElements()){
return false;
}
if(STy1->hasName() && STy2->hasName()){
if(STy1->getName().startswith(STy2->getName()) ||
STy2->getName().startswith(STy1->getName())){
return true;
}
}
return false;
}else{
return false;
}
}
return false;
}
void add_indirect_calls(Json::Value & Fnode, Function & F, Instruction & I, CallSite & cs ){
std::string str;
raw_string_ostream callee_name(str);
std::string str2;
raw_string_ostream callee_type_str(str2);
FunctionType * IndirectType;
Json::Value *Indirect;
I.print(callee_name);
Indirect = &OutputJsonRoot[callee_name.str()];
(*Indirect)["Attr"]["Type"] = "Indirect";
(*Indirect)["Attr"]["Function"] = I.getFunction()->getName().str();
add_connection(Fnode,callee_name.str(),"Indirect Call Type");
IndirectType = cs.getFunctionType();
IndirectType->print(callee_type_str);
(*Indirect)["Attr"]["LLVMType"] = callee_type_str.str();
for (Function & Funct : F.getParent()->getFunctionList()){
//if ( IndirectType == Funct.getFunctionType() &&
if ( TypesEqual(IndirectType,Funct.getFunctionType()) &&
Funct.hasAddressTaken() ){
add_connection(Fnode,Funct.getName().str(),"Indirect Call");
add_connection(*Indirect,Funct.getName().str(),"Indirect Call");
}
}
}
class DataDependancy{
public:
SmallSet<Function *,32> functions;
DataDependancy(Value * v,Type * t,const DataLayout & DL,unsigned ad=0){
V = v;
read = false;
write = false;
isArg = false;
isParam = false;
argNum = 0;
ty = t;
addr = ad;
determineSize(DL);
id = dd_class_id;
dd_class_id++;
}
bool getRead(){
return read;
}
bool getWrite(){
return write;
}
void setIsArg(unsigned n){
isArg =true;
argNum = n;
}
void setIsParam(unsigned n){
isParam =true;
argNum = n;
}
void add_function(Function *F){
functions.insert(F);
}
unsigned getAddr(){
return addr;
}
unsigned getSize(){
return size;
}
void WriteNode(Json::Value &JsonNode){
std::stringstream ss;
ss << ".Peripheral_"<<id;
Json::Value & ThisNode = JsonNode[ss.str()];
errs()<< "Writing Json Node: " << ss.str() <<"\n";
writeJsonAttributes(ThisNode["Attr"]);
for (Function * F : functions){
ThisNode["Connections"][F->getName()]["Type"]="Peripheral";
}
}
bool inside(unsigned value){
if (this->addr <= value && value < this->addr+this->size){
return true;
}
return false;
}
bool overlap(DataDependancy *DD){
if (inside(DD->getAddr()) || DD->inside(this->addr)){
return true;
}
return false;
}
void determineSize(const DataLayout & DL){
size = 0;
if(ty){
if(PointerType * PT = dyn_cast<PointerType>(ty)){
size = DL.getTypeAllocSize(PT->getElementType());
}
else{
size = DL.getTypeAllocSize(ty);
}
}
}
void writeJsonAttributes(Json::Value & Rnode){
std::string s;
raw_string_ostream stream(s);
if (addr){
Rnode["Type"] = "Peripheral";
Rnode["Addr"] = addr;
}
if (V->hasName()){
Rnode["Name"] = V->getName().str();
}
if(ty){
ty->print(stream);
Rnode["DataType"] =stream.str();
Rnode["DataSize"] = size;
}
Rnode["Read"] = read;
Rnode["Write"] = write;
std::string st;
raw_string_ostream ss(st);
V->print(ss);
Rnode["LLVM::Value"] =ss.str();
Rnode["IsArg"] = isArg;
Rnode["IsParam"] = isParam;
Rnode["ArgNum"] = argNum;
}
void updateProperties(Value *v){
if(isa<LoadInst>(v)){
read = true;
}else if (isa<StoreInst>(v)){
write = true;
}
}
void determineAttributes(Value * v){
errs() << "Determining Attributes\n";
v->dump();
if(Instruction * I =dyn_cast<Instruction>(v)){
errs() << "Adding Function ";
errs().write_escaped(I->getFunction()->getName());
errs()<< "\n";
functions.insert(I->getFunction());
if(CallInst * CI = dyn_cast<CallInst>(v)){
SmallSet<Function *,32> Callees;
getPotentialCallees(CI,Callees);
for(Function * Callee : Callees){
functions.insert(Callee);
}
}else if(isa<LoadInst>(v)){
read = true;
}else if (isa<StoreInst>(v)){
write = true;
}
}else{
for(User * U: v->users()){
determineAttributes(U);
}
}
}
private:
unsigned id;
Value * V;
bool read;
bool write;
bool isArg;
bool isParam;
unsigned argNum;
unsigned addr;
unsigned size;
Type * ty;
};
static unsigned dd_class_id;
static void getPotentialCallees(CallInst * CI,SmallSet<Function *,32> &Callees){
Function *Callee = CI->getCalledFunction();
if (Callee){
Callees.insert(Callee);
}else{
for(auto & Fun : CI->getFunction()->getParent()->functions()){
if (Fun.getFunctionType() == CI->getFunctionType()){
Callees.insert(&Fun);
}
}
}
}
void getFunctionResources(Module * M){
DenseMap<Function *,DenseMap<Value *,DataDependancy*>> DependanceMap;
SmallSet<Constant *,32> PeripheralWorklist;
SmallSet<Value *,32>LocalWorklist;
SmallSet<GlobalVariable *,32> GlobalWorklist;
for (Function & F :M->functions()){
if(F.getName().startswith("llvm.dbg.")){
continue;
}
for (inst_iterator itr=inst_begin(F); itr!=inst_end(F);++itr){
Instruction *I = &*itr;
for (unsigned i=0;i<I->getNumOperands();i++){
Value *V = I->getOperand(i);
if(ConstantExpr *C = dyn_cast<ConstantExpr>(V)){
PeripheralWorklist.insert(C);
}else if (AllocaInst *AI = dyn_cast<AllocaInst>(V)){
LocalWorklist.insert(AI);
}else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)){
GlobalWorklist.insert(GV);
}
}
}
AddFunctionToJSON(F);
}
getPeripheralDependancies(PeripheralWorklist,M->getDataLayout());
}
void getPeripheralDependancies(SmallSet<Constant *,32> &Worklist, const DataLayout & DL){
DataDependancy * DD;
for (auto * C : Worklist){
unsigned addr;
Type * ty=nullptr;
errs() << "Checking Constant: ";
C->dump();
addr = getConstIntToPtr(C,ty);
if (addr != 0){
DD = new DataDependancy(C,ty,DL,addr);
errs() << "Creating DD: ";
C->dump();
for (User * U : C->users()){
DD->determineAttributes(U);
}
DD->WriteNode(OutputJsonRoot);
delete DD;
}
}
}
unsigned getConstIntToPtr(Value * V,Type * &ty){
unsigned addr = 0;
if (IntToPtrInst * I2P = dyn_cast<IntToPtrInst>(V)){
Value *Val = I2P->getOperand(0);
if (ConstantInt * CInt = dyn_cast<ConstantInt>(Val)){
addr = CInt->getValue().getLimitedValue(0xFFFFFFFF);
ty = I2P->getType();
errs() << "Int: " << addr << "\n";
errs()<<"Type: "; ty->dump();
return addr;
}else{
return 0;
}
}else if (Instruction * I = dyn_cast<Instruction>(V)){
for (unsigned i=0;i<I->getNumOperands();i++){
addr = getConstIntToPtr(I->getOperand(i),ty);
if (addr){
return addr;
}
}
}else if (ConstantExpr * C = dyn_cast<ConstantExpr>(V)){
Instruction *Instr = C->getAsInstruction();
addr = getConstIntToPtr(Instr,ty);
delete(Instr);
}else{
return 0;
}
return addr;
}
/**
* @brief doInitialization
* @param M
* @return
*/
bool doInitialization(Module &M) override{
if ( HexboxAnalysisResults.compare("-") == 0 ){
return false;
}
for (GlobalVariable &GV : M.globals()){
if( GV.hasInitializer() && !GV.getName().startswith(".") ){
addFunctionUses(GV,&GV,M);
}else{
errs() << "GV Has no Initializer:";
GV.dump();
}
}
getFunctionResources(&M);
return false;
}
StringRef getPassName() const override {
return StringRef("HexboxAnalysis");
}
bool runOnFunction(Function & F) override {
if ( HexboxAnalysisResults.compare("-") == 0 ){
return false;
}
NumFunctions++;
return false;
}
void addFunctionUses(GlobalVariable & GV, Value * V, Module & M){
for (User * U : V->users()){
Json::Value * Global;
Function * F = nullptr;
if ( Instruction * I = dyn_cast<Instruction>(U) ) {
F = I->getFunction();
Global = &OutputJsonRoot[GV.getName().str()];
add_connection(*Global,F->getName().str(),"Data");
(*Global)["Attr"]["Type"]="Global";
(*Global)["Attr"]["Size"] = M.getDataLayout().getTypeAllocSize(GV.getType());
// Don't know why you use 0 in the getMetadata() below but I've tried a bunch of other options
// like Metadata::DIGlobalVariableExpressionKind etc and always get null
if ( DIGlobalVariableExpression * DI_GVE = dyn_cast_or_null<DIGlobalVariableExpression>(GV.getMetadata(0)) ){
(*Global)["Attr"]["Filename"] = DI_GVE->getVariable()->getFilename().str();
}
}else if ( Constant * C = dyn_cast<Constant>(U) ){
addFunctionUses(GV,C,M);
}else{
errs() << "Unknown Use";
U->dump();
}
}
}
bool doFinalization(Module &M) override{
if ( HexboxAnalysisResults.compare("-") == 0 ){
return false;
}
std::ofstream jsonFile;
jsonFile.open(HexboxAnalysisResults);
jsonFile <<OutputJsonRoot;
jsonFile.close();
return false;
}
// We don't modify the program, so we preserve all analyses.
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesAll();
}
};
}
unsigned HexboxAnalysis::dd_class_id =0;
char HexboxAnalysis::ID = 0;
INITIALIZE_PASS_BEGIN(HexboxAnalysis, "HexboxAnaysis", "Performs HexBox LLVM Analysis",false, false)
INITIALIZE_PASS_END(HexboxAnalysis, "HexboxAnaysis", "Performs HexBox LLVM Analysis",false, false)
FunctionPass *llvm::createHexboxAnalysisPass(){
return new HexboxAnalysis();
}
| 31.609952 | 126 | 0.475296 | [
"object",
"vector"
] |
43c577f81da554b7ddf5b5ea2b3ca4337d763567 | 1,574 | hpp | C++ | standards/histogram.hpp | FIshikawa/standards | d146e99a53504c07226d6ef6b38255ea31c58f5c | [
"BSL-1.0"
] | null | null | null | standards/histogram.hpp | FIshikawa/standards | d146e99a53504c07226d6ef6b38255ea31c58f5c | [
"BSL-1.0"
] | null | null | null | standards/histogram.hpp | FIshikawa/standards | d146e99a53504c07226d6ef6b38255ea31c58f5c | [
"BSL-1.0"
] | null | null | null | // Copyright (C) 2018 by Synge Todo <wistaria@phys.s.u-tokyo.ac.jp>
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef STANDARDS_HISTOGRAM_HPP
#define STANDARDS_HISTOGRAM_HPP
#include <cstdint>
#include <stdexcept>
namespace standards {
class histogram {
public:
typedef std::uint64_t count_t;
histogram(double xmin, double xmax, std::size_t nbins)
: xmin_(xmin), xmax_(xmax), bins_(nbins, 0) {
if (xmax <= xmin)
throw std::invalid_argument("xmax should be larger than xmin");
if (nbins == 0)
throw std::invalid_argument("nbins should be non-zero");
dxinv_ = nbins / (xmax - xmin);
}
histogram& operator<<(double x) {
++count_;
if (x >= xmin_) {
std::size_t k = dxinv_ * (x - xmin_);
if (k < bins_.size()) {
++valid_;
++bins_[k];
}
}
return *this;
}
std::size_t num_bins() const { return nbins_; }
count_t count() const { return count_; }
count_t valid() const { return valid_; }
double mean(std::size_t k) const {
if (count_ == 0) std::runtime_error("no measurements");
if (k >= num_binds()) std::invalid_argument("index out of range");
return dxinv_ * bins_[k] / count_;
}
private:
double xmin_, xmax_;
std::vector<count_t> bins_;
count_t count_, valid_;
double dxinv_;
};
inline std::ostream& operator<<(std::ostream& os, histogram const& hist) {
return os;
}
} // end namespace standards
#endif // STANDARDS_HISTOGRAM_HPP
| 26.233333 | 79 | 0.651842 | [
"vector"
] |
43cd5d91c0819a43e854652da8a0b767b38142c3 | 3,770 | cpp | C++ | c++/leetcode/0673-Number_of_Longest_Increasing_Subsequence-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | 1 | 2020-03-02T10:56:22.000Z | 2020-03-02T10:56:22.000Z | c++/leetcode/0673-Number_of_Longest_Increasing_Subsequence-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | c++/leetcode/0673-Number_of_Longest_Increasing_Subsequence-M.cpp | levendlee/leetcode | 35e274cb4046f6ec7112cd56babd8fb7d437b844 | [
"Apache-2.0"
] | null | null | null | // 673 Number of Longest Increasing Subsequence
// https://leetcode.com/problems/number-of-longest-increasing-subsequence
// version: 1; create time: 2020-01-24 22:40:25;
class Solution {
public:
int findNumberOfLIS(vector<int>& nums) {
const int n = nums.size();
if (n <= 1) return n;
vector<vector<int>> dp(n);
int total_max_len = 0;
int total_max_cnt = 0;
for (int i = 0; i < n; ++i) {
int max_len = 1;
int max_cnt = 1;
for (int j = 0; j < i; ++j) {
if (nums[j] >= nums[i]) continue;
if (dp[j][0] + 1 > max_len) {
max_len = dp[j][0] + 1;
max_cnt = dp[j][1];
} else if (dp[j][0] + 1 == max_len) {
max_cnt += dp[j][1];
}
}
dp[i] = {max_len, max_cnt};
if (max_len > total_max_len) {
total_max_len = max_len;
total_max_cnt = max_cnt;
} else if (max_len == total_max_len) {
total_max_cnt += max_cnt;
}
}
return total_max_cnt;
}
};
struct Node {
int range_left;
int range_right;
pair<int, int> max_len_cnt;
Node* node_left;
Node* node_right;
Node(int left, int right) : range_left(left), range_right(right), node_left(nullptr), node_right(nullptr) {}
int range_mid() const {
if (range_left + 1 == range_right)
return range_left;
else
return (range_left + range_right) / 2;
}
Node* left() {
if (!node_left) node_left = new Node(range_left, range_mid());
return node_left;
}
Node* right() {
if (!node_right) node_right = new Node(range_mid() + 1, range_right);
return node_right;
}
};
// Segment Tree
class Solution {
private:
pair<int, int> merge(const pair<int, int>& lhs, const pair<int, int>& rhs) {
if (lhs.first == rhs.first) {
if (lhs.first == 0) {
return {0, 1};
} else {
return {lhs.first, lhs.second + rhs.second};
}
} else {
return std::max(lhs, rhs);
}
}
void update(Node* node, int key, const pair<int, int>& len_cnt) {
if (node->range_right >= key) {
if (node->range_left == node->range_right) {
node->max_len_cnt = merge(node->max_len_cnt, len_cnt);
} else {
if (node->range_mid() >= key && node->left()->range_right != node->range_right) {
update(node->left(), key, len_cnt);
} else {
update(node->right(), key, len_cnt);
}
node->max_len_cnt = merge(node->left()->max_len_cnt, node->right()->max_len_cnt);
}
}
}
pair<int, int> query(Node* node, int upper) {
if (node->range_right <= upper) {
return node->max_len_cnt;
} else if (node->range_left > upper) {
return {0, 1};
} else {
auto lhs = query(node->left(), upper);
auto rhs = query(node->right(), upper);
return merge(lhs, rhs);
}
}
public:
int findNumberOfLIS(vector<int>& nums) {
const int n = nums.size();
if (n <= 1) return n;
const auto ss = *std::min_element(nums.begin(), nums.end());
const auto se = *std::max_element(nums.begin(), nums.end());
Node* node = new Node(ss, se);
for (int i = 0; i < n; ++i) {
auto res = query(node, nums[i] - 1);
++res.first;
update(node, nums[i], res);
}
return node->max_len_cnt.second;
}
};
| 30.650407 | 112 | 0.490716 | [
"vector"
] |
43cfe558a17d362698dbaca3f32d1acffa1406b4 | 3,396 | cpp | C++ | assignment10/src/assignment10.cpp | tilhr/C- | 96b3bdec197c24586cd49abb85a6d07e477b888d | [
"MIT"
] | 3 | 2019-12-28T07:14:57.000Z | 2019-12-30T12:52:32.000Z | assignment10/src/assignment10.cpp | tilhr/Cpp | 96b3bdec197c24586cd49abb85a6d07e477b888d | [
"MIT"
] | null | null | null | assignment10/src/assignment10.cpp | tilhr/Cpp | 96b3bdec197c24586cd49abb85a6d07e477b888d | [
"MIT"
] | 3 | 2020-10-01T06:58:48.000Z | 2021-09-20T11:11:11.000Z | //============================================================================
// Name : rodgersA10.cpp
// Author : Tyler ROdgers
// Version :
// Copyright : Your copyright notice
// Description : Hello World in C++, Ansi-style
//============================================================================
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
using namespace std;
struct Vertex{ //vertecies
int vertexValue;
bool visited;
vector<int>neighbor;
};
void buildGraph(vector<Vertex>&graph){ //builds graph
fstream file;
file.open("data.txt");
if(!file){
cout<<"File couldn't be opened!!";
exit(0);
}
int count=0;
string line;
while(getline(file,line))
count++;
file.close();
file.open("data.txt");
for(int i=0;i<count;i++){ //for each vertex
int vertexValue; //reads value
file>>vertexValue;
vector<int>neighbor;
int x;
while(file>>x && x!=-1) //reads all neighbor till -1
neighbor.push_back(x);
graph.push_back({vertexValue,false,neighbor}); //i don't know why this isn't working, it worked earlier in my testing
cout<<"Vertex number "<<i<<" value "<<vertexValue<<" neighbors->";
for(int i:neighbor){ //????????????
cout<<i<<" ";
}
cout<<endl;
}
}
void dftInternal(vector<Vertex>&graph,int vertex){
if(graph[vertex].visited)
return;
graph[vertex].visited=true; //marks visited
cout<<graph[vertex].vertexValue<<" ";
for(int i:graph[vertex].neighbor){ //i don't know why this isn't working
dftInternal(graph,i);
}
}
void dft(vector<Vertex>&graph){
cout<<"Depth-first Traversal:\n";
for(int i=0;i<graph.size();i++){}
}
void bft(vector<Vertex>&graph){
cout<<"\nBreadth-first Traversal:\n";
for(int i=0;i<graph.size();i++)
graph[i].visited=false;
queue<int>q;
q.push(0);
graph[0].visited=true;
label:
while(!q.empty()){
int cur=q.front();
q.pop();
cout<<cur<<" ";
for(int i:graph[cur].neighbor){ //why doesn't this work???? c'mon tyler. do better.
if(!graph[i].visited){
graph[i].visited = true;
q.push(i);
}
}
}
for(int i=0;i<graph.size();i++){
if(!graph[i].visited){
graph[i].visited=true;
q.push(i);
goto label;
}
}
}
int main(){
//function calling
vector<Vertex>graph;
buildGraph(graph);
dft(graph);
bft(graph);
}
// prints BFS traversal
/*void BFS(T src){
queue <T> q;
map <T, bool> visited; //using a hash map to check if the nodes have been visited
q.push(src);
visited[src] = true;
while(!q.empty()){
T node = q.front();
cout << node << "";
q.pop();
for (T neighbour: adjList[node]){
if (!visited[neighbour]){
q.push(neighbour);
visited[neighbour] = true;
}
}
}
}*/
/*
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
*/
| 21.493671 | 125 | 0.518846 | [
"vector"
] |
43dcc94580f2bd581f7aafabbdd811b872977ee4 | 1,135 | cpp | C++ | uva/1174.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 3 | 2018-01-08T02:52:51.000Z | 2021-03-03T01:08:44.000Z | uva/1174.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | null | null | null | uva/1174.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 1 | 2020-08-13T18:07:35.000Z | 2020-08-13T18:07:35.000Z | #include <bits/stdc++.h>
#define le 50004
#define li 2003
using namespace std;
int p[li];
struct edge{
int x, y, w;
};
bool comp(edge a, edge b){
return a.w < b.w;
}
vector<edge> v;
int fnc(int a){
if(p[a] == a) return a;
return p[a] = fnc(p[a]);
}
int mst(int n){
sort(v.begin(), v.end(), comp);
int ans = 0, co = 0;
for(int i = 0; i < (int)v.size(); i++){
int a = fnc(v[i].x);
int b = fnc(v[i].y);
if(a != b){
p[b] = a;
ans += v[i].w;
co++;
if(co == n - 1) break;
}
}
return ans;
}
int main(){
//freopen("input.txt", "r", stdin);
//freopen("output.txt", "w", stdout);
int t, co = 0, n, m, c;
string s, s1;
for(scanf("%d", &t); t--; ){
if(co) printf("\n");
int l = 1;
edge eg;
map<string, int> mp;
scanf("%d %d", &n, &m);
for(int i = 0; i < n + 1; p[i] = i, i++);
for(int i = 0; i < m; i++){
cin >> s >> s1 >> c;
if(!mp[s]) mp[s] = l++;
if(!mp[s1]) mp[s1] = l++;
eg.x = mp[s];
eg.y = mp[s1];
eg.w = c;
v.push_back(eg);
}
printf("%d\n", mst(n));
v.clear();
co++;
}
return 0;
}
| 19.237288 | 45 | 0.440529 | [
"vector"
] |
43df182f26e27cd11358acb342529219b29e5b51 | 7,189 | cpp | C++ | libpeconv/src/exported_func.cpp | bak724/libpeconv | a73c9241431ce099117b3fe28d9679292a4093bf | [
"BSD-2-Clause"
] | 1 | 2021-10-16T01:40:27.000Z | 2021-10-16T01:40:27.000Z | libpeconv/src/exported_func.cpp | metablaster/libpeconv | ad8421489cae861104aa55b89f73f89f6c2c5b23 | [
"BSD-2-Clause"
] | null | null | null | libpeconv/src/exported_func.cpp | metablaster/libpeconv | ad8421489cae861104aa55b89f73f89f6c2c5b23 | [
"BSD-2-Clause"
] | null | null | null | #include "peconv/exported_func.h"
#include <string>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <iostream>
#include "peconv/file_util.h"
using namespace peconv;
std::string peconv::get_dll_shortname(const std::string& str)
{
std::size_t len = str.length();
size_t ext_pos = len;
size_t separator_pos = 0;
for (size_t k = len; k != 0; k--) {
size_t i = k - 1;
char c = str[i];
// search first '.' from the end:
if (c == '.' && ext_pos == len) {
ext_pos = i;
}
// search first path separator from the end:
if (c == '\\' || c == '/') {
separator_pos = k;
break;
}
}
const size_t new_len = ext_pos - separator_pos;
std::string name = str.substr(separator_pos, new_len);
std::transform(name.begin(), name.end(), name.begin(), tolower);
return name;
}
size_t peconv::forwarder_name_len(BYTE* fPtr)
{
// names can be also mangled, i.e. MSVCRT.??0__non_rtti_object@std@@QAE@ABV01@@Z
bool has_dot = false;
size_t len = 0;
while ((*fPtr >= 'a' && *fPtr <= 'z')
|| (*fPtr >= 'A' && *fPtr <= 'Z')
|| (*fPtr >= '0' && *fPtr <= '9')
|| (*fPtr == '.')
|| (*fPtr == '_')
|| (*fPtr == '#')
|| (*fPtr == '@')
|| (*fPtr == '?')
|| (*fPtr == '-'))
{
if (*fPtr == '.') has_dot = true;
len++;
fPtr++;
}
if (*fPtr == '\0') {
if (!has_dot) {
return 0; //this is not a valid forwarder
}
return len;
}
return 0;
}
std::string peconv::get_func_name(const std::string& str)
{
std::size_t len = str.length();
std::size_t ext = str.find_last_of(".");
if (ext >= len) return "";
std::string name = str.substr(ext+1, len - (ext+1));
return name;
}
std::string peconv::ordinal_to_string(DWORD func_ordinal)
{
std::stringstream stream;
stream << "#";
stream << std::dec << func_ordinal;
return stream.str();
}
bool peconv::is_ordinal_string(const std::string& func_name_str)
{
if (func_name_str.length() < 2) return false;
return (func_name_str[0] == '#');
}
DWORD peconv::ordinal_string_to_val(const std::string& func_name_str)
{
if (!is_ordinal_string(func_name_str)) return 0;
const char* func_name = func_name_str.c_str();
return atoi(func_name + 1);
}
std::string peconv::format_dll_func(const std::string& str)
{
std::string dllName = get_dll_shortname(str);
std::string funcName = get_func_name(str);
if (dllName.length() == 0 || funcName.length() == 0) {
return "";
}
std::transform(dllName.begin(), dllName.end(), dllName.begin(), tolower);
return dllName + "." + funcName;
}
ExportedFunc::ExportedFunc(std::string libName, std::string funcName, DWORD funcOrdinal)
{
this->libName = ExportedFunc::formatName(libName);
this->funcName = funcName;
this->funcOrdinal = funcOrdinal;
this->isByOrdinal = false;
}
ExportedFunc::ExportedFunc(std::string libName, DWORD funcOrdinal)
{
this->libName = ExportedFunc::formatName(libName);
this->funcOrdinal = funcOrdinal;
this->isByOrdinal = true;
}
ExportedFunc::ExportedFunc(const ExportedFunc& other)
{
this->libName = other.libName;
this->funcName = other.funcName;
this->funcOrdinal = other.funcOrdinal;
this->isByOrdinal = other.isByOrdinal;
}
ExportedFunc::ExportedFunc(const std::string &forwarderName)
{
this->libName = get_dll_shortname(forwarderName);
std::string func_name_str = get_func_name(forwarderName);
if (func_name_str.length() < 2) {
this->funcOrdinal = -1;
this->funcName = "";
this->isByOrdinal = false;
#ifdef _DEBUG
std::cerr << "Invalid function data" << std::endl;
#endif
return;
}
if (is_ordinal_string(func_name_str)) {
// it is an ordinal in a string form, i.e.: "COMBASE.#110"
this->funcOrdinal = peconv::ordinal_string_to_val(func_name_str);
this->isByOrdinal = true;
this->funcName = "";
//std::cout << "[O] Adding forwarded func: " << forwarderName << " parsed: " << this->toString() << std::endl;
} else {
this->funcName = func_name_str;
this->isByOrdinal = false;
this->funcOrdinal = 0;
//std::cout << "[N] Adding forwarded func:" << this->toString() << std::endl;
}
}
std::string ExportedFunc::formatName(std::string name)
{
if (name.length() == 0) {
return "";
}
std::transform(name.begin(), name.end(), name.begin(), tolower);
return name;
}
bool ExportedFunc::isTheSameFuncName(const peconv::ExportedFunc& func1, const peconv::ExportedFunc& func2)
{
if (!func1.isByOrdinal && !func2.isByOrdinal) {
if (func1.funcName == func2.funcName) {
return true;
}
}
if (func1.funcOrdinal == func2.funcOrdinal) {
return true;
}
return false;
}
namespace peconv
{
bool is_valid_extension(const std::string &ext)
{
if (ext.length() > 3) {
//probably not an extension
return false;
}
for (size_t j = 0; j < ext.length(); j++) {
if (!isalpha(ext[j])) {
return false;
}
}
return true;
}
std::string remove_module_extension(IN const std::string str)
{
size_t len = str.length();
size_t ext_pos = find_extension_pos(str);
if (ext_pos == len) {
return str;
}
std::string ext = str.substr(ext_pos + 1);
if (is_valid_extension(ext)) {
std::string str1 = str.substr(0, ext_pos);
return str1;
}
return str;
}
}; //namespace peconv
bool ExportedFunc::isTheSameDllName(const peconv::ExportedFunc& func1, const peconv::ExportedFunc& func2)
{
const std::string file1 = peconv::get_file_name(func1.libName);
const std::string file2 = peconv::get_file_name(func2.libName);
if (file1 == file2) {
return true;
}
const std::string short1 = peconv::remove_module_extension(file1);
const std::string short2 = peconv::remove_module_extension(file2);
if (short1 == short2) {
return true;
}
return false;
}
bool ExportedFunc::isTheSameFunc(const peconv::ExportedFunc& func1, const peconv::ExportedFunc& func2)
{
if (!peconv::ExportedFunc::isTheSameFuncName(func1, func2)) {
return false;
}
if (!isTheSameDllName(func1, func2)) {
return false;
}
return true;
}
std::string ExportedFunc::toString() const
{
if (!isValid()) {
return "[Invalid func]";
}
std::stringstream stream;
stream << this->libName;
stream << ".";
if (!this->isByOrdinal) {
stream << this->funcName;
stream << " ";
}
stream << ordinal_to_string(this->funcOrdinal);
return stream.str();
}
std::string ExportedFunc::nameToString() const
{
if (!isValid()) {
return "";
}
if (this->isByOrdinal) {
return ordinal_to_string(this->funcOrdinal);
}
return this->funcName;
}
| 27.438931 | 118 | 0.585339 | [
"transform"
] |
43e442448cca4740e315e12f11cd4dc2e7eb778f | 509 | cpp | C++ | LeetCode/0682. Baseball Game/solution.cpp | InnoFang/oh-my-algorithms | f559dba371ce725a926725ad28d5e1c2facd0ab2 | [
"Apache-2.0"
] | 1 | 2017-03-31T15:24:01.000Z | 2017-03-31T15:24:01.000Z | LeetCode/0682. Baseball Game/solution.cpp | InnoFang/Algorithm-Library | 1896b9d8b1fa4cd73879aaecf97bc32d13ae0169 | [
"Apache-2.0"
] | null | null | null | LeetCode/0682. Baseball Game/solution.cpp | InnoFang/Algorithm-Library | 1896b9d8b1fa4cd73879aaecf97bc32d13ae0169 | [
"Apache-2.0"
] | null | null | null | /**
* 39 / 39 test cases passed.
* Runtime: 4 ms
* Memory Usage: 8 MB
*/
class Solution {
public:
int calPoints(vector<string>& ops) {
vector<int> stk;
for (auto &op : ops) {
if (op == "C") stk.pop_back();
else if (op == "D") stk.push_back(stk.back() * 2);
else if (op == "+") stk.push_back(stk[stk.size() - 2] + stk.back());
else stk.push_back(atoi(op.c_str()));
}
return accumulate(stk.begin(),stk.end(), 0);
}
};
| 26.789474 | 80 | 0.499018 | [
"vector"
] |
43e4b7d4089e5827829ca4d8ca7e9872afbb6864 | 7,849 | cpp | C++ | live/src/v20180801/model/DelayInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | live/src/v20180801/model/DelayInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | live/src/v20180801/model/DelayInfo.cpp | sinjoywong/tencentcloud-sdk-cpp | 1b931d20956a90b15a6720f924e5c69f8786f9f4 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/live/v20180801/model/DelayInfo.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Live::V20180801::Model;
using namespace std;
DelayInfo::DelayInfo() :
m_domainNameHasBeenSet(false),
m_appNameHasBeenSet(false),
m_streamNameHasBeenSet(false),
m_delayIntervalHasBeenSet(false),
m_createTimeHasBeenSet(false),
m_expireTimeHasBeenSet(false),
m_statusHasBeenSet(false)
{
}
CoreInternalOutcome DelayInfo::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("DomainName") && !value["DomainName"].IsNull())
{
if (!value["DomainName"].IsString())
{
return CoreInternalOutcome(Error("response `DelayInfo.DomainName` IsString=false incorrectly").SetRequestId(requestId));
}
m_domainName = string(value["DomainName"].GetString());
m_domainNameHasBeenSet = true;
}
if (value.HasMember("AppName") && !value["AppName"].IsNull())
{
if (!value["AppName"].IsString())
{
return CoreInternalOutcome(Error("response `DelayInfo.AppName` IsString=false incorrectly").SetRequestId(requestId));
}
m_appName = string(value["AppName"].GetString());
m_appNameHasBeenSet = true;
}
if (value.HasMember("StreamName") && !value["StreamName"].IsNull())
{
if (!value["StreamName"].IsString())
{
return CoreInternalOutcome(Error("response `DelayInfo.StreamName` IsString=false incorrectly").SetRequestId(requestId));
}
m_streamName = string(value["StreamName"].GetString());
m_streamNameHasBeenSet = true;
}
if (value.HasMember("DelayInterval") && !value["DelayInterval"].IsNull())
{
if (!value["DelayInterval"].IsUint64())
{
return CoreInternalOutcome(Error("response `DelayInfo.DelayInterval` IsUint64=false incorrectly").SetRequestId(requestId));
}
m_delayInterval = value["DelayInterval"].GetUint64();
m_delayIntervalHasBeenSet = true;
}
if (value.HasMember("CreateTime") && !value["CreateTime"].IsNull())
{
if (!value["CreateTime"].IsString())
{
return CoreInternalOutcome(Error("response `DelayInfo.CreateTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_createTime = string(value["CreateTime"].GetString());
m_createTimeHasBeenSet = true;
}
if (value.HasMember("ExpireTime") && !value["ExpireTime"].IsNull())
{
if (!value["ExpireTime"].IsString())
{
return CoreInternalOutcome(Error("response `DelayInfo.ExpireTime` IsString=false incorrectly").SetRequestId(requestId));
}
m_expireTime = string(value["ExpireTime"].GetString());
m_expireTimeHasBeenSet = true;
}
if (value.HasMember("Status") && !value["Status"].IsNull())
{
if (!value["Status"].IsInt64())
{
return CoreInternalOutcome(Error("response `DelayInfo.Status` IsInt64=false incorrectly").SetRequestId(requestId));
}
m_status = value["Status"].GetInt64();
m_statusHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void DelayInfo::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_domainNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DomainName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_domainName.c_str(), allocator).Move(), allocator);
}
if (m_appNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "AppName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_appName.c_str(), allocator).Move(), allocator);
}
if (m_streamNameHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "StreamName";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_streamName.c_str(), allocator).Move(), allocator);
}
if (m_delayIntervalHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "DelayInterval";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_delayInterval, allocator);
}
if (m_createTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "CreateTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_createTime.c_str(), allocator).Move(), allocator);
}
if (m_expireTimeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "ExpireTime";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_expireTime.c_str(), allocator).Move(), allocator);
}
if (m_statusHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Status";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, m_status, allocator);
}
}
string DelayInfo::GetDomainName() const
{
return m_domainName;
}
void DelayInfo::SetDomainName(const string& _domainName)
{
m_domainName = _domainName;
m_domainNameHasBeenSet = true;
}
bool DelayInfo::DomainNameHasBeenSet() const
{
return m_domainNameHasBeenSet;
}
string DelayInfo::GetAppName() const
{
return m_appName;
}
void DelayInfo::SetAppName(const string& _appName)
{
m_appName = _appName;
m_appNameHasBeenSet = true;
}
bool DelayInfo::AppNameHasBeenSet() const
{
return m_appNameHasBeenSet;
}
string DelayInfo::GetStreamName() const
{
return m_streamName;
}
void DelayInfo::SetStreamName(const string& _streamName)
{
m_streamName = _streamName;
m_streamNameHasBeenSet = true;
}
bool DelayInfo::StreamNameHasBeenSet() const
{
return m_streamNameHasBeenSet;
}
uint64_t DelayInfo::GetDelayInterval() const
{
return m_delayInterval;
}
void DelayInfo::SetDelayInterval(const uint64_t& _delayInterval)
{
m_delayInterval = _delayInterval;
m_delayIntervalHasBeenSet = true;
}
bool DelayInfo::DelayIntervalHasBeenSet() const
{
return m_delayIntervalHasBeenSet;
}
string DelayInfo::GetCreateTime() const
{
return m_createTime;
}
void DelayInfo::SetCreateTime(const string& _createTime)
{
m_createTime = _createTime;
m_createTimeHasBeenSet = true;
}
bool DelayInfo::CreateTimeHasBeenSet() const
{
return m_createTimeHasBeenSet;
}
string DelayInfo::GetExpireTime() const
{
return m_expireTime;
}
void DelayInfo::SetExpireTime(const string& _expireTime)
{
m_expireTime = _expireTime;
m_expireTimeHasBeenSet = true;
}
bool DelayInfo::ExpireTimeHasBeenSet() const
{
return m_expireTimeHasBeenSet;
}
int64_t DelayInfo::GetStatus() const
{
return m_status;
}
void DelayInfo::SetStatus(const int64_t& _status)
{
m_status = _status;
m_statusHasBeenSet = true;
}
bool DelayInfo::StatusHasBeenSet() const
{
return m_statusHasBeenSet;
}
| 27.348432 | 135 | 0.680087 | [
"model"
] |
43ee321d30f2e3f59ff4723505ff89d7b2f4a1ef | 604 | cpp | C++ | tjw5866Engine/tjw5866Engine/main.cpp | UberCelloCzar/BlockSlideEngine | 973a120e0c629a5c957eb3fed74ed14d2f160e07 | [
"MIT"
] | null | null | null | tjw5866Engine/tjw5866Engine/main.cpp | UberCelloCzar/BlockSlideEngine | 973a120e0c629a5c957eb3fed74ed14d2f160e07 | [
"MIT"
] | null | null | null | tjw5866Engine/tjw5866Engine/main.cpp | UberCelloCzar/BlockSlideEngine | 973a120e0c629a5c957eb3fed74ed14d2f160e07 | [
"MIT"
] | null | null | null | // Trevor Walden, IGME 209 Section 2, 17 March 2016
// This is an exercise in learning OpenGL and shaders (GLSL)
#include <GL/glew.h> // Use OpenGL, extensions, and extra tools
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtx/transform.hpp>
#include <FreeImage.h>
#include <vector>
#include <iostream>
#include "Engine.h"
int main(void)
{
Engine engine = Engine();
if (!engine.init()) // Initialize and end if failure
{
return -1;
}
if (engine.useShaders())
{
engine.gameLoop(); // Draw to the screen
}
std::cin.get();
glfwTerminate(); // Safely exit engine
return 0;
} | 20.133333 | 63 | 0.682119 | [
"vector",
"transform"
] |
43eea94c6522b28ec2d38d9aded0d5937937dcee | 3,997 | cpp | C++ | main.cpp | marklit/dbf2csv | a11b9769cbc40aea3ed6c1ef1bf0f29419f39ee6 | [
"MIT"
] | null | null | null | main.cpp | marklit/dbf2csv | a11b9769cbc40aea3ed6c1ef1bf0f29419f39ee6 | [
"MIT"
] | null | null | null | main.cpp | marklit/dbf2csv | a11b9769cbc40aea3ed6c1ef1bf0f29419f39ee6 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <sstream>
#include <iomanip>
#include <boost/filesystem/operations.hpp>
#include "DbfTable.h"
#include "Version.h"
using namespace std;
typedef enum Mode {
kVersion,
kSummary,
kCsv
} Mode;
void print_usage() {
cout << "usage: dbf2csv [-h|-v|-s|-c|-k] filename" << endl;
cout << " -a = append CSV header and data (format: '<header><separator><data>', separator: \\t, \\r, \\n, ;)" << endl;
cout << " -c = create a CSV file" << endl;
cout << " -h = print this message" << endl;
cout << " -k = skip deleted records (default: true)" << endl;
cout << " -l = output csv header names in lowercase (default: false)" << endl;
cout << " -s = print summary information" << endl;
cout << " -v = print the program version" << endl;
}
int main(int argc, char *argv[]) {
Mode mode = kVersion;
bool skip_deleted = true;
bool lowercase_header_names = false;
std::string append_csv_header;
std::string append_csv_data;
int opt;
while ((opt = getopt(argc, argv, "a:chk:l:sv")) != -1) {
switch (opt) {
case 'a': {
std::vector<std::string> parts;
boost::split(parts, optarg, boost::is_any_of("\t\r\n;"));
if (parts.size() == 2) {
append_csv_header = parts[0];
append_csv_data = parts[1];
}
else {
cerr << "Invalid append option: '" << optopt << "'" << endl;
return 1;
}
break;
}
case 'c':
mode = kCsv;
break;
case 'h':
print_usage();
return 0;
case 'k':
skip_deleted = (optarg[0] == 'Y' || optarg[0] == 'y');
break;
case 'l':
lowercase_header_names = (optarg[0] == 'Y' || optarg[0] == 'y');
break;
case 's':
mode = kSummary;
break;
case 'v':
mode = kVersion;
break;
default:
cerr << "Unrecognized option: '" << optopt << "'" << endl;
print_usage();
return 1;
}
}
if (mode == kVersion) {
cout << "dbf2csv version: " << Version << endl;
print_usage();
return 0;
}
string dbf_filename = argv[optind];
DbfTablePtr dbf_table = DbfTablePtr(new DbfTable(dbf_filename, skip_deleted));
if (!dbf_table->good()) {
cerr << "Unable to open file: " << dbf_filename << endl;
return 1;
}
if (mode == kSummary) {
cout << "Database: " << dbf_filename << endl;
const DbfHeaderPtr header = dbf_table->header();
cout << "Type: (" << hex << header->version() << dec << ") " << header->version_description() << endl;
cout << "Memo File: " << (dbf_table->has_memo_file() ? "true" : "false") << endl;
cout << "Records: " << header->record_count() << endl;
cout << "Last updated at: " << header->updated_at() << endl;
cout << endl;
cout << "Fields:" << endl;
cout << "Name Type Length Decimal" << endl;
cout << "------------------------------------------------------------------------------" << endl;
std::vector<DbfColumnPtr> columns = dbf_table->columns();
for (auto it = std::begin(columns); it != std::end(columns); ++it) {
DbfColumnPtr column(*it);
cout << left << setw(17) << column->name();
cout << left << setw(11) << (char)column->type();
cout << left << setw(11) << column->length();
cout << left << column->decimal();
cout << endl;
}
}
else {
dbf_table->to_csv(cout, lowercase_header_names, append_csv_header, append_csv_data);
}
return 0;
}
| 32.762295 | 123 | 0.475106 | [
"vector"
] |
43f0a5f6c59ab8ff7b75618b01ebe646e189b35e | 3,765 | cpp | C++ | CrossApp/network/assets-manager/downloader/Downloader.cpp | AojiaoZero/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | [
"MIT"
] | 794 | 2015-01-01T04:59:48.000Z | 2022-03-09T03:31:13.000Z | CrossApp/network/assets-manager/downloader/Downloader.cpp | AojiaoZero/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | [
"MIT"
] | 83 | 2015-01-04T06:00:35.000Z | 2021-05-20T08:48:38.000Z | CrossApp/network/assets-manager/downloader/Downloader.cpp | AojiaoZero/CrossApp | 1f5375e061bf69841eb19728598f5ae3f508d620 | [
"MIT"
] | 598 | 2015-01-02T02:38:13.000Z | 2022-03-09T03:31:37.000Z |
#include "Downloader.h"
#include "Downloader-curl.h"
#include "platform/CAFileUtils.h"
#define DownloaderImpl DownloaderCURL
NS_CC_BEGIN
DownloadTask::DownloadTask()
{
DLLOG("Construct DownloadTask %p", this);
}
DownloadTask::~DownloadTask()
{
DLLOG("Destruct DownloadTask %p", this);
}
////////////////////////////////////////////////////////////////////////////////
// Implement Downloader
Downloader::Downloader() : Downloader(DownloaderHints{6, 45, ".tmp"}) { }
Downloader::Downloader(const DownloaderHints& hints)
{
DLLOG("Construct Downloader %p", this);
_impl.reset(new DownloaderImpl(hints));
_impl->onTaskProgress = [this](const DownloadTask& task,
int64_t bytesReceived,
int64_t totalBytesReceived,
int64_t totalBytesExpected,
std::function<int64_t(void *buffer, int64_t len)>& /*transferDataToBuffer*/)
{
if (onTaskProgress)
{
onTaskProgress(task, bytesReceived, totalBytesReceived, totalBytesExpected);
}
};
_impl->onTaskFinish = [this](const DownloadTask& task,
int errorCode,
int errorCodeInternal,
const std::string& errorStr,
std::vector<unsigned char>& data)
{
if (DownloadTask::ERROR_NO_ERROR != errorCode)
{
if (onTaskError)
{
onTaskError(task, errorCode, errorCodeInternal, errorStr);
}
return;
}
// success callback
if (task.storagePath.length())
{
if (onFileTaskSuccess)
{
onFileTaskSuccess(task);
}
}
else
{
// data task
if (onDataTaskSuccess)
{
onDataTaskSuccess(task, data);
}
}
};
}
Downloader::~Downloader()
{
DLLOG("Destruct Downloader %p", this);
}
std::shared_ptr<const DownloadTask> Downloader::createDownloadDataTask(const std::string& srcUrl, const std::string& identifier/* = ""*/)
{
DownloadTask *task_ = new (std::nothrow) DownloadTask();
std::shared_ptr<const DownloadTask> task(task_);
do
{
task_->requestURL = srcUrl;
task_->identifier = identifier;
if (0 == srcUrl.length())
{
if (onTaskError)
{
onTaskError(*task, DownloadTask::ERROR_INVALID_PARAMS, 0, "URL or is empty.");
}
task.reset();
break;
}
task_->_coTask.reset(_impl->createCoTask(task));
} while (0);
return task;
}
std::shared_ptr<const DownloadTask> Downloader::createDownloadFileTask(const std::string& srcUrl,
const std::string& storagePath,
const std::string& identifier/* = ""*/)
{
DownloadTask *task_ = new (std::nothrow) DownloadTask();
std::shared_ptr<const DownloadTask> task(task_);
do
{
task_->requestURL = srcUrl;
task_->storagePath = storagePath;
task_->identifier = identifier;
if (0 == srcUrl.length() || 0 == storagePath.length())
{
if (onTaskError)
{
onTaskError(*task, DownloadTask::ERROR_INVALID_PARAMS, 0, "URL or storage path is empty.");
}
task.reset();
break;
}
task_->_coTask.reset(_impl->createCoTask(task));
} while (0);
return task;
}
NS_CC_END;
| 29.186047 | 137 | 0.513147 | [
"vector"
] |
43f31df73fd67a70b78ce092207c784b1c6f58ea | 2,499 | cpp | C++ | src/scripting/ScriptSymbolQueries.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 399 | 2019-01-06T17:55:18.000Z | 2022-03-21T17:41:18.000Z | src/scripting/ScriptSymbolQueries.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 101 | 2019-04-18T21:03:53.000Z | 2022-01-08T13:27:01.000Z | src/scripting/ScriptSymbolQueries.cpp | KirmesBude/REGoth-bs | 2e13dc3b9005744fccd7cea9c7e7cc1f94809e4a | [
"MIT"
] | 56 | 2019-04-10T10:18:27.000Z | 2022-02-08T01:23:31.000Z | #include "ScriptSymbolQueries.hpp"
#include "ScriptSymbolStorage.hpp"
#include "ScriptSymbols.hpp"
namespace REGoth
{
namespace Scripting
{
namespace Queries
{
bs::Vector<SymbolIndex> findAllClasses(const ScriptSymbolStorage& storage)
{
auto isClass = [](const SymbolBase& s) {
return s.type == SymbolType::Class; //
};
return storage.query(isClass);
}
bs::Vector<SymbolIndex> findAllInstancesOfClass(const ScriptSymbolStorage& storage,
const bs::String& className)
{
SymbolClass& classSymbol = storage.getSymbol<SymbolClass>(className);
auto isInstanceOfClass = [&](const SymbolBase& s) {
if (s.type != SymbolType::Instance) return false;
if (s.parent == SYMBOL_INDEX_INVALID) return false;
if (s.parent != classSymbol.index)
{
// If the instances parent is not the class itself, it could be a prototype.
// The prototype then has to have the class as parent.
SymbolBase& parent = storage.getSymbolBase(s.parent);
if (parent.type != SymbolType::Prototype) return false;
if (parent.parent != classSymbol.index) return false;
}
return true;
};
return storage.query(isInstanceOfClass);
}
bs::Vector<SymbolIndex> findAllWithParentOf(const ScriptSymbolStorage& storage,
SymbolIndex parent)
{
auto isMemberVariable = [&](const SymbolBase& s) {
if (s.parent != parent) return false;
if (!s.isClassVar) return false;
return true;
};
return storage.query(isMemberVariable);
}
SymbolIndex findSymbolOfFunctionByAddress(const ScriptSymbolStorage& storage,
bs::UINT32 address)
{
auto isCorrectFunction = [&](const SymbolBase& s) {
if (s.type != SymbolType::ScriptFunction) return false;
const SymbolScriptFunction& fn = (const SymbolScriptFunction&)s;
return fn.address == address;
};
auto result = storage.query(isCorrectFunction);
if (result.empty())
{
return SYMBOL_INDEX_INVALID;
}
else
{
return result[0];
}
}
} // namespace Queries
} // namespace Scripting
} // namespace REGoth
| 30.47561 | 89 | 0.573429 | [
"vector"
] |
43f324c54914fe46a2795e0c2f647f7d1e57c7cc | 7,298 | cc | C++ | ui/gfx/gtk_native_view_id_manager.cc | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | ui/gfx/gtk_native_view_id_manager.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | ui/gfx/gtk_native_view_id_manager.cc | 1065672644894730302/Chromium | 239dd49e906be4909e293d8991e998c9816eaa35 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.000Z | // Copyright (c) 2012 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 "ui/gfx/gtk_native_view_id_manager.h"
#include <gtk/gtk.h>
#include <gdk/gdkx.h>
#include "base/logging.h"
#include "base/rand_util.h"
#include "ui/base/gtk/gtk_compat.h"
#include "ui/base/gtk/gdk_x_compat.h"
#include "ui/gfx/gtk_preserve_window.h"
// -----------------------------------------------------------------------------
// Bounce functions for GTK to callback into a C++ object...
void OnRealize(gfx::NativeView widget, void* arg) {
GtkNativeViewManager* manager = reinterpret_cast<GtkNativeViewManager*>(arg);
manager->OnRealize(widget);
}
void OnUnrealize(gfx::NativeView widget, void *arg) {
GtkNativeViewManager* manager = reinterpret_cast<GtkNativeViewManager*>(arg);
manager->OnUnrealize(widget);
}
static void OnDestroy(GtkObject* obj, void* arg) {
GtkNativeViewManager* manager = reinterpret_cast<GtkNativeViewManager*>(arg);
manager->OnDestroy(reinterpret_cast<GtkWidget*>(obj));
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Public functions...
GtkNativeViewManager::GtkNativeViewManager() {
}
GtkNativeViewManager::~GtkNativeViewManager() {
}
// static
GtkNativeViewManager* GtkNativeViewManager::GetInstance() {
return Singleton<GtkNativeViewManager>::get();
}
gfx::NativeViewId GtkNativeViewManager::GetIdForWidget(gfx::NativeView widget) {
// This is just for unit tests:
if (!widget)
return 0;
base::AutoLock locked(lock_);
std::map<gfx::NativeView, gfx::NativeViewId>::const_iterator i =
native_view_to_id_.find(widget);
if (i != native_view_to_id_.end())
return i->second;
gfx::NativeViewId new_id =
static_cast<gfx::NativeViewId>(base::RandUint64());
while (id_to_info_.find(new_id) != id_to_info_.end())
new_id = static_cast<gfx::NativeViewId>(base::RandUint64());
NativeViewInfo info;
info.widget = widget;
if (gtk_widget_get_realized(widget)) {
GdkWindow *gdk_window = gtk_widget_get_window(widget);
DCHECK(gdk_window);
info.x_window_id = GDK_WINDOW_XID(gdk_window);
}
native_view_to_id_[widget] = new_id;
id_to_info_[new_id] = info;
g_signal_connect(widget, "realize", G_CALLBACK(::OnRealize), this);
g_signal_connect(widget, "unrealize", G_CALLBACK(::OnUnrealize), this);
g_signal_connect(widget, "destroy", G_CALLBACK(::OnDestroy), this);
return new_id;
}
bool GtkNativeViewManager::GetXIDForId(XID* output, gfx::NativeViewId id) {
base::AutoLock locked(lock_);
std::map<gfx::NativeViewId, NativeViewInfo>::const_iterator i =
id_to_info_.find(id);
if (i == id_to_info_.end())
return false;
*output = i->second.x_window_id;
return true;
}
bool GtkNativeViewManager::GetNativeViewForId(gfx::NativeView* output,
gfx::NativeViewId id) {
base::AutoLock locked(lock_);
std::map<gfx::NativeViewId, NativeViewInfo>::const_iterator i =
id_to_info_.find(id);
if (i == id_to_info_.end())
return false;
*output = i->second.widget;
return true;
}
bool GtkNativeViewManager::GetPermanentXIDForId(XID* output,
gfx::NativeViewId id) {
base::AutoLock locked(lock_);
std::map<gfx::NativeViewId, NativeViewInfo>::iterator i =
id_to_info_.find(id);
if (i == id_to_info_.end())
return false;
// We only return permanent XIDs for widgets that allow us to guarantee that
// the XID will not change.
DCHECK(GTK_IS_PRESERVE_WINDOW(i->second.widget));
GtkPreserveWindow* widget =
reinterpret_cast<GtkPreserveWindow*>(i->second.widget);
gtk_preserve_window_set_preserve(widget, TRUE);
*output = GDK_WINDOW_XID(gtk_widget_get_window(i->second.widget));
// Update the reference count on the permanent XID.
PermanentXIDInfo info;
info.widget = widget;
info.ref_count = 1;
std::pair<std::map<XID, PermanentXIDInfo>::iterator, bool> ret =
perm_xid_to_info_.insert(std::make_pair(*output, info));
if (!ret.second) {
DCHECK(ret.first->second.widget == widget);
ret.first->second.ref_count++;
}
return true;
}
bool GtkNativeViewManager::AddRefPermanentXID(XID xid) {
base::AutoLock locked(lock_);
std::map<XID, PermanentXIDInfo>::iterator i =
perm_xid_to_info_.find(xid);
if (i == perm_xid_to_info_.end())
return false;
i->second.ref_count++;
return true;
}
void GtkNativeViewManager::ReleasePermanentXID(XID xid) {
base::AutoLock locked(lock_);
std::map<XID, PermanentXIDInfo>::iterator i =
perm_xid_to_info_.find(xid);
if (i == perm_xid_to_info_.end())
return;
if (i->second.ref_count > 1) {
i->second.ref_count--;
} else {
if (i->second.widget) {
gtk_preserve_window_set_preserve(i->second.widget, FALSE);
} else {
GdkWindow* window = reinterpret_cast<GdkWindow*>(
gdk_x11_window_lookup_for_display(gdk_display_get_default(), xid));
DCHECK(window);
gdk_window_destroy(window);
}
perm_xid_to_info_.erase(i);
}
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
// Private functions...
gfx::NativeViewId GtkNativeViewManager::GetWidgetId(gfx::NativeView widget) {
lock_.AssertAcquired();
std::map<gfx::NativeView, gfx::NativeViewId>::const_iterator i =
native_view_to_id_.find(widget);
CHECK(i != native_view_to_id_.end());
return i->second;
}
void GtkNativeViewManager::OnRealize(gfx::NativeView widget) {
base::AutoLock locked(lock_);
const gfx::NativeViewId id = GetWidgetId(widget);
std::map<gfx::NativeViewId, NativeViewInfo>::iterator i =
id_to_info_.find(id);
CHECK(i != id_to_info_.end());
GdkWindow* gdk_window = gtk_widget_get_window(widget);
CHECK(gdk_window);
i->second.x_window_id = GDK_WINDOW_XID(gdk_window);
}
void GtkNativeViewManager::OnUnrealize(gfx::NativeView widget) {
base::AutoLock locked(lock_);
const gfx::NativeViewId id = GetWidgetId(widget);
std::map<gfx::NativeViewId, NativeViewInfo>::iterator i =
id_to_info_.find(id);
CHECK(i != id_to_info_.end());
}
void GtkNativeViewManager::OnDestroy(gfx::NativeView widget) {
base::AutoLock locked(lock_);
std::map<gfx::NativeView, gfx::NativeViewId>::iterator i =
native_view_to_id_.find(widget);
CHECK(i != native_view_to_id_.end());
std::map<gfx::NativeViewId, NativeViewInfo>::iterator j =
id_to_info_.find(i->second);
CHECK(j != id_to_info_.end());
// If the XID is supposed to outlive the widget, mark it
// in the lookup table.
if (GTK_IS_PRESERVE_WINDOW(widget) &&
gtk_preserve_window_get_preserve(
reinterpret_cast<GtkPreserveWindow*>(widget))) {
std::map<XID, PermanentXIDInfo>::iterator k =
perm_xid_to_info_.find(GDK_WINDOW_XID(gtk_widget_get_window(widget)));
if (k != perm_xid_to_info_.end())
k->second.widget = NULL;
}
native_view_to_id_.erase(i);
id_to_info_.erase(j);
}
// -----------------------------------------------------------------------------
| 28.732283 | 80 | 0.661003 | [
"object"
] |
43f343df39c3db5e51f4900fcbba2bda5a564c99 | 907 | cc | C++ | psdaq/drp/test-mpscqueue.cc | JBlaschke/lcls2 | 30523ef069e823535475d68fa283c6387bcf817b | [
"BSD-3-Clause-LBNL"
] | 16 | 2017-11-09T17:10:56.000Z | 2022-03-09T23:03:10.000Z | psdaq/drp/test-mpscqueue.cc | JBlaschke/lcls2 | 30523ef069e823535475d68fa283c6387bcf817b | [
"BSD-3-Clause-LBNL"
] | 6 | 2017-12-12T19:30:05.000Z | 2020-07-09T00:28:33.000Z | psdaq/drp/test-mpscqueue.cc | JBlaschke/lcls2 | 30523ef069e823535475d68fa283c6387bcf817b | [
"BSD-3-Clause-LBNL"
] | 25 | 2017-09-18T20:02:43.000Z | 2022-03-27T22:27:42.000Z | #include "mpscqueue.hh"
#include <chrono>
#include <fstream>
#include <iostream>
#include <thread>
#include <unistd.h>
#include <vector>
const int N = 1048576;
void producer(MPSCQueue& queue, uint32_t* buffer, int rank)
{
int length = N / 8;
for (int i = 0; i < length; i++) {
int index = i + rank * length;
buffer[index] = index;
queue.push(&buffer[index]);
}
}
int main()
{
int nworkers = 8;
MPSCQueue queue(N);
uint32_t* buffer = new uint32_t[N];
std::vector<std::thread> workers;
for (int i = 0; i < nworkers; i++) {
workers.emplace_back(producer, std::ref(queue), buffer, i);
}
std::ofstream out("test.dat");
for (int i = 0; i < N; i++) {
out << queue.pop()[0] << '\n';
// usleep(10);
}
for (int i = 0; i < nworkers; i++) {
workers[i].join();
}
delete[] buffer;
return 0;
}
| 19.717391 | 67 | 0.545755 | [
"vector"
] |
43f80e44f81705ecdfd39898b14adc4f227086b2 | 16,223 | cpp | C++ | src/Matrix.cpp | nicksacco17/QPU | 29949a6dfe6a43673413925908440138862a3050 | [
"MIT"
] | null | null | null | src/Matrix.cpp | nicksacco17/QPU | 29949a6dfe6a43673413925908440138862a3050 | [
"MIT"
] | null | null | null | src/Matrix.cpp | nicksacco17/QPU | 29949a6dfe6a43673413925908440138862a3050 | [
"MIT"
] | null | null | null |
#include "../include/Matrix.h"
#include "../include/Utility.h"
#include <iostream>
#include <algorithm>
#include <functional>
#include <chrono>
#include <math.h>
#ifdef USE_GPU
#include <cuda_runtime.h>
#include <cusolverDn.h>
#include <cuComplex.h>
#include <cublas_v2.h>
#endif
using std::cout;
using std::endl;
/* ****************************** CONSTRUCTORS ****************************** */
Matrix::Matrix()
{
m_num_row = 2;
m_num_col = 2;
m_dim = 2;
m_mat = { 1, 0, 0, 1 };
m_determinant = 1;
m_trace = 2;
}
Matrix::Matrix(unsigned int in_row, unsigned int in_col)
{
m_num_row = in_row;
m_num_col = in_col;
m_dim = (m_num_row == m_num_col) ? m_num_row : -1;
m_mat = vector<complex<double>>(m_num_row * m_num_col, 0.0);
m_determinant = 9999;
m_trace = 9999;
}
Matrix::Matrix(const vector<vector<complex<double>>>& in_mat)
{
m_num_row = in_mat.size();
m_num_col = in_mat.at(0).size();
m_dim = (m_num_row == m_num_col) ? m_num_row : -1;
for (unsigned int i = 0; i < in_mat.size(); i++)
{
m_mat.insert(m_mat.end(), in_mat.at(i).begin(), in_mat.at(i).end());
}
m_determinant = 9999;
m_trace = 9999;
}
Matrix::Matrix(const vector<complex<double>>& in_vec, unsigned int in_row, unsigned int in_col)
{
m_mat = in_vec;
m_num_row = in_row;
m_num_col = in_col;
}
Matrix::~Matrix()
{
m_mat.clear();
}
/* ************************************************************************** */
/* ******************************* OPERATORS ******************************** */
// Assignment (A = B)
Matrix& Matrix::operator=(const Matrix& mat)
{
if (this != &mat)
{
this->m_num_row = mat.m_num_row;
this->m_num_col = mat.m_num_col;
this->m_mat = mat.m_mat;
}
return *this;
}
// (Strict) Equality (A == B)
bool Matrix::operator==(const Matrix& mat)
{
if (this->m_num_row == mat.m_num_row && this->m_num_col == mat.m_num_col)
{
for (unsigned int i = 0; i < this->m_mat.size(); i++)
{
if (this->m_mat.at(i) != mat.m_mat.at(i))
{
return false;
}
}
}
else
{
return false;
}
return true;
}
// Not Equal (A != B)
bool Matrix::operator!=(const Matrix& mat)
{
return !(*this == mat);
}
// Scalar Addition (A += B)
Matrix& Matrix::operator+=(const Matrix& mat)
{
if (this->m_num_row == mat.m_num_row && this->m_num_col == mat.m_num_col)
{
#ifdef USE_GPU
cout << "GPU MATRIX ADDITION..." << endl;
cudaError_t CUDA_STATUS;
cublasStatus_t CUBLAS_STATUS;
cublasHandle_t CUDA_HANDLE;
cuDoubleComplex* d_MAT_A = NULL;
cuDoubleComplex* d_MAT_B = NULL;
complex<double> alpha = 1.0;
CUDA_STATUS = cudaMalloc((void**)&d_MAT_A, sizeof(complex<double>) * this->m_mat.size());
CUDA_STATUS = cudaMalloc((void**)&d_MAT_B, sizeof(complex<double>) * mat.m_mat.size());
CUBLAS_STATUS = cublasCreate(&CUDA_HANDLE);
CUDA_STATUS = cudaMemcpy(d_MAT_A, this->get_col_order_mat().data(), sizeof(complex<double>) * (this->m_num_row * this->m_num_col), cudaMemcpyHostToDevice);
CUDA_STATUS = cudaMemcpy(d_MAT_B, mat.get_col_order_mat().data(), sizeof(complex<double>) * (mat.m_num_row * mat.m_num_col), cudaMemcpyHostToDevice);
CUBLAS_STATUS = cublasZaxpy(CUDA_HANDLE, (this->m_num_row * this->m_num_col), (cuDoubleComplex*)&alpha, d_MAT_B, 1, d_MAT_A, 1);
CUDA_STATUS = cudaDeviceSynchronize();
CUDA_STATUS = cudaMemcpy(this->m_mat.data(), d_MAT_A, sizeof(complex<double>) * (this->m_num_row * this->m_num_col), cudaMemcpyDeviceToHost);
// NEED TO FIX THIS
this->transpose();
#else
std::transform(this->m_mat.begin(), this->m_mat.end(), mat.m_mat.begin(), this->m_mat.begin(), std::plus<complex<double>>());
#endif
}
return *this;
}
// Scalar Addition (C = A + B)
const Matrix Matrix::operator+(const Matrix& mat) const
{
Matrix TEMP = *this;
TEMP += mat;
return TEMP;
}
// Scalar Subtraction (A -= B)
Matrix& Matrix::operator-=(const Matrix& mat)
{
if (this->m_num_row == mat.m_num_row && this->m_num_col == mat.m_num_col)
{
#ifdef USE_GPU
cout << "GPU MATRIX SUBTRACTION..." << endl;
cudaError_t CUDA_STATUS;
cublasStatus_t CUBLAS_STATUS;
cublasHandle_t CUDA_HANDLE;
cuDoubleComplex* d_MAT_A = NULL;
cuDoubleComplex* d_MAT_B = NULL;
complex<double> alpha = -1.0;
CUDA_STATUS = cudaMalloc((void**)&d_MAT_A, sizeof(complex<double>) * this->m_mat.size());
CUDA_STATUS = cudaMalloc((void**)&d_MAT_B, sizeof(complex<double>) * mat.m_mat.size());
CUBLAS_STATUS = cublasCreate(&CUDA_HANDLE);
CUDA_STATUS = cudaMemcpy(d_MAT_A, this->get_col_order_mat().data(), sizeof(complex<double>) * (this->m_num_row * this->m_num_col), cudaMemcpyHostToDevice);
CUDA_STATUS = cudaMemcpy(d_MAT_B, mat.get_col_order_mat().data(), sizeof(complex<double>) * (mat.m_num_row * mat.m_num_col), cudaMemcpyHostToDevice);
CUBLAS_STATUS = cublasZaxpy(CUDA_HANDLE, (this->m_num_row * this->m_num_col), (cuDoubleComplex*)&alpha, d_MAT_B, 1, d_MAT_A, 1);
CUDA_STATUS = cudaDeviceSynchronize();
CUDA_STATUS = cudaMemcpy(this->m_mat.data(), d_MAT_A, sizeof(complex<double>) * (this->m_num_row * this->m_num_col), cudaMemcpyDeviceToHost);
// NEED TO FIX THIS
this->transpose();
#else
std::transform(this->m_mat.begin(), this->m_mat.end(), mat.m_mat.begin(), this->m_mat.begin(), std::minus<complex<double>>());
#endif
}
return *this;
}
// Scalar Subtraction (C = A - B)
const Matrix Matrix::operator-(const Matrix& mat) const
{
Matrix TEMP = *this;
TEMP -= mat;
return TEMP;
}
// Scalar Multiplication (A *= a)
Matrix& Matrix::operator*=(const complex<double> alpha)
{
#ifdef USE_GPU
cout << "GPU SCALAR MULTIPLICATION..." << endl;
cudaError_t CUDA_STATUS;
cublasStatus_t CUBLAS_STATUS;
cublasHandle_t CUDA_HANDLE;
cuDoubleComplex* d_MAT = NULL;
CUDA_STATUS = cudaMalloc((void**) &d_MAT, sizeof(complex<double>) * m_mat.size());
CUBLAS_STATUS = cublasCreate(&CUDA_HANDLE);
CUDA_STATUS = cudaMemcpy(d_MAT, this->get_col_order_mat().data(), sizeof(complex<double>) * (m_num_row * m_num_col), cudaMemcpyHostToDevice);
CUBLAS_STATUS = cublasZscal(CUDA_HANDLE, m_mat.size(), ((cuDoubleComplex*) &alpha), &d_MAT[0], 1);
CUDA_STATUS = cudaDeviceSynchronize();
CUDA_STATUS = cudaMemcpy(this->m_mat.data(), d_MAT, sizeof(complex<double>) * (m_num_row * m_num_col), cudaMemcpyDeviceToHost);
// NEED TO FIX THIS
this->transpose();
#else
std::transform(this->m_mat.begin(), this->m_mat.end(), this->m_mat.begin(), std::bind1st(std::multiplies<complex<double>>(), alpha));
#endif
return *this;
}
// Scalar Multiplication (B = A * a)
const Matrix Matrix::operator*(const complex<double> alpha) const
{
Matrix TEMP = *this;
TEMP *= alpha;
return TEMP;
}
// Scalar Division (A *= 1/a)
Matrix& Matrix::operator/=(const complex<double> alpha)
{
if (!iszero(alpha))
{
complex<double> inv_alpha = (1.0 / alpha);
#ifdef USE_GPU
cout << "GPU SCALAR DIVISION..." << endl;
cudaError_t CUDA_STATUS;
cublasStatus_t CUBLAS_STATUS;
cublasHandle_t CUDA_HANDLE;
cuDoubleComplex* d_MAT = NULL;
CUDA_STATUS = cudaMalloc((void**) &d_MAT, sizeof(complex<double>) * m_mat.size());
CUBLAS_STATUS = cublasCreate(&CUDA_HANDLE);
CUDA_STATUS = cudaMemcpy(d_MAT, this->get_col_order_mat().data(), sizeof(complex<double>) * (m_num_row * m_num_col), cudaMemcpyHostToDevice);
CUBLAS_STATUS = cublasZscal(CUDA_HANDLE, m_mat.size(), ((cuDoubleComplex*) &inv_alpha), &d_MAT[0], 1);
CUDA_STATUS = cudaDeviceSynchronize();
CUDA_STATUS = cudaMemcpy(this->m_mat.data(), d_MAT, sizeof(complex<double>) * (m_num_row * m_num_col), cudaMemcpyDeviceToHost);
// NEED TO FIX THIS
this->transpose();
#else
if (std::real(alpha) > 1e-10 && std::imag(alpha) > 1e-10)
{
std::transform(this->m_mat.begin(), this->m_mat.end(), this->m_mat.begin(), std::bind1st(std::multiplies<complex<double>>(), inv_alpha));
}
#endif
}
return *this;
}
// Scalar Division (B = A * 1/a)
const Matrix Matrix::operator/(const complex<double> a) const
{
Matrix TEMP = *this;
TEMP /= a;
return TEMP;
}
// Matrix Multiplication (A *= B)
Matrix& Matrix::operator*=(const Matrix& mat)
{
if (this->m_num_col == mat.m_num_row)
{
#ifdef USE_GPU
cout << "MATRIX MULTIPLICATION THROUGH GPU" << endl;
cudaError_t CUDA_STATUS;
cublasStatus_t CUBLAS_STATUS;
cublasHandle_t CUDA_HANDLE;
cuDoubleComplex* d_MAT_A = NULL;
cuDoubleComplex* d_MAT_B = NULL;
complex<double> alpha = 1.0;
complex<double> beta = 0.0;
CUDA_STATUS = cudaMalloc((void**)&d_MAT_A, sizeof(complex<double>) * this->m_mat.size());
CUDA_STATUS = cudaMalloc((void**)&d_MAT_B, sizeof(complex<double>) * mat.m_mat.size());
CUBLAS_STATUS = cublasCreate(&CUDA_HANDLE);
CUDA_STATUS = cudaMemcpy(d_MAT_A, this->get_col_order_mat().data(), sizeof(complex<double>) * (this->m_num_row * this->m_num_col), cudaMemcpyHostToDevice);
CUDA_STATUS = cudaMemcpy(d_MAT_B, mat.get_col_order_mat().data(), sizeof(complex<double>) * (mat.m_num_row * mat.m_num_col), cudaMemcpyHostToDevice);
CUBLAS_STATUS = cublasZgemm(CUDA_HANDLE, CUBLAS_OP_N, CUBLAS_OP_N, this->m_num_row, mat.m_num_col, this->m_num_col, (cuDoubleComplex*)&alpha, d_MAT_A, this->m_num_row, d_MAT_B, mat.m_num_row, (cuDoubleComplex*)&beta, d_MAT_A, this->m_num_row);
//CUBLAS_STATUS = cublasZaxpy(CUDA_HANDLE, (this->m_num_row * this->m_num_col), alpha, d_MAT_B, 1, d_MAT_A, 1);
CUDA_STATUS = cudaDeviceSynchronize();
CUDA_STATUS = cudaMemcpy(this->m_mat.data(), d_MAT_A, sizeof(complex<double>) * (this->m_num_row * this->m_num_col), cudaMemcpyDeviceToHost);
this->m_num_row = this->m_num_row;
this->m_num_col = mat.m_num_col;
// NEED TO FIX THIS
this->transpose();
#else
//if (this != &mat && this->m_num_col == mat.m_num_row)
unsigned int NUM_ELEMENTS = this->m_num_row * mat.m_num_col;
unsigned int COMMON_DIM = this->m_num_col;
vector<complex<double>> NEW_MAT(NUM_ELEMENTS, 0.0);
for (unsigned int i = 0; i < this->m_num_row; i++)
{
for (unsigned int k = 0; k < COMMON_DIM; k++)
{
for (unsigned int j = 0; j < mat.m_num_col; j++)
{
NEW_MAT.at(RC_TO_INDEX(i, j, m_num_col)) += (this->m_mat.at(RC_TO_INDEX(i, k, m_num_col)) * mat.m_mat.at(RC_TO_INDEX(k, j, m_num_col)));
}
}
}
this->m_mat = NEW_MAT;
this->m_num_row = this->m_num_row;
this->m_num_col = mat.m_num_col;
#endif
}
return *this;
}
// Matrix Multiplication (C = A * B)
const Matrix Matrix::operator*(const Matrix& mat) const
{
Matrix TEMP = *this;
TEMP *= mat;
return TEMP;
}
/* ************************************************************************** */
/* ************************** ACCESSORS & MUTATORS ************************** */
complex<double> Matrix::get_element(unsigned int row, unsigned int col) const
{
return m_mat.at(RC_TO_INDEX(row, col, m_num_col));
}
void Matrix::set_element(unsigned int row, unsigned int col, complex<double> in_value)
{
m_mat.at(RC_TO_INDEX(row, col, m_num_col)) = in_value;
}
unsigned int Matrix::get_num_rows() const
{
return m_num_row;
}
unsigned int Matrix::get_num_cols() const
{
return m_num_col;
}
void Matrix::set_dims(unsigned int in_row, unsigned int in_col)
{
m_num_row = in_row;
m_num_col = in_col;
m_dim = (m_num_row == m_num_col) ? m_num_row : -1;
m_mat = vector<complex<double>>(m_num_row * m_num_col, 0.0);
}
vector<complex<double>> Matrix::get_row_order_mat() const
{
return m_mat;
}
vector<complex<double>> Matrix::get_col_order_mat() const
{
vector<complex<double>> COL_MAT;
// For each column
for (unsigned int j = 0; j < m_num_col; j++)
{
// Get all the elements in the row
for (unsigned int i = 0; i < m_num_row; i++)
{
COL_MAT.push_back(m_mat.at(RC_TO_INDEX(i, j, m_num_col)));
}
}
return COL_MAT;
}
vector<vector<complex<double>>> Matrix::get_matrix()
{
return { {1, 0}, {1, 2} };
}
void Matrix::set_matrix(vector<vector<complex<double>>>& in_mat)
{
m_num_row = in_mat.size();
m_num_col = in_mat.at(0).size();
m_dim = (m_num_row == m_num_col) ? m_num_row : -1;
for (unsigned int i = 0; i < in_mat.size(); i++)
{
m_mat.insert(m_mat.end(), in_mat.at(i).begin(), in_mat.at(i).end());
}
m_determinant = 9999;
m_trace = 9999;
}
void Matrix::set_matrix(vector<complex<double>>& in_vec, unsigned int in_row, unsigned int in_col)
{
m_mat = in_vec;
m_num_row = in_row;
m_num_col = in_col;
}
Matrix Matrix::get_submatrix(unsigned int row1, unsigned int row2, unsigned int col1, unsigned int col2)
{
Matrix SUB_MAT;
unsigned int NUM_ROWS = (row2 - row1) + 1;
unsigned int NUM_COLS = (col2 - col1) + 1;
vector<complex<double>> sub_mat_elements;
for (unsigned int i = row1; i <= row2; i++)
{
for (unsigned int j = col1; j <= col2; j++)
{
sub_mat_elements.push_back(this->m_mat[RC_TO_INDEX(i, j, m_num_col)]);
}
}
SUB_MAT.set_matrix(sub_mat_elements, NUM_ROWS, NUM_COLS);
return SUB_MAT;
}
void Matrix::set_submatrix(unsigned int row1, unsigned int row2, unsigned int col1, unsigned int col2, const Matrix& submatrix)
{
unsigned int COL_STRIDE = submatrix.m_num_col;
//cout << RC_TO_INDEX()
for (unsigned int i = row1; i <= row2; i++)
{
for (unsigned int j = col1; j <= col2; j++)
{
//cout << "(i, j) = (" << i - row1 << ", " << j - col1 << ") = " << submatrix.m_mat.at(RC_TO_INDEX(i - row1, j - col1)) << endl;
this->m_mat.at(RC_TO_INDEX(i, j, m_num_col)) = submatrix.m_mat.at(RC_TO_INDEX(i - row1, j - col1, submatrix.m_num_col));
}
}
}
/* ************************************************************************** */
/* ******************************* FUNCTIONS ******************************** */
void Matrix::createIdentityMatrix()
{
m_mat = vector<complex<double>>(m_num_row * m_num_col, 0.0);
if (m_num_row == m_num_col)
{
for (unsigned int k = 0; k < m_num_row; k++)
{
m_mat.at(RC_TO_INDEX(k, k, m_num_col)) = 1;
}
}
}
void Matrix::transpose()
{
unsigned int new_num_row = this->m_num_col;
unsigned int new_num_col = this->m_num_row;
complex<double> TEMP;
// If square matrix
if (m_num_row == m_num_col)
{
for (unsigned int row = 0; row < m_num_row - 1; row++)
{
for (unsigned int col = row + 1; col < m_num_col; col++)
{
TEMP = m_mat.at(RC_TO_INDEX(row, col, m_num_col));
m_mat.at(RC_TO_INDEX(row, col, m_num_col)) = m_mat.at(RC_TO_INDEX(col, row, m_num_col));
m_mat.at(RC_TO_INDEX(col, row, m_num_col)) = TEMP;
}
}
}
// Else if not square
else
{
vector<complex<double>> NEW_MAT(new_num_row * new_num_col, 0.0);
for (unsigned int row = 0; row < m_num_row; row++)
{
for (unsigned int col = 0; col < m_num_col; col++)
{
NEW_MAT.at(RC_TO_INDEX(col, row, new_num_col)) = m_mat.at(RC_TO_INDEX(row, col, m_num_col));
}
}
m_mat = NEW_MAT;
}
m_num_row = new_num_row;
m_num_col = new_num_col;
}
void Matrix::conjugate()
{
}
void Matrix::hermitian_conjugate()
{
}
complex<double> Matrix::get_determinant() const
{
return m_determinant;
}
complex<double> Matrix::get_trace() const
{
return m_trace;
}
/* ************************************************************************** */
/* ******************************** UTILITY ********************************* */
void Matrix::print() const
{
cout << "---------- PRINT MATRIX ----------" << endl;
cout << "DIMENSION: (" << m_num_row << " x " << m_num_col << ")" << endl;
cout << "TRACE: " << m_trace << endl;
cout << "DETERMINANT: " << m_determinant << endl;
cout << "ELEMENTS:\n" << endl;
for (unsigned int i = 0; i < m_num_row; i++)
{
cout << "| ";
for (unsigned int j = 0; j < m_num_col; j++)
{
//cout << "(i, j) = (" << i << ", " << j << ") = " << RC_TO_INDEX(i, j, m_num_col) << endl;
cout << m_mat.at(RC_TO_INDEX(i, j, m_num_col)) << " ";
}
cout << "|" << endl;
}
cout << "\n---------- PRINT MATRIX ----------" << endl;
}
void Matrix::print_shape() const
{
for (unsigned int i = 0; i < m_num_row; i++)
{
cout << "| ";
for (unsigned int j = 0; j < m_num_col; j++)
{
if (iszero_print(m_mat.at(RC_TO_INDEX(i, j, m_num_col))))
{
cout << "0 ";
}
else if (i == j)
{
cout << "+ ";
}
else
{
cout << "* ";
}
}
cout << "|" << endl;
}
}
void Matrix::clear()
{
m_mat = vector<complex<double>>(m_num_row * m_num_col, 0.0);
}
/* ************************************************************************** */ | 25.151938 | 245 | 0.637737 | [
"vector",
"transform"
] |
43f93a93f05e9f51c3e08931d5e4d3d9aa7d2c39 | 26,160 | cxx | C++ | inetsrv/query/query/regacc.cxx | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | inetsrv/query/query/regacc.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | inetsrv/query/query/regacc.cxx | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //+-------------------------------------------------------------------------
//
// Microsoft Windows
// Copyright (C) Microsoft Corporation, 1992 - 2000.
//
// File: RegAcc.cxx
//
// Contents: 'Simple' registry access
//
// History: 21-Dec-93 KyleP Created
//
//--------------------------------------------------------------------------
#include <pch.cxx>
#pragma hdrstop
#include <regacc.hxx>
#include <regevent.hxx>
//+-------------------------------------------------------------------------
//
// Method: CRegNotifyKey::CRegNotifyKey, public
//
// Purpose: A smart pointer to a registry key
//
// History: 07-Jun-94 DwightKr Created
//
//--------------------------------------------------------------------------
inline CRegNotifyKey::CRegNotifyKey( const WCHAR * wcsRegKey )
{
wcscpy( _wcsKey, wcsRegKey );
RtlInitUnicodeString( &_KeyName, _wcsKey );
InitializeObjectAttributes( &_ObjectAttr, // Structure
&_KeyName, // Name
OBJ_CASE_INSENSITIVE, // Attributes
NULL, // Root
NULL ); // Security
}
//+-------------------------------------------------------------------------
//
// Method: CRegChangeEvent::CRegChangeEvent, public
//
// Purpose: Sets up waiting on a registry change event
//
// History: 07-Jun-94 DwightKr Created
//
//--------------------------------------------------------------------------
CRegChangeEvent::CRegChangeEvent( const WCHAR * wcsRegKey,
BOOL fDeferInit ) :
CRegNotifyKey( wcsRegKey ),
_regEvent(TRUE),
_hKey(INVALID_HANDLE_VALUE),
_fDeferInit( fDeferInit ),
_fNotifyEnabled( FALSE )
{
if (!fDeferInit)
Reset();
}
//+-------------------------------------------------------------------------
//
// Method: CRegChangeEvent::~CRegChangeEvent, public
//
// Purpose: Destructs a registry change event
//
// History: 17-Jul-98 dlee Created
//
//--------------------------------------------------------------------------
CRegChangeEvent::~CRegChangeEvent()
{
if ( INVALID_HANDLE_VALUE != _hKey )
{
NtClose( _hKey );
// Wait for the notification to complete if it is enabled.
// It'll write into the IO_STATUS_BLOCK when it aborts due to the
// key close above.
if ( _fNotifyEnabled )
_regEvent.Wait();
}
} //~CRegChangeEvent
//+---------------------------------------------------------------------------
//
// Member: CRegChangeEvent::Register
//
// Synopsis: Closes an existing key handle (if open) and reopens it.
//
// History: 10-08-96 srikants Created
//
//----------------------------------------------------------------------------
void CRegChangeEvent::Register()
{
Win4Assert( !_fNotifyEnabled );
//
// Close previous handle.
//
if ( _hKey != INVALID_HANDLE_VALUE )
{
NtClose( _hKey );
_hKey = INVALID_HANDLE_VALUE;
}
//
// Try to re-open. This sub-optimal behavior works around peculiarities
// in Gibraltar.
//
NTSTATUS Status = NtOpenKey( &_hKey, // Resulting handle
KEY_NOTIFY, // Access requested
&_ObjectAttr);
if ( NT_ERROR( Status ) )
{
ciDebugOut((DEB_ERROR, "NtOpenKey(%ws) failed, rc=0x%x\n",
_wcsKey, Status ));
_hKey = INVALID_HANDLE_VALUE;
}
}
//+-------------------------------------------------------------------------
//
// Method: CRegChangeEvent::Reset, public
//
// Purpose: Sets up waiting on a registry change event
//
// History: 07-Jun-94 DwightKr Created
//
//--------------------------------------------------------------------------
void CRegChangeEvent::Reset()
{
_fNotifyEnabled = FALSE;
_regEvent.Reset();
NTSTATUS Status = STATUS_SUCCESS;
//
// There seems to be some peculiarities with the event based notifies.
// After the first notify, NtNotifyChangeKey returns STATUS_KEY_DELETED
// if we use the same key handle. So, close it and reopen it.
//
Register();
if ( INVALID_HANDLE_VALUE != _hKey )
{
Status = NtNotifyChangeKey( _hKey, // Handle to watch
_regEvent.GetHandle(), // Event to set
NULL, // Optional APC
NULL, // Optional context
&_IoStatus,
REG_NOTIFY_CHANGE_ATTRIBUTES |
REG_NOTIFY_CHANGE_NAME |
REG_NOTIFY_CHANGE_LAST_SET,
TRUE, // Watch tree
NULL, // Buffer
0, // buffer size
TRUE ); // Asynchronous
}
if ( NT_SUCCESS( Status ) )
{
_fNotifyEnabled = TRUE;
}
else
{
ciDebugOut ((DEB_ERROR, "NtNotifyChangeKey failed, rc=0x%x\n", Status ));
}
}
//+-------------------------------------------------------------------------
//
// Method: CRegChangeEvent::Init, public
//
// Purpose: Deferred initialization.
//
// History: 27-Apr-97 KrishnaN Created
//
//--------------------------------------------------------------------------
void CRegChangeEvent::Init()
{
Win4Assert(_fDeferInit);
Reset();
}
//+-------------------------------------------------------------------------
//
// Method: CRegNotify::CRegNotify, public
//
// Purpose: Sets up waiting on a registry change event
//
// History: 07-Jun-94 DwightKr Created
//
//--------------------------------------------------------------------------
CRegNotify::CRegNotify( const WCHAR * wcsRegKey ) :
_fShutdown(FALSE),
_hKey( INVALID_HANDLE_VALUE ),
_refCount( 1 ),
_mtx(),
CRegNotifyKey( wcsRegKey )
{
Register();
}
//+-------------------------------------------------------------------------
//
// Method: CRegNotify::DisableNotification, public
//
// Purpose: Close registry notifcation. Leads to destruction after
// APC completes.
//
// History: 26-Feb-96 KyleP Created
//
//--------------------------------------------------------------------------
void CRegNotify::DisableNotification()
{
{
CLock lck(_mtx);
HANDLE hKey=_hKey;
Win4Assert ( INVALID_HANDLE_VALUE != _hKey );
_fShutdown=TRUE;
if ( INVALID_HANDLE_VALUE != _hKey )
{
_hKey = INVALID_HANDLE_VALUE;
NtClose( hKey );
}
}
Release();
}
//+---------------------------------------------------------------------------
//
// Member: CRegNotify::~CRegNotify, protected
//
// Synopsis: Destructor
//
// History: 2-26-96 KyleP Added header
//
//----------------------------------------------------------------------------
CRegNotify::~CRegNotify()
{
Win4Assert( 0 == _refCount );
Win4Assert( _hKey == INVALID_HANDLE_VALUE );
}
//+---------------------------------------------------------------------------
//
// Member: CRegNotify::AddRef
//
// History: 2-26-96 KyleP Created
//
//----------------------------------------------------------------------------
void CRegNotify::AddRef()
{
InterlockedIncrement(&_refCount);
}
//+---------------------------------------------------------------------------
//
// Member: CRegNotify::Release
//
// Synopsis: If the refcount goes to 0, the object will be deleted.
//
// History: 2-26-96 KyleP Created
//
//----------------------------------------------------------------------------
void CRegNotify::Release()
{
Win4Assert( _refCount > 0 );
if ( InterlockedDecrement(&_refCount) <= 0 )
delete this;
}
//+---------------------------------------------------------------------------
//
// Member: CRegNotify::Register
//
// Synopsis: Re-registers APC
//
// History: 2-26-96 KyleP Added header
//
//----------------------------------------------------------------------------
void CRegNotify::Register()
{
CLock lck(_mtx);
if ( _fShutdown )
return;
//
// Close previous handle.
//
if ( _hKey != INVALID_HANDLE_VALUE )
{
NtClose( _hKey );
_hKey = INVALID_HANDLE_VALUE;
}
//
// Try to re-open. This sub-optimal behavior works around peculiarities
// in Gibraltar.
//
NTSTATUS Status = STATUS_SUCCESS;
Status = NtOpenKey( &_hKey, // Resulting handle
KEY_NOTIFY, // Access requested
&_ObjectAttr);
if ( NT_ERROR( Status ) )
{
ciDebugOut((DEB_ERROR, "NtOpenKey(%ws) failed, rc=0x%x\n", _wcsKey, Status ));
}
if ( _hKey != INVALID_HANDLE_VALUE )
{
Status = NtNotifyChangeKey( _hKey, // Handle to watch
0, // Event to set
APC, // Optional APC
this, // Optional context
&_IoStatus,
REG_NOTIFY_CHANGE_ATTRIBUTES |
REG_NOTIFY_CHANGE_NAME |
REG_NOTIFY_CHANGE_LAST_SET,
TRUE, // Watch tree
NULL, // Buffer
0, // buffer size
TRUE ); // Asynchronous
}
if ( NT_ERROR( Status ) )
{
ciDebugOut ((DEB_ERROR, "NtNotifyChangeKey failed, rc=0x%x\n", Status ));
}
else
AddRef();
}
//+---------------------------------------------------------------------------
//
// Member: CRegNotify::APC
//
// Synopsis: Asynchronous Procedure Call invoked by the system when there
// is a change notification (or related error).
//
// Arguments: [ApcContext] - Pointer to "this"
// [IoStatusBlock] -
// [Reserved] -
//
// History: 2-20-96 KyleP Created
//
//----------------------------------------------------------------------------
void CRegNotify::APC( void * ApcContext,
IO_STATUS_BLOCK * IoStatusBlock,
ULONG Reserved )
{
Win4Assert( 0 != ApcContext );
CRegNotify * pthis = (CRegNotify *)ApcContext;
TRY
{
//
// NTRAID#DB-NTBUG9-84531-2000/07/31-dlee Indexing Service registry notifications don't re-register after errors.
//
if ( NT_ERROR(IoStatusBlock->Status) )
{
ciDebugOut(( DEB_ERROR,
"Error 0x%x during Registry APC processing.\n",
IoStatusBlock->Status ));
}
if ( IoStatusBlock->Status != STATUS_NOTIFY_CLEANUP)
{
if( !NT_ERROR(IoStatusBlock->Status) )
{
pthis->DoIt();
pthis->Register();
}
else
{
ciDebugOut(( DEB_ERROR, "Status 0x%x during Registry APC processing.\n",
IoStatusBlock->Status));
}
}
else
{
Win4Assert(pthis->_fShutdown);
//
// Key closed
//
}
}
CATCH( CException, e )
{
ciDebugOut(( DEB_ERROR, "Exception 0x%x during Registry APC processing.\n",
e.GetErrorCode() ));
}
END_CATCH
pthis->Release();
}
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::CRegAccess, public
//
// Synopsis: Initialize registry access object
//
// Arguments: [ulRelative] -- Position in registry from which [pwcsRegPath]
// begins. See ntrtl.h for constants.
// [pwcsRegPath] -- Path to node.
//
// History: 21-Dec-93 KyleP Created
// 19-Aug-98 KLam Removed END_CONSTRUCTION
//
//--------------------------------------------------------------------------
CRegAccess::CRegAccess( ULONG ulRelative, WCHAR const * pwcsRegPath )
: _ulRelative( ulRelative ),
_wcsPath( 0 )
{
//
// Setup unchanged regtable entries.
//
_regtab[0].DefaultType = REG_NONE;
_regtab[0].DefaultData = 0;
_regtab[0].DefaultLength = 0;
_regtab[0].QueryRoutine = 0;
_regtab[1].QueryRoutine = 0;
_regtab[1].Flags = 0;
int cch = wcslen( pwcsRegPath ) + 1;
WCHAR * wcsPath = _wcsPathBuf;
if( cch > sizeof(_wcsPathBuf)/sizeof(_wcsPathBuf[0]) )
{
_wcsPath = new WCHAR[ cch ];
wcsPath = _wcsPath;
}
memcpy( wcsPath, pwcsRegPath, cch * sizeof(WCHAR) );
}
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::Get, public
//
// Synopsis: Retrive value of specified key from registry.
//
// Arguments: [pwcsKey] -- Key to retrieve value of.
// [wcsVal] -- String stored here.
// [cc] -- Size (in characters) of [wcsVal]
//
// History: 21-Dec-93 KyleP Created
//
// Notes: Key must be string for successful retrieval.
//
//--------------------------------------------------------------------------
void CRegAccess::Get( WCHAR const * pwcsKey, WCHAR * wcsVal, unsigned cc )
{
WCHAR * wcsPath = _wcsPath ? _wcsPath : _wcsPathBuf;
UNICODE_STRING usVal;
usVal.Buffer = wcsVal;
usVal.MaximumLength = (USHORT)(cc*sizeof(WCHAR));
SetName( pwcsKey );
SetEntryContext( &usVal );
NTSTATUS Status = RtlQueryRegistryValues( _ulRelative,
wcsPath,
&_regtab[0],
0,
0 );
if ( NT_ERROR(Status) )
{
ciDebugOut(( DEB_IERROR,
"RtlQueryRegistryValues (...\\%ws %ws) returned 0x%x\n",
wcsPath, pwcsKey, Status ));
QUIETTHROW( CException( Status ) );
}
} //Get
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::CallBackDWORD, public
//
// Synopsis: CallBack function that retrieves a DWORD value
//
// Arguments: [pValueName] -- name of value
// [uValueType] -- type such as REG_MULTI_SZ
// [pValueData] -- data associated with value
// [uValueLength] -- length of valueData
// [context] -- ptr to RTL_QUERY_REGISTRY_TABLE
// [entryContext] -- where the DWORD goes
//
// Returns: NTSTATUS
//
// History: 21-Sep-1998 dlee Created
//
//--------------------------------------------------------------------------
NTSTATUS CRegAccess::CallBackDWORD(
WCHAR * pValueName,
ULONG uValueType,
VOID * pValueData,
ULONG uValueLength,
VOID * pContext,
VOID * pEntryContext )
{
Win4Assert( 0 != pContext );
RTL_QUERY_REGISTRY_TABLE *p = (RTL_QUERY_REGISTRY_TABLE *) pContext;
ciDebugOut(( DEB_ITRACE,
"callback for %ws, type %d, pValueData %#x, defaultData %#x\n",
pValueName, uValueType, pValueData, p->DefaultData ));
if ( REG_DWORD == uValueType )
{
// If there is no value in the registry, return an error
// Note: if there is a default value, NT passes the default value
// in pValueData. pValueData will only be 0 if there is no
// default.
if ( 0 == pValueData )
return STATUS_OBJECT_NAME_NOT_FOUND;
Win4Assert( sizeof DWORD == uValueLength );
// The value is a DWORD and it exists
RtlCopyMemory( pEntryContext, pValueData, sizeof DWORD );
}
else
{
// The type isn't DWORD as expected, so try to use the default.
// If there is no default, return an error
if ( 0 == p->DefaultData )
return STATUS_OBJECT_TYPE_MISMATCH;
// Copy the default value
Win4Assert( sizeof DWORD == p->DefaultLength );
RtlCopyMemory( pEntryContext, p->DefaultData, sizeof DWORD );
}
return STATUS_SUCCESS;
} //CallBackDWORD
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::ReadDWORD, private
//
// Synopsis: Retrive value of specified key from registry, use default if
// key was not present or was of type other than DWORD
//
// Arguments: [pwcsKey] -- Value name
// [pDefaultValue] -- The default value if none exists or
// if the type isn't DWORD. If this is 0,
// an exception is thrown if a DWORD isn't
// found.
//
// Returns: Value of [pwcsKey].
//
// History: 22-Sep-98 dlee created
//
//--------------------------------------------------------------------------
ULONG CRegAccess::ReadDWORD( WCHAR const * pwcsKey, ULONG * pDefaultValue )
{
WCHAR * wcsPath = _wcsPath ? _wcsPath : _wcsPathBuf;
DWORD dwVal;
RTL_QUERY_REGISTRY_TABLE rtab[2];
rtab[0].DefaultType = REG_DWORD;
rtab[0].DefaultLength = sizeof DWORD;
rtab[0].QueryRoutine = CallBackDWORD;
rtab[0].Name = (WCHAR *) pwcsKey;
rtab[0].Flags = RTL_QUERY_REGISTRY_REQUIRED;
rtab[0].EntryContext = &dwVal;
rtab[0].DefaultData = pDefaultValue;
rtab[1].QueryRoutine = 0;
rtab[1].Flags = 0;
NTSTATUS Status = RtlQueryRegistryValues( _ulRelative,
wcsPath,
&rtab[0],
&rtab[0],
0 );
if ( NT_ERROR(Status) )
{
if ( STATUS_OBJECT_NAME_NOT_FOUND == Status &&
0 != pDefaultValue )
dwVal = *pDefaultValue;
else
{
ciDebugOut(( DEB_IERROR,
"RtlQueryRegistryValues (...\\%ws %ws) returned 0x%x\n",
wcsPath, pwcsKey, Status ));
THROW( CException( Status ) );
}
}
return dwVal;
} //Read
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::Get, public
//
// Synopsis: Retrive value of specified key from registry. Throws if the
// value doesn't exist or is of type other than DWORD.
//
// Arguments: [pwcsKey] -- Key to retrieve value of.
//
// Returns: Value of [pwcsKey].
//
// History: 21-Dec-93 KyleP Created
//
// Notes: Key must be dword for successful retrieval.
//
//--------------------------------------------------------------------------
ULONG CRegAccess::Get( WCHAR const * pwcsKey )
{
return ReadDWORD( pwcsKey, 0 );
} //Get
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::Read, public
//
// Synopsis: Retrive value of specified key from registry, use default if
// key was not present or was of type other than DWORD
//
// Arguments: [pwcsKey] -- Key to retrieve value of.
// [ulDefaultValue] -- Default value if not found
//
// Returns: Value of [pwcsKey].
//
// History: 13-Jun-94 DwightKr Created
//
// Notes: Key must be dword for successful retrieval.
//
//--------------------------------------------------------------------------
ULONG CRegAccess::Read( WCHAR const * pwcsKey, ULONG ulDefaultValue )
{
return ReadDWORD( pwcsKey, &ulDefaultValue );
} //Read
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::CallBack, public
//
// Synopsis: CallBack function that casts Context to CRegCallBack and
// then calls CRegCallBack::CallBack
//
// Arguments: [pValueName] -- name of value
// [uValueType] -- type such as REG_MULTI_SZ
// [pValueData] -- data associated with value
// [uVvalueLength] -- length of valueData
// [pContext] -- ptr to CRegCallBack
// [pEntryContext] -- ignored
//
// Returns: status
//
// History: 29-Aug-1994 SitaramR Created
//
//--------------------------------------------------------------------------
NTSTATUS CRegAccess::CallBack(WCHAR *pValueName, ULONG uValueType,
VOID *pValueData, ULONG uValueLength,
VOID *pContext, VOID *pEntryContext )
{
NTSTATUS status = ( (CRegCallBack *) pContext)->CallBack( pValueName,
uValueType,
pValueData,
uValueLength );
return status;
}
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::EnumerateValues, public
//
// Synopsis: Enumerate (REG_MULTI_SZ) values of a given key. Call the
// callback routine passing each such enumerated value.
//
// Arguments: [wszValue] -- value to be enumerated
// [regCallBack] -- callback class
//
// History: 15-Aug-1994 SitaramR Created
//
//--------------------------------------------------------------------------
void CRegAccess::EnumerateValues( WCHAR *wszValue,
CRegCallBack& regCallBack )
{
WCHAR * wcsPath = _wcsPath ? _wcsPath : _wcsPathBuf;
NTSTATUS status;
SetName( wszValue );
SetEntryContext( 0 );
_regtab[0].QueryRoutine = CRegAccess::CallBack;
status = RtlQueryRegistryValues( _ulRelative,
wcsPath,
&_regtab[0],
®CallBack,
0 );
if ( NT_ERROR(status) && STATUS_OBJECT_NAME_NOT_FOUND != status )
{
ciDebugOut(( DEB_ITRACE,
"RtlQueryRegistryValues(..%ws) returned 0x%x\n",
wcsPath, status ));
QUIETTHROW( CException( status ) );
}
}
//+-------------------------------------------------------------------------
//
// Member: CRegAccess::Read, public
//
// Synopsis: Retrive value of specified key from registry, use default if
// key was not present
//
// Arguments: [pwcsKey] -- Key to retrieve value of.
// [pwcsDefaultValue] -- Default value if not found
//
// Returns: Value of [pwcsKey].
//
// History: 18-Aug-98 KLam Created header
//
// Notes: Key must be a string for successful retrieval.
//
//--------------------------------------------------------------------------
WCHAR * CRegAccess::Read( WCHAR const * pwcsKey, WCHAR const * pwcsDefaultValue )
{
WCHAR * wcsPath = _wcsPath ? _wcsPath : _wcsPathBuf;
UNICODE_STRING usVal;
SetName( pwcsKey );
SetEntryContext( &usVal );
usVal.Length = 50 * sizeof(WCHAR);
usVal.Buffer = 0;
NTSTATUS Status = STATUS_BUFFER_TOO_SMALL;
while ( Status == STATUS_BUFFER_TOO_SMALL )
{
// could cause a delete before any call to new
if ( 0 != usVal.Buffer )
delete [] usVal.Buffer;
usVal.Length *= 2;
usVal.MaximumLength = usVal.Length;
usVal.Buffer = new WCHAR[ usVal.Length/sizeof(WCHAR) ];
Status = RtlQueryRegistryValues( _ulRelative,
wcsPath,
&_regtab[0],
0,
0 );
}
WCHAR * pwcs = 0;
if ( NT_ERROR(Status) )
{
if ( 0 != usVal.Buffer )
delete [] usVal.Buffer;
usVal.Buffer = 0;
if ( Status == STATUS_OBJECT_NAME_NOT_FOUND )
{
unsigned cc = wcslen(pwcsDefaultValue) + 1;
pwcs = new WCHAR[cc];
memcpy( pwcs, pwcsDefaultValue, cc*sizeof(WCHAR) );
}
else
{
ciDebugOut(( DEB_IERROR,
"RtlQueryRegistryValues (...\\%ws %ws) returned 0x%x\n",
wcsPath, pwcsKey, Status ));
THROW( CException( Status ) );
}
}
else
{
//
// Copy string to new heap
//
pwcs = usVal.Buffer;
usVal.Buffer = 0;
}
return pwcs;
} //Read
| 31.068884 | 122 | 0.434289 | [
"object"
] |
43f94e4e64027b388fca0523588f307ec719e035 | 579 | hpp | C++ | include/Pancake/Graphics/Image.hpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | include/Pancake/Graphics/Image.hpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | include/Pancake/Graphics/Image.hpp | Dante12129/Pancake | 35282814e2f3b2d5e155a539ca5ddee32e240d3e | [
"Zlib"
] | null | null | null | #ifndef IMAGE_HPP
#define IMAGE_HPP
#include <cstdint>
#include <string>
#include <vector>
#include <SDL2/SDL_surface.h>
#include <glm/vec2.hpp>
namespace pcke
{
class Image
{
public:
bool loadFromFile(const std::string& file);
bool loadFromSurface(SDL_Surface* surface);
glm::uvec2 getSize() const;
const std::uint8_t* getPixels() const;
private:
bool created_ = false;
std::vector<std::uint8_t> data_;
glm::uvec2 size_;
};
}
#endif // IMAGE_HPP
| 18.09375 | 55 | 0.576857 | [
"vector"
] |
43fdc1bb4f8779508814e0e1a3009668a4183571 | 10,572 | cpp | C++ | ext/openMVG/software/SfM/main_IncrementalSfM2.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 90 | 2019-05-19T03:48:23.000Z | 2022-02-02T15:20:49.000Z | ext/openMVG/software/SfM/main_IncrementalSfM2.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 11 | 2019-05-22T07:45:46.000Z | 2021-05-20T01:48:26.000Z | ext/openMVG/software/SfM/main_IncrementalSfM2.cpp | bitlw/EGSfM | d5b4260d38237c6bd814648cadcf1fcf2f8f5d31 | [
"BSD-3-Clause"
] | 18 | 2019-05-19T03:48:32.000Z | 2021-05-29T18:19:16.000Z | // This file is part of OpenMVG, an Open Multiple View Geometry C++ library.
// Copyright (c) 2018 Pierre MOULON.
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "openMVG/cameras/Camera_Common.hpp"
#include "openMVG/cameras/Cameras_Common_command_line_helper.hpp"
#include "openMVG/sfm/pipelines/sequential/sequential_SfM2.hpp"
#include "openMVG/sfm/pipelines/sequential/SfmSceneInitializerMaxPair.hpp"
#include "openMVG/sfm/pipelines/sequential/SfmSceneInitializerStellar.hpp"
#include "openMVG/sfm/pipelines/sfm_features_provider.hpp"
#include "openMVG/sfm/pipelines/sfm_matches_provider.hpp"
#include "openMVG/sfm/sfm_data.hpp"
#include "openMVG/sfm/sfm_data_io.hpp"
#include "openMVG/sfm/sfm_report.hpp"
#include "openMVG/sfm/sfm_view.hpp"
#include "openMVG/system/timer.hpp"
#include "openMVG/types.hpp"
#include "third_party/cmdLine/cmdLine.h"
#include "third_party/stlplus3/filesystemSimplified/file_system.hpp"
#include <cstdlib>
#include <memory>
#include <string>
#include <utility>
enum class ESfMSceneInitializer
{
INITIALIZE_EXISTING_POSES,
INITIALIZE_MAX_PAIR,
INITIALIZE_AUTO_PAIR,
INITIALIZE_STELLAR
};
bool StringToEnum_ESfMSceneInitializer
(
const std::string & str,
ESfMSceneInitializer & scene_initializer
)
{
const std::map<std::string, ESfMSceneInitializer> string_to_enum_mapping =
{
{"EXISTING_POSE", ESfMSceneInitializer::INITIALIZE_EXISTING_POSES},
{"MAX_PAIR", ESfMSceneInitializer::INITIALIZE_MAX_PAIR},
{"AUTO_PAIR", ESfMSceneInitializer::INITIALIZE_AUTO_PAIR},
{"STELLAR", ESfMSceneInitializer::INITIALIZE_STELLAR},
};
auto it = string_to_enum_mapping.find(str);
if (it == string_to_enum_mapping.end())
return false;
scene_initializer = it->second;
return true;
}
using namespace openMVG;
using namespace openMVG::cameras;
using namespace openMVG::sfm;
int main(int argc, char **argv)
{
using namespace std;
std::cout << "Sequential/Incremental reconstruction (Engine 2)" << std::endl
<< std::endl;
CmdLine cmd;
std::string sSfM_Data_Filename;
std::string sMatchesDir, sMatchFilename;
std::string sOutDir = "";
std::string sIntrinsic_refinement_options = "ADJUST_ALL";
std::string sSfMInitializer_method = "STELLAR";
int i_User_camera_model = PINHOLE_CAMERA_RADIAL3;
bool b_use_motion_priors = false;
cmd.add( make_option('i', sSfM_Data_Filename, "input_file") );
cmd.add( make_option('m', sMatchesDir, "matchdir") );
cmd.add( make_option('M', sMatchFilename, "match_file") );
cmd.add( make_option('o', sOutDir, "outdir") );
cmd.add( make_option('c', i_User_camera_model, "camera_model") );
cmd.add( make_option('f', sIntrinsic_refinement_options, "refineIntrinsics") );
cmd.add( make_option('S', sSfMInitializer_method, "sfm_initializer") );
cmd.add( make_switch('P', "prior_usage") );
try {
if (argc == 1) throw std::string("Invalid parameter.");
cmd.process(argc, argv);
} catch (const std::string& s) {
std::cerr << "Usage: " << argv[0] << '\n'
<< "[-i|--input_file] path to a SfM_Data scene\n"
<< "[-m|--matchdir] path to the matches that corresponds to the provided SfM_Data scene\n"
<< "[-o|--outdir] path where the output data will be stored\n"
<< "\n[Optional]\n"
<< "[-c|--camera_model] Camera model type for view with unknown intrinsic:\n"
<< "\t 1: Pinhole \n"
<< "\t 2: Pinhole radial 1\n"
<< "\t 3: Pinhole radial 3 (default)\n"
<< "\t 4: Pinhole radial 3 + tangential 2\n"
<< "\t 5: Pinhole fisheye\n"
<< "[-S|--sfm_initializer] Choose the SfM initializer method:\n"
<< "\t 'EXISTING_POSE'-> Initialize the reconstruction from the existing sfm_data camera poses\n"
<< "\t 'MAX_PAIR'-> Initialize the reconstruction from the pair that has the most of matches\n"
<< "\t 'AUTO_PAIR'-> Initialize the reconstruction with a pair selected automatically\n"
<< "\t 'STELLAR'-> Initialize the reconstruction with a 'stellar' reconstruction.\n"
<< "[-f|--refineIntrinsics] Intrinsic parameters refinement option\n"
<< "\t ADJUST_ALL -> refine all existing parameters (default) \n"
<< "\t NONE -> intrinsic parameters are held as constant\n"
<< "\t ADJUST_FOCAL_LENGTH -> refine only the focal length\n"
<< "\t ADJUST_PRINCIPAL_POINT -> refine only the principal point position\n"
<< "\t ADJUST_DISTORTION -> refine only the distortion coefficient(s) (if any)\n"
<< "\t -> NOTE: options can be combined thanks to '|'\n"
<< "\t ADJUST_FOCAL_LENGTH|ADJUST_PRINCIPAL_POINT\n"
<< "\t\t-> refine the focal length & the principal point position\n"
<< "\t ADJUST_FOCAL_LENGTH|ADJUST_DISTORTION\n"
<< "\t\t-> refine the focal length & the distortion coefficient(s) (if any)\n"
<< "\t ADJUST_PRINCIPAL_POINT|ADJUST_DISTORTION\n"
<< "\t\t-> refine the principal point position & the distortion coefficient(s) (if any)\n"
<< "[-P|--prior_usage] Enable usage of motion priors (i.e GPS positions) (default: false)\n"
<< "[-M|--match_file] path to the match file to use.\n"
<< std::endl;
std::cerr << s << std::endl;
return EXIT_FAILURE;
}
if ( !isValid(openMVG::cameras::EINTRINSIC(i_User_camera_model)) ) {
std::cerr << "\n Invalid camera type" << std::endl;
return EXIT_FAILURE;
}
const cameras::Intrinsic_Parameter_Type intrinsic_refinement_options =
cameras::StringTo_Intrinsic_Parameter_Type(sIntrinsic_refinement_options);
if (intrinsic_refinement_options == static_cast<cameras::Intrinsic_Parameter_Type>(0) )
{
std::cerr << "Invalid input for the Bundle Adjusment Intrinsic parameter refinement option" << std::endl;
return EXIT_FAILURE;
}
ESfMSceneInitializer scene_initializer_enum;
if (!StringToEnum_ESfMSceneInitializer(sSfMInitializer_method, scene_initializer_enum))
{
std::cerr << "Invalid input for the SfM initializer option" << std::endl;
return EXIT_FAILURE;
}
// Load input SfM_Data scene
SfM_Data sfm_data;
if (!Load(sfm_data, sSfM_Data_Filename, ESfM_Data(VIEWS|INTRINSICS|EXTRINSICS))) {
std::cerr << std::endl
<< "The input SfM_Data file \""<< sSfM_Data_Filename << "\" cannot be read." << std::endl;
return EXIT_FAILURE;
}
// Init the regions_type from the image describer file (used for image regions extraction)
using namespace openMVG::features;
const std::string sImage_describer = stlplus::create_filespec(sMatchesDir, "image_describer", "json");
std::unique_ptr<Regions> regions_type = Init_region_type_from_file(sImage_describer);
if (!regions_type)
{
std::cerr << "Invalid: "
<< sImage_describer << " regions type file." << std::endl;
return EXIT_FAILURE;
}
// Features reading
std::shared_ptr<Features_Provider> feats_provider = std::make_shared<Features_Provider>();
if (!feats_provider->load(sfm_data, sMatchesDir, regions_type)) {
std::cerr << std::endl
<< "Invalid features." << std::endl;
return EXIT_FAILURE;
}
// Matches reading
std::shared_ptr<Matches_Provider> matches_provider = std::make_shared<Matches_Provider>();
if // Try to read the provided match filename or the default one (matches.f.txt/bin)
(
!(matches_provider->load(sfm_data, sMatchFilename) ||
matches_provider->load(sfm_data, stlplus::create_filespec(sMatchesDir, "matches.f.txt")) ||
matches_provider->load(sfm_data, stlplus::create_filespec(sMatchesDir, "matches.f.bin")))
)
{
std::cerr << std::endl
<< "Invalid matches file." << std::endl;
return EXIT_FAILURE;
}
if (sOutDir.empty()) {
std::cerr << "\nIt is an invalid output directory" << std::endl;
return EXIT_FAILURE;
}
if (!stlplus::folder_exists(sOutDir))
{
if (!stlplus::folder_create(sOutDir))
{
std::cerr << "\nCannot create the output directory" << std::endl;
}
}
//---------------------------------------
// Sequential reconstruction process
//---------------------------------------
openMVG::system::Timer timer;
std::unique_ptr<SfMSceneInitializer> scene_initializer;
switch(scene_initializer_enum)
{
case ESfMSceneInitializer::INITIALIZE_AUTO_PAIR:
std::cerr << "Not yet implemented." << std::endl;
return EXIT_FAILURE;
break;
case ESfMSceneInitializer::INITIALIZE_MAX_PAIR:
scene_initializer.reset(new SfMSceneInitializerMaxPair(sfm_data,
feats_provider.get(),
matches_provider.get()));
break;
case ESfMSceneInitializer::INITIALIZE_EXISTING_POSES:
scene_initializer.reset(new SfMSceneInitializer(sfm_data,
feats_provider.get(),
matches_provider.get()));
break;
case ESfMSceneInitializer::INITIALIZE_STELLAR:
scene_initializer.reset(new SfMSceneInitializerStellar(sfm_data,
feats_provider.get(),
matches_provider.get()));
break;
default:
return EXIT_FAILURE;
}
if (!scene_initializer)
{
std::cerr << "Invalid scene initializer." << std::endl;
return EXIT_FAILURE;
}
SequentialSfMReconstructionEngine2 sfmEngine(
scene_initializer.get(),
sfm_data,
sOutDir,
stlplus::create_filespec(sOutDir, "Reconstruction_Report.html"));
// Configure the features_provider & the matches_provider
sfmEngine.SetFeaturesProvider(feats_provider.get());
sfmEngine.SetMatchesProvider(matches_provider.get());
// Configure reconstruction parameters
sfmEngine.Set_Intrinsics_Refinement_Type(intrinsic_refinement_options);
sfmEngine.SetUnknownCameraType(EINTRINSIC(i_User_camera_model));
b_use_motion_priors = cmd.used('P');
sfmEngine.Set_Use_Motion_Prior(b_use_motion_priors);
if (sfmEngine.Process())
{
std::cout << std::endl << " Total Ac-Sfm took (s): " << timer.elapsed() << std::endl;
std::cout << "...Generating SfM_Report.html" << std::endl;
Generate_SfM_Report(sfmEngine.Get_SfM_Data(),
stlplus::create_filespec(sOutDir, "SfMReconstruction_Report.html"));
//-- Export to disk computed scene (data & visualizable results)
std::cout << "...Export SfM_Data to disk." << std::endl;
Save(sfmEngine.Get_SfM_Data(),
stlplus::create_filespec(sOutDir, "sfm_data", ".bin"),
ESfM_Data(ALL));
Save(sfmEngine.Get_SfM_Data(),
stlplus::create_filespec(sOutDir, "cloud_and_poses", ".ply"),
ESfM_Data(ALL));
return EXIT_SUCCESS;
}
return EXIT_FAILURE;
}
| 38.166065 | 109 | 0.699205 | [
"geometry",
"model"
] |
a1000544f38f49953e9b4aca6316117f44ccc18b | 1,059 | hpp | C++ | include/CoreLib/NetworkSessionManager.hpp | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | null | null | null | include/CoreLib/NetworkSessionManager.hpp | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | null | null | null | include/CoreLib/NetworkSessionManager.hpp | AntoineJT/BurgWar | 8e435bd58dda0610d7dfc3ba6d313bd443c9b4b8 | [
"MIT"
] | null | null | null | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#pragma once
#ifndef BURGWAR_SERVER_NETWORKSESSIONMANAGER_HPP
#define BURGWAR_SERVER_NETWORKSESSIONMANAGER_HPP
#include <CoreLib/NetworkReactor.hpp>
#include <CoreLib/SessionManager.hpp>
#include <Nazara/Core/MemoryPool.hpp>
#include <vector>
namespace bw
{
class MatchClientSession;
class MatchSessions;
class NetworkSessionManager : public SessionManager
{
public:
NetworkSessionManager(MatchSessions* owner, Nz::UInt16 port, std::size_t maxClient);
~NetworkSessionManager();
void Poll() override;
private:
void HandlePeerConnection(bool outgoing, std::size_t peerId, Nz::UInt32 data);
void HandlePeerDisconnection(std::size_t peerId, Nz::UInt32 data);
void HandlePeerPacket(std::size_t peerId, Nz::NetPacket&& packet);
std::vector<MatchClientSession*> m_peerIdToSession;
NetworkReactor m_reactor;
};
}
#include <CoreLib/NetworkSessionManager.inl>
#endif
| 25.829268 | 87 | 0.778093 | [
"vector"
] |
a108bb3dd61657bfb823df0a63400daf7c838649 | 2,116 | cpp | C++ | lib/async/src/net/Connection.cpp | astateful/dyplat | 37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44 | [
"BSD-3-Clause"
] | null | null | null | lib/async/src/net/Connection.cpp | astateful/dyplat | 37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44 | [
"BSD-3-Clause"
] | null | null | null | lib/async/src/net/Connection.cpp | astateful/dyplat | 37c37c7ee9f55cc2a3abaa0f8ebbde34588d2f44 | [
"BSD-3-Clause"
] | null | null | null | #include "astateful/async/net/Connection.hpp"
namespace astateful {
namespace async {
namespace net {
Connection::Connection() :
m_flag( flag_e::RECV ),
async::Connection() {}
Connection::Connection( const std::vector<uint8_t>& buffer ) :
m_flag( flag_e::SEND ),
async::Connection( buffer ) {
m_wsa_buf.len = static_cast<ULONG>( m_buffer.size() );
m_wsa_buf.buf = reinterpret_cast<char *>( m_buffer.data() );
}
bool Connection::update( DWORD transferred,
const async::pipe::client::Engine& pipe ) {
switch ( m_flag ) {
case flag_e::RECV: return recvEvent( transferred, pipe ); break;
case flag_e::SEND: return sendEvent( transferred, pipe ); break;
}
return false;
}
bool Connection::transfer( SOCKET socket,
const pipe::client::Engine& pipe ) {
ZeroMemory( &overlapped, sizeof( WSAOVERLAPPED ) );
// This branch will create a new socket operation depending on the new
// value of the flag.
if ( m_flag == flag_e::SEND ) {
if ( !send( socket ) )
{
int x = WSAGetLastError();
return false;
}
} else if ( m_flag == flag_e::RECV ) {
if ( !recv( socket ) ) {
int x = WSAGetLastError();
return false;
}
}
return true;
}
bool Connection::recv( SOCKET socket )
{
DWORD flag = 0;
if ( WSARecv( socket,
&m_wsa_buf,
1,
nullptr,
&flag,
&overlapped,
nullptr
) == SOCKET_ERROR ) {
if ( WSAGetLastError() != ERROR_IO_PENDING ) return false;
}
return true;
}
bool Connection::send( SOCKET socket )
{
DWORD flag = 0;
if ( WSASend( socket,
&m_wsa_buf,
1,
nullptr,
flag,
&overlapped,
nullptr
) == SOCKET_ERROR ) {
if ( WSAGetLastError() != ERROR_IO_PENDING ) return false;
}
return true;
}
}
}
}
| 24.045455 | 74 | 0.523157 | [
"vector"
] |
a10cec2ce7a8364c9c95f33fb65d66fb5a7755ca | 2,935 | cpp | C++ | src/gct/acceleration_structure_geometry_triangles_data.cpp | Fadis/gct | bde211f9336e945e4db21f5abb4ce01dcad78049 | [
"MIT"
] | 1 | 2022-03-03T09:27:09.000Z | 2022-03-03T09:27:09.000Z | src/gct/acceleration_structure_geometry_triangles_data.cpp | Fadis/gct | bde211f9336e945e4db21f5abb4ce01dcad78049 | [
"MIT"
] | 1 | 2021-12-02T03:45:45.000Z | 2021-12-03T23:44:37.000Z | src/gct/acceleration_structure_geometry_triangles_data.cpp | Fadis/gct | bde211f9336e945e4db21f5abb4ce01dcad78049 | [
"MIT"
] | null | null | null | #include <iostream>
#include <gct/acceleration_structure_geometry_triangles_data.hpp>
#ifdef VK_KHR_ACCELERATION_STRUCTURE_EXTENSION_NAME
#include <variant>
#include <memory>
#include <optional>
#include <vulkan/vulkan.hpp>
#include <nlohmann/json_fwd.hpp>
#include <gct/extension.hpp>
#include <gct/device_or_host_address_const.hpp>
#include <vulkan2json/AccelerationStructureGeometryTrianglesDataKHR.hpp>
#ifdef VK_NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME
#include <vulkan2json/AccelerationStructureGeometryMotionTrianglesDataNV.hpp>
#endif
namespace gct {
acceleration_structure_geometry_triangles_data_t &acceleration_structure_geometry_triangles_data_t::rebuild_chain() {
if( chained ) return *this;
if( vertex_data )
vertex_data.rebuild_chain();
if( index_data )
index_data.rebuild_chain();
if( transform_data )
transform_data.rebuild_chain();
{
auto basic = get_basic();
if( vertex_data ) {
basic.setVertexData( *vertex_data );
}
if( index_data )
basic.setIndexData( *index_data );
if( transform_data )
basic.setTransformData( *transform_data );
set_basic( std::move( basic ) );
}
LIBGCT_EXTENSION_BEGIN_REBUILD_CHAIN
#ifdef VK_NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME
LIBGCT_EXTENSION_REBUILD_CHAIN( motion )
#endif
LIBGCT_EXTENSION_END_REBUILD_CHAIN
}
acceleration_structure_geometry_triangles_data_t &acceleration_structure_geometry_triangles_data_t::set_vertex_data( const device_or_host_address_const_t &v ) {
vertex_data = v;
chained = false;
return *this;
}
acceleration_structure_geometry_triangles_data_t &acceleration_structure_geometry_triangles_data_t::clear_vertex_data() {
vertex_data.reset();
chained = false;
return *this;
}
acceleration_structure_geometry_triangles_data_t &acceleration_structure_geometry_triangles_data_t::set_index_data( const device_or_host_address_const_t &v ) {
index_data = v;
chained = false;
return *this;
}
acceleration_structure_geometry_triangles_data_t &acceleration_structure_geometry_triangles_data_t::clear_index_data() {
index_data.reset();
chained = false;
return *this;
}
acceleration_structure_geometry_triangles_data_t &acceleration_structure_geometry_triangles_data_t::set_transform_data( const device_or_host_address_const_t &v ) {
transform_data = v;
chained = false;
return *this;
}
acceleration_structure_geometry_triangles_data_t &acceleration_structure_geometry_triangles_data_t::clear_transform_data() {
transform_data.reset();
chained = false;
return *this;
}
void to_json( nlohmann::json &root, const acceleration_structure_geometry_triangles_data_t &v ) {
root = nlohmann::json::object();
root[ "basic" ] = v.get_basic();
#ifdef VK_NV_RAY_TRACING_MOTION_BLUR_EXTENSION_NAME
LIBGCT_EXTENSION_TO_JSON( motion )
#endif
}
}
#endif
| 35.361446 | 165 | 0.772743 | [
"object"
] |
a10d4fadcff541344862e7b671255ed1e566df9f | 8,436 | cc | C++ | src/c++/latency/latency.cc | seemk/demikernel | 69b047add66c196d152660449099b17d452eb7d5 | [
"MIT"
] | null | null | null | src/c++/latency/latency.cc | seemk/demikernel | 69b047add66c196d152660449099b17d452eb7d5 | [
"MIT"
] | null | null | null | src/c++/latency/latency.cc | seemk/demikernel | 69b047add66c196d152660449099b17d452eb7d5 | [
"MIT"
] | null | null | null | // -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*-
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#include <dmtr/latency.h>
#include <algorithm>
#include <boost/chrono.hpp>
#include <cassert>
#include <dmtr/annot.h>
#include <dmtr/fail.h>
#include <stdint.h>
#include <string>
#include <vector>
// The number of the maximum distribution type. Since we use
// characters as distribution types, this is 127. We could probably
// shift things down by 32 to save some space, but that's probably not
// worth anything.
#define LATENCY_MAX_DIST 127
// The maximum number of unique distribution types in a single latency
// distribution.
#define LATENCY_DIST_POOL_SIZE 5
// The width of a printed histogram in characters.
#define LATENCY_HISTOGRAM_WIDTH 50
// The number of histogram buckets.
#define LATENCY_NUM_BUCKETS 65
// The maximum number of iterations we will record latencies for
#define MAX_ITERATIONS 1000000
typedef boost::chrono::duration<uint64_t, boost::nano> duration_type;
typedef struct Latency_Dist_t
{
uint64_t min, max, total, count;
uint32_t buckets[LATENCY_NUM_BUCKETS];
char type;
} Latency_Dist_t;
typedef struct dmtr_latency
{
std::string name;
Latency_Dist_t *dists[LATENCY_MAX_DIST];
Latency_Dist_t distPool[LATENCY_DIST_POOL_SIZE];
int distPoolNext = 0;
std::vector<uint64_t> latencies;
} dmtr_latency_t;
static inline void
LatencyAddStat(dmtr_latency_t *l, char type, uint64_t val)
{
//if (l->latencies.size() == 0)
if (l->latencies.size() < MAX_ITERATIONS)
l->latencies.push_back(val);
}
static inline Latency_Dist_t *
LatencyAddHist(dmtr_latency_t *l, char type, uint64_t val, uint32_t count)
{
if (!l->dists[(int)type]) {
if (l->distPoolNext == LATENCY_DIST_POOL_SIZE) {
DMTR_PANIC("Too many distributions; maybe increase "
"LATENCY_DIST_POOL_SIZE");
}
l->dists[(int)type] = &l->distPool[l->distPoolNext++];
l->dists[(int)type]->type = type;
}
Latency_Dist_t *d = l->dists[(int)type];
int bucket = 0;
val >>= 1;
while (val) {
val >>= 1;
++bucket;
}
assert(bucket < LATENCY_NUM_BUCKETS);
d->buckets[bucket] += count;
return d;
}
static void
LatencyAdd(dmtr_latency_t *l, char type, uint64_t val)
{
Latency_Dist_t *d = LatencyAddHist(l, type, val, 1);
LatencyAddStat(l, type, val);
if (val < d->min)
d->min = val;
if (val > d->max)
d->max = val;
d->total += val;
++d->count;
}
void
Latency_Sum(dmtr_latency_t *dest, dmtr_latency_t *summand)
{
for (int i = 0; i < summand->distPoolNext; ++i) {
Latency_Dist_t *d = &summand->distPool[i];
for (int b = 0; b < LATENCY_NUM_BUCKETS; ++b) {
if (d->buckets[b] == 0)
continue;
LatencyAddHist(dest, d->type, 1ll<<b, d->buckets[b]);
}
}
for (int i = 0; i < LATENCY_MAX_DIST; ++i) {
Latency_Dist_t *dd = dest->dists[i];
Latency_Dist_t *ds = summand->dists[i];
if (!ds)
continue;
if (ds->min < dd->min)
dd->min = ds->min;
if (ds->max > dd->max)
dd->max = ds->max;
dd->total += ds->total;
dd->count += ds->count;
}
}
static char *
LatencyFmtNS(uint64_t ns, char *buf)
{
static const char *units[] = {"ns", "us", "ms", "s"};
unsigned int unit = 0;
while (ns >= 10000 && unit < (sizeof units / sizeof units[0]) - 1) {
ns /= 1000;
++unit;
}
sprintf(buf, "%lu %s", ns, units[unit]);
return buf;
}
int
Latency_Dump(FILE *f, dmtr_latency_t *l)
{
// return 0;
DMTR_NOTNULL(EINVAL, f);
DMTR_NOTNULL(EINVAL, l);
if (l->distPoolNext == 0) {
// No distributions yet
return 0;
}
char buf[5][64];
// Keep track of the index of the first used distribution, and
// for each other used distribution, the index of the next
// used distribution. This way we only have to make one scan
// over all the distributions and the rest of our scans
// (especially when printing the histograms) are fast.
int firstType = -1;
int nextTypes[LATENCY_MAX_DIST];
int *ppnext = &firstType;
for (int type = 0; type < LATENCY_MAX_DIST; ++type) {
Latency_Dist_t *d = l->dists[type];
if (!d)
continue;
*ppnext = type;
ppnext = &nextTypes[type];
// Find the median
uint64_t accum = 0;
int medianBucket;
for (medianBucket = 0; medianBucket < LATENCY_NUM_BUCKETS;
++medianBucket) {
accum += d->buckets[medianBucket];
if (accum >= d->count / 2)
break;
}
char extra[3] = {'/', (char)type, 0};
if (type == '=')
extra[0] = '\0';
fprintf(f, "LATENCY %s%s: %s %s/%s %s (%lu samples, %s total)\n",
l->name.c_str(), extra, LatencyFmtNS(d->min, buf[0]),
LatencyFmtNS(d->total / d->count, buf[1]),
LatencyFmtNS((uint64_t)1 << medianBucket, buf[2]),
LatencyFmtNS(d->max, buf[3]), d->count,
LatencyFmtNS(d->total, buf[4]));
}
*ppnext = -1;
l->latencies.shrink_to_fit();
sort(l->latencies.begin(), l->latencies.end());
fprintf(f, "TAIL LATENCY 99=%s 99.9=%s 99.99=%s\n",
LatencyFmtNS(l->latencies.at((int)((float)l->latencies.size() * 0.99)), buf[0]),
LatencyFmtNS(l->latencies.at((int)((float)l->latencies.size() * 0.999)), buf[1]),
LatencyFmtNS(l->latencies.at((int)((float)l->latencies.size() * 0.9999)), buf[2]));
// Find the count of the largest bucket so we can scale the
// histogram
uint64_t largestCount = LATENCY_HISTOGRAM_WIDTH;
for (int i = 0; i < LATENCY_NUM_BUCKETS; ++i) {
uint64_t total = 0;
for (int dist = 0; dist < l->distPoolNext; ++dist) {
Latency_Dist_t *d = &l->distPool[dist];
total += d->buckets[i];
}
if (total > largestCount)
largestCount = total;
}
// Display the histogram
int lastPrinted = LATENCY_NUM_BUCKETS;
for (int i = 0; i < LATENCY_NUM_BUCKETS; ++i) {
char bar[LATENCY_HISTOGRAM_WIDTH + 1];
int pos = 0;
uint64_t total = 0;
for (int type = firstType; type != -1; type = nextTypes[type]) {
Latency_Dist_t *d = l->dists[type];
if (!d)
continue;
total += d->buckets[i];
int goal = ((total * LATENCY_HISTOGRAM_WIDTH)
/ largestCount);
for (; pos < goal; ++pos)
bar[pos] = type;
}
if (total > 0) {
bar[pos] = '\0';
if (lastPrinted < i - 3) {
fprintf(f, "%10s |\n", "...");
} else {
for (++lastPrinted; lastPrinted < i;
++lastPrinted)
fprintf(f, "%10s | %10ld |\n",
LatencyFmtNS((uint64_t)1 << lastPrinted,
buf[0]), 0L);
}
fprintf(f, "%10s | %10ld | %s\n",
LatencyFmtNS((uint64_t)1 << i, buf[0]),
total,
bar);
lastPrinted = i;
}
}
return 0;
}
int dmtr_new_latency(dmtr_latency_t **latency_out, const char *name) {
DMTR_NOTNULL(EINVAL, latency_out);
*latency_out = NULL;
DMTR_NOTNULL(EINVAL, name);
auto latency = new dmtr_latency_t();
latency->name = name;
latency->latencies.reserve(MAX_ITERATIONS);
for (int i = 0; i < LATENCY_DIST_POOL_SIZE; ++i) {
Latency_Dist_t *d = &latency->distPool[i];
d->min = ~0ll;
}
*latency_out = latency;
return 0;
}
int dmtr_record_latency(dmtr_latency_t *latency, uint64_t ns) {
DMTR_NOTNULL(EINVAL, latency);
//DMTR_NONZERO(EINVAL, ns);
if (ns != 0) {
LatencyAdd(latency, '=', ns);
}
return 0;
}
int dmtr_dump_latency(FILE *f, dmtr_latency_t *latency) {
DMTR_OK(Latency_Dump(f, latency));
return 0;
}
int dmtr_delete_latency(dmtr_latency_t **latency) {
DMTR_NOTNULL(EINVAL, latency);
delete *latency;
*latency = NULL;
return 0;
}
uint64_t dmtr_now_ns() {
auto t = boost::chrono::steady_clock::now();
return t.time_since_epoch().count();
}
| 28.308725 | 88 | 0.571835 | [
"vector"
] |
a10db91cad5e5954ae2b669eb3c424f6c0ec60a7 | 40,521 | cpp | C++ | src/BoxTools/Chombo_BRMeshRefine.cpp | novertonCSU/Chombo_4 | b833e49793758a7d6d22f976694c9d2e90d29c00 | [
"BSD-3-Clause-LBNL"
] | 11 | 2019-06-08T01:20:51.000Z | 2021-12-21T12:18:54.000Z | src/BoxTools/Chombo_BRMeshRefine.cpp | novertonCSU/Chombo_4 | b833e49793758a7d6d22f976694c9d2e90d29c00 | [
"BSD-3-Clause-LBNL"
] | 3 | 2020-03-13T06:25:55.000Z | 2021-06-23T18:12:53.000Z | src/BoxTools/Chombo_BRMeshRefine.cpp | novertonCSU/Chombo_4 | b833e49793758a7d6d22f976694c9d2e90d29c00 | [
"BSD-3-Clause-LBNL"
] | 4 | 2019-08-27T14:34:34.000Z | 2021-10-04T21:46:59.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include <fstream>
#include <iostream>
#include "Chombo_SPMD.H"
#include "Chombo_CH_Timer.H"
// Constants for Berger-Rigoutsos algorithm
#if ! defined(_BR_MIN_INFLECTION_MAG_)
#define _BR_MIN_INFLECTION_MAG_ ( 3 )
#endif
#define MAXBOXES 2000000 // petermc: was 20000
#define P_BUFFERSIZE (MAXBOXES * 8 * CH_SPACEDIM)
// Berger-Rigoutsos Mesh refinement class
// ---------
// class BRMeshRefine
//
///////////////////////////////////////////////////////////////////////////////
// Include files:
#include "Chombo_BRMeshRefine.H"
#include "Chombo_MayDay.H"
#include "Chombo_parstream.H"
#include "Chombo_NamespaceHeader.H"
//recursive function to enforce max size of boxes in a given direction
void
breakBoxes(Vector<Box>& a_vboxin, const int& a_maxBoxSize, const int& a_idir)
{
int nboxes = a_vboxin.size();
//need to use STL vector for bools.
using std::vector;
vector<bool> splitDec(nboxes);
bool anyBoxesToSplit = false;
//find out which boxes need to be chopped and in what direction
for (int ibox = 0; ibox < nboxes; ibox++)
{
if ( a_vboxin[ibox].size(a_idir ) > a_maxBoxSize )
{
splitDec[ibox] = true;
anyBoxesToSplit = true;
}
else
{
splitDec[ibox] = false;
}
}
//if there are no boxes to split, just return
//otherwise, split all the boxes that need to be
//split ONCE and then call function recursively
// and set the return vector to the temporary after
// the recursion
if (anyBoxesToSplit)
{
Vector<Box> vboxtemp;
for (int ibox = 0; ibox < nboxes; ibox++)
{
Box boxone = a_vboxin[ibox];
if (splitDec[ibox])
{
//int len = (boxone.smallEnd(a_idir) + boxone.bigEnd(a_idir))/2;
int mid = boxone.smallEnd(a_idir)+a_maxBoxSize ;
Box boxtwo = boxone.chop(a_idir, mid);
vboxtemp.push_back(boxone);
vboxtemp.push_back(boxtwo);
}
else
{
vboxtemp.push_back(boxone);
}
}
breakBoxes(vboxtemp, a_maxBoxSize, a_idir);
a_vboxin = vboxtemp;
}
return;
}
BRMeshRefine::BRMeshRefine()
{
m_fillRatio = 1.0;
setRefineDirs(IntVect::Unit);
}
BRMeshRefine::~BRMeshRefine()
{
}
BRMeshRefine::BRMeshRefine(const Box& a_baseDomain,
const Vector<int>& a_refRatios,
const Real a_fillRatio,
const int a_blockFactor,
const int a_bufferSize,
const int a_maxBoxSize)
{
ProblemDomain crseDom(a_baseDomain);
define(crseDom, a_refRatios, a_fillRatio, a_blockFactor,
a_bufferSize, a_maxBoxSize);
}
BRMeshRefine::BRMeshRefine(const ProblemDomain& a_baseDomain,
const Vector<int>& a_refRatios,
const Real a_fillRatio,
const int a_blockFactor,
const int a_bufferSize,
const int a_maxBoxSize)
{
define(a_baseDomain, a_refRatios, a_fillRatio, a_blockFactor,
a_bufferSize, a_maxBoxSize);
}
void
BRMeshRefine::define(const Box& a_baseDomain,
const Vector<int>& a_refRatios,
const Real a_fillRatio,
const int a_blockFactor,
const int a_bufferSize,
const int a_maxBoxSize)
{
ProblemDomain crseDom(a_baseDomain);
define(crseDom, a_refRatios, a_fillRatio, a_blockFactor,
a_bufferSize, a_maxBoxSize);
}
void
BRMeshRefine::define(const ProblemDomain& a_baseDomain,
const Vector<int>& a_refRatios,
const Real a_fillRatio,
const int a_blockFactor,
const int a_bufferSize,
const int a_maxBoxSize)
{
// nothing new here
MeshRefine::define(a_baseDomain, a_refRatios, a_fillRatio,
a_blockFactor, a_bufferSize, a_maxBoxSize);
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: makeBoxes
//
// Short Description:
// Construct a set of boxes that cover a set of tagged cells.
//
// Purpose:
// Given a set of tagged cells defined on a single level of an AMR grid,
// construct a BoxArray that covers all these cells that minimizes the
// number of boxes and maximizes the ratio of tagged cells in each box.
// This is part of the process of refining a mesh hierarchy based on error
// estimates.
//
// Caveat:
// The mesh that is created must lie within the proper nesting domain (Pnd)
//
// Usage Notes:
//
// Numerical Algorithm:
// <Berger-Rigoutsos algorithm>
//
// Implementation Method:
//
// Implementation Notes:
// This gets tricky when the minbox around a set of tags has a non-zero offset.
// Have to be careful to remember this when looking at box sizes.
//
// References:
// M. Berger, I. Rigoutsos, "An Algorithm for Point Clustering and Grid Generation",
// _IEEE_Transactions_on_Systems,_Man,_and_Cybernetics_, Vol. 21, No.5, pp. 1278-1286,
// Sept./Oct. 1991.
//
///////////////////////////////////////////////////////////////////////////////
void
BRMeshRefine::makeBoxes(Vector<Box>& a_mesh,
const IntVectSet& a_tags,
const IntVectSet& a_pnd,
const ProblemDomain& a_domain,
const int a_maxBoxSize,
const int a_totalBufferSize
) const
{
CH_TIME("BRMeshRefine::makeBoxes");
std::list<Box> boxes;
#ifdef CH_MPI
int size;
MPI_Comm_size (CH4_SPMD::Chombo_MPI::comm, &size );
Interval interval(0, size-1);
makeBoxesParallel(boxes, (IntVectSet&)a_tags, a_pnd, a_domain, a_maxBoxSize, 0, a_totalBufferSize,
100, interval);
#else
makeBoxes(boxes, (IntVectSet&)a_tags, a_pnd, a_domain, a_maxBoxSize, 0, a_totalBufferSize);
#endif
//boxes.sort();
a_mesh.resize(boxes.size());
std::list<Box>::iterator it = boxes.begin();
for (int i=0; i<a_mesh.size(); ++i, ++it) a_mesh[i]=*it;
}
void
BRMeshRefine::makeBoxes(std::list<Box>& a_mesh,
IntVectSet& a_tags,
const IntVectSet& a_pnd,
const ProblemDomain& a_domain,
const int a_maxBoxSize,
const int a_depth,
const int a_totalBufferSize
) const
{
unsigned long long int Ntags = a_tags.numPts();
Box minbx ; //min box around Tags
std::list<Box> mesh_hi ; //boxes from recursion
IntVectSet& tags_lo = a_tags;
IntVectSet tags_hi ; //tags for recursion
a_mesh.clear();
//
// Handle special cases of no tags
//
if ( a_tags.isEmpty() )
{
// return null box
return;
}
//
// Validate inputs
//
// The number of tagged cells in a box cannot exceed the number
// of cells in the box so enforce an upper bound on \var{FillRatio}.
//[NOTE: 0 or negative values are allowed -- they mean any box
// is acceptable. This will probably be a mistake by the
// caller, but there is no obvious lower valid value for
// this variable (1e-6 is just as likely a mistake as 0).]
CH_assert ( m_fillRatio <= 1.0 );
//
// Handle the case of all tags fitting in one box.
// This always happens at the bottom of the recursion.
//
Box minbox = a_tags.minBox() ;
bool nested = properlyNested(minbox, a_domain, a_pnd, a_totalBufferSize);
if (!nested && Ntags == 1)
{
CH_assert(minbox.numPts() == 1);
return; // IntVect wasn't in PND after all (bvs)
}
// If minbox has enough tagged cells and is properly nested, want
// to add this minbox to the mesh.
// If not, continue with splitting it and recursing on the pieces.
if ( (Ntags >= (minbox.numPts() * m_fillRatio)) && nested )
{
// no IntVects in the box are outside the PND so this box can
// be accepted. If it is larger than the maximum box size, split
// it into two boxes
//[NOTE: one of the boxes may violate the FillRatio requirement, but
// we will ignore this.]
// pout()<< "split Box "<<minbox<<" maxsize "<<a_maxBoxSize<<std::endl;
a_mesh.push_front(minbox) ;
if (a_maxBoxSize > 0)
{
for (std::list<Box>::iterator it=a_mesh.begin(); it != a_mesh.end(); ++it)
{
splitBox( a_mesh, it, a_maxBoxSize ) ;
}
} // end if we are enforcing a max box size
}
else
{
// if efficiency criterion not met or box not properly nested...
// Note tags_lo contains a_tags going in
splitTagsInBestDimension(tags_lo, tags_hi, a_maxBoxSize);
// Recurse on the two halves of the Tags
if (!(tags_lo.isEmpty()))
{
// low interval
makeBoxes( a_mesh, tags_lo, a_pnd, a_domain, a_maxBoxSize, a_depth+1, a_totalBufferSize);
}
if (!(tags_hi.isEmpty()))
{
// high interval
makeBoxes( mesh_hi, tags_hi, a_pnd, a_domain, a_maxBoxSize, a_depth+1, a_totalBufferSize);
}
// combine the results into a single mesh
a_mesh.splice(a_mesh.begin(), mesh_hi);
} // done if we need to split the box
// Done
} //end of makeBoxes
void
BRMeshRefine::makeBoxesParallel(std::list<Box>& a_mesh,
IntVectSet& a_tags,
const IntVectSet& a_pnd,
const ProblemDomain& a_domain,
const int a_maxBoxSize,
const int a_depth,
const int a_totalBufferSize,
const int a_minSize,
const Interval& a_procInterval
) const
{
if (a_procInterval.size() == 1)
{
makeBoxes(a_mesh, a_tags, a_pnd, a_domain, a_maxBoxSize, a_depth, a_totalBufferSize);
return;
}
unsigned long long int Ntags = a_tags.numPts();
std::list<Box> mesh_hi ; //boxes from recursion
IntVectSet& tags_lo = a_tags;
IntVectSet tags_hi ; //tags for recursion
a_mesh.clear() ;
//
// Handle special cases of no tags
//
if ( a_tags.isEmpty() )
{
//return null box
return;
}
//
// Validate inputs
//
// The number of tagged cells in a box cannot exceed the number
// of cells in the box so enforce an upper bound on \var{FillRatio}.
//[NOTE: 0 or negative values are allowed -- they mean any box
// is acceptable. This will probably be a mistake by the
// caller, but there is no obvious lower valid value for
// this variable (1e-6 is just as likely a mistake as 0).]
CH_assert ( m_fillRatio <= 1.0 );
//
// Handle the case of all tags fitting in one box.
// This always happens at the bottom of the recursion.
//
Box minbox = a_tags.minBox() ;
bool nested = properlyNested(minbox, a_domain, a_pnd, a_totalBufferSize);
if (!nested && Ntags == 1)
{
CH_assert(minbox.numPts() == 1);
return; // IntVect was not in PND after all
}
// If minbox has enough tagged cells and is properly nested, want
// to add this minbox to the mesh.
// If not, continue with splitting it and recursing on the pieces.
if ( (Ntags >= minbox.numPts() * m_fillRatio) && nested)
{
// no IntVects in the box are outside the PND so this box can
// be accepted. If it is larger than the maximum box size, split
// it into two boxes
//[NOTE: one of the boxes may violate the FillRatio requirement, but
// we will ignore this.]
// pout()<< "split Box "<<minbox<<" maxsize "<<a_maxBoxSize<<std::endl;
a_mesh.push_front(minbox) ;
if (a_maxBoxSize > 0)
{
for (std::list<Box>::iterator it=a_mesh.begin(); it != a_mesh.end(); ++it)
{
splitBox( a_mesh, it, a_maxBoxSize ) ;
}
} // end if we are enforcing a max box size
}
else
{
// if efficiency criterion not met or box not properly nested...
//
// Note tags_lo = a_tags going in
splitTagsInBestDimension(tags_lo, tags_hi, a_maxBoxSize);
//a_tags.makeEmpty();
if (a_procInterval.size() == 1 ||
Ntags <= a_minSize ) // do the regular algorithm for BRMeshRefine
{
// Recurse on the two halves of the Tags
if ( !tags_lo.isEmpty() )
{
makeBoxes( a_mesh, tags_lo, a_pnd, a_domain, a_maxBoxSize, a_depth+1, a_totalBufferSize);
}
if ( !tags_hi.isEmpty() )
{
makeBoxes( mesh_hi, tags_hi, a_pnd, a_domain, a_maxBoxSize, a_depth+1, a_totalBufferSize);
}
}
else // do makeBoxes in Parallel
{
//pout()<<"depth, interval "<<a_depth<<" "<<a_procInterval.begin()
// <<a_procInterval.end()<<std::endl;
// first, split interval in two
Interval lo_interval(a_procInterval.begin(),
(a_procInterval.end()+a_procInterval.begin()-1)/2);
Interval hi_interval(lo_interval.end()+1, a_procInterval.end());
// pout()<<"lo "<<lo_interval.begin()<<lo_interval.end()
// <<"\nhi "<<hi_interval.begin()<<hi_interval.end()<<std::endl;
using CH4_SPMD::procID;
if (lo_interval.contains(procID()) && !tags_lo.isEmpty())
{
makeBoxesParallel( a_mesh, tags_lo, a_pnd, a_domain, a_maxBoxSize,
a_depth+1, a_totalBufferSize, a_minSize, lo_interval);
sendBoxesParallel( a_mesh, a_depth);
}
if (hi_interval.contains(procID()) && !tags_hi.isEmpty() )
{
makeBoxesParallel( mesh_hi, tags_hi, a_pnd, a_domain, a_maxBoxSize,
a_depth+1, a_totalBufferSize, a_minSize, hi_interval);
sendBoxesParallel( mesh_hi, a_depth);
}
if (hi_interval.contains(procID()) && !tags_lo.isEmpty() )
{
receiveBoxesParallel(hi_interval, lo_interval, a_mesh, a_depth);
}
if (lo_interval.contains(procID()) && !tags_hi.isEmpty() )
{
receiveBoxesParallel(lo_interval, hi_interval, mesh_hi, a_depth);
}
}
// combine the results into a single mesh
a_mesh.splice(a_mesh.begin(), mesh_hi);
}
// Done
} //end of makeBoxesParallel
// Compute the traces (signatures) of the minbox in each direction, and
// find a hole in the trace (zero value) and an inflection point (zero
// Laplacian) in each direction; keep the best of each.
//[NOTE: both \func{find*} functions return -1 if nothing was found.]
//[NOTE: \var{infl_val} is modified by \func{findMaxInflectionPoint}.]
//[NOTE: \var{trace} indexes from 0, so indices into \var{trace} must
// be shifted to be used as indices into the \var{a_tags}.]
// a_tags_inout_lo holds the input tags coming in, and the lo tags going out.
// maxBoxSize is the maxboxsize and is used in determining where
// to begin searching for a split index.
void BRMeshRefine::splitTagsInBestDimension(IntVectSet& a_tags_inout_lo,
IntVectSet& a_tags_hi,
const int a_maxBoxSize) const
{
int hole_indx[SpaceDim], best_hole_dim; //holes in traces
int infl_indx[SpaceDim], best_infl_dim; //inflection points in traces
int infl_val [SpaceDim] ; //magnitudes of infl.points
Vector<int> traces[SpaceDim];
// makeTraces( a_tags_inout_lo, traces) ;
Box minbox = a_tags_inout_lo.minBox() ;
IntVect offset = minbox.smallEnd() ;
const IntVect& size = minbox.size();
D_TERM6(traces[0].resize(size[0],0);,
traces[1].resize(size[1],0);,
traces[2].resize(size[2],0);,
traces[3].resize(size[3],0);,
traces[4].resize(size[4],0);,
traces[5].resize(size[5],0););
IntVect iv;
IVSIterator i(a_tags_inout_lo);
for (i.begin() ; i.ok() ; ++i )
{
iv = i() - offset;
D_TERM6(traces[0][iv[0]]++,; traces[1][iv[1]]++,;traces[2][iv[2]]++,;
traces[3][iv[3]]++,; traces[4][iv[4]]++,;traces[5][iv[5]]++);
}
for ( int idim = 0 ; idim < SpaceDim ; idim++ )
{
if (m_refineDirs[idim] == 1)
{
//hole_indx[idim] = findSplit( traces[idim] ) ;
//infl_indx[idim] = findMaxInflectionPoint(traces[idim], infl_val[idim] ) ;
// The following two functions, with the a_maxBoxSize argument,
// help balance the tag splitting by changing where to begin
// searching for a split or inflection index.
hole_indx[idim] = findSplit( traces[idim], a_maxBoxSize);
infl_indx[idim] = findMaxInflectionPoint(traces[idim], infl_val[idim], a_maxBoxSize) ;
}
}
// Take the highest index as the best one because we want to take as large
// a box as possible (fewer large boxes are better than many small ones)
best_hole_dim = maxloc( hole_indx, SpaceDim ) ;
best_infl_dim = maxloc( infl_indx, SpaceDim ) ;
//
// Split the Tag set at a hole in one of the traces, if there is one, or an
// inflection point in the Laplacian of the traces. Failing that, split
// at the middle of the longest dimension of the enclosing box.
int split_dim, split_index;
if ( hole_indx[best_hole_dim] >= 0 )
{
// split at a hole in the trace, adjusting the trace index for the
// offset into \var{a_tags_inout_lo} indices
split_dim = best_hole_dim;
split_index = hole_indx[best_hole_dim] + minbox.smallEnd(best_hole_dim);
}
else if ( infl_indx[best_infl_dim] >= 0 )
{
// split at an inflection point in the trace, adjusting the trace
// index for the offset into \var{a_tags_inout_lo} indices
split_dim = best_infl_dim;
split_index = infl_indx[best_infl_dim] + minbox.smallEnd(best_infl_dim);
}
else
{
// split on the midpoint of the longest side of \var{minbox}, rounding up,
// allowing for \var{minbox} to have a non-zero offset
// minbox.longside(split_dim); //[NOTE: split_dim is set by \func(longside)]
longsideRefineDirs(minbox, split_dim);
split_index = (minbox.smallEnd(split_dim) + minbox.bigEnd(split_dim) +1)/2;
}
splitTagsInPlace( split_dim, split_index, a_tags_inout_lo, a_tags_hi );
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: splitBox()
//
// Short description:
// If the box in the given Vector pointed to by the given index is larger
// than the given maximum size in the given dimension, split it into two
// boxes and recurse on each.
//
///////////////////////////////////////////////////////////////////////////////
void
BRMeshRefine::splitBox( std::list<Box>& a_boxes,
const std::list<Box>::iterator& a_box,
const int a_dim,
const int a_maxBoxSize) const
{
// See if the box needs to be split in this dimension. If not, do nothing.
Box& b = *a_box;
if ( b.size( a_dim ) > a_maxBoxSize )
{
// pout() <<"splitting box "<<a_boxes[a_boxIndex]<<std::endl;
// chop() returns the upper half as a new box (which is appended to
// the vector) and modifies the original box to be the lower half
int len =
( b.smallEnd( a_dim )+
b.bigEnd( a_dim )+1 )/2;
std::list<Box>::iterator c = a_boxes.insert(a_box, b.chop(a_dim, len));
// recurse on the two boxes
splitBox( a_boxes, a_box , a_dim, a_maxBoxSize ) ;
splitBox( a_boxes, c , a_dim, a_maxBoxSize ) ;
}
// Done
}
void
BRMeshRefine::splitBox( std::list<Box>& a_boxes,
const std::list<Box>::iterator& a_box,
const int a_maxBoxSize) const
{
// See if the box needs to be split in this dimension. If not, do nothing.
Box& b = *a_box;
int dir;
// int longside = b.longside(dir);
int longside = longsideRefineDirs(b, dir);
if ( longside > a_maxBoxSize )
{
// pout() <<"splitting box "<<a_boxes[a_boxIndex]<<std::endl;
// chop() returns the upper half as a new box (which is appended to
// the vector) and modifies the original box to be the lower half
int len =
( b.smallEnd( dir )+
b.bigEnd( dir )+1 )/2;
std::list<Box>::iterator c = a_boxes.insert(a_box, b.chop(dir, len));
// recurse on the two boxes
splitBox( a_boxes, a_box , a_maxBoxSize ) ;
splitBox( a_boxes, c , a_maxBoxSize ) ;
}
// Done
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: makeTrace()
//
// Short description:
// Count the number of cells in the IVS at every index in the specified
// coordinate direction. In other words, make a histogram using the
// \var{Dir}'th coordinate as data.
//
// Note: Vectors index from 0 so the trace indices have to be shifted from
// the box indices by the value of the lower bound.
//
// References:
// The trace computed here is the \Sigma value computed in Berger-Rigoutsos.
//
///////////////////////////////////////////////////////////////////////////////
Vector<int>
BRMeshRefine::makeTrace( const IntVectSet& a_Ivs, int a_dir ) const
{
//
// Validate inputs
//
CH_assert( a_dir >= 0 && a_dir < SpaceDim ) ;
//
// Histogram the coordinates of \var{a_Ivs} in direction \var{a_dir} into
// \var{trace}. The index range of \var{trace} must start at 0
// regardless of the bounds of the minbox of \var{a_Ivs}
//
Box minbox = a_Ivs.minBox() ;
int offset = minbox.smallEnd(a_dir) ;
Vector<int> trace( minbox.size(a_dir), 0 ) ; //initialize to 0
IVSIterator i(a_Ivs) ;
for ( i.begin() ; i.ok() ; ++i )
{
trace[i()[a_dir]-offset] += 1 ;
}
// Done
return( trace ) ;
}
void BRMeshRefine::makeTraces ( const IntVectSet& a_Ivs, Vector<int>* traces) const
{
Box minbox = a_Ivs.minBox() ;
IntVect offset = minbox.smallEnd() ;
const IntVect& size = minbox.size();
D_TERM6(traces[0].resize(size[0],0);,
traces[1].resize(size[1],0);,
traces[2].resize(size[2],0);,
traces[3].resize(size[3],0);,
traces[4].resize(size[4],0);,
traces[5].resize(size[5],0););
IVSIterator i(a_Ivs) ;
for ( i.begin() ; i.ok() ; ++i )
{
IntVect iv = i();
iv-=offset;
D_TERM6(traces[0][iv[0]]++,; traces[1][iv[1]]++,;traces[2][iv[2]]++,;
traces[3][iv[3]]++,; traces[4][iv[4]]++,;traces[5][iv[5]]++);
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: findSplit()
//
// Short Description:
// Given a trace (ie. signature) of a Tag set, find a place in the trace
// with a zero count. Assumes the first and last elements of the trace
// are non-zero.
//
// Usage Note:
// If there are no acceptable zeros in the trace, this returns -1.
// \var{Vector}s index from 0, so the result may have to be shifted to be
// used as an index into the \var{IntVectSect} which produced the trace.
//
///////////////////////////////////////////////////////////////////////////////
int
BRMeshRefine::findSplit( const Vector<int>& a_trace ) const
{
// look for a place to split at -- begin at the index after the first nonzero
for ( int i = 1 ; i < a_trace.size() -1 ; i++ )
{
if ( a_trace[i] == 0 ) return( i ) ;
}
// nothing acceptable
return( -1 ) ;
}
// If the traces are large enough, begin looking for a split index in the center
int
BRMeshRefine::findSplit( const Vector<int>& a_trace, const int a_maxBoxSize ) const
{
// If length of trace is larger than 2 times the maxboxsize (arbitrary),
// do somthing different
if (a_trace.size() > 2*a_maxBoxSize)
{
// look for a place to split at -- begin in the middle, count down to 1,
// look in both directions
int ibegin = a_trace.size()/2;
int iforward = ibegin+1;
for ( int i = ibegin ; (i >= 1 && iforward < a_trace.size()-1 ); i-- )
{
if ( a_trace[i] == 0 ) return( i );
if ( a_trace[iforward] == 0 ) return( iforward );
iforward++;
}
}
else
{
int firstHole = findSplit(a_trace); // perform original algorithm
return(firstHole);
}
// nothing acceptable
return( -1 ) ;
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: findMaxInflectionPoint
//
// Short Description:
// Find the largest inflection point in the given trace (ie. signature)
// and return the index and set the value of the inflection in the last
// argument. The index will be the edge-centered location where a
// chop should be made in the BR algorithm.
//
// If there are no inflection points or if none of them are larger than the
// cutoff tolerance, -1 is returned.
//
// Implementation Note:
// The smallest acceptable inflection magnitude is the global constant
// _MIN_INFLECTION_MAG_
//
///////////////////////////////////////////////////////////////////////////////
int
BRMeshRefine::findMaxInflectionPoint(const Vector<int>& a_trace,
int& a_maxVal) const
{
// first compute the discrete Laplacian of the trace
Vector<int> d2Trace( a_trace.size(), 0 ) ;
for ( int i = 1 ; i < a_trace.size()-1 ; i++ )
{
d2Trace[i] = a_trace[i-1] - 2*a_trace[i] + a_trace[i+1] ;
}
// find inflection points and save one with the largest magnitude
int absval, imax=0;
a_maxVal = -1 ;
for ( int i = 2 ; i < a_trace.size()-1 ; i++ )
{
absval = abs( d2Trace[i-1] - d2Trace[i] ) ;
if ( d2Trace[i-1] * d2Trace[i] < 0 && absval > a_maxVal )
{
imax = i ; a_maxVal = absval ;
}
}
// Find the largest inflection point, if one exists and
// has magnitude large enough and return its index.
// return edge-centered location of chop point.
if ( a_maxVal == -1 ) return( -1 ) ;
else if ( a_maxVal < _BR_MIN_INFLECTION_MAG_ ) return( -1 ) ;
else return( imax);
}
// If the traces are large enough, begin looking for a split index in the center
int
BRMeshRefine::findMaxInflectionPoint(const Vector<int>& a_trace,
int& a_maxVal,
const int a_maxBoxSize) const
{
int imax=0;
// If length of trace is larger than 2 times the maxboxsize (arbitrary),
// do somthing different
if (a_trace.size() > 2*a_maxBoxSize)
{
// first compute the discrete Laplacian of the trace
Vector<int> d2Trace( a_trace.size(), 0 ) ;
for ( int i = 1 ; i < a_trace.size()-1 ; i++ )
{
d2Trace[i] = a_trace[i-1] - 2*a_trace[i] + a_trace[i+1] ;
}
// find inflection points and save one with the largest magnitude
int absval;
a_maxVal = -1;
// look for inflection -- begin in the middle, count down to 1,
// look in both directions
int ibegin = a_trace.size()/2;
int iforward = ibegin+1;
for ( int i = ibegin ; (i >= 2 && iforward < a_trace.size()-1); i-- )
{
absval = abs( d2Trace[i-1] - d2Trace[i] ) ;
if ( d2Trace[i-1] * d2Trace[i] < 0 && absval > a_maxVal )
{
imax = i ;
a_maxVal = absval ;
}
// same thing in the forward direction
absval = abs( d2Trace[iforward-1] - d2Trace[iforward] ) ;
if ( d2Trace[iforward-1] * d2Trace[iforward] < 0 && absval > a_maxVal )
{
imax = iforward ;
a_maxVal = absval ;
}
iforward++;
}
}
else
{ // call original algorithm
int inflectionPoint = findMaxInflectionPoint(a_trace, a_maxVal);
return(inflectionPoint);
}
// Find the largest inflection point, if one exists and
// has magnitude large enough and return its index.
// return edge-centered location of chop point.
if ( a_maxVal == -1 ) return( -1 ) ;
else if ( a_maxVal < _BR_MIN_INFLECTION_MAG_ ) return( -1 ) ;
else return( imax);
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: splitTags
//
// Purpose:
// Given a direction and an index in that direction, split the IntVectSet of
// tags into two sets (lo,hi) on either side of the index. Tags that match
// the index exactly go into the hi set.
//
// Implementation Method:
// For each tag in the set, look at the coordinate in the direction specified,
// and if it is <= the specified index, copy the tag into the lo set. Else
// copy it into the hi set.
//
// Usage Note:
// It is acceptable for the split index to be outside of the box containing Tags.
// This forces all the Tags to end up in one of the two output sets.
//
///////////////////////////////////////////////////////////////////////////////
void
BRMeshRefine::splitTags(const IntVectSet& a_tags,
const int a_split_dir, const int a_split_indx,
IntVectSet& a_tags_lo, IntVectSet& a_tags_hi ) const
{
// Validate inputs
//[NOTE: it is ok if the a_split_indx is outside the box containing a_tags.]
CH_assert( a_split_dir >= 0 && a_split_dir < SpaceDim );
CH_assert( !a_tags.isEmpty() );
// Copy the whole set into a_tags_lo and extract the cells that aren't
// below the split index into a_tags_hi, keeping the leftover in a_tags_lo
// (i.e., the a_split_indx'th cells go into the high set).
a_tags_lo = a_tags ;
a_tags_hi = a_tags_lo.chop( a_split_dir, a_split_indx );
}
void BRMeshRefine::splitTagsInPlace(const int a_split_dir, const int a_split_indx,
IntVectSet& a_tags_inout_lo,
IntVectSet& a_tags_hi) const
{
a_tags_inout_lo.chop(a_split_dir, a_split_indx, a_tags_hi);
}
//recursive function to enforce max size of boxes in a given direction
void
BRMeshRefine::breakBoxes(Vector<Box>& a_vboxin,
const int& a_maxBoxSize, const int& a_idir) const
{
int nboxes = a_vboxin.size();
//need to use STL vector for bools.
using std::vector;
vector<bool> splitDec(nboxes);
bool anyBoxesToSplit = false;
//find out which boxes need to be chopped and in what direction
for (int ibox = 0; ibox < nboxes; ibox++)
{
if ( a_vboxin[ibox].size(a_idir ) > a_maxBoxSize )
{
splitDec[ibox] = true;
anyBoxesToSplit = true;
}
else
{
splitDec[ibox] = false;
}
}
//if there are no boxes to split, just return
//otherwise, split all the boxes that need to be
//split ONCE and then call function recursively
// and set the return vector to the temporary after
// the recursion
if (anyBoxesToSplit)
{
Vector<Box> vboxtemp;
for (int ibox = 0; ibox < nboxes; ibox++)
{
Box boxone = a_vboxin[ibox];
if (splitDec[ibox])
{
// int len = (boxone.smallEnd(a_idir) +
// boxone.bigEnd(a_idir))/2;
int len = boxone.smallEnd(a_idir)+a_maxBoxSize-1;
Box boxtwo = boxone.chop(a_idir, len);
vboxtemp.push_back(boxone);
vboxtemp.push_back(boxtwo);
}
else
{
vboxtemp.push_back(boxone);
}
} // end loop over boxes
breakBoxes(vboxtemp, a_maxBoxSize, a_idir);
a_vboxin = vboxtemp;
}
return;
}
///////////////////////////////////////////////////////////////////////////////
//
// Function: maxloc
//
// Purpose: find the maximum value in a Vector<int> or an int[] and return its index.
//
// Usage Notes:
// Returns -1 if the Vector has no entries.
//
///////////////////////////////////////////////////////////////////////////////
int
BRMeshRefine::maxloc( const int* a_V, const int a_Size ) const
{
// Need only m_lowestRefineDir and m_refineDirs.
// CH_assert( isDefined() );
// int imax = 0 ;
int imax = m_lowestRefineDir;
// for ( int i=1 ; i<a_Size ; i++ ) if ( a_V[i] > a_V[imax] ) imax = i ;
for ( int i=m_lowestRefineDir+1 ; i<a_Size ; i++ )
{
if (m_refineDirs[i] == 1)
{
if ( a_V[i] > a_V[imax] ) imax = i ;
}
}
return( imax ) ;
}
// at the moment, this is a pretty hokey approach
// (first build a BRMeshRefine, then "generate" grids
// hopefully will have a better version soon...
void
domainSplit(const ProblemDomain& a_domain, Vector<Box>& a_vbox,
int a_maxBoxSize, int a_blockFactor, IntVect a_refineDirs)
{
const Box& domBox = a_domain.domainBox();
domainSplit(domBox, a_vbox, a_maxBoxSize, a_blockFactor, a_refineDirs);
}
void
domainSplit(const Box& a_domain, Vector<Box>& a_vbox, int a_maxBoxSize, int a_blockFactor, IntVect a_refineDirs)
{
CH_TIME("BRMeshRefine::domainSplit");
a_vbox.resize(0);
if (a_maxBoxSize == 0)
{
a_vbox.push_back(a_domain);
return;
}
int ratio = a_maxBoxSize/a_blockFactor;
// Set blockFactorDirs[d] = a_blockFactor if a_refineDirs[d] == 1; else 1.
IntVect blockFactorDirs = (a_blockFactor-1)*a_refineDirs + IntVect::Unit;
Box d(a_domain);
d.coarsen(blockFactorDirs);
if (refine(d, blockFactorDirs) != a_domain)
{
MayDay::Error("domainSplit: a_domain not coarsenable by blockingFactor");
}
/*
//recursive version here is too cute for very large box counts (bvs)
// apparently testRThetaZ needs domainSplit to work thsi way. I suspect the test needs a larger block factor
a_vbox.push_back(d);
for (int i=0; i<CH_SPACEDIM; ++i)
{
if (a_refineDirs[i] == 1)
{
breakBoxes(a_vbox, ratio, i);
}
}
for (int b=0; b<a_vbox.size(); ++b)
{
a_vbox[b].refine(blockFactorDirs);
}
*/
size_t count[CH_SPACEDIM+1] = {1};
for(int i=0; i<CH_SPACEDIM; ++i)
{
count[i+1]=count[i];
if(a_refineDirs[i]==1)
{
int c = (d.bigEnd()[i]-d.smallEnd()[i]+ratio)/ratio;
count[i+1]*=c;
}
}
a_vbox.resize(count[CH_SPACEDIM]);
//#pragma omp parallel for
for (int b=0; b<a_vbox.size(); ++b)
{
IntVect Lo(d.smallEnd()), Hi(d.bigEnd());
for(int i=0; i<CH_SPACEDIM ; i++)
{
if(a_refineDirs[i]==1)
{
int m = (b/count[i])%(count[i+1]/count[i]);
Lo[i]+=m*ratio;
Hi[i]=std::min(d.bigEnd()[i],Lo[i]+ratio-1);
}
}
a_vbox[b]=Box(Lo, Hi);
a_vbox[b].refine(blockFactorDirs);
}
}
// void
// domainSplit(const Box& a_domain, Vector<Box>& a_vbox, int a_maxBoxSize, int a_blockFactor)
// {
// CH_assert(!a_domain.isEmpty());
// CH_assert(a_maxBoxSize > 0);
// int iref = 1;
// Box coardom = coarsen(a_domain, iref);
// Vector<Box> domains(2);
// domains[0] = coardom;
// domains[1] = a_domain;
// Vector<Box> oldGrid0(1, coardom);
// Vector<Vector<Box> > oldMeshes(1);
// oldMeshes[0] = oldGrid0;
// if (a_maxBoxSize/a_blockFactor/iref < 1)
// MayDay::Error("DomainSplit: maxsize and blocking factor incompatible");
// Vector<Vector<Box> > newMeshes;
// Vector<int> refratio(1,iref);
// IntVectSet tags(coardom);
// // make irreg_boxes using berger-rigoutsos
// Real fillrat = 0.7;
// int buffersize = 1;
// int block_factor= a_blockFactor;
// Box testdom = coarsen(a_domain, iref*block_factor);
// testdom.refine(iref*block_factor);
// if (a_domain != testdom)
// MayDay::Error("DomainSplit:domain and Blocking Factor incompatible");
// BRMeshRefine mrobject(domains[0], refratio, fillrat,
// block_factor, buffersize, a_maxBoxSize);
// mrobject.regrid(newMeshes, tags, 0, 0,
// oldMeshes);
// CH_assert(newMeshes.size() == 2);
// a_vbox = newMeshes[1];
// }
std::list<int*> sendBuffers;
std::list<int> ch_count;
void
BRMeshRefine::sendBoxesParallel( const std::list<Box>& a_mesh,
int tag) const
{
#ifdef CH_MPI
const int boxSize = 2*CH_SPACEDIM;
int numBox = a_mesh.size();
int* next = new int[numBox*boxSize];
sendBuffers.push_back(next);
ch_count.push_back(numBox*boxSize);
std::list<Box>::const_iterator it = a_mesh.begin();
for (; it!=a_mesh.end(); ++it, next+=boxSize)
{
Box b = *it;
D_TERM6(next[0]=b.smallEnd(0);next[1]=b.bigEnd(0);,
next[2]=b.smallEnd(1);next[3]=b.bigEnd(1);,
next[4]=b.smallEnd(2);next[5]=b.bigEnd(2);,
next[6]=b.smallEnd(3);next[7]=b.bigEnd(3);,
next[8]=b.smallEnd(4);next[9]=b.bigEnd(4);,
next[10]=b.smallEnd(5);next[11]=b.bigEnd(5););
}
#endif
}
void
BRMeshRefine::receiveBoxesParallel(const Interval& a_from,
const Interval& a_to,
std::list<Box>& a_mesh,
int tag) const
{
#ifdef CH_MPI
// pout()<<"from "<<a_from.begin()<<a_from.end()<<"\n"
// <<"to "<<a_to.begin()<<a_to.end()<<"\n";
if(m_messageBuffer.size()<ch_count.back())
{
m_messageBuffer.resize(ch_count.back() + P_BUFFERSIZE);
}
int* recBuffer = &(m_messageBuffer[0]);
int* next = recBuffer;
MPI_Status status;
const int boxSize = 2*CH_SPACEDIM;
int source, dest;
source = CH4_SPMD::procID()-a_from.begin() + a_to.begin();
dest = source;
bool hang=false;
if (a_from.size() > a_to.size() && CH4_SPMD::procID()== a_from.end()) hang = true;
if (a_to.size() > a_from.size() && CH4_SPMD::procID()== a_to.end()) hang = true;
if (a_from.size() == a_to.size() || !hang)
{
// pout()<<"expecting boxes from "<<source<<"\n";
// pout()<<"sending "<<ch_count.back()/boxSize<<" boxes to "<<dest<<std::endl;
MPI_Sendrecv( sendBuffers.back(), ch_count.back(), MPI_INT,
dest, tag,
recBuffer, MAXBOXES*boxSize, MPI_INT,
source, tag, CH4_SPMD::Chombo_MPI::comm, &status );
}
// OK, need to pick up the oddball stragler here.
if (a_from.size() < a_to.size() && CH4_SPMD::procID()==a_from.end())
{
dest = a_to.end();
// pout()<<"SEnding "<<ch_count.back()/boxSize<<" boxes to "<<dest<<std::endl;
MPI_Send(sendBuffers.back(), ch_count.back(), MPI_INT,
a_to.end(), tag, CH4_SPMD::Chombo_MPI::comm);
}
if (a_from.size() > a_to.size() && CH4_SPMD::procID()==a_from.end())
{
source = a_to.end();
// pout()<<"EXpecting boxes from "<<source<<"\n";
MPI_Recv(recBuffer, MAXBOXES*boxSize, MPI_INT,
source, tag, CH4_SPMD::Chombo_MPI::comm, &status );
}
delete [] sendBuffers.back();
sendBuffers.pop_back();
ch_count.pop_back();
int numInt;
MPI_Get_count(&status, MPI_INT, &numInt);
int* end = next+numInt;
Box b;
IntVect& lo = (IntVect&)(b.smallEnd());
IntVect& hi = (IntVect&)(b.bigEnd());
for (; next<end; next+=(2*CH_SPACEDIM))
{
D_TERM6(lo[0]=next[0];hi[0]=next[1];,
lo[1]=next[2];hi[1]=next[3];,
lo[2]=next[4];hi[2]=next[5];,
lo[3]=next[6];hi[3]=next[7];,
lo[4]=next[8];hi[4]=next[9];,
lo[5]=next[10];hi[5]=next[11];);
b.computeBoxLenNotEmpty();
a_mesh.push_back(b);
}
//pout()<<"received "<<a_mesh.size()<<" boxes from "<<source<<std::endl;
#endif
}
int
BRMeshRefine::longsideRefineDirs(const Box& a_bx, int& a_dir) const
{
// Need only m_lowestRefineDir and m_refineDirs.
// CH_assert( isDefined() );
int maxlen = a_bx.size(m_lowestRefineDir);
a_dir = m_lowestRefineDir;
for (int idir = m_lowestRefineDir+1; idir < SpaceDim; idir++)
{
if (m_refineDirs[idir] == 1)
{
int len = a_bx.size(idir);
if (len > maxlen)
{
maxlen = len;
a_dir = idir;
}
}
}
return maxlen;
}
#include "Chombo_NamespaceFooter.H"
| 33.241181 | 113 | 0.581748 | [
"mesh",
"vector"
] |
a10f5e6a2a4bacbad98f6ff3fb6fcd0d527dd17c | 14,545 | cc | C++ | Validation/pyFrame3DD-master/gcc-master/gcc/brig/brigfrontend/brig-util.cc | djamal2727/Main-Bearing-Analytical-Model | 2f00c2219c71be0175c6f4f8f1d4cca231d97096 | [
"Apache-2.0"
] | null | null | null | Validation/pyFrame3DD-master/gcc-master/gcc/brig/brigfrontend/brig-util.cc | djamal2727/Main-Bearing-Analytical-Model | 2f00c2219c71be0175c6f4f8f1d4cca231d97096 | [
"Apache-2.0"
] | null | null | null | Validation/pyFrame3DD-master/gcc-master/gcc/brig/brigfrontend/brig-util.cc | djamal2727/Main-Bearing-Analytical-Model | 2f00c2219c71be0175c6f4f8f1d4cca231d97096 | [
"Apache-2.0"
] | null | null | null | /* brig-util.cc -- gccbrig utility functions
Copyright (C) 2016-2020 Free Software Foundation, Inc.
Contributed by Pekka Jaaskelainen <pekka.jaaskelainen@parmance.com>
for General Processor Tech.
This file is part of GCC.
GCC 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, or (at your option) any later
version.
GCC is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
for more details.
You should have received a copy of the GNU General Public License
along with GCC; see the file COPYING3. If not see
<http://www.gnu.org/licenses/>. */
#include <sstream>
#include "stdint.h"
#include "hsa-brig-format.h"
#include "brig-util.h"
#include "errors.h"
#include "diagnostic-core.h"
#include "print-tree.h"
bool
group_variable_offset_index::has_variable (const std::string &name) const
{
varname_offset_table::const_iterator i = m_group_offsets.find (name);
return i != m_group_offsets.end ();
}
/* Adds a new group segment variable. */
void
group_variable_offset_index::add (const std::string &name, size_t size,
size_t alignment)
{
size_t align_padding = m_next_group_offset % alignment == 0 ?
0 : (alignment - m_next_group_offset % alignment);
m_next_group_offset += align_padding;
m_group_offsets[name] = m_next_group_offset;
m_next_group_offset += size;
}
size_t
group_variable_offset_index::segment_offset (const std::string &name) const
{
varname_offset_table::const_iterator i = m_group_offsets.find (name);
gcc_assert (i != m_group_offsets.end ());
return (*i).second;
}
/* Return true if operand number OPNUM of instruction with OPCODE is an output.
False if it is an input. Some code reused from Martin Jambor's gcc-hsa
tree. */
bool
gccbrig_hsa_opcode_op_output_p (BrigOpcode16_t opcode, int opnum)
{
switch (opcode)
{
case BRIG_OPCODE_BR:
case BRIG_OPCODE_SBR:
case BRIG_OPCODE_CBR:
case BRIG_OPCODE_ST:
case BRIG_OPCODE_ATOMICNORET:
case BRIG_OPCODE_SIGNALNORET:
case BRIG_OPCODE_INITFBAR:
case BRIG_OPCODE_JOINFBAR:
case BRIG_OPCODE_WAITFBAR:
case BRIG_OPCODE_ARRIVEFBAR:
case BRIG_OPCODE_LEAVEFBAR:
case BRIG_OPCODE_RELEASEFBAR:
case BRIG_OPCODE_DEBUGTRAP:
return false;
default:
return opnum == 0;
}
}
unsigned
gccbrig_hsa_type_bit_size (BrigType16_t t)
{
unsigned pack_type = t & ~BRIG_TYPE_BASE_MASK;
if (pack_type == BRIG_TYPE_PACK_32)
return 32;
else if (pack_type == BRIG_TYPE_PACK_64)
return 64;
else if (pack_type == BRIG_TYPE_PACK_128)
return 128;
switch (t)
{
case BRIG_TYPE_NONE:
return 0;
case BRIG_TYPE_B1:
return 1;
case BRIG_TYPE_U8:
case BRIG_TYPE_S8:
case BRIG_TYPE_B8:
return 8;
case BRIG_TYPE_U16:
case BRIG_TYPE_S16:
case BRIG_TYPE_B16:
case BRIG_TYPE_F16:
return 16;
case BRIG_TYPE_U32:
case BRIG_TYPE_S32:
case BRIG_TYPE_B32:
case BRIG_TYPE_F32:
case BRIG_TYPE_U8X4:
case BRIG_TYPE_U16X2:
case BRIG_TYPE_S8X4:
case BRIG_TYPE_S16X2:
case BRIG_TYPE_F16X2:
case BRIG_TYPE_SIG32:
return 32;
case BRIG_TYPE_U64:
case BRIG_TYPE_S64:
case BRIG_TYPE_F64:
case BRIG_TYPE_B64:
case BRIG_TYPE_U8X8:
case BRIG_TYPE_U16X4:
case BRIG_TYPE_U32X2:
case BRIG_TYPE_S8X8:
case BRIG_TYPE_S16X4:
case BRIG_TYPE_S32X2:
case BRIG_TYPE_F16X4:
case BRIG_TYPE_F32X2:
case BRIG_TYPE_SIG64:
return 64;
case BRIG_TYPE_B128:
case BRIG_TYPE_U8X16:
case BRIG_TYPE_U16X8:
case BRIG_TYPE_U32X4:
case BRIG_TYPE_U64X2:
case BRIG_TYPE_S8X16:
case BRIG_TYPE_S16X8:
case BRIG_TYPE_S32X4:
case BRIG_TYPE_S64X2:
case BRIG_TYPE_F16X8:
case BRIG_TYPE_F32X4:
case BRIG_TYPE_F64X2:
return 128;
default:
printf ("HMM %d %x\n", t, t);
gcc_unreachable ();
}
}
/* gcc-hsa borrowed code ENDS. */
uint64_t
gccbrig_to_uint64_t (const BrigUInt64 &brig_type)
{
return (uint64_t (brig_type.hi) << 32) | uint64_t (brig_type.lo);
}
int
gccbrig_reg_size (const BrigOperandRegister *brig_reg)
{
switch (brig_reg->regKind)
{
case BRIG_REGISTER_KIND_CONTROL:
return 1;
case BRIG_REGISTER_KIND_SINGLE:
return 32;
case BRIG_REGISTER_KIND_DOUBLE:
return 64;
case BRIG_REGISTER_KIND_QUAD:
return 128;
default:
gcc_unreachable ();
break;
}
}
std::string
gccbrig_reg_name (const BrigOperandRegister *reg)
{
std::ostringstream strstr;
switch (reg->regKind)
{
case BRIG_REGISTER_KIND_CONTROL:
strstr << 'c';
break;
case BRIG_REGISTER_KIND_SINGLE:
strstr << 's';
break;
case BRIG_REGISTER_KIND_DOUBLE:
strstr << 'd';
break;
case BRIG_REGISTER_KIND_QUAD:
strstr << 'q';
break;
default:
gcc_unreachable ();
return "";
}
strstr << reg->regNum;
return strstr.str ();
}
std::string
gccbrig_type_name (BrigType16_t type)
{
switch (type)
{
case BRIG_TYPE_U8:
return "u8";
case BRIG_TYPE_U16:
return "u16";
case BRIG_TYPE_U32:
return "u32";
case BRIG_TYPE_U64:
return "u64";
case BRIG_TYPE_S8:
return "s8";
case BRIG_TYPE_S16:
return "s16";
case BRIG_TYPE_S32:
return "s32";
case BRIG_TYPE_S64:
return "s64";
default:
gcc_unreachable ();
break;
}
}
std::string
gccbrig_segment_name (BrigSegment8_t segment)
{
if (segment == BRIG_SEGMENT_GLOBAL)
return "global";
else if (segment == BRIG_SEGMENT_GROUP)
return "group";
else if (segment == BRIG_SEGMENT_PRIVATE)
return "private";
else
gcc_unreachable ();
}
bool
gccbrig_is_float_type (BrigType16_t type)
{
return (type == BRIG_TYPE_F32 || type == BRIG_TYPE_F64
|| type == BRIG_TYPE_F16);
}
BrigType16_t
gccbrig_tree_type_to_hsa_type (tree tree_type)
{
if (INTEGRAL_TYPE_P (tree_type))
{
if (TYPE_UNSIGNED (tree_type))
{
switch (int_size_in_bytes (tree_type))
{
case 1:
return BRIG_TYPE_U8;
case 2:
return BRIG_TYPE_U16;
case 4:
return BRIG_TYPE_U32;
case 8:
return BRIG_TYPE_U64;
default:
break;
}
}
else
{
switch (int_size_in_bytes (tree_type))
{
case 1:
return BRIG_TYPE_S8;
case 2:
return BRIG_TYPE_S16;
case 4:
return BRIG_TYPE_S32;
case 8:
return BRIG_TYPE_S64;
default:
break;
}
}
}
else if (VECTOR_TYPE_P (tree_type))
{
tree element_type = TREE_TYPE (tree_type);
size_t element_size = int_size_in_bytes (element_type) * 8;
BrigType16_t brig_element_type;
switch (element_size)
{
case 8:
brig_element_type
= TYPE_UNSIGNED (element_type) ? BRIG_TYPE_U8 : BRIG_TYPE_S8;
break;
case 16:
brig_element_type
= TYPE_UNSIGNED (element_type) ? BRIG_TYPE_U16 : BRIG_TYPE_S16;
break;
case 32:
brig_element_type
= TYPE_UNSIGNED (element_type) ? BRIG_TYPE_U32 : BRIG_TYPE_S32;
break;
case 64:
brig_element_type
= TYPE_UNSIGNED (element_type) ? BRIG_TYPE_U64 : BRIG_TYPE_S64;
break;
default:
gcc_unreachable ();
}
BrigType16_t pack_type;
switch (int_size_in_bytes (tree_type) * 8)
{
case 32:
pack_type = BRIG_TYPE_PACK_32;
break;
case 64:
pack_type = BRIG_TYPE_PACK_64;
break;
case 128:
pack_type = BRIG_TYPE_PACK_128;
break;
default:
gcc_unreachable ();
}
return brig_element_type | pack_type;
}
gcc_unreachable ();
}
/* Returns true in case the operation is a "bit level" operation,
that is, not having operand type depending semantical differences. */
bool
gccbrig_is_bit_operation (BrigOpcode16_t opcode)
{
return opcode == BRIG_OPCODE_CMOV || opcode == BRIG_OPCODE_SHUFFLE
|| opcode == BRIG_OPCODE_UNPACK || opcode == BRIG_OPCODE_UNPACKLO
|| opcode == BRIG_OPCODE_UNPACKHI || opcode == BRIG_OPCODE_ST
|| opcode == BRIG_OPCODE_PACK;
}
/* The program scope definition can be left external within the
kernel binary which means it must be defined by the host via
HSA runtime. For these we have special treatment:
Create additional pointer indirection when accessing the variable
value from kernel code through a generated pointer
__gccbrig_ptr_variable_name. The pointer value then can be set either
within the kernel binary (in case of a later linked in definition)
or from the host. */
bool
gccbrig_might_be_host_defined_var_p (const BrigDirectiveVariable *brigVar)
{
bool is_definition = brigVar->modifier & BRIG_VARIABLE_DEFINITION;
return (brigVar->segment == BRIG_SEGMENT_GLOBAL
|| brigVar->segment == BRIG_SEGMENT_READONLY) && !is_definition
&& brigVar->linkage == BRIG_LINKAGE_PROGRAM
&& (brigVar->allocation == BRIG_ALLOCATION_PROGRAM
|| brigVar->allocation == BRIG_ALLOCATION_AGENT);
}
/* Produce a GENERIC type for the given HSA/BRIG type. Returns the element
type in case of vector instructions. */
tree
gccbrig_tree_type_for_hsa_type (BrigType16_t brig_type)
{
tree tree_type = NULL_TREE;
if (hsa_type_packed_p (brig_type))
{
/* The element type is encoded in the bottom 5 bits. */
BrigType16_t inner_brig_type = brig_type & BRIG_TYPE_BASE_MASK;
unsigned full_size = gccbrig_hsa_type_bit_size (brig_type);
if (inner_brig_type == BRIG_TYPE_F16)
return build_vector_type (gccbrig_tree_type_for_hsa_type (BRIG_TYPE_U16),
full_size / 16);
tree inner_type = gccbrig_tree_type_for_hsa_type (inner_brig_type);
unsigned inner_size = gccbrig_hsa_type_bit_size (inner_brig_type);
unsigned nunits = full_size / inner_size;
tree_type = build_vector_type (inner_type, nunits);
}
else
{
switch (brig_type)
{
case BRIG_TYPE_NONE:
tree_type = void_type_node;
break;
case BRIG_TYPE_B1:
tree_type = boolean_type_node;
break;
case BRIG_TYPE_S8:
case BRIG_TYPE_S16:
case BRIG_TYPE_S32:
case BRIG_TYPE_S64:
/* Ensure a fixed width integer. */
tree_type
= build_nonstandard_integer_type
(gccbrig_hsa_type_bit_size (brig_type), false);
break;
case BRIG_TYPE_U8:
return unsigned_char_type_node;
case BRIG_TYPE_U16:
case BRIG_TYPE_U32:
case BRIG_TYPE_U64:
case BRIG_TYPE_B8: /* Handle bit vectors as unsigned ints. */
case BRIG_TYPE_B16:
case BRIG_TYPE_B32:
case BRIG_TYPE_B64:
case BRIG_TYPE_B128:
case BRIG_TYPE_SIG32: /* Handle signals as integers for now. */
case BRIG_TYPE_SIG64:
tree_type = build_nonstandard_integer_type
(gccbrig_hsa_type_bit_size (brig_type), true);
break;
case BRIG_TYPE_F16:
tree_type = uint16_type_node;
break;
case BRIG_TYPE_F32:
/* TODO: make sure that the alignment of the float are at least as
strict than mandated by HSA, and conform to IEEE (like mandated
by HSA). */
tree_type = float_type_node;
break;
case BRIG_TYPE_F64:
tree_type = double_type_node;
break;
case BRIG_TYPE_SAMP:
case BRIG_TYPE_ROIMG:
case BRIG_TYPE_WOIMG:
case BRIG_TYPE_RWIMG:
{
/* Handle images and samplers as target-specific blobs of data
that should be allocated earlier on from the runtime side.
Create a void* that should be initialized to point to the blobs
by the kernel launcher. Images and samplers are accessed
via builtins that take void* as the reference. TODO: who and
how these arrays should be initialized? */
tree void_ptr = build_pointer_type (void_type_node);
return void_ptr;
}
default:
gcc_unreachable ();
break;
}
}
/* Drop const qualifiers. */
return tree_type;
}
/* Calculates numeric identifier for the HSA register REG.
Returned value is bound to [0, BRIG_2_TREE_HSAIL_TOTAL_REG_COUNT]. */
size_t
gccbrig_hsa_reg_id (const BrigOperandRegister ®)
{
size_t offset = reg.regNum;
switch (reg.regKind)
{
case BRIG_REGISTER_KIND_QUAD:
offset
+= BRIG_2_TREE_HSAIL_D_REG_COUNT + BRIG_2_TREE_HSAIL_S_REG_COUNT
+ BRIG_2_TREE_HSAIL_C_REG_COUNT;
break;
case BRIG_REGISTER_KIND_DOUBLE:
offset += BRIG_2_TREE_HSAIL_S_REG_COUNT + BRIG_2_TREE_HSAIL_C_REG_COUNT;
break;
case BRIG_REGISTER_KIND_SINGLE:
offset += BRIG_2_TREE_HSAIL_C_REG_COUNT;
case BRIG_REGISTER_KIND_CONTROL:
break;
default:
gcc_unreachable ();
break;
}
return offset;
}
std::string
gccbrig_hsa_reg_name_from_id (size_t reg_id)
{
char reg_name[32];
long unsigned int reg_hash = (long unsigned int) reg_id;
if (reg_hash < BRIG_2_TREE_HSAIL_C_REG_COUNT)
{
sprintf (reg_name, "$c%lu", reg_hash);
return reg_name;
}
reg_hash -= BRIG_2_TREE_HSAIL_C_REG_COUNT;
if (reg_hash < BRIG_2_TREE_HSAIL_S_REG_COUNT)
{
sprintf (reg_name, "$s%lu", reg_hash);
return reg_name;
}
reg_hash -= BRIG_2_TREE_HSAIL_S_REG_COUNT;
if (reg_hash < BRIG_2_TREE_HSAIL_D_REG_COUNT)
{
sprintf (reg_name, "$d%lu", reg_hash);
return reg_name;
}
reg_hash -= BRIG_2_TREE_HSAIL_D_REG_COUNT;
if (reg_hash < BRIG_2_TREE_HSAIL_Q_REG_COUNT)
{
sprintf (reg_name, "$q%lu", reg_hash);
return reg_name;
}
gcc_unreachable ();
return "$??";
}
/* Prints statistics of register usage to stdout. */
void
gccbrig_print_reg_use_info (FILE *dump, const regs_use_index &info)
{
regs_use_index::const_iterator begin_it = info.begin ();
regs_use_index::const_iterator end_it = info.end ();
for (regs_use_index::const_iterator it = begin_it; it != end_it; it++)
{
std::string hsa_reg = gccbrig_hsa_reg_name_from_id (it->first);
printf ("%s:\n", hsa_reg.c_str ());
const reg_use_info &info = it->second;
typedef std::vector<std::pair<tree, size_t> >::const_iterator reg_use_it;
reg_use_it begin_it2 = info.m_type_refs.begin ();
reg_use_it end_it2 = info.m_type_refs.end ();
for (reg_use_it it2 = begin_it2; it2 != end_it2; it2++)
{
fprintf (dump, "(%lu) ", (long unsigned int) it2->second);
print_node_brief (dump, "", it2->first, 0);
fprintf (dump, "\n");
}
}
}
/* Return true if TYPE is a packed HSA type. */
bool
hsa_type_packed_p (BrigType16_t type)
{
return (type & BRIG_TYPE_PACK_MASK) != BRIG_TYPE_PACK_NONE;
}
| 25.295652 | 79 | 0.699828 | [
"vector"
] |
e164525cdcd92a73b8c0efa510ea19a8996b25a3 | 1,435 | cpp | C++ | gps/gps.cpp | devangel77b/hull13 | 8658d8c0be99b60656d6c57442222832c891a4f7 | [
"Apache-2.0"
] | null | null | null | gps/gps.cpp | devangel77b/hull13 | 8658d8c0be99b60656d6c57442222832c891a4f7 | [
"Apache-2.0"
] | 14 | 2018-04-29T12:24:46.000Z | 2018-07-24T17:58:50.000Z | gps/gps.cpp | devangel77b/hull13 | 8658d8c0be99b60656d6c57442222832c891a4f7 | [
"Apache-2.0"
] | null | null | null | /*
gps.cpp implementation file
Dennis Evangelista, 2018
*/
#include "mbed.h"
#include "rtos.h"
#include "gps.h"
#include "TinyGPSplus.h"
/*
Callback function for the gps, to be attached to RxIrq on the Serial
connection _gps to the Copernicus II.
*/
void Gps::_rx_callback(void){
// have to actually read to clear the interrupt
char c = Gps::_gps.getc();
//printf("%c",c);
Gps::parser.encode(c); //Gps::_gps.getc());
}
/**
Gps(tx,rx) is the constructor. Use this to declare a Gps
connected to a particular port, e.g. Gps gps(PC_3,PC_3).
@param tx is the RS232 serial tx pin
@param rx is the RS232 serial rx pin
@returns a Gps object
For Hull 13 mod 2 rev D, GPSTX is PC_2, GPSRX is PC_3.
The Copernicus II uses 4800 8N1 and is expected to put out
NMEA0183 compliant sentences.
*/
Gps::Gps(PinName tx, PinName rx):_gps(tx,rx){
debug("Gps constructor called.\n"); // for debugging.
Gps::_gps.baud(4800); // 4800 8N1
Gps::_gps.format(8,SerialBase::None,1);
// the next line attaches the rx callback to Gps rx irq
Gps::_gps.attach(callback(this,&Gps::_rx_callback),Serial::RxIrq);
} // Gps(tx,rx) constructor
/**
~Gps() is the destructor. This one is not too complicated, not much
to do...
*/
Gps::~Gps(){
debug("Gps destructor called.\n");
} // ~Gps() destructor
| 19.391892 | 72 | 0.625087 | [
"object"
] |
e1649d6a233907efa33d5a49b1849f1a5dc63058 | 8,762 | cpp | C++ | src/libsalt/Simulation.cpp | etri-city-traffic-brain/traffic-simulator | 6d5061febeaef484388b2b5aee14d9894099d98a | [
"Apache-2.0"
] | 8 | 2020-08-27T05:44:05.000Z | 2021-12-27T05:11:17.000Z | src/libsalt/Simulation.cpp | etri-city-traffic-brain/traffic-simulator | 6d5061febeaef484388b2b5aee14d9894099d98a | [
"Apache-2.0"
] | null | null | null | src/libsalt/Simulation.cpp | etri-city-traffic-brain/traffic-simulator | 6d5061febeaef484388b2b5aee14d9894099d98a | [
"Apache-2.0"
] | 1 | 2020-11-27T05:17:29.000Z | 2020-11-27T05:17:29.000Z | /****************************************************************************/
// C++ libsalt API implementation
/****************************************************************************/
#include <cstring>
#include <utils/config.h>
#include <utils/etc.h>
#include "LibsaltDefs.h"
#include "Simulation.h"
#include "VisClient.hpp"
namespace libsalt {
// ===========================================================================
// static member initializations
// ===========================================================================
Clock::time_point Simulation::timeStart;
Clock::time_point Simulation::timeEnd;
std::string Simulation::scenarioFile;
std::string Simulation::partitionID;
SALT::SimulationController* Simulation::SC = nullptr;
VisClient* VC = nullptr;
// ===========================================================================
// static member definitions
// ===========================================================================
void
Simulation::load(std::string argv) {
if (argv == "") {
std::cerr << "--- Error: Scenario File Not Specified ---" << std::endl;
return;
} else {
scenarioFile = argv;
std::cout << "scenarioFile: " << scenarioFile << std::endl;
}
std::cout << "[SALT Simulator 2.0] " << std::endl;
std::cout << "--- Scenario File: " << scenarioFile << std::endl;
// Create simulation controller
SC = new SALT::SimulationController();
SALT::Result configResult = SC->configureSimulation(scenarioFile);
if (configResult == SALT::FAILURE) {
std::cerr << "--- Error: Configuration Failed ---" << std::endl;
return;
}
cout << "--- Configuration Done ---" << endl;
SC->printSimulationSetting();
// #define RENDER
#ifdef RENDER
render()
#endif
// ===========================================
// Start TCP server
// master's host and port
string host = SC->getScenarioInfo()->simhost;
int port = SC->getScenarioInfo()->simport;
int interval = SC->getScenarioInfo()->siminterval;
if (port != 0) {
VC = new VisClient(SC, host, port);
VC->interval = interval;
VC->start();
}
// ===========================================
// Run simulation
timeStart = Clock::now();
std::cout << "[Simulation Start]" << std::endl;
SC->assertReady();
}
void
Simulation::render() {
// Road Network Rendering
auto nodes = SC->getNodeList();
for (auto node: nodes) {
std::cout << "Node " << node->getID() << " shape: " << node->getShape() << std::endl;
}
auto links = SC->getLinkList();
for (auto link: links){
std::cout << "Link " << link->getID() << " #section: " << link->getNumSection() << " #lane: " << link->getNumLane() << " shape: " << link->getShape() << std::endl;
}
auto cells = SC->getCellList();
for(auto cell: cells){
std::cout << "Cell " << cell->getMyLink()->getID() << "-" << cell->getSection() << "-" << cell->getLane() << ": " << cell->getMyCurrentVolume() << std::endl;
}
// Traffic Signal Rendering
auto trafficSignals = SC->getTrafficSignalList();
for (auto ts : trafficSignals){
SALT::Node* signalizedNode = ts->getMyNode();
string currentSignalState = signalizedNode->getCurrentTrafficSignalState(); //
// iterate over all the connections on the node
cout << signalizedNode->getID() << endl;
auto conns = signalizedNode->getOrderedConnectionList();
for (unsigned order = 0; order < conns.size(); order++){
SALT::Connection* targetConnection = conns[order];
// get connection's info and traffic signal on the connection
SALT::Link* fromLink = targetConnection->getFromLink(); // where to render
int fromLane = targetConnection->getFromLane(); // where to render
SALT::Vector2D direction = targetConnection->getDirection(); // what to render (vector img)
std::string rotationDir = targetConnection->getRotationDir(); // "L", "S", "R"
char& currentSignal = currentSignalState[order]; // one of 'G', 'g', 'r','y'
// render a colored(signal) arrow(direction vector) at location(fromLink,fromLane)
std::cout << "Render a colored(" << string(1, currentSignal) << ") turn info(" << rotationDir << ")\t at (" << fromLane << ")th lane of Link" << fromLink->getID() << std::endl;
}
std::cout << "Done\n";;
}
}
bool
Simulation::isLoaded() {
if (SC->getSimulationState() != SALT::SIMULATION_READY) {
return false;
}
return true;
}
void
Simulation::step(const int timestep) {
SALT::SALTTime endStep = (SALT::SALTTime)timestep;
SALT::SALTTime currentStep = SC->getCurrentStep();
// cout << "SC->getBeginStep(): " << SC->getBeginStep() << ", SC->getEndStep(): " << SC->getEndStep() << ", currentStep: " << currentStep << endl;
if (SC->getEndStep() < currentStep) {
return;
}
do {
auto timeStepStart = Clock::now();
currentStep = SC->getCurrentStep();
#ifdef DEBUG
std::cout << "(Step " << currentStep << ")" << std::endl;
#endif
// update status of vehicles, traffic signals and events
SC->doSimulationStep(currentStep);
// #define RENDER
#ifdef RENDER
// access only the activated cells at the current step
const auto activeCells = SC->getActiveCellSet();
for (auto activeCell: activeCells){
string cellID= activeCell->getID();
int currentVehNum = activeCell->getMyCurrentVolume();
float density = (5.0f * currentVehNum) / activeCell->getMyLength();
std::cout << "Cell id: " << cellID << " current #(veh): " << currentVehNum << " density: " << density << std::endl;
}
#endif
SC->printStep(currentStep, 20);
auto timeStepEnd = Clock::now();
auto elapsedTime = chrono::duration_cast<std::chrono::milliseconds>(timeStepEnd - timeStepStart).count();
SC->writeProgress(currentStep, std::to_string(elapsedTime));
// Send visualization data to VisServer
if (VC != nullptr) {
int interval = VC->interval; // Send every ratio'th data to VisServer
if (currentStep % interval == 0) {
VC->sendDataMessageInternal();
}
}
if (endStep > currentStep) {
SC->increaseCurrentStep();
}
} while (endStep > currentStep);
}
void
Simulation::setCurrentStep(const int timestep) {
SALT::SALTTime endStep = (SALT::SALTTime)timestep;
SALT::SALTTime currentStep = SC->getCurrentStep();
std::cout << "[Jump currentStep from " << currentStep << " to " << endStep << "]" << std::endl;
do {
// std::cout << "(Step " << currentStep << ")" << std::endl;
if (endStep > currentStep) {
SC->increaseCurrentStep();
}
currentStep = SC->getCurrentStep();
} while (endStep > currentStep);
}
void
Simulation::close(const std::string& reason) {
timeEnd = Clock::now();
std::cout << "[Simulation End]" << std::endl;
auto elapsedTime = chrono::duration_cast<std::chrono::seconds>(timeEnd - timeStart).count();
std::cout << "Elapsed Time: " << elapsedTime << " seconds" << std::endl;
SC->stop();
SC = nullptr;
if (VC != nullptr) {
VC->stop();
VC = nullptr;
}
}
int
Simulation::getCurrentStep() {
return SC->getCurrentStep();
}
int
Simulation::getBeginStep() {
return SC->getBeginStep();
}
int
Simulation::getEndStep() {
return SC->getEndStep();
}
SALT::NetworkManager*
Simulation::getNetworkManager() {
return SC->myNetworkManager;
}
SALT::VehicleManager*
Simulation::getVehicleManager() {
return SC->myVehicleManager;
}
SALT::TrafficSignalManager*
Simulation::getTrafficSignalManager() {
return SC->myTrafficSignalManager;
}
} // end of namespace libsalt
/****************************************************************************/ | 35.617886 | 189 | 0.510157 | [
"render",
"shape",
"vector"
] |
e164e6b51174f3d35fada92f854fe7c35251db30 | 24,940 | cpp | C++ | src/qt/bdappage.cpp | blackrangersoftware/brs-dynamic-core | 21d2e1d944acaf50fead74e3137a67082658da6f | [
"MIT"
] | 1 | 2020-12-29T15:35:45.000Z | 2020-12-29T15:35:45.000Z | src/qt/bdappage.cpp | yangbaitu/Dynamic | 21d2e1d944acaf50fead74e3137a67082658da6f | [
"MIT"
] | null | null | null | src/qt/bdappage.cpp | yangbaitu/Dynamic | 21d2e1d944acaf50fead74e3137a67082658da6f | [
"MIT"
] | null | null | null | // Copyright (c) 2016-2019 Duality Blockchain Solutions Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bdappage.h"
#include "bdap/fees.h"
#include "bdapaccounttablemodel.h"
#include "bdapaddlinkdialog.h"
#include "bdapadduserdialog.h"
#include "bdapfeespopup.h"
#include "bdaplinkdetaildialog.h"
#include "bdaplinktablemodel.h"
#include "bdapupdateaccountdialog.h"
#include "bdapuserdetaildialog.h"
#include "clientmodel.h"
#include "dynode-sync.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "rpc/client.h"
#include "rpc/register.h"
#include "rpc/server.h"
#include "ui_bdappage.h"
#include "walletmodel.h"
#include <stdio.h>
#include <boost/algorithm/string.hpp>
#include <QTableWidget>
BdapPage::BdapPage(const PlatformStyle* platformStyle, QWidget* parent) : QWidget(parent),
ui(new Ui::BdapPage),
clientModel(0),
model(0),
bdapAccountTableModel(0)
{
ui->setupUi(this);
evaluateTransactionButtons();
bdapAccountTableModel = new BdapAccountTableModel(this);
bdapLinkTableModel = new BdapLinkTableModel(this);
ui->lineEditUserCommonNameSearch->setFixedWidth(COMMONNAME_COLWIDTH);
ui->lineEditUserFullPathSearch->setFixedWidth(FULLPATH_COLWIDTH);
ui->lineEditGroupCommonNameSearch->setFixedWidth(COMMONNAME_COLWIDTH);
ui->lineEditGroupFullPathSearch->setFixedWidth(FULLPATH_COLWIDTH);
//Users tab
connect(ui->pushButton_All, SIGNAL(clicked()), this, SLOT(listAllUsers()));
connect(ui->addUser, SIGNAL(clicked()), this, SLOT(addUser()));
connect(ui->pushButtonUpdateUser, SIGNAL(clicked()), this, SLOT(updateUser()));
connect(ui->deleteUser, SIGNAL(clicked()), this, SLOT(deleteUser()));
connect(ui->checkBoxMyUsers, SIGNAL(clicked()), this, SLOT(listAllUsers()));
connect(ui->lineEditUserCommonNameSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listAllUsers()));
connect(ui->lineEditUserFullPathSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listAllUsers()));
connect(ui->tableWidget_Users, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(getUserDetails(int,int)));
//Groups tab
connect(ui->pushButton_AllGroups, SIGNAL(clicked()), this, SLOT(listAllGroups()));
connect(ui->addGroup, SIGNAL(clicked()), this, SLOT(addGroup()));
connect(ui->pushButtonUpdateGroup, SIGNAL(clicked()), this, SLOT(updateGroup()));
connect(ui->deleteGroup, SIGNAL(clicked()), this, SLOT(deleteGroup()));
connect(ui->checkBoxMyGroups, SIGNAL(clicked()), this, SLOT(listAllGroups()));
connect(ui->lineEditGroupCommonNameSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listAllGroups()));
connect(ui->lineEditGroupFullPathSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listAllGroups()));
connect(ui->tableWidget_Groups, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(getGroupDetails(int,int)));
//Links tab
connect(ui->pushButtonRefreshAllLinks, SIGNAL(clicked()), this, SLOT(listLinksAll()));
connect(ui->lineEditCompleteRequestorSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listLinksComplete()));
connect(ui->lineEditCompleteRecipientSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listLinksComplete()));
connect(ui->lineEditPARequestorSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listPendingAccept()));
connect(ui->lineEditPARecipientSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listPendingAccept()));
connect(ui->lineEditPRRequestorSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listPendingRequest()));
connect(ui->lineEditPRRecipientSearch, SIGNAL(textChanged(const QString &)), this, SLOT(listPendingRequest()));
connect(ui->pushButtonAccept, SIGNAL(clicked()), this, SLOT(acceptLink()));
connect(ui->tableWidgetPendingAccept, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(getLinkDetails(int,int)));
connect(ui->tableWidgetPendingRequest, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(getLinkDetails(int,int)));
connect(ui->tableWidgetComplete, SIGNAL(cellDoubleClicked(int,int)), this, SLOT(getLinkDetails(int,int)));
connect(ui->pushButtonAddLink, SIGNAL(clicked()), this, SLOT(addLink()));
}
BdapPage::~BdapPage()
{
delete ui;
}
void BdapPage::setModel(WalletModel* model)
{
this->model = model;
}
void BdapPage::setClientModel(ClientModel* _clientModel)
{
this->clientModel = _clientModel;
if (_clientModel) {
connect(_clientModel, SIGNAL(numBlocksChanged(int, QDateTime, double, bool)), this, SLOT(updateBDAPLists()));
}
}
void BdapPage::evaluateTransactionButtons()
{
int currentIndex = ui->tabWidget->currentIndex();
bool myUsersChecked = ui->checkBoxMyUsers->isChecked();
bool myGroupsChecked = ui->checkBoxMyGroups->isChecked();
switch (currentIndex) {
case 0: //Users
ui->pushButtonUpdateUser->setVisible(myUsersChecked);
ui->deleteUser->setVisible(myUsersChecked);
break;
case 1: //Groups
ui->pushButtonUpdateGroup->setVisible(myGroupsChecked);
ui->deleteGroup->setVisible(myGroupsChecked);
break;
}; //end switch
} //evaluateTransactionButtons
//Links tab =========================================================================
void BdapPage::listLinksAll()
{
bdapLinkTableModel->refreshAll();
} //listLinksAll
void BdapPage::listLinksComplete()
{
bdapLinkTableModel->refreshComplete();
} //listLinksComplete
void BdapPage::listPendingAccept()
{
bdapLinkTableModel->refreshPendingAccept();
} //listPendingAccept
void BdapPage::listPendingRequest()
{
bdapLinkTableModel->refreshPendingRequest();
} //listPendingRequest
//Groups tab ========================================================================
void BdapPage::listAllGroups()
{
evaluateTransactionButtons();
bdapAccountTableModel->refreshGroups();
} //listAllGroups
void BdapPage::addGroup()
{
//Check to see if wallet needs upgrading
if (model->getWallet()->WalletNeedsUpgrading()) {
QMessageBox::critical(this, QObject::tr("Older wallet version detected"),
QObject::tr("Your wallet has not been fully upgraded to version 2.4. Please unlock your wallet to continue."));
return;
}
if (!dynodeSync.IsBlockchainSynced()) {
QMessageBox::information(this, QObject::tr("Wallet not synced"), QObject::tr("Cannot create BDAP objects while wallet is not synced."));
return;
}
BdapAddUserDialog dlg(this,model->getOptionsModel()->getDisplayUnit(),BDAP::ObjectType::BDAP_GROUP);
dlg.setWindowTitle(QObject::tr("Add BDAP Group"));
dlg.exec();
if (dlg.result() == 1) {
bdapAccountTableModel->refreshGroups();
}
} //addGroup
void BdapPage::deleteGroup()
{
if (!dynodeSync.IsBlockchainSynced()) {
QMessageBox::information(this, QObject::tr("Wallet not synced"), QObject::tr("Cannot create/modify BDAP objects while wallet is not synced."));
return;
}
QMessageBox::StandardButton reply;
std::string account = "";
std::string displayedMessage = "";
QItemSelectionModel* selectionModel = ui->tableWidget_Groups->selectionModel();
QModelIndexList selected = selectionModel->selectedRows();
int nSelectedRow = selected.count() ? selected.at(0).row() : -1;
if (nSelectedRow == -1) return; //do nothing if no rows are selected
account = ui->tableWidget_Groups->item(nSelectedRow,1)->text().toStdString();
displayedMessage = "Are you sure you want to delete \"" + account + "\""; //std::to_string(nSelectedRow);
reply = QMessageBox::question(this, QObject::tr("Confirm Delete Account"), QObject::tr(displayedMessage.c_str()), QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
executeDeleteAccount(account, BDAP::ObjectType::BDAP_GROUP);
};
} //deleteGroup
void BdapPage::updateGroup()
{
if (!dynodeSync.IsBlockchainSynced()) {
QMessageBox::information(this, QObject::tr("Wallet not synced"), QObject::tr("Cannot create/modify BDAP objects while wallet is not synced."));
return;
}
std::string account = "";
std::string commonName = "";
std::string expirationDate = "";
QItemSelectionModel* selectionModel = ui->tableWidget_Groups->selectionModel();
QModelIndexList selected = selectionModel->selectedRows();
int nSelectedRow = selected.count() ? selected.at(0).row() : -1;
if (nSelectedRow == -1) return; //do nothing if no rows are selected
account = ui->tableWidget_Groups->item(nSelectedRow,1)->text().toStdString();
commonName = ui->tableWidget_Groups->item(nSelectedRow,0)->text().toStdString();
expirationDate = ui->tableWidget_Groups->item(nSelectedRow,2)->text().toStdString();
BdapUpdateAccountDialog dlg(this,BDAP::ObjectType::BDAP_GROUP,account,commonName,expirationDate,model->getOptionsModel()->getDisplayUnit());
dlg.setWindowTitle(QObject::tr("Update BDAP Group"));
dlg.exec();
if (dlg.result() == 1) {
bdapAccountTableModel->refreshGroups();
}
} //updateGroup
void BdapPage::getGroupDetails(int row, int column)
{
BdapUserDetailDialog dlg(this,BDAP::ObjectType::BDAP_GROUP,ui->tableWidget_Groups->item(row,1)->text().toStdString());
dlg.setWindowTitle(QObject::tr("BDAP Group Detail"));
dlg.exec();
} //getGroupDetails
void BdapPage::updateBDAPLists()
{
if (dynodeSync.IsBlockchainSynced()) {
evaluateTransactionButtons();
bdapAccountTableModel->refreshUsers();
bdapAccountTableModel->refreshGroups();
bdapLinkTableModel->refreshComplete();
bdapLinkTableModel->refreshPendingAccept();
bdapLinkTableModel->refreshPendingRequest();
}
} //updateBDAPLists
//Users tab =========================================================================
void BdapPage::listAllUsers()
{
evaluateTransactionButtons();
bdapAccountTableModel->refreshUsers();
} //listAllUsers
void BdapPage::addUser()
{
//Check to see if wallet needs upgrading
if (model->getWallet()->WalletNeedsUpgrading()) {
QMessageBox::critical(this, QObject::tr("Older wallet version detected"),
QObject::tr("Your wallet has not been fully upgraded to version 2.4. Please unlock your wallet to continue."));
return;
}
if (!dynodeSync.IsBlockchainSynced()) {
QMessageBox::information(this, QObject::tr("Wallet not synced"), QObject::tr("Cannot create BDAP objects while wallet is not synced."));
return;
}
BdapAddUserDialog dlg(this,model->getOptionsModel()->getDisplayUnit());
dlg.exec();
if (dlg.result() == 1) {
bdapAccountTableModel->refreshUsers();
}
} //addUser
void BdapPage::getUserDetails(int row, int column)
{
BdapUserDetailDialog dlg(this,BDAP::ObjectType::BDAP_USER,ui->tableWidget_Users->item(row,1)->text().toStdString());
dlg.setWindowTitle(QObject::tr("BDAP User Detail"));
dlg.exec();
} //getUserDetails
void BdapPage::addLink()
{
//Check to see if wallet needs upgrading
if (model->getWallet()->WalletNeedsUpgrading()) {
QMessageBox::critical(this, QObject::tr("Older wallet version detected"),
QObject::tr("Your wallet has not been fully upgraded to version 2.4. Please unlock your wallet to continue."));
return;
}
if (!dynodeSync.IsBlockchainSynced()) {
QMessageBox::information(this, QObject::tr("Wallet not synced"), QObject::tr("Cannot create BDAP objects while wallet is not synced."));
return;
}
BdapAddLinkDialog dlg(this, model->getOptionsModel()->getDisplayUnit());
dlg.exec();
if (dlg.result() == 1) {
bdapLinkTableModel->refreshAll();
}
} //addLink
void BdapPage::acceptLink()
{
if (!dynodeSync.IsBlockchainSynced()) {
QMessageBox::information(this, QObject::tr("Wallet not synced"), QObject::tr("Cannot create BDAP objects while wallet is not synced."));
return;
}
QMessageBox::StandardButton reply;
std::string requestor = "";
std::string recipient = "";
std::string displayedMessage = "";
QItemSelectionModel* selectionModel = ui->tableWidgetPendingAccept->selectionModel();
QModelIndexList selected = selectionModel->selectedRows();
int nSelectedRow = selected.count() ? selected.at(0).row() : -1;
if (nSelectedRow == -1) return; //do nothing if no rows are selected
requestor = ui->tableWidgetPendingAccept->item(nSelectedRow,0)->text().toStdString();
recipient = ui->tableWidgetPendingAccept->item(nSelectedRow,1)->text().toStdString();
displayedMessage = "Are you sure you want to confirm link from \"" + requestor + "\" to \"" + recipient + "\"?"; //std::to_string(nSelectedRow);
reply = QMessageBox::question(this, QObject::tr("Confirm Accept Link"), QObject::tr(displayedMessage.c_str()), QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
if (!bdapFeesPopup(this,OP_BDAP_NEW,OP_BDAP_LINK_ACCEPT,BDAP::ObjectType::BDAP_LINK_ACCEPT,model->getOptionsModel()->getDisplayUnit())) {
return;
}
executeLinkTransaction(LinkActions::LINK_ACCEPT, requestor, recipient);
}
} //acceptLink
void BdapPage::getLinkDetails(int row, int column)
{
std::string requestor = "";
std::string recipient = "";
std::string displayedMessage = "";
LinkActions actionType = LinkActions::LINK_DEFAULT;
//figure out which table called us
QTableWidget* tableSource = qobject_cast<QTableWidget*>(sender());
requestor = tableSource->item(row,0)->text().toStdString();
recipient = tableSource->item(row,1)->text().toStdString();
if (tableSource == ui->tableWidgetPendingAccept) actionType = LinkActions::LINK_PENDING_ACCEPT_DETAIL;
else if (tableSource == ui->tableWidgetPendingRequest) actionType = LinkActions::LINK_PENDING_REQUEST_DETAIL;
else if (tableSource == ui->tableWidgetComplete) actionType = LinkActions::LINK_COMPLETE_DETAIL;
executeLinkTransaction(actionType, requestor, recipient);
} //linkDetails
void BdapPage::deleteUser()
{
if (!dynodeSync.IsBlockchainSynced()) {
QMessageBox::information(this, QObject::tr("Wallet not synced"), QObject::tr("Cannot create/modify BDAP objects while wallet is not synced."));
return;
}
QMessageBox::StandardButton reply;
std::string account = "";
std::string displayedMessage = "";
QItemSelectionModel* selectionModel = ui->tableWidget_Users->selectionModel();
QModelIndexList selected = selectionModel->selectedRows();
int nSelectedRow = selected.count() ? selected.at(0).row() : -1;
if (nSelectedRow == -1) return; //do nothing if no rows are selected
account = ui->tableWidget_Users->item(nSelectedRow,1)->text().toStdString();
displayedMessage = "Are you sure you want to delete \"" + account + "\""; //std::to_string(nSelectedRow);
reply = QMessageBox::question(this, QObject::tr("Confirm Delete Account"), QObject::tr(displayedMessage.c_str()), QMessageBox::Yes|QMessageBox::No);
if (reply == QMessageBox::Yes) {
executeDeleteAccount(account, BDAP::ObjectType::BDAP_USER);
}
} //deleteUser
void BdapPage::updateUser()
{
if (!dynodeSync.IsBlockchainSynced()) {
QMessageBox::information(this, QObject::tr("Wallet not synced"), QObject::tr("Cannot create/modify BDAP objects while wallet is not synced."));
return;
}
std::string account = "";
std::string commonName = "";
std::string expirationDate = "";
QItemSelectionModel* selectionModel = ui->tableWidget_Users->selectionModel();
QModelIndexList selected = selectionModel->selectedRows();
int nSelectedRow = selected.count() ? selected.at(0).row() : -1;
if (nSelectedRow == -1) return; //do nothing if no rows are selected
account = ui->tableWidget_Users->item(nSelectedRow,1)->text().toStdString();
commonName = ui->tableWidget_Users->item(nSelectedRow,0)->text().toStdString();
expirationDate = ui->tableWidget_Users->item(nSelectedRow,2)->text().toStdString();
BdapUpdateAccountDialog dlg(this,BDAP::ObjectType::BDAP_USER,account,commonName,expirationDate,model->getOptionsModel()->getDisplayUnit());
dlg.setWindowTitle(QObject::tr("Update BDAP User"));
dlg.exec();
if (dlg.result() == 1) {
bdapAccountTableModel->refreshUsers();
}
} //updateUser
void BdapPage::executeDeleteAccount(std::string account, BDAP::ObjectType accountType) {
std::string objectID = "";
std::vector<std::string> results;
std::string outputmessage = "";
boost::split(results, account, [](char c){return c == '@';});
if (results.size() > 0) {
objectID = results[0];
}
JSONRPCRequest jreq;
std::vector<std::string> params;
params.push_back(objectID);
switch (accountType) {
case (BDAP::ObjectType::BDAP_USER):
jreq.params = RPCConvertValues("deleteuser", params);
jreq.strMethod = "deleteuser";
break;
case (BDAP::ObjectType::BDAP_GROUP):
jreq.params = RPCConvertValues("deletegroup", params);
jreq.strMethod = "deletegroup";
break;
default:
jreq.params = RPCConvertValues("deleteuser", params);
jreq.strMethod = "deleteuser";
break;
} //end switch
try {
UniValue result = tableRPC.execute(jreq);
outputmessage = result.getValues()[0].get_str();
BdapUserDetailDialog dlg(this,accountType,"",result,true);
if (accountType == BDAP::ObjectType::BDAP_USER) {
dlg.setWindowTitle(QObject::tr("Successfully deleted user"));
} else { //only other option for now is group
dlg.setWindowTitle(QObject::tr("Successfully deleted group"));
}; //end accountType if
dlg.exec();
if (accountType == BDAP::ObjectType::BDAP_USER) bdapAccountTableModel->refreshUsers();
else if (accountType == BDAP::ObjectType::BDAP_GROUP) bdapAccountTableModel->refreshGroups();
return;
} catch (const UniValue& objError) {
std::string message = find_value(objError, "message").get_str();
outputmessage = message;
} catch (const std::exception& e) {
outputmessage = e.what();
}
QMessageBox::critical(this, "BDAP Error", QObject::tr(outputmessage.c_str()));
} //executeDeleteAccount
void BdapPage::executeLinkTransaction(LinkActions actionType, std::string requestor, std::string recipient) {
std::string outputmessage = "";
bool displayMessage = false;
JSONRPCRequest jreq;
std::vector<std::string> params;
switch (actionType) {
case (LinkActions::LINK_ACCEPT):
params.push_back("accept");
params.push_back(recipient);
params.push_back(requestor);
jreq.params = RPCConvertValues("link", params);
jreq.strMethod = "link";
displayMessage = true;
break;
case (LinkActions::LINK_PENDING_ACCEPT_DETAIL):
params.push_back("pending");
params.push_back("accept");
params.push_back(requestor);
params.push_back(recipient);
jreq.params = RPCConvertValues("link", params);
jreq.strMethod = "link";
break;
case (LinkActions::LINK_PENDING_REQUEST_DETAIL):
params.push_back("pending");
params.push_back("request");
params.push_back(requestor);
params.push_back(recipient);
jreq.params = RPCConvertValues("link", params);
jreq.strMethod = "link";
break;
case (LinkActions::LINK_COMPLETE_DETAIL):
params.push_back("complete");
params.push_back(requestor);
params.push_back(recipient);
jreq.params = RPCConvertValues("link", params);
jreq.strMethod = "link";
break;
default:
params.push_back("complete");
jreq.params = RPCConvertValues("link", params);
jreq.strMethod = "link";
break;
} //end switch
try {
UniValue resultToPass = UniValue(UniValue::VOBJ);
UniValue result = tableRPC.execute(jreq);
//NOTE: this payload is a list of details that contains one item for everything (so far) EXCEPT for LINK_ACCEPT
if (actionType != LinkActions::LINK_ACCEPT) {
resultToPass = result[0];
} else {
resultToPass = result;
}
BdapLinkDetailDialog dlg(this,actionType,"","",resultToPass,displayMessage);
if (actionType == LinkActions::LINK_ACCEPT) {
dlg.setWindowTitle(QObject::tr("Successfully accepted link"));
} else if (actionType == LinkActions::LINK_PENDING_ACCEPT_DETAIL) {
dlg.setWindowTitle(QObject::tr("BDAP Pending Accept Link Detail"));
} else if (actionType == LinkActions::LINK_PENDING_REQUEST_DETAIL) {
dlg.setWindowTitle(QObject::tr("BDAP Pending Request Link Detail"));
} else if (actionType == LinkActions::LINK_COMPLETE_DETAIL) {
dlg.setWindowTitle(QObject::tr("BDAP Complete Link Detail"));
} //end actionType if
dlg.exec();
if (actionType == LinkActions::LINK_ACCEPT) bdapLinkTableModel->refreshAll();
return;
} catch (const UniValue& objError) {
std::string message = find_value(objError, "message").get_str();
outputmessage = message;
QMessageBox::critical(this, "BDAP Error", QObject::tr(outputmessage.c_str()));
} catch (const std::exception& e) {
outputmessage = e.what();
QMessageBox::critical(this, "BDAP Error", QObject::tr(outputmessage.c_str()));
}
} //executeLinkTransaction
BdapAccountTableModel* BdapPage::getBdapAccountTableModel()
{
return bdapAccountTableModel;
}
BdapLinkTableModel* BdapPage::getBdapLinkTableModel()
{
return bdapLinkTableModel;
}
QTableWidget* BdapPage::getCompleteTable()
{
return ui->tableWidgetComplete;
}
QTableWidget* BdapPage::getPendingAcceptTable()
{
return ui->tableWidgetPendingAccept;
}
QTableWidget* BdapPage::getPendingRequestTable()
{
return ui->tableWidgetPendingRequest;
}
QTableWidget* BdapPage::getUserTable()
{
return ui->tableWidget_Users;
}
QTableWidget* BdapPage::getGroupTable()
{
return ui->tableWidget_Groups;
}
QLabel* BdapPage::getUserStatus()
{
return ui->labelUserStatus;
}
QLabel* BdapPage::getNumRecordsFound()
{
return ui->labelNumRecordsFound;
}
QLabel* BdapPage::getLinkCompleteRecords()
{
return ui->labelCompleteRecords;
}
QLabel* BdapPage::getPendingAcceptRecords()
{
return ui->labelPARecords;
}
QLabel* BdapPage::getPendingRequestRecords()
{
return ui->labelPRRecords;
}
QLabel* BdapPage::getGroupStatus()
{
return ui->labelGroupStatus;
}
int BdapPage::getCurrentIndex()
{
return ui->tabWidget->currentIndex();
}
bool BdapPage::getMyUserCheckBoxChecked()
{
return ui->checkBoxMyUsers->isChecked();
}
bool BdapPage::getMyGroupCheckBoxChecked()
{
return ui->checkBoxMyGroups->isChecked();
}
std::string BdapPage::getCommonUserSearch()
{
return ui->lineEditUserCommonNameSearch->text().toStdString();
}
std::string BdapPage::getPathUserSearch()
{
return ui->lineEditUserFullPathSearch->text().toStdString();
}
std::string BdapPage::getCommonGroupSearch()
{
return ui->lineEditGroupCommonNameSearch->text().toStdString();
}
std::string BdapPage::getPathGroupSearch()
{
return ui->lineEditGroupFullPathSearch->text().toStdString();
}
std::string BdapPage::getCompleteRequestorSearch()
{
return ui->lineEditCompleteRequestorSearch->text().toStdString();
}
std::string BdapPage::getCompleteRecipientSearch()
{
return ui->lineEditCompleteRecipientSearch->text().toStdString();
}
std::string BdapPage::getPARequestorSearch()
{
return ui->lineEditPARequestorSearch->text().toStdString();
}
std::string BdapPage::getPARecipientSearch()
{
return ui->lineEditPARecipientSearch->text().toStdString();
}
std::string BdapPage::getPRRequestorSearch()
{
return ui->lineEditPRRequestorSearch->text().toStdString();
}
std::string BdapPage::getPRRecipientSearch()
{
return ui->lineEditPRRecipientSearch->text().toStdString();
} | 34.929972 | 152 | 0.669487 | [
"vector",
"model"
] |
e167c7aa2579d384903ddf5df16b44cc13e11b47 | 21,067 | hpp | C++ | src/hotspot/share/opto/matcher.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | src/hotspot/share/opto/matcher.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | src/hotspot/share/opto/matcher.hpp | siweilxy/openjdkstudy | 8597674ec1d6809faf55cbee1f45f4e9149d670d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef SHARE_OPTO_MATCHER_HPP
#define SHARE_OPTO_MATCHER_HPP
#include "libadt/vectset.hpp"
#include "memory/resourceArea.hpp"
#include "opto/node.hpp"
#include "opto/phaseX.hpp"
#include "opto/regmask.hpp"
class Compile;
class Node;
class MachNode;
class MachTypeNode;
class MachOper;
//---------------------------Matcher-------------------------------------------
class Matcher : public PhaseTransform {
friend class VMStructs;
public:
// State and MStack class used in xform() and find_shared() iterative methods.
enum Node_State { Pre_Visit, // node has to be pre-visited
Visit, // visit node
Post_Visit, // post-visit node
Alt_Post_Visit // alternative post-visit path
};
class MStack: public Node_Stack {
public:
MStack(int size) : Node_Stack(size) { }
void push(Node *n, Node_State ns) {
Node_Stack::push(n, (uint)ns);
}
void push(Node *n, Node_State ns, Node *parent, int indx) {
++_inode_top;
if ((_inode_top + 1) >= _inode_max) grow();
_inode_top->node = parent;
_inode_top->indx = (uint)indx;
++_inode_top;
_inode_top->node = n;
_inode_top->indx = (uint)ns;
}
Node *parent() {
pop();
return node();
}
Node_State state() const {
return (Node_State)index();
}
void set_state(Node_State ns) {
set_index((uint)ns);
}
};
private:
// Private arena of State objects
ResourceArea _states_arena;
VectorSet _visited; // Visit bits
// Used to control the Label pass
VectorSet _shared; // Shared Ideal Node
VectorSet _dontcare; // Nothing the matcher cares about
// Private methods which perform the actual matching and reduction
// Walks the label tree, generating machine nodes
MachNode *ReduceInst( State *s, int rule, Node *&mem);
void ReduceInst_Chain_Rule( State *s, int rule, Node *&mem, MachNode *mach);
uint ReduceInst_Interior(State *s, int rule, Node *&mem, MachNode *mach, uint num_opnds);
void ReduceOper( State *s, int newrule, Node *&mem, MachNode *mach );
// If this node already matched using "rule", return the MachNode for it.
MachNode* find_shared_node(Node* n, uint rule);
// Convert a dense opcode number to an expanded rule number
const int *_reduceOp;
const int *_leftOp;
const int *_rightOp;
// Map dense opcode number to info on when rule is swallowed constant.
const bool *_swallowed;
// Map dense rule number to determine if this is an instruction chain rule
const uint _begin_inst_chain_rule;
const uint _end_inst_chain_rule;
// We want to clone constants and possible CmpI-variants.
// If we do not clone CmpI, then we can have many instances of
// condition codes alive at once. This is OK on some chips and
// bad on others. Hence the machine-dependent table lookup.
const char *_must_clone;
// Find shared Nodes, or Nodes that otherwise are Matcher roots
void find_shared( Node *n );
bool find_shared_visit(MStack& mstack, Node* n, uint opcode, bool& mem_op, int& mem_addr_idx);
void find_shared_post_visit(Node* n, uint opcode);
#ifdef X86
bool is_bmi_pattern(Node *n, Node *m);
#endif
// Debug and profile information for nodes in old space:
GrowableArray<Node_Notes*>* _old_node_note_array;
// Node labeling iterator for instruction selection
Node *Label_Root( const Node *n, State *svec, Node *control, const Node *mem );
Node *transform( Node *dummy );
Node_List _projection_list; // For Machine nodes killing many values
Node_Array _shared_nodes;
debug_only(Node_Array _old2new_map;) // Map roots of ideal-trees to machine-roots
debug_only(Node_Array _new2old_map;) // Maps machine nodes back to ideal
// Accessors for the inherited field PhaseTransform::_nodes:
void grow_new_node_array(uint idx_limit) {
_nodes.map(idx_limit-1, NULL);
}
bool has_new_node(const Node* n) const {
return _nodes.at(n->_idx) != NULL;
}
Node* new_node(const Node* n) const {
assert(has_new_node(n), "set before get");
return _nodes.at(n->_idx);
}
void set_new_node(const Node* n, Node *nn) {
assert(!has_new_node(n), "set only once");
_nodes.map(n->_idx, nn);
}
#ifdef ASSERT
// Make sure only new nodes are reachable from this node
void verify_new_nodes_only(Node* root);
Node* _mem_node; // Ideal memory node consumed by mach node
#endif
// Mach node for ConP #NULL
MachNode* _mach_null;
void handle_precedence_edges(Node* n, MachNode *mach);
public:
int LabelRootDepth;
// Convert ideal machine register to a register mask for spill-loads
static const RegMask *idealreg2regmask[];
RegMask *idealreg2spillmask [_last_machine_leaf];
RegMask *idealreg2debugmask [_last_machine_leaf];
RegMask *idealreg2mhdebugmask[_last_machine_leaf];
void init_spill_mask( Node *ret );
// Convert machine register number to register mask
static uint mreg2regmask_max;
static RegMask mreg2regmask[];
static RegMask STACK_ONLY_mask;
MachNode* mach_null() const { return _mach_null; }
bool is_shared( Node *n ) { return _shared.test(n->_idx) != 0; }
void set_shared( Node *n ) { _shared.set(n->_idx); }
bool is_visited( Node *n ) { return _visited.test(n->_idx) != 0; }
void set_visited( Node *n ) { _visited.set(n->_idx); }
bool is_dontcare( Node *n ) { return _dontcare.test(n->_idx) != 0; }
void set_dontcare( Node *n ) { _dontcare.set(n->_idx); }
// Mode bit to tell DFA and expand rules whether we are running after
// (or during) register selection. Usually, the matcher runs before,
// but it will also get called to generate post-allocation spill code.
// In this situation, it is a deadly error to attempt to allocate more
// temporary registers.
bool _allocation_started;
// Machine register names
static const char *regName[];
// Machine register encodings
static const unsigned char _regEncode[];
// Machine Node names
const char **_ruleName;
// Rules that are cheaper to rematerialize than to spill
static const uint _begin_rematerialize;
static const uint _end_rematerialize;
// An array of chars, from 0 to _last_Mach_Reg.
// No Save = 'N' (for register windows)
// Save on Entry = 'E'
// Save on Call = 'C'
// Always Save = 'A' (same as SOE + SOC)
const char *_register_save_policy;
const char *_c_reg_save_policy;
// Convert a machine register to a machine register type, so-as to
// properly match spill code.
const int *_register_save_type;
// Maps from machine register to boolean; true if machine register can
// be holding a call argument in some signature.
static bool can_be_java_arg( int reg );
// Maps from machine register to boolean; true if machine register holds
// a spillable argument.
static bool is_spillable_arg( int reg );
// List of IfFalse or IfTrue Nodes that indicate a taken null test.
// List is valid in the post-matching space.
Node_List _null_check_tests;
void collect_null_checks( Node *proj, Node *orig_proj );
void validate_null_checks( );
Matcher();
// Get a projection node at position pos
Node* get_projection(uint pos) {
return _projection_list[pos];
}
// Push a projection node onto the projection list
void push_projection(Node* node) {
_projection_list.push(node);
}
Node* pop_projection() {
return _projection_list.pop();
}
// Number of nodes in the projection list
uint number_of_projections() const {
return _projection_list.size();
}
// Select instructions for entire method
void match();
// Helper for match
OptoReg::Name warp_incoming_stk_arg( VMReg reg );
// Transform, then walk. Does implicit DCE while walking.
// Name changed from "transform" to avoid it being virtual.
Node *xform( Node *old_space_node, int Nodes );
// Match a single Ideal Node - turn it into a 1-Node tree; Label & Reduce.
MachNode *match_tree( const Node *n );
MachNode *match_sfpt( SafePointNode *sfpt );
// Helper for match_sfpt
OptoReg::Name warp_outgoing_stk_arg( VMReg reg, OptoReg::Name begin_out_arg_area, OptoReg::Name &out_arg_limit_per_call );
// Initialize first stack mask and related masks.
void init_first_stack_mask();
// If we should save-on-entry this register
bool is_save_on_entry( int reg );
// Fixup the save-on-entry registers
void Fixup_Save_On_Entry( );
// --- Frame handling ---
// Register number of the stack slot corresponding to the incoming SP.
// Per the Big Picture in the AD file, it is:
// SharedInfo::stack0 + locks + in_preserve_stack_slots + pad2.
OptoReg::Name _old_SP;
// Register number of the stack slot corresponding to the highest incoming
// argument on the stack. Per the Big Picture in the AD file, it is:
// _old_SP + out_preserve_stack_slots + incoming argument size.
OptoReg::Name _in_arg_limit;
// Register number of the stack slot corresponding to the new SP.
// Per the Big Picture in the AD file, it is:
// _in_arg_limit + pad0
OptoReg::Name _new_SP;
// Register number of the stack slot corresponding to the highest outgoing
// argument on the stack. Per the Big Picture in the AD file, it is:
// _new_SP + max outgoing arguments of all calls
OptoReg::Name _out_arg_limit;
OptoRegPair *_parm_regs; // Array of machine registers per argument
RegMask *_calling_convention_mask; // Array of RegMasks per argument
// Does matcher have a match rule for this ideal node?
static const bool has_match_rule(int opcode);
static const bool _hasMatchRule[_last_opcode];
// Does matcher have a match rule for this ideal node and is the
// predicate (if there is one) true?
// NOTE: If this function is used more commonly in the future, ADLC
// should generate this one.
static const bool match_rule_supported(int opcode);
// identify extra cases that we might want to provide match rules for
// e.g. Op_ vector nodes and other intrinsics while guarding with vlen
static const bool match_rule_supported_vector(int opcode, int vlen);
// Some microarchitectures have mask registers used on vectors
static const bool has_predicated_vectors(void);
// Some uarchs have different sized float register resources
static const int float_pressure(int default_pressure_threshold);
// Used to determine if we have fast l2f conversion
// USII has it, USIII doesn't
static const bool convL2FSupported(void);
// Vector width in bytes
static const int vector_width_in_bytes(BasicType bt);
// Limits on vector size (number of elements).
static const int max_vector_size(const BasicType bt);
static const int min_vector_size(const BasicType bt);
static const bool vector_size_supported(const BasicType bt, int size) {
return (Matcher::max_vector_size(bt) >= size &&
Matcher::min_vector_size(bt) <= size);
}
// Vector ideal reg
static const uint vector_ideal_reg(int len);
static const uint vector_shift_count_ideal_reg(int len);
// CPU supports misaligned vectors store/load.
static const bool misaligned_vectors_ok();
// Should original key array reference be passed to AES stubs
static const bool pass_original_key_for_aes();
// Used to determine a "low complexity" 64-bit constant. (Zero is simple.)
// The standard of comparison is one (StoreL ConL) vs. two (StoreI ConI).
// Depends on the details of 64-bit constant generation on the CPU.
static const bool isSimpleConstant64(jlong con);
// These calls are all generated by the ADLC
// TRUE - grows up, FALSE - grows down (Intel)
virtual bool stack_direction() const;
// Java-Java calling convention
// (what you use when Java calls Java)
// Alignment of stack in bytes, standard Intel word alignment is 4.
// Sparc probably wants at least double-word (8).
static uint stack_alignment_in_bytes();
// Alignment of stack, measured in stack slots.
// The size of stack slots is defined by VMRegImpl::stack_slot_size.
static uint stack_alignment_in_slots() {
return stack_alignment_in_bytes() / (VMRegImpl::stack_slot_size);
}
// Array mapping arguments to registers. Argument 0 is usually the 'this'
// pointer. Registers can include stack-slots and regular registers.
static void calling_convention( BasicType *, VMRegPair *, uint len, bool is_outgoing );
// Convert a sig into a calling convention register layout
// and find interesting things about it.
static OptoReg::Name find_receiver( bool is_outgoing );
// Return address register. On Intel it is a stack-slot. On PowerPC
// it is the Link register. On Sparc it is r31?
virtual OptoReg::Name return_addr() const;
RegMask _return_addr_mask;
// Return value register. On Intel it is EAX. On Sparc i0/o0.
static OptoRegPair return_value(uint ideal_reg, bool is_outgoing);
static OptoRegPair c_return_value(uint ideal_reg, bool is_outgoing);
RegMask _return_value_mask;
// Inline Cache Register
static OptoReg::Name inline_cache_reg();
static int inline_cache_reg_encode();
// Register for DIVI projection of divmodI
static RegMask divI_proj_mask();
// Register for MODI projection of divmodI
static RegMask modI_proj_mask();
// Register for DIVL projection of divmodL
static RegMask divL_proj_mask();
// Register for MODL projection of divmodL
static RegMask modL_proj_mask();
// Use hardware DIV instruction when it is faster than
// a code which use multiply for division by constant.
static bool use_asm_for_ldiv_by_con( jlong divisor );
static const RegMask method_handle_invoke_SP_save_mask();
// Java-Interpreter calling convention
// (what you use when calling between compiled-Java and Interpreted-Java
// Number of callee-save + always-save registers
// Ignores frame pointer and "special" registers
static int number_of_saved_registers();
// The Method-klass-holder may be passed in the inline_cache_reg
// and then expanded into the inline_cache_reg and a method_oop register
static OptoReg::Name interpreter_method_oop_reg();
static int interpreter_method_oop_reg_encode();
static OptoReg::Name compiler_method_oop_reg();
static const RegMask &compiler_method_oop_reg_mask();
static int compiler_method_oop_reg_encode();
// Interpreter's Frame Pointer Register
static OptoReg::Name interpreter_frame_pointer_reg();
// Java-Native calling convention
// (what you use when intercalling between Java and C++ code)
// Array mapping arguments to registers. Argument 0 is usually the 'this'
// pointer. Registers can include stack-slots and regular registers.
static void c_calling_convention( BasicType*, VMRegPair *, uint );
// Frame pointer. The frame pointer is kept at the base of the stack
// and so is probably the stack pointer for most machines. On Intel
// it is ESP. On the PowerPC it is R1. On Sparc it is SP.
OptoReg::Name c_frame_pointer() const;
static RegMask c_frame_ptr_mask;
// !!!!! Special stuff for building ScopeDescs
virtual int regnum_to_fpu_offset(int regnum);
// Is this branch offset small enough to be addressed by a short branch?
bool is_short_branch_offset(int rule, int br_size, int offset);
// Optional scaling for the parameter to the ClearArray/CopyArray node.
static const bool init_array_count_is_in_bytes;
// Some hardware needs 2 CMOV's for longs.
static const int long_cmove_cost();
// Some hardware have expensive CMOV for float and double.
static const int float_cmove_cost();
// Should the Matcher clone shifts on addressing modes, expecting them to
// be subsumed into complex addressing expressions or compute them into
// registers? True for Intel but false for most RISCs
bool clone_address_expressions(AddPNode* m, MStack& mstack, VectorSet& address_visited);
// Clone base + offset address expression
bool clone_base_plus_offset_address(AddPNode* m, MStack& mstack, VectorSet& address_visited);
static bool narrow_oop_use_complex_address();
static bool narrow_klass_use_complex_address();
static bool const_oop_prefer_decode();
static bool const_klass_prefer_decode();
// Generate implicit null check for narrow oops if it can fold
// into address expression (x64).
//
// [R12 + narrow_oop_reg<<3 + offset] // fold into address expression
// NullCheck narrow_oop_reg
//
// When narrow oops can't fold into address expression (Sparc) and
// base is not null use decode_not_null and normal implicit null check.
// Note, decode_not_null node can be used here since it is referenced
// only on non null path but it requires special handling, see
// collect_null_checks():
//
// decode_not_null narrow_oop_reg, oop_reg // 'shift' and 'add base'
// [oop_reg + offset]
// NullCheck oop_reg
//
// With Zero base and when narrow oops can not fold into address
// expression use normal implicit null check since only shift
// is needed to decode narrow oop.
//
// decode narrow_oop_reg, oop_reg // only 'shift'
// [oop_reg + offset]
// NullCheck oop_reg
//
static bool gen_narrow_oop_implicit_null_checks();
// Is it better to copy float constants, or load them directly from memory?
// Intel can load a float constant from a direct address, requiring no
// extra registers. Most RISCs will have to materialize an address into a
// register first, so they may as well materialize the constant immediately.
static const bool rematerialize_float_constants;
// If CPU can load and store mis-aligned doubles directly then no fixup is
// needed. Else we split the double into 2 integer pieces and move it
// piece-by-piece. Only happens when passing doubles into C code or when
// calling i2c adapters as the Java calling convention forces doubles to be
// aligned.
static const bool misaligned_doubles_ok;
// Does the CPU require postalloc expand (see block.cpp for description of
// postalloc expand)?
static const bool require_postalloc_expand;
// Perform a platform dependent implicit null fixup. This is needed
// on windows95 to take care of some unusual register constraints.
void pd_implicit_null_fixup(MachNode *load, uint idx);
// Advertise here if the CPU requires explicit rounding operations
// to implement the UseStrictFP mode.
static const bool strict_fp_requires_explicit_rounding;
// Are floats conerted to double when stored to stack during deoptimization?
static bool float_in_double();
// Do ints take an entire long register or just half?
static const bool int_in_long;
// Do the processor's shift instructions only use the low 5/6 bits
// of the count for 32/64 bit ints? If not we need to do the masking
// ourselves.
static const bool need_masked_shift_count;
// Whether code generation need accurate ConvI2L types.
static const bool convi2l_type_required;
// This routine is run whenever a graph fails to match.
// If it returns, the compiler should bailout to interpreter without error.
// In non-product mode, SoftMatchFailure is false to detect non-canonical
// graphs. Print a message and exit.
static void soft_match_failure() {
if( SoftMatchFailure ) return;
else { fatal("SoftMatchFailure is not allowed except in product"); }
}
// Check for a following volatile memory barrier without an
// intervening load and thus we don't need a barrier here. We
// retain the Node to act as a compiler ordering barrier.
static bool post_store_load_barrier(const Node* mb);
// Does n lead to an uncommon trap that can cause deoptimization?
static bool branches_to_uncommon_trap(const Node *n);
#ifdef ASSERT
void dump_old2new_map(); // machine-independent to machine-dependent
Node* find_old_node(Node* new_node) {
return _new2old_map[new_node->_idx];
}
#endif
};
#endif // SHARE_OPTO_MATCHER_HPP
| 37.822262 | 124 | 0.723691 | [
"vector",
"transform"
] |
e16c858b1c89fa51d3c90cd5b722dea3cb0e0580 | 6,299 | cc | C++ | tensorflow/core/kernels/dml_topk_op.cc | BenjaminWegener/tensorflow-directml | ecdbdbd2691e17dcc462fc49138fc7cc1536b7d5 | [
"Apache-2.0"
] | 351 | 2020-09-01T08:36:28.000Z | 2022-03-29T06:54:29.000Z | tensorflow/core/kernels/dml_topk_op.cc | BenjaminWegener/tensorflow-directml | ecdbdbd2691e17dcc462fc49138fc7cc1536b7d5 | [
"Apache-2.0"
] | 80 | 2020-09-02T01:57:33.000Z | 2022-03-28T08:51:57.000Z | tensorflow/core/kernels/dml_topk_op.cc | BenjaminWegener/tensorflow-directml | ecdbdbd2691e17dcc462fc49138fc7cc1536b7d5 | [
"Apache-2.0"
] | 29 | 2020-09-14T06:29:58.000Z | 2022-03-01T09:21:17.000Z | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Portions Copyright (c) Microsoft Corporation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/common_runtime/dml/dml_operator_helper.h"
#include "tensorflow/core/common_runtime/dml/dml_util.h"
#include "tensorflow/core/framework/bounds_check.h"
#include "tensorflow/core/framework/register_types.h"
#include "tensorflow/core/kernels/dml_kernel_wrapper.h"
#include "tensorflow/core/kernels/dml_ops_common.h"
namespace tensorflow {
class DmlTopKInitHelper : public InitializationHelper {
public:
struct Attributes {
explicit Attributes(OpKernelConstruction* ctx) {
OP_REQUIRES_OK(ctx, ctx->GetAttr("sorted", &sorted_));
if (ctx->num_inputs() < 2) { // k is an attr (TopK).
OP_REQUIRES_OK(ctx, ctx->GetAttr("k", &k_));
} else { // k is an input (TopKV2), so we won't know it until Compute.
k_ = -1;
}
}
int k_;
// sorted_ attr is not used because tensorflow has no specification for
// sorted_=False
bool sorted_;
};
DmlTopKInitHelper(OpKernelContext* ctx,
std::shared_ptr<const Attributes> attr)
: attr_(std::move(attr)) {
k = attr_->k_;
if (ctx->num_inputs() >= 2) {
const auto& k_in = ctx->input(1);
OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(k_in.shape()),
errors::InvalidArgument("k must be scalar, got shape ",
k_in.shape().DebugString()));
k = k_in.scalar<int32>()();
}
OP_REQUIRES(ctx, k >= 0, errors::InvalidArgument("Need k >= 0, got ", k));
const auto& input_in = ctx->input(0);
OP_REQUIRES(ctx, input_in.dims() >= 1,
errors::InvalidArgument("input must be >= 1-D, got shape ",
input_in.shape().DebugString()));
OP_REQUIRES(ctx, input_in.dim_size(input_in.dims() - 1) >= k,
errors::InvalidArgument(
"input must have at least k columns. Had ",
input_in.dim_size(input_in.dims() - 1), ", needed ", k));
}
int GetK() const { return k; }
private:
int k = -1;
const std::shared_ptr<const Attributes> attr_;
};
class TopKShapeHelper : public ShapeHelper {
public:
std::vector<TensorShape> GetOutputShapes(
OpKernelContext* ctx,
const InitializationHelper* initialization_helper) const override {
auto init_helper =
static_cast<const DmlTopKInitHelper*>(initialization_helper);
int k = init_helper->GetK();
const TensorShape& input_shape = ctx->input(0).shape();
TensorShape output_shape;
for (int i = 0; i < input_shape.dims() - 1; ++i) {
output_shape.AddDim(input_shape.dim_size(i));
}
output_shape.AddDim(k);
return {output_shape, output_shape};
}
};
class DmlTopKKernel : public DmlKernel {
public:
using InitHelper = DmlTopKInitHelper;
explicit DmlTopKKernel(DmlKernelConstruction* ctx,
const InitHelper* init_helper) {
DCHECK(ctx->GetInputCount() == 1 || ctx->GetInputCount() == 2);
DCHECK(ctx->GetOutputCount() == 2);
const TensorShape& tensor_shape = ctx->GetInputTensorShape(0);
const TensorShape& output_shape = ctx->GetOutputTensorShape(0);
DmlTensorInfo input;
input.kernel_index = 0;
input.desc = DmlTensorDesc::Create(ctx->GetInputDataType(0), tensor_shape,
tensor_shape);
DmlTensorInfo values_output;
values_output.kernel_index = 0;
values_output.desc = DmlTensorDesc::Create(ctx->GetOutputDataType(0),
output_shape, output_shape);
DmlTensorInfo indices_output;
indices_output.kernel_index = 1;
indices_output.desc = DmlTensorDesc::Create(ctx->GetOutputDataType(1),
output_shape, output_shape);
indices_output.desc.ForceUnsignedDataType();
DmlKernelTensors tensors;
tensors.inputs = {input};
tensors.outputs = {values_output, indices_output};
auto inputs = GetDmlTensorDescs(tensors.inputs);
auto scope = dml::Graph(ctx->GetDmlDevice());
auto input_tensor = dml::InputTensor(scope, 0, inputs[0]);
uint32_t k = init_helper->GetK();
uint32_t axis = input.desc.GetDimensionCount() - 1;
dml::TopKOutputs result =
dml::TopK(input_tensor, axis, k, DML_AXIS_DIRECTION_DECREASING);
// TFDML #24881131
if (Is64BitSignedIntegerType(ctx->GetOutputDataType(0))) {
result.value = dml::ConvertInt32ToInt64(result.value);
}
Microsoft::WRL::ComPtr<IDMLCompiledOperator> compiled_op =
scope.Compile(DML_EXECUTION_FLAG_NONE, {result.value, result.index});
Initialize(ctx, std::move(tensors), compiled_op.Get());
}
};
#define DML_REGISTER_KERNEL(type) \
REGISTER_KERNEL_BUILDER( \
Name("TopK").Device(DEVICE_DML).TypeConstraint<type>("T"), \
DmlKernelWrapper<DmlTopKKernel, TopKShapeHelper>); \
REGISTER_KERNEL_BUILDER(Name("TopKV2") \
.Device(DEVICE_DML) \
.TypeConstraint<type>("T") \
.HostMemory("k"), \
DmlKernelWrapper<DmlTopKKernel, TopKShapeHelper>);
TF_CALL_DML_FLOAT_TYPES(DML_REGISTER_KERNEL);
TF_CALL_int64(DML_REGISTER_KERNEL);
TF_CALL_int32(DML_REGISTER_KERNEL);
TF_CALL_uint16(DML_REGISTER_KERNEL);
TF_CALL_int16(DML_REGISTER_KERNEL);
TF_CALL_uint8(DML_REGISTER_KERNEL);
TF_CALL_int8(DML_REGISTER_KERNEL);
#undef DML_REGISTER_KERNEL
} // namespace tensorflow | 39.616352 | 80 | 0.641372 | [
"shape",
"vector"
] |
e16d5f36b387109e1696669fc06b6be64ab5e8ba | 3,376 | hpp | C++ | include/order_statistic_map/details/fixed_size_allocator.hpp | gbalduzz/Random-Access-Map-Library | ca7d741d747f8134105b322696c82e1bbef55a42 | [
"BSD-3-Clause"
] | 1 | 2020-10-04T16:37:04.000Z | 2020-10-04T16:37:04.000Z | include/order_statistic_map/details/fixed_size_allocator.hpp | gbalduzz/Random-Access-Map-Library | ca7d741d747f8134105b322696c82e1bbef55a42 | [
"BSD-3-Clause"
] | null | null | null | include/order_statistic_map/details/fixed_size_allocator.hpp | gbalduzz/Random-Access-Map-Library | ca7d741d747f8134105b322696c82e1bbef55a42 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (C) ETH Zurich
// Copyright (C) 2020 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
//
// Author: Giovanni Balduzzi (gbalduzz@itp.phys.ethz.ch)
//
// Author: Giovanni Balduzzi (gbalduzz@itp.phys.ethz.ch)
//
// Non thread-safe allocator to quickly allocate and deallocate objects of fixes memory size.
// Inspired by https://codereview.stackexchange.com/questions/82869/fixed-size-block-allocator
#pragma once
#include <memory>
#include <vector>
namespace maplib {
template <class T, std::size_t objects_per_pool = 64>
class FixedSizeAllocator {
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using is_always_equal = std::false_type;
template <class U>
struct rebind {
using other = FixedSizeAllocator<U, objects_per_pool>;
};
FixedSizeAllocator() = default;
FixedSizeAllocator(const FixedSizeAllocator&) = delete;
FixedSizeAllocator& operator=(const FixedSizeAllocator&) = delete;
FixedSizeAllocator(FixedSizeAllocator&&) = default;
FixedSizeAllocator& operator=(FixedSizeAllocator&&) = default;
// Performs memory allocation and calls the constructor with arguments args.
// Must be matched by a call to destroy on the pointer returned by this function.
template <class... Args>
[[nodiscard]] T* create(Args&&... args);
// Calls the destructor and deallocate ptr.
void destroy(T* ptr) noexcept;
[[nodiscard]] T* allocate(std::size_t n = 1);
void deallocate(T* ptr, std::size_t n = 1) noexcept;
private:
void allocatePool();
union TNode {
char data[sizeof(T)];
TNode* next;
};
using Pool = std::array<TNode, objects_per_pool>;
TNode* free_ = nullptr; // the topmost free chunk of memory.
std::vector<std::unique_ptr<Pool>> pools_; // all allocated pools of memory
};
template <class T, std::size_t objects_per_pool>
template <class... Args>
T* FixedSizeAllocator<T, objects_per_pool>::create(Args&&... args) {
T* allocation = allocate();
return new (allocation) T(std::forward<Args>(args)...);
}
template <class T, std::size_t objects_per_pool>
void FixedSizeAllocator<T, objects_per_pool>::destroy(T* ptr) noexcept {
if (ptr) {
ptr->~T();
deallocate(ptr);
}
}
template <class T, std::size_t objects_per_pool>
T* FixedSizeAllocator<T, objects_per_pool>::allocate(std::size_t n) {
assert(n == 1);
if (!free_) {
allocatePool();
}
TNode* result = free_; // allocate the topmost element.
free_ = free_->next; // and pop it from the stack of free chunks
return reinterpret_cast<T*>(&result->data);
}
template <class T, std::size_t objects_per_pool>
void FixedSizeAllocator<T, objects_per_pool>::deallocate(T* ptr, std::size_t n) noexcept {
assert(n == 1);
if (!ptr)
return;
TNode* node = reinterpret_cast<TNode*>(ptr);
// add to the stack of chunks
node->next = free_;
free_ = node;
}
template <class T, std::size_t objects_per_pool>
void FixedSizeAllocator<T, objects_per_pool>::allocatePool() {
// Allocate new memory.
pools_.emplace_back(std::make_unique<Pool>());
// Form a stack from this pool.
auto& new_pool = *pools_.back();
for (int i = 0; i < objects_per_pool - 1; ++i) {
new_pool[i].next = &new_pool[i + 1];
}
new_pool.back().next = nullptr;
free_ = new_pool.data();
}
} // namespace maplib
| 28.369748 | 94 | 0.69609 | [
"vector"
] |
e16f672467618ef141698db73f3ebdc260292fb7 | 3,591 | cpp | C++ | atcoder/corp/codethanksfes2017_h.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | 1 | 2018-11-12T15:18:55.000Z | 2018-11-12T15:18:55.000Z | atcoder/corp/codethanksfes2017_h.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | null | null | null | atcoder/corp/codethanksfes2017_h.cpp | knuu/competitive-programming | 16bc68fdaedd6f96ae24310d697585ca8836ab6e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef pair<int, int> P;
typedef pair<ll, ll> Pll;
typedef vector<int> Vi;
//typedef tuple<int, int, int> T;
#define FOR(i,s,x) for(int i=s;i<(int)(x);i++)
#define REP(i,x) FOR(i,0,x)
#define ALL(c) c.begin(), c.end()
#define DUMP( x ) cerr << #x << " = " << ( x ) << endl
const int dr[4] = {-1, 0, 1, 0};
const int dc[4] = {0, 1, 0, -1};
struct DisjointSet {
vector<int> parent, rank;
DisjointSet(int N) {
parent.resize(N), rank.resize(N, 0);
for (int i = 0; i < N; i++) parent[i] = i;
}
int find(int x) {
if (parent[x] == x) {
return x;
} else {
return parent[x] = find(parent[x]);
}
}
void unite(int x, int y) {
x = find(x), y = find(y);
if (x == y) return ;
if (rank[x] < rank[y]) {
parent[x] = y;
} else {
parent[y] = x;
if (rank[x] == rank[y]) rank[x]++;
}
}
bool same(int x, int y) { return find(x) == find(y); }
};
#define MAX_LOG_V 17
Vi edge[100010];
int root;
int parent[MAX_LOG_V][100010];
int depth[100010];
void dfs(int v, int par, int dep) {
parent[0][v] = par;
depth[v] = dep;
for (auto child : edge[v]) {
if (child != par) dfs(child, v, dep + 1);
}
}
void init(int V) {
dfs(root, -1, 0);
for (int k = 0; k + 1 < MAX_LOG_V; k++) {
for (int v = 0; v < V; v++) {
if (parent[k][v] < 0) {
parent[k+1][v] = -1;
} else {
parent[k+1][v] = parent[k][parent[k][v]];
}
}
}
}
int u_cnt, v_cnt;
int lca(int u, int v) {
u_cnt = 0, v_cnt = 0;
if (depth[u] > depth[v]) swap(u, v);
for (int k = 0; k < MAX_LOG_V; k++) {
if ((depth[v] - depth[u]) >> k & 1) {
v = parent[k][v];
v_cnt += 1 << k;
}
}
if (u == v) return u;
for (int k = MAX_LOG_V - 1; k >= 0; k--) {
if (parent[k][u] != parent[k][v]) {
u = parent[k][u];
v = parent[k][v];
u_cnt += 1 << k;
v_cnt += 1 << k;
}
}
u_cnt++, v_cnt++;
return parent[0][u];
}
int get_cnt(int v, int cnt) {
for (int k = MAX_LOG_V - 1; k >= 0; k--) {
if (cnt >> k & 1) {
v = parent[k][v];
}
}
return v;
}
int main() {
// use scanf in CodeForces!
//cin.tie(0);
//ios_base::sync_with_stdio(false);
int N, M; cin >> N >> M;
DisjointSet uf(N);
vector<int> q_num(N, -1);
root = N;
REP(i, M) {
int a, b; cin >> a >> b; a--, b--;
if (not uf.same(a, b)) {
a = uf.find(a), b = uf.find(b);
uf.unite(a, b);
edge[a].emplace_back(b);
edge[b].emplace_back(a);
if (uf.find(a) == a) {
q_num[b] = i + 1;
} else {
q_num[a] = i + 1;
}
}
}
REP(i, N) if (uf.parent[i] == i) edge[N].emplace_back(i);
init(N + 1);
/*
REP(i, N) {
REP(j, 10) cout << parent[j][i] << ' ';
cout << endl;
}
//*/
//REP(i, N) cout << q_num[i] << (i == N - 1 ? '\n' : ' ');
int Q; cin >> Q;
REP(i, Q) {
int x, y; cin >> x >> y; x--, y--;
if (not uf.same(x, y)) {
cout << -1 << endl;
} else {
if (depth[x] > depth[y]) swap(x, y);
int anc = lca(x, y);
int v1 = get_cnt(x, max(0, u_cnt - 1));
int v2 = get_cnt(y, max(0, v_cnt - 1));
//cout << anc << ':' << u_cnt << ' ' << v_cnt << ':' << v1 << ' ' << v2 << endl;
if (u_cnt == 0) {
cout << q_num[v2] << endl;
} else if (v_cnt == 0) {
cout << q_num[v1] << endl;
} else {
cout << max(q_num[v1], q_num[v2]) << endl;
}
//cout << anc << endl;
//cout << u_cnt << ' ' << v_cnt << endl;
}
}
return 0;
}
| 21.248521 | 86 | 0.455862 | [
"vector"
] |
e176404c79fed43732e6928bc0edd65f10113783 | 24,732 | cpp | C++ | src/model/markmodel.cpp | aalele/MRCEditor | 016f77e6f986a5134e3fd27680208c12a574129b | [
"MIT"
] | null | null | null | src/model/markmodel.cpp | aalele/MRCEditor | 016f77e6f986a5134e3fd27680208c12a574129b | [
"MIT"
] | null | null | null | src/model/markmodel.cpp | aalele/MRCEditor | 016f77e6f986a5134e3fd27680208c12a574129b | [
"MIT"
] | null | null | null | #include "markmodel.h"
#include "widgets/sliceeditorwidget.h"
#include "globals.h"
#include "abstract/abstractslicedatamodel.h"
#include "markitem.h"
#include "model/roottreeitem.h"
#include "model/categorytreeitem.h"
#include <QStyledItemDelegate>
#include <QScopedPointer>
#include <QAbstractItemView>
#include <QPainter>
#include <QDebug>
#include <cstring>
/**
* \brief This is a function to get the internal data structure from \a index
*
*
* \param index \a Either an invalid index or a valid index with
* internal pointer refer to root tree item gives the pointer refer to root item
* \return Returns a non-null pointer anyway
*/
TreeItem* MarkModel::treeItem(const QModelIndex& index) const
{
if (index.isValid())
{
const auto item = static_cast<TreeItem*>(index.internalPointer());
if (item)
return item;
}
return m_rootItem;
}
/**
* \brief This is a convenience function to returns the root tree item pointer
*/
TreeItem* MarkModel::rootItem() const
{
return (m_rootItem);
}
/**
* \brief
* \param mark
*/
void MarkModel::addMarkInSliceHelper(StrokeMarkItem * mark)
{
const int index = mark->sliceIndex();
MarkSliceList * markList;
switch (mark->sliceType())
{
case SliceType::Top:
markList = &m_topSliceVisibleMarks;
break;
case SliceType::Right:
markList = &m_rightSliceVisibleMarks;
break;
case SliceType::Front:
markList = &m_frontSliceVisibleMarks;
break;
}
(*markList)[index].append(mark);
setDirty();
}
/**
* \brief
* \param mark
*/
void MarkModel::removeMarkInSliceHelper(StrokeMarkItem * mark)
{
const auto index = mark->sliceIndex();
const auto type = mark->sliceType();
switch (type)
{
case SliceType::Top:
m_topSliceVisibleMarks[index].removeOne(mark);
break;
case SliceType::Front:
m_rightSliceVisibleMarks[index].removeOne(mark);
break;
case SliceType::Right:
m_frontSliceVisibleMarks[index].removeOne(mark);
break;
}
setDirty();
}
/**
* \brief
* \param mark
*/
void MarkModel::updateMarkVisibleHelper(StrokeMarkItem * mark)
{
//Q_ASSERT_X(m_view,"MarkModel::updateMarkVisible_Helper","null pointer");
if (m_view == nullptr)
return;
int index = -1;
index = m_view->currentSliceIndex(static_cast<SliceType>(mark->sliceType()));
if (index != mark->sliceIndex())
return;
const auto visible = mark->visibleState();
mark->setVisible(visible);
setDirty();
}
QSharedPointer<char> MarkModel::rawMarks() const
{
const auto topSize = tester().topSliceSize();
QImage slice(topSize, QImage::Format_Grayscale8);
slice.fill(Qt::black);
const size_t width = slice.width(), height = slice.height(), depth = tester().rightSliceSize().width();
QSharedPointer<char> buffer(new char[width * height * depth], [](char * obj) {delete[] obj; });
size_t sliceCount = 0;
Q_ASSERT(width == slice.bytesPerLine());
const auto visibleMarks = topVisibleMarks();
QPainter p;
for (const auto & items : visibleMarks) {
p.begin(&slice);
for (const auto & item : items)
if (item != nullptr)
item->paint(&p, nullptr, nullptr);
p.end();
//qDebug() << "Slice:" << sliceCount << " count:" << items.size();
// Because QImage is 32bit-aligned, so we need write it for each scan line
for (auto i = size_t(0); i < height; i++)
std::memcpy(buffer.data() + width * height * sliceCount + i * width, slice.bits() + i * slice.bytesPerLine(), slice.bytesPerLine());
sliceCount++;
slice.fill(Qt::black); // This will also use paint device
}
return buffer;
}
QSharedPointer<int> MarkModel::markMask() const
{
const auto topSize = tester().topSliceSize();
QImage slice(topSize, QImage::Format_ARGB32_Premultiplied);
slice.fill(Qt::black);
const size_t width = slice.width(), height = slice.height(), depth = tester().rightSliceSize().width();
QSharedPointer<int> buffer(new int[width * height * depth], [](int * obj) {delete[] obj; });
size_t sliceCount = 0;
const auto visibleMarks = topVisibleMarks();
QPainter p(&slice);
for (const auto & items : visibleMarks) {
const auto offset = buffer.data() + sliceCount * width*height;
p.begin(&slice);
for (const auto & item : items)
if (item != nullptr)
item->paint(&p, nullptr, nullptr);
p.end();
for (auto h = size_t(0); h < height; h++) {
for (auto w = size_t(0); w < width; w++) {
const QColor color = slice.pixel(w, h);
offset[h*width + w] = color.red() + color.green() * 255 + color.blue() * 255 * 255; // Convert RGB Color to a integer by a one-to-one mapping
}
}
sliceCount++;
slice.fill(Qt::black);
}
return buffer;
}
void MarkModel::retrieveData(TreeItem * root, TreeItemType type, int column, QVector<QVariant>& data, int role)
{
if (root == nullptr)
return;
if (root->type() == type) {
if (role == MetaDataRole) {
data << QVariant::fromValue(root->metaData());
}
else {
data << root->data(column, role);
}
}
for (int i = 0; i < root->childCount(); i++) {
retrieveData(root->child(i), type, column, data, role);
}
}
/**
* \brief This is a helper function for get specified \a type to \a items in the parent of \parent
*
* It is called in recursively, which may lead a time-consuming operation.
*/
void MarkModel::retrieveTreeItem(TreeItem * parent, TreeItemType type, QList<TreeItem*>* items)
{
Q_ASSERT(items);
if (parent == nullptr)
{
return;
}
const auto nChild = parent->childCount();
for (auto i = 0; i < nChild; i++) {
auto item = parent->child(i);
if (item->type() == type) {
items->append(item);
}
retrieveTreeItem(item, type, items);
}
}
QModelIndex MarkModel::_hlp_indexByItem(TreeItem * parent, TreeItem* item) {
if(parent != nullptr) {
const auto nChild = parent->childCount();
for(int i=0;i<nChild;i++) {
const auto child = parent->child(i);
if(child == item) {
return createIndex(i, 0, item);
}else {
return _hlp_indexByItem(child, item);
}
}
}
return QModelIndex();
}
/**
* \interal
* \brief This is a internal helper function
*
* This function is used to initialize and identify whether mark model and slice model match
*/
void MarkModel::initSliceMarkContainerHelper()
{
Q_ASSERT_X(m_identity.isValid() == true,
"MarkModel::initSliceMarkContainer_Helper", "IdentityTester is not valid");
m_topSliceVisibleMarks.resize(m_identity.topSliceCount());
m_rightSliceVisibleMarks.resize(m_identity.rightSliceCount());
m_frontSliceVisibleMarks.resize(m_identity.frontSliceCount());
}
/**
* \internal
* \brief This is a internal helper function
*
* This function is used to sort marks by their position and divide them into several groups
* \param marks Mass marks
* \return Mark groups returned by the functions
*/
QVector<QList<StrokeMarkItem*>> MarkModel::refactorMarks(QList<StrokeMarkItem*> & marks)
{
/* TODO::
* QList<QGraphicsItem*> marks has not been sorted so far. Maybe it can be sorted
* when item is inserted at once so as to get a better performance here.
*/
std::sort(marks.begin(), marks.end(), [](const StrokeMarkItem * it1, const StrokeMarkItem * it2)->bool
{
return it1->sliceIndex() < it2->sliceIndex();
});
/*
* After sorting by slice index. We need to add each mark item to corresponding mesh according to
* the maximum intersected area between bounding box of the mark item and the newest representative
* bounding box of the mesh.
*/
QVector<QList<StrokeMarkItem*>> meshes;
QVector<QRectF> bounds;
for (const auto item : marks) {
auto meshIndex = -1;
auto maxIntersectedArea = 0.0;
const auto r = item->boundingRect(); // Rectangle of current mark
for (auto i = 0; i < bounds.size(); i++) {
if (bounds[i].intersects(r) == true) {
const auto intersectedRect = bounds[i].intersected(r);
const auto intersectedArea = intersectedRect.width()*intersectedRect.height();
if (maxIntersectedArea < intersectedArea) {
maxIntersectedArea = intersectedArea;
meshIndex = i;
}
}
}
if (meshIndex != -1) { // Add into a existed mesh
bounds[meshIndex] = r; // Update Rectangle
meshes[meshIndex].push_back(item);
}
else { // Create a new mesh
bounds.push_back(r);
meshes.push_back(QList<StrokeMarkItem*>{item});
}
}
return meshes;
}
/**
* \brief This is a private constructor
*
* A mark model can only be constructed by SliceEditorWidget.
* \sa SliceEditorWidget
*/
MarkModel::MarkModel(AbstractSliceDataModel* dataModel,
SliceEditorWidget * view,
//TreeItem * root,
QObject * parent) :
QAbstractItemModel(parent),
//m_dataModel(dataModel),
m_rootItem(nullptr),
m_view(view),
m_dirty(false),
m_selectionModel(new QItemSelectionModel(this, this)),
m_identity(dataModel)
{
m_rootItem = new RootTreeItem(QModelIndex(), nullptr);
m_rootItem->updateModelIndex(createIndex(0, 0, m_rootItem));
initSliceMarkContainerHelper();
}
/**
* \brief Creates a mark model from a file.
*
*/
MarkModel::MarkModel(const QString & fileName) :
m_rootItem(nullptr),
//m_dataModel(nullptr),
m_view(nullptr),
m_dirty(false),
m_selectionModel(new QItemSelectionModel(this, this))
{
QFile file(fileName);
file.open(QIODevice::ReadOnly);
if (file.isOpen() == false)
return;
QDataStream in(&file);
in.setVersion(QDataStream::Qt_5_9);
int magicNumber;
in >> magicNumber;
if (magicNumber != MagicNumber)
return;
/////
in >> m_identity;
TreeItem * root;
in >> root;
if(root->type() != TreeItemType::Root) {
Q_ASSERT_X(false, "MarkModel::MarkModel(const QString & fileName)", "Not a root tree item");
return;
}
m_rootItem = static_cast<RootTreeItem*>(root);
m_rootItem->setModelIndexRecursively(createIndex(0,0,m_rootItem));
////
//construct sliceMarks from the tree
initSliceMarkContainerHelper();
auto items = QList<StrokeMarkItem*>(); //
QVector<QVariant> data;
retrieveData(m_rootItem, TreeItemType::Mark, 0, data, MetaDataRole);
foreach(const auto var, data)
{
Q_ASSERT_X(var.canConvert<void*>(),
"MarkModel::marks", "convert failed");
items << static_cast<StrokeMarkItem*>(var.value<void*>());
}
foreach(auto item,items)
{
SliceType type = item->sliceType();
const auto index = item->sliceIndex();
item->setFlags(QGraphicsItem::ItemIsSelectable);
switch(type)
{
case SliceType::Top:
m_topSliceVisibleMarks[index].append(item);
break;
case SliceType::Right:
m_rightSliceVisibleMarks[index].append(item);
break;
case SliceType::Front:
m_frontSliceVisibleMarks[index].append(item);
break;
}
}
}
/**
* \brief Destroyes the mark model
*
*/
MarkModel::~MarkModel()
{
if (m_rootItem != nullptr)
{
delete m_rootItem;
m_rootItem = nullptr;
}
//if(m_selectionModel != nullptr) { //It's trivial.
// m_selectionModel->deleteLater();
//}
}
/**
* \brief Returns all tree items according to a given parent index \a parent and a \a type
*/
QList<TreeItem*> MarkModel::treeItems(const QModelIndex & parent, int type)
{
QList<TreeItem*> items;
const auto item = treeItem(parent);
retrieveTreeItem(item, (TreeItemType)type, &items);
return items;
}
/**
* \brief Return the index represents the underlying data \a item
*
* \param item
* \return Returns a valid \a QModelIndex if the \a item exsits in the tree model otherwise return
* an invalid QModelIndex
*
* \note An invalid QModelIndex indicates that there is no an \a item in the tree model
* rather than it represents a root item
*/
QModelIndex MarkModel::indexByItem(TreeItem * item)
{
return _hlp_indexByItem(m_rootItem, item);
}
/**
* \brief This is a convenience function for inserting an tree item into the tree model by the pointer itself \a item
* and its parent index \a parent
*
* \param item The pointer need to be inserted
* \param parent The parent index of the pointer
* \return Returns \a true if it is inserted successfully otherwise returns \a false
*/
bool MarkModel::insertTreeItem(TreeItem * item, const QModelIndex & parent)
{
const auto nChild = rowCount(parent);
const auto success = insertRows(nChild, 1, parent);
if(success) {
const auto newIndex = index(nChild, 0, parent);
setData(newIndex, QVariant::fromValue<void*>(static_cast<void*>(item)), TreeItemRole);
}
return success;
}
/**
* \brief This is a convenience function for inserting a bundle of tree items into the tree model by the pointers themselves \a items
* and their parent index \a parent
*
* \param items The pointers needed to be inserted
* \param parent The parent index of the pointers
* \return Returns \a true if they are inserted successfully otherwise returns \a false
*/
bool MarkModel::insertTreeItems(const QList<TreeItem*>& items, const QModelIndex & parent)
{
const auto nChild = rowCount(parent), nItems = items.size();
const auto success = insertRows(nChild, nItems, parent);
if (success) {
for(int i=0;i<nItems;i++) {
const auto newIndex = index(nChild+i, 0, parent);
setData(newIndex, QVariant::fromValue<void*>(static_cast<void*>(items[i])), TreeItemRole);
}
}
return success;
}
/**
* \brief This is a convenience function for removing a item in the the tree model by its pointer \item and its parent index \parent
*
* \param item The pointer need to be removed
* \param parent The parent index of the pointer \a item belongs to
* \return Returns \a true if it is deleted successfully otherwise returns \a false
*/
bool MarkModel::removeTreeItem(TreeItem * item)
{
const auto index = indexByItem(item);
const auto parent = MarkModel::parent(index);
return removeRow(index.row(), parent);
}
/**
* \brief This is a convenience function for removed a bundle of tree items into the tree model by the pointers themselves \a items
*
* \param items The pointers needed to be inserted
* \return Returns \a true if they are removed successfully otherwise returns \a false
*/
bool MarkModel::removeTreeItems(const QList<TreeItem*>& items)
{
for (auto item : items)
removeTreeItem(item);
return true;
}
/**
* \brief Save current marks contained in the mark model
* \param fileName
* \param format
* \return return \a true if saving successes or return \a false
*/
bool MarkModel::save(const QString& fileName, MarkModel::MarkFormat format)
{
if (format == MarkFormat::Binary)
{
QFile file(fileName);
file.open(QIODevice::WriteOnly);
if (!file.isOpen())
return false;
QDataStream stream(&file);
stream.setVersion(QDataStream::Qt_5_8);
stream << static_cast<qint32>(MagicNumber); // Magic Number first
stream << m_identity; // Identity Tester
stream << static_cast<TreeItem*>(m_rootItem); // Root Item
resetDirty();
return true;
}
else if (format == MarkFormat::Raw)
{
//resetDirt();
//QImage origin = m_dataModel->originalTopSlice(0);
const auto topSize = tester().topSliceSize();
//QImage slice(topSize, QImage::Format_Grayscale8);
//slice.fill(Qt::black);
const size_t width = topSize.width(), height = topSize.height(), depth = tester().rightSliceSize().width();
//QSharedPointer<char> buffer(new char[width * height * depth], [](char * obj) {delete[] obj; });
//size_t sliceCount = 0;
//Q_ASSERT(width == slice.bytesPerLine());
//const auto visibleMarks = topVisibleMarks();
//for(const auto & items: visibleMarks) {
// QPainter p(&slice);
// for(const auto & item: items) {
// if (item != nullptr) {
// item->paint(&p, nullptr, nullptr);
// }
// }
// // Because QImage is 32bit-aligned, so we need write it for each scan line
// for(auto i = size_t(0) ;i < height; i++)
// std::memcpy(buffer.data() + width * height * sliceCount + i*width, slice.bits()+i*slice.bytesPerLine(), slice.bytesPerLine());
// sliceCount++;
// slice.fill(Qt::black);
//}
const auto buffer = rawMarks();
QFile out(fileName);
out.open(QIODevice::WriteOnly);
if (!out.isOpen())
return false;
out.write(static_cast<const char *>(buffer.data()), width*height*depth*sizeof(char));
resetDirty();
return true;
}else if(MarkFormat::Mask == format) {
//const auto topSize = tester().topSliceSize();
//QImage slice(topSize, QImage::Format_ARGB32_Premultiplied);
const auto topSize = tester().topSliceSize();
//slice.fill(Qt::black);
//const size_t width = slice.width(), height = slice.height(), depth = tester().rightSliceSize().width();
//QSharedPointer<int> buffer(new int[width * height * depth],[](int * obj) {delete[] obj;});
const size_t width = topSize.width(), height = topSize.height(), depth = tester().rightSliceSize().width();
//size_t sliceCount = 0;
//const auto visibleMarks = topVisibleMarks();
//for (const auto & items : visibleMarks) {
// const auto offset = buffer.data() + sliceCount * width*height;
// QPainter p(&slice);
// for (const auto & item : items)
// if (item != nullptr)
// item->paint(&p, nullptr, nullptr);
//
// for (auto h = size_t(0); h < height; h++) {
// for (auto w = size_t(0); w < width; w++) {
// const QColor color = slice.pixel(w, h);
// offset[h*width + w] = color.red() + color.green() * 255 + color.blue() * 255 * 255; // Convert RGB Color to a integer by a one-to-one mapping
// }
// }
// sliceCount++;
// slice.fill(Qt::black);
//}
const auto buffer = markMask();
QFile out(fileName);
out.open(QIODevice::WriteOnly);
if (!out.isOpen())
return false;
out.write(reinterpret_cast<const char *>(buffer.data()), width*height*depth*sizeof(int));
resetDirty();
return true;
}
return false;
}
/**
* \brief Reimplemented from QAbstractItemModel::data(const QModelIndex & index,int role)
*
* Available \a role includes all enums in \a Qt::ItemDataRole
* \param index
* \param role
* \return
*/
QVariant MarkModel::data(const QModelIndex & index, int role) const
{
if (index.isValid() == false)
return QVariant();
const auto item = treeItem(index);
Q_ASSERT_X(item, "MarkModel::data", "null pointer");
return item->data(index.column(), role);
}
/**
* \brief Reimplemeted from QAbstractItemModel::flags(const QModelIndex & index)const
*/
Qt::ItemFlags MarkModel::flags(const QModelIndex & index) const
{
if (index.isValid() == false) //root
return 0;
if (index.column() == 0) //only the first column can be selected
return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsUserCheckable | Qt::ItemIsEditable;
if (index.column() == 1)
return Qt::ItemIsEnabled;
return QAbstractItemModel::flags(index);
//return 0;
}
/**
* \brief Reimplemented from QAbstractItemModel::setData(const QModelIndex & index, const QVariant & value, int role)
*
*
* Available \a role includes all enums in \a Qt::ItemDataRole.
*
* There are some customized roles besides above.
* \a MetaDataRole means that this function call will set \a value as the meta data field of \a TreeItem*, which
* is the exact data stored in the \a TreeItem.
* \a TreeItemRole means that this function call will set \a value as the specific instance of \a TreeItem in
* the node represented by \a index. \a Under this situation, the type of internal data in \a value should be \a void*
* and the value of \a column() of \a index is ignored
*
* \return Returns \a true if this call is successful otherwise return \a false.
*
* \note If \a role is Qt::CheckStateRole, the function will be called recursively to apply the same setting
* for its children
*
* \warning When \a role is TreeItemRole, the old \a TreeItem* pointer would be deleted at once.
* \sa TreeItem, Qt::ItemDataRole, MarkModelItemRole
*
* \internal
*/
bool MarkModel::setData(const QModelIndex & index, const QVariant & value, int role)
{
if (role == TreeItemRole) {
//Insert specially. column of the index is ignored.
const auto r = index.row();
const auto parentModelIndex = parent(index);
const auto item = treeItem(parentModelIndex);
const auto newItem = static_cast<TreeItem*>(value.value<void*>());
if(newItem->type() == TreeItemType::Mark) // If it is a mark, add to slice mark cache.
{
addMarkInSliceHelper(static_cast<StrokeMarkItem*>(newItem->metaData()));
}
delete item->takeChild(index.row(), newItem, nullptr);
// Update the internal pointer refer to underlying data
const auto newIndex = createIndex(index.row(), index.column(), newItem);
newItem->updateModelIndex(newIndex);
emit dataChanged(newIndex, newIndex, QVector<int>{role});
return true;
}
else { //Insert normally.
const auto item = treeItem(index);
Q_ASSERT_X(item, "MarkModel::data", "null pointer");
if (item == nullptr) return false;
item->setData(index.column(), value, role);
if(item->type() == TreeItemType::Mark)
{
updateMarkVisibleHelper(static_cast<StrokeMarkItem*>(item->metaData()));
}
if (role == Qt::CheckStateRole) { // The modification on CheckStateRole will be applied recursively.
const auto c = rowCount(index);
for (int i = 0; i < c; i++) {
setData(MarkModel::index(i, 0, index), value, Qt::CheckStateRole);
}
}
emit dataChanged(index, index, QVector<int>{role});
return true;
}
}
/**
* \brief insert \a count columns at the position \a column of \a parent
*
* Reimplemented from QAbstractItemModel::insertColumns(int column, int count, const QModelIndex & parent)
*/
bool MarkModel::insertColumns(int column, int count, const QModelIndex & parent)
{
const auto item = treeItem(parent);
if (item == nullptr)
return false;
beginInsertColumns(parent, column, column + count - 1);
const auto success = item->insertColumns(column, count);
endInsertColumns();
return success;
}
/**
* \brief Reimplemented from QAbstractItemModel::removeColumns(int column, int count, const QModelIndex & parent))
*/
bool MarkModel::removeColumns(int column, int count, const QModelIndex & parent)
{
const auto item = treeItem(parent);
if (item == nullptr)
return false;
beginRemoveColumns(parent, column, column + count - 1);
const auto success = item->insertColumns(column, count);
endRemoveColumns();
return success;
}
/**
* \brie Reimplemented from QAbstractItemModel::insertRows(int row, int count, const QModelIndex & parent)
*/
bool MarkModel::insertRows(int row, int count, const QModelIndex & parent)
{
const auto item = treeItem(parent);
beginInsertRows(parent, row, count + row - 1);
QVector<TreeItem*> children;
for (auto i = 0; i < count; i++)
{
children << new EmptyTreeItem(QPersistentModelIndex(QModelIndex()), item);
}
const auto success = item->insertChildren(row, children);
endInsertRows();
setDirty();
return success;
}
/**
* \brie Reimplemented from QAbstractItemModel::removeRows(int row, int count, const QModelIndex & parent)
*/
bool MarkModel::removeRows(int row, int count, const QModelIndex & parent)
{
const auto item = treeItem(parent);
beginRemoveRows(parent, row, row + count - 1);
const auto success = item->removeChildren(row, count);
endRemoveRows();
return success;
}
/**
* \brief Reimplemented from QAbstractItemModel::headerData(int section, Qt::Orientation orientation, int role) const
*/
QVariant MarkModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal && role == Qt::DisplayRole) {
if (section == 0)
return QStringLiteral("Mark");
if (section == 1)
return QStringLiteral("Desc");
}
return QVariant{};
}
/**
* \brief Reimplemented from QAbstractItemModel::index(int row, int column, const QModelIndex & parent) const
*/
QModelIndex MarkModel::index(int row, int column, const QModelIndex & parent) const
{
const auto parentItem = treeItem(parent);
const auto childItem = parentItem->child(row);
//Add QModelIndex to TreeItem * here
return createIndex(row, column, childItem);
}
/**
* \brief Reimplemented from QAbstractItemModel::parent(const QModelIndex & index) const
*/
QModelIndex MarkModel::parent(const QModelIndex & index) const
{
//Index points to a root item
const auto item = treeItem(index);
if (index.isValid() == false || item == m_rootItem)
return QModelIndex();
const auto parentItem = item->parentItem();
//If index points to a child item of root item
if (parentItem == m_rootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);
}
/**
* \brief Reimplemented from QAbstractItemModel::rowCount(const QModelIndex & parent) const
*/
int MarkModel::rowCount(const QModelIndex & parent) const
{
//Only a item with 0 column number has children
if (parent.column() > 0)
return 0;
TreeItem * item = treeItem(parent);
return item->childCount();
}
/**
* \brief Reimplemented from QAbstractItemModel::columnCount(const QModelIndex & parent) const
*/
int MarkModel::columnCount(const QModelIndex & parent) const
{
if (parent.isValid() == false) {
return m_rootItem->columnCount();
}
const auto item = static_cast<TreeItem*>(parent.internalPointer());
return item->columnCount();
}
| 29.690276 | 149 | 0.698326 | [
"mesh",
"model"
] |
e1794b784456ed269f328decb22d38573c2a110a | 11,193 | hpp | C++ | include/ODBCLSLB/blobs.hpp | aliakseis/odbcpp | 7dc71f3019502674a15cac52dd90aa46e1183594 | [
"MIT"
] | null | null | null | include/ODBCLSLB/blobs.hpp | aliakseis/odbcpp | 7dc71f3019502674a15cac52dd90aa46e1183594 | [
"MIT"
] | null | null | null | include/ODBCLSLB/blobs.hpp | aliakseis/odbcpp | 7dc71f3019502674a15cac52dd90aa46e1183594 | [
"MIT"
] | null | null | null | #pragma once
typedef char BLOBFORMAT;
enum {
FMT_BITMAP = 1,
FMT_METAFILEPICT = 2,
NUM_FMT_ENTRIES = 5,
SIZE_FMT_ENTRIES = NUM_FMT_ENTRIES * sizeof(BLOBFORMAT)
};
class odbcEXPORTED odbcBLOB {
private:
odbcCURSOR* pGetCursor;
odbcCURSOR* pPutCursor;
UWORD iCol;
UWORD iParam;
void* pData_;
UDWORD cbAllocatedSize;
UDWORD cbMaxSize;
SWORD fSqlType;
UDWORD cbPutChunkSize;
UDWORD cbGetChunkSize;
SDWORD cbValue;
public:
SDWORD cbMaxBlobSize;
protected:
/****************************************************************
ReleaseMem
Free memory on the internal pointer.
****************************************************************/
void ReleaseMem();
public:
/****************************************************************
odbcBLOB
Constructor. Pass address of owning cursor, number of the
associated column, and maximum size of the parameter;
optionally also pass the column's SQL data type and
put- and get-chunk granularities.
****************************************************************/
odbcBLOB(
odbcCURSOR* pCurs,
UWORD iSentCol,
UDWORD cbSentMaxSize,
SWORD fSentSqlType = SQL_LONGVARBINARY,
UWORD iSentParam = 0,
SDWORD cbSentPutChunkSize = BLOB_CHUNK_PUT_SIZE,
SDWORD cbSentGetChunkSize = BLOB_CHUNK_GET_SIZE
);
/****************************************************************
~odbcBLOB
Destructor.
****************************************************************/
virtual ~odbcBLOB();
/****************************************************************
SetData
Copy passed value (of passed size) into internal memory.
****************************************************************/
virtual RETCODE SetData
(
void* pSentData,
UDWORD cbSentSize
);
/****************************************************************
PutData
Invoke odbcSTMT::PutData in loop if necessary to pass entire
value in chunks to the driver. Optionally set value before
invoking odbcSTMT::PutData.
****************************************************************/
virtual RETCODE PutData
(
void* pSentData = NULL,
UDWORD cbSentSize = 0
);
/****************************************************************
IsEmpty
Returns true if the current value is empty.
****************************************************************/
virtual bool IsEmpty()
{
return (cbValue == 0);
}
/****************************************************************
IsNull
Returns true if the current value is NULL.
****************************************************************/
virtual bool IsNull()
{
return (cbValue == SQL_NULL_DATA);
}
/****************************************************************
GetData
Perform loop (if needed) to retrieve data for the column
assigned to this odbcBLOB object.
****************************************************************/
virtual RETCODE GetData();
/****************************************************************
GetMem
Allocate memory to the internal pointer. We only ever have
one pointer in use, so free it first if it is not null. If
zero is passed, just return the current pointer.
****************************************************************/
virtual void* GetMem(UDWORD cbSize = 0);
/****************************************************************
GetcbValue
Get current cbValue value (length of data returned or
possibly SQL_NULL_DATA).
****************************************************************/
virtual SDWORD GetcbValue()
{
return cbValue;
}
/****************************************************************
SetNull
Set up for a NULL PutValue.
****************************************************************/
virtual void SetNull()
{
cbValue = SQL_NULL_DATA;
}
/****************************************************************
GetCursor
Get the associated cursor object used for GetData operations.
****************************************************************/
virtual odbcCURSOR* GetCursor()
{
return pGetCursor;
}
/****************************************************************
PutCursor
Get the associated cursor object used for PutData and BindParameter
operations.
****************************************************************/
virtual odbcCURSOR* PutCursor()
{
return pPutCursor;
}
/****************************************************************
SetPutCursor
Set the associated cursor object used for PutData and BindParameter
operations.
****************************************************************/
virtual odbcCURSOR* SetPutCursor(odbcCURSOR* pNewPutCursor)
{
odbcCURSOR* pOldPutCursor = pPutCursor;
pPutCursor = pNewPutCursor;
return pOldPutCursor;
}
/****************************************************************
SetGetCursor
Set the associated cursor object used for GetData and BindParameter
operations.
****************************************************************/
virtual odbcCURSOR* SetGetCursor(odbcCURSOR* pNewGetCursor)
{
odbcCURSOR* pOldGetCursor = pGetCursor;
pGetCursor = pNewGetCursor;
return pOldGetCursor;
}
/****************************************************************
BindParameter
Bind a parameter.
****************************************************************/
virtual RETCODE BindParameter();
/****************************************************************
SetParamNumber
Set the parameter number for a parameter. Sets to column number
if zero is sent. Returns old value.
****************************************************************/
virtual UWORD SetParamNumber(UWORD iSentParam)
{
UWORD iSaveParam = iParam;
// set to column number if zero is sent
if (iSentParam == 0)
iParam = iCol;
else
iParam = iSentParam;
return iSaveParam;
}
/****************************************************************
SetGetChunkSize
Set the chunk size for GetData() operations. Returns old value.
****************************************************************/
virtual UDWORD SetGetChunkSize(UDWORD cbSent)
{
UDWORD cbSave = cbSent;
cbGetChunkSize = cbSent;
return cbSave;
}
/****************************************************************
SetPutChunkSize
Set the chunk size for PutData() operations. Returns old value.
****************************************************************/
virtual UDWORD SetPutChunkSize(UDWORD cbSent)
{
UDWORD cbSave = cbSent;
cbPutChunkSize = cbSent;
return cbSave;
}
/****************************************************************
SettHGlobalInBlob
Set the content of the internal memory from a global memory
object, allocated via GlobalAlloc, which will be locked, copied, and
unlocked.
****************************************************************/
virtual RETCODE SetHGlobalInBlob(HGLOBAL hGlobal);
/****************************************************************
GetHGlobalFromBlob
Get the content of the internal memory as a global memory
object, allocated via GlobalAlloc, locked, copied, and
unlocked.
Returns NULL without error setting if the BLOB is empty or
contains null data. If memory allocation or locking fails,
returns NULL and sets allocation error on get and put cursors.
After copying the data it is wise to shrink its allocation in the
BLOB's internal memory by calling GetMem(1).
****************************************************************/
virtual HGLOBAL GetHGlobalFromBlob(UINT fuAlloc = GHND);
/****************************************************************
SetLPSTRInBlob
Given a huge pointer to a null-terminated string, allocate
the necessary amount of internal memory in the BLOB and
copy the string to the BLOB's internal memory.
****************************************************************/
virtual RETCODE SetLPSTRInBlob(char *lpstr);
/****************************************************************
GetLPSTRFromBlob
Allocate memory to the internal pointer. We only ever have
one pointer in use, so free it first if it is not null. If
zero is passed, just return the current pointer. Return the
poinster as an LPSTR.
****************************************************************/
virtual LPSTR GetLPSTRFromBlob(UDWORD cbSize = 0)
{
if (cbSize == 0 && IsNull())
return NULL;
return (LPSTR)GetMem(cbSize);
}
/****************************************************************
HasFormat
Given a BLOB that has been retrieved from the database,
make sure it contains the correct type of data.
****************************************************************/
bool HasFormat(BLOBFORMAT bfFormatToCheck);
/****************************************************************
SetBitmapInBlob
Given a HBITMAP, store it in the BLOB so that it can be
used as insertion or update data.
****************************************************************/
virtual RETCODE SetBitmapInBlob(HBITMAP hSentBitmap);
/****************************************************************
GetBitmapFromBlob
Given a BLOB that has been retrieved from the database,
translate it into a HBITMAP.
****************************************************************/
virtual RETCODE GetBitmapFromBlob(HBITMAP* pHBitmapToFill);
/****************************************************************
SetMetaFilePictInBlob
Given a METAFILEPICT, store it in the BLOB so that it can be
used as insertion or update data.
****************************************************************/
virtual RETCODE SetMetaFilePictInBlob(METAFILEPICT* pSentMetaFilePict);
/****************************************************************
GetMetaFilePictFromBlob
Given a BLOB that has been retrieved from the database,
translate it into a METAFILEPICT.
****************************************************************/
virtual RETCODE GetMetaFilePictFromBlob(METAFILEPICT* pMetaFilePictToFill);
}; // end odbcBLOB class
| 30.008043 | 79 | 0.419637 | [
"object"
] |
e17a8fc76f8d4fa276d43d5c39b0dda8e53b31b9 | 7,396 | cpp | C++ | 3rdParty/boost/1.61.0/libs/compute/test/test_reduce.cpp | mikestaub/arangodb | 1bdf414de29b31bcaf80769a095933f66f8256ce | [
"ICU",
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | 5 | 2017-01-19T09:35:40.000Z | 2021-02-26T07:31:38.000Z | libs/compute/test/test_reduce.cpp | crystax/android-vendor-boost-1-61-0 | a1f467d25d815dc7613fbee06c632cae423f52ca | [
"BSL-1.0"
] | 1 | 2015-11-09T15:38:28.000Z | 2015-11-12T11:14:58.000Z | libs/compute/test/test_reduce.cpp | crystax/android-vendor-boost-1-61-0 | a1f467d25d815dc7613fbee06c632cae423f52ca | [
"BSL-1.0"
] | 3 | 2015-11-02T09:37:09.000Z | 2017-05-05T06:38:49.000Z | //---------------------------------------------------------------------------//
// Copyright (c) 2013 Kyle Lutz <kyle.r.lutz@gmail.com>
//
// Distributed under the Boost Software License, Version 1.0
// See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//
// See http://boostorg.github.com/compute for more information.
//---------------------------------------------------------------------------//
#define BOOST_TEST_MODULE TestReduce
#include <boost/test/unit_test.hpp>
#include <boost/compute/lambda.hpp>
#include <boost/compute/system.hpp>
#include <boost/compute/functional.hpp>
#include <boost/compute/algorithm/reduce.hpp>
#include <boost/compute/container/vector.hpp>
#include <boost/compute/iterator/constant_iterator.hpp>
#include <boost/compute/iterator/counting_iterator.hpp>
#include <boost/compute/iterator/transform_iterator.hpp>
#include <boost/compute/types/complex.hpp>
#include "check_macros.hpp"
#include "context_setup.hpp"
namespace compute = boost::compute;
BOOST_AUTO_TEST_CASE(reduce_int)
{
int data[] = { 1, 5, 9, 13, 17 };
compute::vector<int> vector(data, data + 5, queue);
int sum;
compute::reduce(vector.begin(), vector.end(), &sum, compute::plus<int>(), queue);
BOOST_CHECK_EQUAL(sum, 45);
int product;
compute::reduce(vector.begin(), vector.end(), &product, compute::multiplies<int>(), queue);
BOOST_CHECK_EQUAL(product, 9945);
}
BOOST_AUTO_TEST_CASE(reduce_empty_vector)
{
compute::vector<short> vector(context);
short sum = 0;
compute::reduce(vector.begin(), vector.end(), &sum, queue);
BOOST_CHECK_EQUAL(sum, short(0));
}
BOOST_AUTO_TEST_CASE(reduce_doctest)
{
int data[] = { 1, 2, 3, 4 };
boost::compute::vector<int> vec(data, data + 4, queue);
//! [sum_int]
int sum = 0;
boost::compute::reduce(vec.begin(), vec.end(), &sum, queue);
//! [sum_int]
BOOST_CHECK_EQUAL(sum, 10);
}
BOOST_AUTO_TEST_CASE(reduce_twos)
{
using compute::uint_;
compute::vector<uint_> vector(8, context);
compute::fill(vector.begin(), vector.end(), uint_(2), queue);
uint_ sum;
compute::reduce(vector.begin(), vector.end(), &sum, compute::plus<uint_>(), queue);
BOOST_CHECK_EQUAL(sum, uint_(16));
uint_ product;
compute::reduce(vector.begin(), vector.end(), &product, compute::multiplies<uint_>(), queue);
BOOST_CHECK_EQUAL(product, uint_(256));
}
BOOST_AUTO_TEST_CASE(reduce_on_device)
{
int data[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
compute::vector<int> input(data, data + 8, queue);
compute::vector<int> result(2, context);
compute::reduce(input.begin(), input.begin() + 4, result.begin(), queue);
compute::reduce(input.begin() + 4, input.end(), result.end() - 1, queue);
CHECK_RANGE_EQUAL(int, 2, result, (10, 26));
}
BOOST_AUTO_TEST_CASE(reduce_int_min_max)
{
int data[] = { 11, 5, 92, 13, 42 };
compute::vector<int> vector(data, data + 5, queue);
int min_value;
compute::reduce(
vector.begin(),
vector.end(),
&min_value,
compute::min<int>(),
queue
);
BOOST_CHECK_EQUAL(min_value, 5);
int max_value;
compute::reduce(
vector.begin(),
vector.end(),
&max_value,
compute::max<int>(),
queue
);
BOOST_CHECK_EQUAL(max_value, 92);
}
BOOST_AUTO_TEST_CASE(reduce_int2)
{
std::vector<compute::int2_> data;
for(int i = 0; i < 6; i++){
compute::int2_ value;
value[0] = i + 1;
value[1] = 2 * i + 1;
data.push_back(value);
}
compute::vector<compute::int2_> vector(data.begin(), data.end(), queue);
compute::int2_ sum;
compute::reduce(
vector.begin(),
vector.end(),
&sum,
queue
);
BOOST_CHECK_EQUAL(sum, compute::int2_(21, 36));
}
BOOST_AUTO_TEST_CASE(reduce_pinned_vector)
{
int data[] = { 2, 5, 8, 11, 15 };
std::vector<int> vector(data, data + 5);
compute::buffer buffer(context,
vector.size() * sizeof(int),
compute::buffer::read_only | compute::buffer::use_host_ptr,
&vector[0]);
int sum;
compute::reduce(
compute::make_buffer_iterator<int>(buffer, 0),
compute::make_buffer_iterator<int>(buffer, 5),
&sum,
compute::plus<int>()
);
BOOST_CHECK_EQUAL(sum, 41);
}
BOOST_AUTO_TEST_CASE(reduce_constant_iterator)
{
int result;
compute::reduce(
compute::make_constant_iterator(1, 0),
compute::make_constant_iterator(1, 5),
&result,
queue
);
BOOST_CHECK_EQUAL(result, 5);
compute::reduce(
compute::make_constant_iterator(3, 0),
compute::make_constant_iterator(3, 5),
&result,
queue
);
BOOST_CHECK_EQUAL(result, 15);
compute::reduce(
compute::make_constant_iterator(2, 0),
compute::make_constant_iterator(2, 5),
&result,
compute::multiplies<int>(),
queue
);
BOOST_CHECK_EQUAL(result, 32);
}
BOOST_AUTO_TEST_CASE(reduce_counting_iterator)
{
int result;
compute::reduce(
compute::make_counting_iterator(1),
compute::make_counting_iterator(10),
&result,
queue
);
BOOST_CHECK_EQUAL(result, 45);
compute::reduce(
compute::make_counting_iterator(1),
compute::make_counting_iterator(5),
&result,
compute::multiplies<int>(),
queue
);
BOOST_CHECK_EQUAL(result, 24);
}
BOOST_AUTO_TEST_CASE(reduce_transform_iterator)
{
using ::boost::compute::_1;
int data[] = { 1, 3, 5, 7, 9 };
compute::vector<int> vector(data, data + 5, queue);
int sum;
compute::reduce(
compute::make_transform_iterator(vector.begin(), _1 + 1),
compute::make_transform_iterator(vector.end(), _1 + 1),
&sum,
queue
);
BOOST_CHECK_EQUAL(sum, 30);
compute::reduce(
compute::make_transform_iterator(vector.begin(), _1 > 4),
compute::make_transform_iterator(vector.end(), _1 > 4),
&sum,
compute::plus<int>(),
queue
);
BOOST_CHECK_EQUAL(sum, 3);
compute::reduce(
compute::make_transform_iterator(vector.begin(), _1 * _1),
compute::make_transform_iterator(vector.end(), _1 * _1),
&sum,
queue
);
BOOST_CHECK_EQUAL(sum, 165);
}
BOOST_AUTO_TEST_CASE(reduce_complex)
{
std::vector<std::complex<float> > data;
data.push_back(std::complex<float>(1, 2));
data.push_back(std::complex<float>(2, 4));
data.push_back(std::complex<float>(3, 6));
data.push_back(std::complex<float>(4, 8));
compute::vector<std::complex<float> > vector(data.size(), context);
compute::copy(data.begin(), data.end(), vector.begin(), queue);
std::complex<float> result;
compute::reduce(
vector.begin(), vector.end(), &result, queue
);
BOOST_CHECK(result == std::complex<float>(10, 20));
compute::reduce(
vector.begin(), vector.end(), &result, compute::plus<std::complex<float> >(), queue
);
BOOST_CHECK(result == std::complex<float>(10, 20));
compute::reduce(
vector.begin(), vector.end(), &result, compute::multiplies<std::complex<float> >(), queue
);
BOOST_CHECK(result == std::complex<float>(-168, -576));
}
BOOST_AUTO_TEST_SUITE_END()
| 27.392593 | 97 | 0.612088 | [
"vector"
] |
e17ad7a980a06b6f14018b81003aba63e78065bb | 4,084 | cpp | C++ | src/c_api/all.cpp | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | 1 | 2019-01-05T17:33:59.000Z | 2019-01-05T17:33:59.000Z | src/c_api/all.cpp | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | null | null | null | src/c_api/all.cpp | bdbabiak/Coda | 5e84624ae2b759fb1743778316f64c801591c48a | [
"Apache-2.0"
] | null | null | null | #include "all.h"
using namespace ccoda;
cSentenceSplitter* cSentenceSplitter_create(Tools::Language language)
{
return (cSentenceSplitter*) new _sentence_splitter::SentenceSplitter(language);
}
void cSentenceSplitter_destroy(cSentenceSplitter* ss)
{
delete (_sentence_splitter::SentenceSplitter*) ss;
}
/// @returns number of items in results buffer
size_t cSentenceSplitter_split(cSentenceSplitter* splitter, const wchar_t* line_to_split, size_t line_length, size_t** result_borders)
{
wstring s(line_to_split, line_length);
auto vect = ((_sentence_splitter::SentenceSplitter*) splitter)->split(s);
*result_borders = (size_t*) malloc(sizeof(size_t) * vect.size());
std::copy(vect.begin(), vect.end(), *result_borders);
return vect.size();
}
void free_mem(void* buf_ptr)
{
free(buf_ptr);
}
cTokenizer* cTokenizer_create(Tools::Language language)
{
auto r = new cTokenizer;
r->This = Tokenization::ITokenizer::GetTokenizer(language);
return r;
}
void cTokenizer_destroy(cTokenizer* tokenizer)
{
delete tokenizer;
}
cTokensStorage* cTokenizer_tokenize(cTokenizer* tokenizer, const wchar_t* line, size_t line_length)
{
wstring s(line, line_length);
auto r = new cTokensStorage;
r->tokens = tokenizer->This->Tokenize(s);
return r;
}
void cTokensStorage_destroy(cTokensStorage* ts)
{
delete ts;
}
cDisambiguator* cDisambiguator_create(Tools::Language language)
{
auto r = new cDisambiguator;
r->This = Disambiguation::IDisambiguator::GetDisambiguator(language);
return r;
}
void cDisambiguator_destroy(cDisambiguator* d)
{
delete d;
}
cDisambiguatedDataStorage* cDisambiguator_disambiguate(cDisambiguator* d, cTokensStorage* parsedTokens)
{
auto r = new cDisambiguatedDataStorage;
r->disambiguated = d->This->Disambiguate(parsedTokens->tokens);
return r;
}
void cDisambiguatedDataStorage_destroy(cDisambiguatedDataStorage* ds)
{
delete ds;
}
cSyntaxParser* cSyntaxParser_create(Tools::Language language)
{
auto r = new cSyntaxParser;
r->This = SyntaxParser::ISyntaxParser::GetSyntaxParser(language);
return r;
}
void cSyntaxParser_destroy(cSyntaxParser* sp)
{
delete sp;
}
cSyntaxTree* cSyntaxParser_parse(cSyntaxParser* syntax_parser, cDisambiguatedDataStorage* dds)
{
return (cSyntaxTree*) new PublicNodesSyntaxTree(
syntax_parser->This->Parse(dds->disambiguated)
);
}
void cSyntaxTree_destroy(cSyntaxTree* t)
{
delete (PublicNodesSyntaxTree*) t;
}
PublicNodesSyntaxTree::PublicNodesSyntaxTree(const SyntaxTree& tree) : SyntaxParser::SyntaxTree(tree)
{
}
SyntaxParser::SyntaxNode* PublicNodesSyntaxTree::getNodeByIndex(size_t idx)
{
return &nodes[idx];
}
cSyntaxNode* cSyntaxTree_getNodeByIndex(cSyntaxTree* tree, size_t idx)
{
return (cSyntaxNode*) ((PublicNodesSyntaxTree*) tree)->getNodeByIndex(idx);
}
int cSyntaxTree_getRootIndex(const cSyntaxTree* tree)
{
return ((PublicNodesSyntaxTree*) tree)->GetRootIndex();
}
int cSyntaxTree_getParentIndex(const cSyntaxTree* tree, int nodeIndex)
{
return ((PublicNodesSyntaxTree*) tree)->GetParentIndex(nodeIndex);
}
cIntVector* cSyntaxNode_getChildrenIndexes(const cSyntaxNode* node)
{
return (cIntVector*) &((SyntaxParser::SyntaxNode*) node)->neighbours;
}
cNodeData cSyntaxNode_get_cNodeData(cSyntaxNode* sNode)
{
auto node = (SyntaxParser::SyntaxNode*) sNode;
cNodeData r;
r.content = (cWstring*) &node->content;
r.punctuation_size = node->punctuation.size();
r.isNextSpace = node->isNextSpace;
r.lemma = (cWstring*) &node->lemma;
r.label = (cWstring*) &node->label;
r.weight = node->weight;
r.lemmaId = node->lemmaId;
return r;
}
cWstring* cSyntaxNode_getPunctuationByIndex(cSyntaxNode* sNode, size_t idx)
{
auto node = (SyntaxParser::SyntaxNode*) sNode;
return (cWstring*) &node->punctuation[idx];
}
size_t cIntVector_getLength(const cIntVector* iv)
{
return ((vector<int>*) iv)->size();
}
int* cIntVector_getPtr(const cIntVector* iv)
{
return ((vector<int>*) iv)->data();
}
size_t cWstring_getLength(const cWstring* v)
{
return ((wstring*) v)->size();
}
const wchar_t* cWstring_getPtr(cWstring* v)
{
return ((wstring*) v)->data();
}
| 21.608466 | 134 | 0.761019 | [
"vector"
] |
e17e1929581ca741c0a857d9032e2a3de9005dde | 3,582 | cpp | C++ | src/snAux/src/auxFunc.cpp | ifritee/skynet | 035dd5917ed61bdae03ab3cab121762b31a0e1fa | [
"MIT"
] | 1 | 2019-12-25T20:13:03.000Z | 2019-12-25T20:13:03.000Z | src/snAux/src/auxFunc.cpp | catcherochek/skynet | d773f730ff7310e27a04e3d2251c725e16454ae5 | [
"MIT"
] | null | null | null | src/snAux/src/auxFunc.cpp | catcherochek/skynet | d773f730ff7310e27a04e3d2251c725e16454ae5 | [
"MIT"
] | 1 | 2020-05-06T13:51:04.000Z | 2020-05-06T13:51:04.000Z | //
// SkyNet Project
// Copyright (C) 2018 by Contributors <https://github.com/Tyill/skynet>
//
// This code is licensed under the MIT License.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files(the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions :
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <thread>
#include <chrono>
#include <cstring>
#include <vector>
#include <algorithm>
#include <cctype>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef WIN32
#include <windows.h>
#endif
using namespace std;
namespace SN_Aux{
// %Y-%m-%d %H:%M:%S:%MS
string CurrDateTimeMs() {
time_t ct = time(nullptr);
tm* lct = localtime(&ct);
uint64_t ms = std::chrono::time_point_cast<std::chrono::milliseconds>(std::chrono::system_clock::now()).time_since_epoch().count();
uint64_t mspr = ms / 1000;
ms -= mspr * 1000;
char curDate[32];
strftime(curDate, 32, "%Y-%m-%d %H:%M:%S:", lct);
sprintf(curDate, "%s%03d", curDate, int(ms));
return curDate;
}
vector<string> split(string text, const char* sep)
{
char* cstr = (char*)text.c_str();
vector<string> res;
char* pch = strtok(cstr, sep);
while (pch != NULL){
res.push_back(string(pch));
pch = strtok(NULL, sep);
}
return res;
}
std::string trim(const std::string& str)
{
size_t first = str.find_first_not_of(' ');
if (std::string::npos == first){
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}
std::string toLower(const std::string& str)
{
string out = str;
std::transform(str.begin(), str.end(), out.begin(), ::tolower);
return out;
}
bool is_number(const std::string& s)
{
return !s.empty() && std::find_if(s.begin(),
s.end(), [](char c) { return !std::isdigit(c); }) == s.end();
}
void sleepMs(int ms){
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}
bool createSubDirectory(const std::string& strDirs){
size_t sz = strDirs.size(); int ret = 0;
string strTmp = "";
for (size_t i = 0; i < sz; ++i) {
char ch = strDirs[i];
if (ch != '\\' && ch != '/') strTmp += ch;
else {
#if defined(_WIN32)
strTmp += "\\";
ret = CreateDirectoryA(strTmp.c_str(), NULL);
#else
strTmp += "/";
ret = mkdir(strTmp.c_str(), 0733);
#endif
}
}
return ret == 0;
}
} | 29.603306 | 139 | 0.600782 | [
"vector",
"transform"
] |
e18d152104cc2d94aa9e0d1e76a5b9eea6f640d3 | 595 | cpp | C++ | src/al_common/entity/AlAttribute.cpp | imalimin/FilmKilns | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 83 | 2020-11-13T01:35:13.000Z | 2022-03-25T02:12:13.000Z | src/al_common/entity/AlAttribute.cpp | mohsinnaqvi110/FilmKilns | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 3 | 2020-03-23T07:28:29.000Z | 2020-09-11T17:16:48.000Z | src/al_common/entity/AlAttribute.cpp | lmylr/hwvc | 2146487c4292d8c7453a53c54d1e24417902f8b7 | [
"MIT"
] | 32 | 2020-11-09T04:20:35.000Z | 2022-03-22T04:11:45.000Z | /*
* Copyright (c) 2018-present, aliminabc@gmail.com.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "AlAttribute.h"
AlAttribute::AlAttribute(std::string &k, std::string &v) {
pair.first = k;
pair.second = v;
}
AlAttribute::AlAttribute(const AlAttribute &o) : Object() {
pair.first = o.pair.first;
pair.second = o.pair.second;
}
AlAttribute::~AlAttribute() {
}
std::string AlAttribute::name() {
return pair.first;
}
std::string AlAttribute::value() {
return pair.second;
}
| 19.193548 | 65 | 0.678992 | [
"object"
] |
e18ebc51c02ec78446ab6adea12a2b53e2aa866b | 6,141 | cc | C++ | build/OLD/AvidaGP-Mancala.cc | mitchelljohnson3/MABE2 | 08a615a8b1affb25021045ed8113720431709028 | [
"MIT"
] | 5 | 2020-04-24T18:57:30.000Z | 2021-07-02T19:23:51.000Z | build/OLD/AvidaGP-Mancala.cc | athaichi/MABE2 | 6d6640a3658c1843611affbce25ce3d564523358 | [
"MIT"
] | 4 | 2021-10-29T23:31:02.000Z | 2022-02-23T16:24:54.000Z | build/OLD/AvidaGP-Mancala.cc | athaichi/MABE2 | 6d6640a3658c1843611affbce25ce3d564523358 | [
"MIT"
] | 9 | 2020-08-11T17:12:23.000Z | 2022-01-13T17:04:45.000Z | // This file is part of Empirical, https://github.com/devosoft/Empirical
// Copyright (C) Michigan State University, 2017.
// Released under the MIT Software license; see doc/LICENSE
#include <iostream>
#include "games/Mancala.h"
#include "hardware/AvidaGP.h"
#include "hardware/InstLib.h"
#include "tools/Random.h"
#include "Evolve/World.h"
constexpr size_t POP_SIZE = 20;
constexpr size_t GENOME_SIZE = 100;
constexpr size_t EVAL_TIME = 500;
constexpr size_t UPDATES = 100;
constexpr size_t TOURNY_SIZE = 4;
// Determine the next move of a human player.
size_t EvalMove(emp::Mancala & game, std::ostream & os=std::cout, std::istream & is=std::cin) {
// Present the current board.
game.Print();
// Request a move from the human.
char move;
os << "Move?" << std::endl;
is >> move;
while (move < 'A' || move > 'F' || game.GetCurSide()[(size_t)(move-'A')] == 0) {
os << "Invalid move! (choose a value 'A' to 'F')" << std::endl;
is.clear();
is.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
is >> move;
}
return (size_t) (move - 'A');
}
// Determine the next move of an AvidaGP player.
size_t EvalMove(emp::Mancala & game, emp::AvidaGP & org) {
// Setup the hardware with proper inputs.
org.ResetHardware();
org.SetInputs(game.AsInput(game.GetCurPlayer()));
// Run the code.
org.Process(EVAL_TIME);
// Determine the chosen move.
int best_move = 0;
for (int i = 1; i < 6; i++) {
if (org.GetOutput(best_move) < org.GetOutput(i)) { best_move = i; }
}
return (size_t) best_move;
}
using mancala_ai_t = std::function< size_t(emp::Mancala & game) >;
// Setup the fitness function for a whole game.
double EvalGame(mancala_ai_t & player0, mancala_ai_t & player1,
bool cur_player=0, bool verbose=false) {
emp::Mancala game(cur_player==0);
size_t round = 0, errors = 0;
while (game.IsDone() == false) {
// Determine the current player and their move.
auto & play_fun = (cur_player == 0) ? player0 : player1;
size_t best_move = play_fun(game);
if (verbose) {
std::cout << "round = " << round++ << " errors = " << errors << std::endl;
game.Print();
char move_sym = (char) ('A' + best_move);
std::cout << "Move = " << move_sym;
if (game.GetCurSide()[best_move] == 0) {
std::cout << " (illegal!)";
}
std::cout << std::endl << std::endl;
}
// If the chosen move is illegal, shift through other options.
while (game.GetCurSide()[best_move] == 0) { // Cannot make a move into an empty pit!
if (cur_player == 0) errors++;
if (++best_move > 5) best_move = 0;
}
// Do the move and determine who goes next.
bool go_again = game.DoMove(cur_player, best_move);
if (!go_again) cur_player = !cur_player;
}
if (verbose) {
std::cout << "Final scores -- A: " << game.ScoreA()
<< " B: " << game.ScoreB()
<< std::endl;
}
return ((double) game.ScoreA()) - ((double) game.ScoreB()) - ((double) errors * 10.0);
}
// Build wrappers for AvidaGP
double EvalGame(emp::AvidaGP & org0, emp::AvidaGP & org1, bool cur_player=0, bool verbose=false) {
mancala_ai_t org_fun0 = [&org0](emp::Mancala & game){ return EvalMove(game, org0); };
mancala_ai_t org_fun1 = [&org1](emp::Mancala & game){ return EvalMove(game, org1); };
return EvalGame(org_fun0, org_fun1, cur_player, verbose);
}
// Otherwise assume a human opponent!
double EvalGame(emp::AvidaGP & org, bool cur_player=0) {
mancala_ai_t fun0 = [&org](emp::Mancala & game){ return EvalMove(game, org); };
mancala_ai_t fun1 = [](emp::Mancala & game){ return EvalMove(game, std::cout, std::cin); };
return EvalGame(fun0, fun1, cur_player, true);
}
int main()
{
emp::Random random;
emp::World<emp::AvidaGP> world(random, "AvidaWorld");
world.SetPopStruct_Mixed(true);
// Build a random initial popoulation.
for (size_t i = 0; i < POP_SIZE; i++) {
emp::AvidaGP cpu;
cpu.PushRandom(random, GENOME_SIZE);
world.Inject(cpu.GetGenome());
}
// Setup the mutation function.
world.SetMutFun( [](emp::AvidaGP & org, emp::Random& random) {
uint32_t num_muts = random.GetUInt(4); // 0 to 3 mutations.
for (uint32_t m = 0; m < num_muts; m++) {
const uint32_t pos = random.GetUInt(GENOME_SIZE);
org.RandomizeInst(pos, random);
}
return (num_muts > 0);
} );
// Setup the fitness function.
std::function<double(emp::AvidaGP &)> fit_fun =
[&random, &world](emp::AvidaGP & org) {
emp::AvidaGP & rand_org = world.GetRandomOrg();
bool cur_player = random.P(0.5);
return EvalGame(org, rand_org, cur_player);
};
world.SetFitFun(fit_fun);
emp::vector< std::function<double(emp::AvidaGP &)> > fit_set(16);
for (size_t out_id = 0; out_id < 16; out_id++) {
// Setup the fitness function.
fit_set[out_id] = [out_id](emp::AvidaGP & org) {
return (double) -std::abs(org.GetOutput((int)out_id) - (double) (out_id * out_id));
};
}
// Do the run...
for (size_t ud = 0; ud < UPDATES; ud++) {
// Keep the best individual.
EliteSelect(world, 1, 1);
// Run a tournament for each spot.
TournamentSelect(world, TOURNY_SIZE, POP_SIZE-1);
// LexicaseSelect(world, POP_SIZE-1);
// EcoSelect(world, fit_set, 100, TOURNY_SIZE, POP_SIZE-1);
world.Update();
std::cout << (ud+1) << " : " << 0 << " : " << world.CalcFitnessID(0) << std::endl;
// Mutate all but the first organism.
world.DoMutations(1);
}
world.CalcFitnessID(0);
std::cout << std::endl;
emp::Mancala game(0);
world[0].PrintGenome("mancala_save.org");
game.DoMove(0);
world.GetOrg(0).ResetHardware();
world.GetOrg(0).SetInputs(game.AsInput(game.GetCurPlayer()));
world.GetOrg(0).Trace(1);
game.DoMove(5);
world.GetOrg(0).ResetHardware();
world.GetOrg(0).SetInputs(game.AsInput(game.GetCurPlayer()));
world.GetOrg(0).Trace(1);
// EvalGame(world[0], world[1], 0, true);
//
// // And try playing it!
// while (true) {
// std::cout << "NEW GAME: Human vs. AI!\n";
// EvalGame(world[0]);
// }
return 0;
}
| 30.705 | 98 | 0.625794 | [
"vector"
] |
e18f126901624d1f7525e5da1d87d9e13f7907e9 | 2,584 | cpp | C++ | ceppengine/src/ceppengine/assets/assetloader.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | 2 | 2017-11-13T11:29:03.000Z | 2017-11-13T12:09:12.000Z | ceppengine/src/ceppengine/assets/assetloader.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | null | null | null | ceppengine/src/ceppengine/assets/assetloader.cpp | Winded/ceppengine | 52a9c1723dc45aba4d85d50e4c919ec8016c8d94 | [
"MIT"
] | null | null | null | #include "assetloader.h"
#include <algorithm>
#include <fstream>
#include "../engine.h"
#include "importers/textureimporter.h"
#include "importers/jsonimporter.h"
#include "importers/shaderimporter.h"
#include "importers/meshimporter.h"
#include "importers/audioimporter.h"
#include "importers/fontimporter.h"
namespace cepp {
AssetLoader::AssetLoader()
{
mLoadPath = "../assets";
}
std::string AssetLoader::loadPath() const
{
return mLoadPath;
}
void AssetLoader::setLoadPath(const std::string &path)
{
mLoadPath = path;
}
void AssetLoader::loadDefaultImporters()
{
mImporters.push_back(new TextureImporter());
mImporters.push_back(new JsonImporter());
mImporters.push_back(new ShaderImporter());
mImporters.push_back(new MeshImporter());
mImporters.push_back(new AudioImporter());
mImporters.push_back(new FontImporter());
}
Asset *AssetLoader::loadAsset(const std::string &path, const std::string &type)
{
// See if we have already loaded this asset
auto asIt = std::find_if(mLoadedAssets.begin(), mLoadedAssets.end(), [path, type](const LoadedAsset &asset) {
return asset.path == path && asset.asset && asset.asset->typeName() == type;
});
if(asIt != mLoadedAssets.end())
return (*asIt).asset;
// Get the right importer for the asset file
std::string ext = path.substr(path.find_last_of('.'));
AssetImporter *importer = 0;
for(auto it = mImporters.begin(); it != mImporters.end(); ++it) {
if((*it)->canLoadExtension(ext)) {
importer = *it;
break;
}
}
if(!importer)
return 0;
// Open input stream
std::istream *stream = Engine::instance()->fileModule()->getAssetReadStream(path);
std::vector<Asset*> assets = importer->import(*stream);
Engine::instance()->fileModule()->closeStream(stream);
Asset *rAsset = 0;
for(auto it = assets.begin(); it != assets.end(); ++it) {
if((*it)->typeName() == type)
rAsset = *it;
mLoadedAssets.push_back(AssetLoader::LoadedAsset(*it, path));
}
return rAsset;
}
void AssetLoader::unloadAssets()
{
mLoadedAssets.clear();
}
std::string AssetLoader::filePathToAssetPath(const std::string &filePath) const
{
assert(filePath.size() > mLoadPath.size());
std::string path = "/" + filePath.substr(mLoadPath.size() + 1);
std::replace(path.begin(), path.end(), '\\', '/');
return path;
}
std::string AssetLoader::assetPathToFilePath(const std::string &assetPath) const
{
return mLoadPath + assetPath;
}
} // namespace cepp
| 27.784946 | 113 | 0.660991 | [
"vector"
] |
e190e2c484b99071c710771fb86f6c64849d8cea | 2,196 | cc | C++ | src/puffrs_factory.cc | akhilPotla97/PUFfRS | 42fdfa6085706536b4066a76955cef1cc35fa93f | [
"Apache-2.0"
] | null | null | null | src/puffrs_factory.cc | akhilPotla97/PUFfRS | 42fdfa6085706536b4066a76955cef1cc35fa93f | [
"Apache-2.0"
] | 5 | 2019-03-01T18:33:36.000Z | 2019-05-14T14:04:10.000Z | src/puffrs_factory.cc | akhilPotla97/PUFfRS | 42fdfa6085706536b4066a76955cef1cc35fa93f | [
"Apache-2.0"
] | 3 | 2018-02-24T01:32:01.000Z | 2019-04-02T21:51:44.000Z | // Copyright 2015 John T. Foster
// 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 "puffrs_factory.h"
#include "puffrs_parser.h"
/** Factory Method to create puffrs objects. This function is overloaded and
* will take a set of three arguments here.
*
* @param kInputFile the input file
* @param kComm pointer to the Xpetra communicator
* @param puffrs_discretization Discretization
* @return kComm puffrs kComm
* @return kPuffrsParameters parameters from input file as puffrs object
* @return puffrs_discretization puffrs discretization
*/
Teuchos::RCP<puffrs::Puffrs> puffrs::PuffrsFactory::Create(
const std::string kInputFile,
const Teuchos::RCP<const Teuchos::Comm<puffrs::types::PuffrsComm> >& kComm,
Teuchos::RCP<puffrs::Discretization> puffrs_discretization) {
const auto kPuffrsParameters = puffrs::PuffrsParser::Parse(kInputFile);
// Create new puffrs object
return Teuchos::rcp(
new puffrs::Puffrs(kComm, kPuffrsParameters, puffrs_discretization));
}
/** Factory Method to create puffrs objects. This function is overloaded and
* will take a set of two arguments here.
*
* @param kInputFile the input file
* @param puffrs_discretization Discretization
* @return kInputFile
* @return kComm
* @return null_discretization null discretization from Teuchos
*/
Teuchos::RCP<puffrs::Puffrs> puffrs::PuffrsFactory::Create(
const std::string kInputFile,
const Teuchos::RCP<const Teuchos::Comm<puffrs::types::PuffrsComm> >&
kComm) {
Teuchos::RCP<puffrs::Discretization> null_discretization;
return Create(kInputFile, kComm, null_discretization);
}
| 39.927273 | 79 | 0.731785 | [
"object"
] |
e191f373b9fe27b90dd5273bdd0c84f0d5d3988b | 9,181 | cpp | C++ | 3rdparty/meshlab-master/src/plugins_unsupported/filter_sdf/filter_sdf+.cpp | HoEmpire/slambook2 | 96d360f32aa5d8b5c5dcbbf9ee7ba865e84409f4 | [
"MIT"
] | 4 | 2016-03-30T14:31:52.000Z | 2019-02-02T05:01:32.000Z | graphics/meshlab/src/meshlabplugins/filter_sdf/filter_sdf+.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | graphics/meshlab/src/meshlabplugins/filter_sdf/filter_sdf+.cpp | hlzz/dotfiles | 0591f71230c919c827ba569099eb3b75897e163e | [
"BSD-3-Clause"
] | null | null | null | #include <vcg/complex/complex.h>
#include <vcg/complex/algorithms/update/topology.h>
#include <vcg/complex/algorithms/update/edges.h>
#include <vcg/complex/algorithms/update/bounding.h>
#include <vcg/complex/algorithms/update/quality.h>
#include <vcg/complex/algorithms/update/color.h>
#include <vcg/complex/algorithms/update/flag.h>
#include <vcg/complex/algorithms/clean.h>
#include <vcg/complex/intersection.h>
#include <vcg/space/index/grid_static_ptr.h>
#include <vcg/space/index/spatial_hashing.h>
#include <vcg/math/matrix33.h>
#include <vcg/space/index/grid_static_ptr.h> // vcg::GridStaticPtr
#include <vcg/space/index/grid_closest.h> // Closest queries
#include <vcg/space/index/spatial_hashing.h> // vcg::SpatialHashTable
#include <wrap/qt/to_string.h>
#include "filter_sdf.h"
#include "mysampling.h"
//--- Uncomment only one of the two following lines to test different data structures
typedef vcg::GridStaticPtr<CMeshO::FaceType, CMeshO::ScalarType> TriMeshGrid;
/* typedef vcg::SpatialHashTable<CMeshO::FaceType, CMeshO::float> TriMeshGrid; */
using namespace std;
using namespace vcg;
SdfPlugin::SdfPlugin() : SingleMeshFilterInterface("Compute SDF"){}
void SdfPlugin::initParameterSet(MeshDocument&, RichParameterSet& par){
QStringList onPrimitive; onPrimitive.push_back("On vertices"); onPrimitive.push_back("On Faces");
par.addParam( new RichEnum("onPrimitive", 0, onPrimitive, "Metric:",
"Choose whether to trace rays from faces or from vertices. "
"Recall that tracing from vertices will use vertex normal "
"estimation."));
par.addParam(new RichFloat("coneWidth", 20, "Cone width: ",
"The standard deviation of the rays that will be casted around "
"the anti-normals. Remember that most sampled directions are "
"expected to fall within 3x this value."));
par.addParam( new RichInt("numberRays", 50, "Number of rays: ",
"The standard deviation of the rays that will be casted around "
"the anti-normals. Remember that most sampled directions are "
"expected to fall within 3x this value."));
par.addParam(new RichFloat("lowQuantile", .1, "Bottom quantile",
"We will throw away the set of ray distances for each cone which distance "
"value falls under this quantile. Value in between [0,1]. 0 Implies all "
"values are kept"));
par.addParam(new RichFloat("hiQuantile", .9, "Top quantile",
"We will throw away the set of ray distances for each cone which distance "
"value falls under this quantile. Value in between [0,1]. 1 Implies all "
"values are kept"));
}
bool SdfPlugin::applyFilter(MeshDocument& md, RichParameterSet& pars, vcg::CallBackPos* cb){
enum ONPRIMITIVE{ON_VERTICES, ON_FACES} onPrimitive;
MeshModel* mm = md.mm();
CMeshO& m = mm->cm;
//--- Retrieve parameters
float widenessRad = math::ToRad(pars.getFloat("coneWidth"));
int raysPerCone = pars.getInt("numberRays");
onPrimitive = (ONPRIMITIVE) pars.getEnum("onPrimitive");
qDebug() << "which primitive?" << onPrimitive;
float lo01pec = pars.getFloat("lowQuantile");
float hi01pec = pars.getFloat("hiQuantile");
assert( onPrimitive==ON_VERTICES && "Face mode not supported yet" );
//--- If on vertices, do some cleaning first
if( onPrimitive == ON_VERTICES ){
int dup = tri::Clean<CMeshO>::RemoveDuplicateVertex(m);
int unref = tri::Clean<CMeshO>::RemoveUnreferencedVertex(m);
if (dup > 0 || unref > 0) Log("Removed %i duplicate and %i unreferenced vertices\n",dup,unref);
}
//--- Updating mesh metadata
tri::UpdateBounding<CMeshO>::Box(m);
tri::UpdateNormals<CMeshO>::PerFaceNormalized(m);
tri::UpdateNormals<CMeshO>::PerVertexAngleWeighted(m);
tri::UpdateNormals<CMeshO>::NormalizeVertex(m);
tri::UpdateFlags<CMeshO>::FaceProjection(m);
//--- Enable & Reset the necessary attributes
switch(onPrimitive){
case ON_VERTICES:
// qDebug() << "initializing vert quality";
mm->updateDataMask(MeshModel::MM_VERTQUALITY);
tri::UpdateQuality<CMeshO>::VertexConstant(m,0);
break;
case ON_FACES:
mm->updateDataMask(MeshModel::MM_FACEQUALITY);
tri::UpdateQuality<CMeshO>::FaceConstant(m,0);
break;
}
//--- Add the mesh to an indexing structure (fast ray intersection)
Log("Initializing spatial accelleration...");
mm->updateDataMask(MeshModel::MM_FACEMARK);
TriMeshGrid static_grid; //TODO: rename spatial index
static_grid.Set(m.face.begin(), m.face.end());
Log("Initializing spatial accelleration... DONE!");
// since we are measuring the interior of the shape
// A ray should never go beyond this value
float maxDist=m.bbox.Diag();
// This is a small number to avoid self-intersection during ray
// casting. It's a very common trick
float epsilon = maxDist / 10000.0;
//--- Ray casting
vector<Ray3f> cone;
vector<float> coneSdf;
Ray3f ray;
float t;
for(unsigned int i=0; i<m.vert.size(); i++){
CVertexO& v = m.vert[i];
//--- Update progressbar
cb( i/m.vert.size(), "Casting rays into volume...");
//--- Generate the set of cones
ray.Set( v.P(), -v.N() );
ray.SetOrigin( ray.P(epsilon) );
generateRayCone( ray, widenessRad, raysPerCone, cone, coneSdf, (i==266) );
//--- Trace rays in cone
float mind = +numeric_limits<float>::max();
float maxd = -numeric_limits<float>::max();
for(unsigned int j=0; j<cone.size(); j++){
bool hasInt = tri::DoRay<CMeshO,TriMeshGrid>(m,static_grid,cone[j],maxDist,t);
coneSdf[j] = (hasInt==true) ? t : numeric_limits<float>::quiet_NaN();
mind = (hasInt && (t<mind)) ? t : mind;
maxd = (hasInt && (t>maxd)) ? t : maxd;
if( i==266 ){
qDebug() << " sampled: " << coneSdf[j]
<< " dir: " << toString(cone[j].Direction())
<< " hasInt: " << hasInt;
}
}
//--- Compute per-cone statistics
Histogram<float> H;
H.Clear();
H.SetRange( mind, maxd, 100);
for(unsigned int j=0; j<cone.size(); j++)
if(!math::IsNAN(coneSdf[j]))
H.Add(coneSdf[j]);
float loperc = H.Percentile(lo01pec);
float hiperc = H.Percentile(hi01pec);
if( i == 266){
qDebug() << "percentiles: " << loperc << " " << hiperc;
}
//--- Compute average of samples, throwing away outliers
if( i == 266)
qDebug() << "averaging samples";
float totVal = 0, totCnt = 0;
for(unsigned int j=0; j<coneSdf.size(); j++)
if( !math::IsNAN(coneSdf[j]) ){
// Histogram statistics valid only for dense sets (more 3 members..)
if( coneSdf[j]<loperc || coneSdf[j]>hiperc && coneSdf.size()>3)
continue;
// Weight giving more importance to aligned samples
float weight = cone[j].Direction().dot( ray.Direction() );
// Even more importance
weight = powf( weight, 10 );
if( i==266 ){
qDebug() << "sampled: " << coneSdf[j] << "weight " << weight
<< " dir:" << toString(cone[j].Direction());
}
totVal += weight*coneSdf[j];
totCnt += weight;
}
//--- Save in mesh
v.Q() = totCnt>0 ? (totVal/totCnt) : 0;
}
//----------------------------------------------------------------------------//
//
// STEROIDS STARTS HERE
//
//----------------------------------------------------------------------------//
//--- Create the medial cloud by offsetting the samples of the medial amount
MeshModel* medCloud = md.addNewMesh("medial cloud.obj", NULL, false);
for(unsigned int i=0; i<m.vert.size(); i++){
Ray3f r;
r.Set(m.vert[i].P(), -m.vert[i].N());
tri::Allocator<CMeshO>::AddVertices(medCloud->cm,1);
medCloud->cm.vert.back().P() = r.P(m.vert[i].Q() / 2 );
}
//--- Data for distance queries
vcg::tri::FaceTmark<CMeshO> mf;
mf.SetMesh( &m );
vcg::face::PointDistanceBaseFunctor<float> PDistFunct;
Log("querying real distances");
// Query the location of closest point on the mesh, then measure the difference
float allowedDiff = .02;
vector<float> realdistances(m.vn, 0);
for(unsigned int i=0; i<m.vert.size(); i++){
Point3f currp = medCloud->cm.vert[i].P();
float minDist = maxDist;
Point3f closest;
GridClosest(static_grid, PDistFunct, mf, currp, maxDist, minDist, closest);
float difference = m.vert[i].Q()/2.0 - minDist;
m.vert[i].Q() = exp( -powf(difference/allowedDiff,2) );
}
// Correct the viewmodel so that after this is done the original mesh
// is shown in wireframe and the medial as a cloud.
// mm->glw.cdm = vcg::GLW::DMWire; // show original mesh in wireframe
medCloud->glw.cdm = vcg::GLW::DMPoints; // show cloud
return true;
}
Q_EXPORT_PLUGIN(SdfPlugin)
| 40.444934 | 104 | 0.61453 | [
"mesh",
"shape",
"vector"
] |
e193e3a0b5db48bf789990b55177dcefedf8a29b | 4,802 | hpp | C++ | include/codegen/include/GlobalNamespace/PS4BeatmapDataAssetFileModel.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/GlobalNamespace/PS4BeatmapDataAssetFileModel.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/GlobalNamespace/PS4BeatmapDataAssetFileModel.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: IBeatmapDataAssetFileModel
#include "GlobalNamespace/IBeatmapDataAssetFileModel.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: GlobalNamespace
namespace GlobalNamespace {
// Forward declaring type: IPreviewBeatmapLevel
class IPreviewBeatmapLevel;
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Action`1<T>
template<typename T>
class Action_1;
}
// Forward declaring namespace: System::Threading::Tasks
namespace System::Threading::Tasks {
// Forward declaring type: Task`1<TResult>
template<typename TResult>
class Task_1;
// Forward declaring type: Task`1<TResult>
template<typename TResult>
class Task_1;
}
// Forward declaring namespace: System::Threading
namespace System::Threading {
// Forward declaring type: CancellationToken
struct CancellationToken;
}
// Completed forward declares
// Type namespace:
namespace GlobalNamespace {
// Autogenerated type: PS4BeatmapDataAssetFileModel
class PS4BeatmapDataAssetFileModel : public ::Il2CppObject, public GlobalNamespace::IBeatmapDataAssetFileModel {
public:
// Nested type: GlobalNamespace::PS4BeatmapDataAssetFileModel::$GetAssetBundleFileForPreviewLevelAsync$d__3
struct $GetAssetBundleFileForPreviewLevelAsync$d__3;
// Nested type: GlobalNamespace::PS4BeatmapDataAssetFileModel::$TryDeleteAssetBundleFileForPreviewLevelAsync$d__4
struct $TryDeleteAssetBundleFileForPreviewLevelAsync$d__4;
// private System.Action`1<LevelDataAssetDownloadUpdate> levelDataAssetDownloadUpdateEvent
// Offset: 0x10
System::Action_1<GlobalNamespace::LevelDataAssetDownloadUpdate>* levelDataAssetDownloadUpdateEvent;
// public System.Void add_levelDataAssetDownloadUpdateEvent(System.Action`1<LevelDataAssetDownloadUpdate> value)
// Offset: 0xBD0EE0
// Implemented from: IBeatmapDataAssetFileModel
// Base method: System.Void IBeatmapDataAssetFileModel::add_levelDataAssetDownloadUpdateEvent(System.Action`1<LevelDataAssetDownloadUpdate> value)
void add_levelDataAssetDownloadUpdateEvent(System::Action_1<GlobalNamespace::LevelDataAssetDownloadUpdate>* value);
// public System.Void remove_levelDataAssetDownloadUpdateEvent(System.Action`1<LevelDataAssetDownloadUpdate> value)
// Offset: 0xBD0F84
// Implemented from: IBeatmapDataAssetFileModel
// Base method: System.Void IBeatmapDataAssetFileModel::remove_levelDataAssetDownloadUpdateEvent(System.Action`1<LevelDataAssetDownloadUpdate> value)
void remove_levelDataAssetDownloadUpdateEvent(System::Action_1<GlobalNamespace::LevelDataAssetDownloadUpdate>* value);
// public System.Threading.Tasks.Task`1<GetAssetBundleFileResult> GetAssetBundleFileForPreviewLevelAsync(IPreviewBeatmapLevel previewBeatmapLevel, System.Threading.CancellationToken cancellationToken)
// Offset: 0xBD1028
// Implemented from: IBeatmapDataAssetFileModel
// Base method: System.Threading.Tasks.Task`1<GetAssetBundleFileResult> IBeatmapDataAssetFileModel::GetAssetBundleFileForPreviewLevelAsync(IPreviewBeatmapLevel previewBeatmapLevel, System.Threading.CancellationToken cancellationToken)
System::Threading::Tasks::Task_1<GlobalNamespace::GetAssetBundleFileResult>* GetAssetBundleFileForPreviewLevelAsync(GlobalNamespace::IPreviewBeatmapLevel* previewBeatmapLevel, System::Threading::CancellationToken cancellationToken);
// public System.Threading.Tasks.Task`1<System.Boolean> TryDeleteAssetBundleFileForPreviewLevelAsync(IPreviewBeatmapLevel previewBeatmapLevel, System.Threading.CancellationToken cancellationToken)
// Offset: 0xBD1134
// Implemented from: IBeatmapDataAssetFileModel
// Base method: System.Threading.Tasks.Task`1<System.Boolean> IBeatmapDataAssetFileModel::TryDeleteAssetBundleFileForPreviewLevelAsync(IPreviewBeatmapLevel previewBeatmapLevel, System.Threading.CancellationToken cancellationToken)
System::Threading::Tasks::Task_1<bool>* TryDeleteAssetBundleFileForPreviewLevelAsync(GlobalNamespace::IPreviewBeatmapLevel* previewBeatmapLevel, System::Threading::CancellationToken cancellationToken);
// public System.Void .ctor()
// Offset: 0xBD1240
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
static PS4BeatmapDataAssetFileModel* New_ctor();
}; // PS4BeatmapDataAssetFileModel
}
#include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::PS4BeatmapDataAssetFileModel*, "", "PS4BeatmapDataAssetFileModel");
#pragma pack(pop)
| 60.025 | 238 | 0.807997 | [
"object"
] |
e196bd3d25e7fc018a5ad4b71762e106e4c0f341 | 3,126 | cc | C++ | poj/1/1204.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | 1 | 2015-04-17T09:54:23.000Z | 2015-04-17T09:54:23.000Z | poj/1/1204.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | poj/1/1204.cc | eagletmt/procon | adbe503eb3c1bbcc1538b2ee8988aa353937e8d4 | [
"MIT"
] | null | null | null | #include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
struct ans
{
int i, j, dir;
ans() : i(-1), j(-1), dir(-1) {}
ans(int a, int b, int c) : i(a), j(b), dir(c) {}
};
int L, C;
char grid[1000][1000];
ans ret[1000];
static const int di[] = {-1, -1, 0, 1, 1, 1, 0, -1};
static const int dj[] = {0, 1, 1, 1, 0, -1, -1, -1};
struct AhoCorasick
{
struct node {
node *failure;
node *edge[26];
vector<int> accepted;
~node() {
for (int i = 0; i < 26; i++) {
if (edge[i] != this) {
delete edge[i];
}
}
}
};
node *root;
AhoCorasick(const char words[1000][1001], int W)
: root(new node())
{
// build trie
for (int i = 0; i < W; i++) {
const char *s = words[i];
node *u = root;
for (int j = 0; s[j] != '\0'; j++) {
const int idx = s[j] - 'A';
if (!u->edge[idx]) {
u->edge[idx] = new node();
}
u = u->edge[idx];
}
u->accepted.push_back(i);
}
// build failure link
root->failure = 0;
queue<node *> q;
for (int i = 0; i < 26; i++) {
if (root->edge[i]) {
node *next = root->edge[i];
q.push(next);
next->failure = root;
} else {
root->edge[i] = root;
}
}
while (!q.empty()) {
node *u = q.front();
q.pop();
for (int i = 0; i < 26; i++) {
node *next = u->edge[i];
if (next) {
q.push(next);
node *rev = u->failure;
while (!rev->edge[i]) {
rev = rev->failure;
}
next->failure = rev->edge[i];
const vector<int> &v = next->failure->accepted;
for (vector<int>::const_iterator it = v.begin(); it != v.end(); ++it) {
next->accepted.push_back(*it);
}
}
}
}
}
~AhoCorasick() {
delete root;
}
void match(int i, int j, int d) const
{
node *u = root;
for (; 0 <= i && i < L && 0 <= j && j < C; i += di[d], j += dj[d]) {
const int idx = grid[i][j] - 'A';
while (!u->edge[idx]) {
u = u->failure;
}
u = u->edge[idx];
for (vector<int>::const_iterator jt = u->accepted.begin(); jt != u->accepted.end(); ++jt) {
ret[*jt] = ans(i, j, d);
}
}
}
};
int main()
{
int W;
scanf("%d %d %d", &L, &C, &W);
for (int i = 0; i < L; i++) {
scanf("%s", grid[i]);
}
static char words[1000][1001];
for (int i = 0; i < W; i++) {
scanf("%s", words[i]);
}
AhoCorasick ac(words, W);
for (int i = 0; i < L; i++) {
ac.match(i, 0, 1);
ac.match(i, 0, 2);
ac.match(i, 0, 3);
ac.match(i, C-1, 5);
ac.match(i, C-1, 6);
ac.match(i, C-1, 7);
}
for (int j = 0; j < C; j++) {
ac.match(L-1, j, 7);
ac.match(L-1, j, 0);
ac.match(L-1, j, 1);
ac.match(0, j, 3);
ac.match(0, j, 4);
ac.match(0, j, 5);
}
for (int i = 0; i < W; i++) {
const ans& a = ret[i];
const int n = strlen(words[i]) - 1;
printf("%d %d %c\n", a.i - di[a.dir]*n, a.j - dj[a.dir]*n, 'A' + a.dir);
}
return 0;
} | 21.708333 | 97 | 0.43602 | [
"vector"
] |
e1a16691fc9d55b084494743162ba9ec43f58c61 | 20,112 | cpp | C++ | libs/iblprefilter/src/IBLPrefilterContext.cpp | baajur/filament | 459f70f7b496cce5b7e7f35febc50e708ab4f475 | [
"Apache-2.0"
] | 1 | 2022-02-02T19:56:53.000Z | 2022-02-02T19:56:53.000Z | libs/iblprefilter/src/IBLPrefilterContext.cpp | baajur/filament | 459f70f7b496cce5b7e7f35febc50e708ab4f475 | [
"Apache-2.0"
] | null | null | null | libs/iblprefilter/src/IBLPrefilterContext.cpp | baajur/filament | 459f70f7b496cce5b7e7f35febc50e708ab4f475 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2021 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 "filament-iblprefilter/IBLPrefilterContext.h"
#include <filament/Engine.h>
#include <filament/IndexBuffer.h>
#include <filament/Material.h>
#include <filament/RenderTarget.h>
#include <filament/RenderableManager.h>
#include <filament/Renderer.h>
#include <filament/Scene.h>
#include <filament/Texture.h>
#include <filament/TextureSampler.h>
#include <filament/VertexBuffer.h>
#include <filament/View.h>
#include <filament/Viewport.h>
#include <utils/Panic.h>
#include <utils/EntityManager.h>
#include <utils/Systrace.h>
#include <math/mat3.h>
#include <math/vec3.h>
#include "generated/resources/iblprefilter_materials.h"
using namespace filament::math;
using namespace filament;
constexpr static float4 sFullScreenTriangleVertices[3] = {
{ -1.0f, -1.0f, 1.0f, 1.0f },
{ 3.0f, -1.0f, 1.0f, 1.0f },
{ -1.0f, 3.0f, 1.0f, 1.0f }
};
constexpr static const uint16_t sFullScreenTriangleIndices[3] = { 0, 1, 2 };
static float DistributionGGX(float NoH, float linearRoughness) noexcept {
// NOTE: (aa-1) == (a-1)(a+1) produces better fp accuracy
float a = linearRoughness;
float f = (a - 1) * ((a + 1) * (NoH * NoH)) + 1;
return (a * a) / ((float)F_PI * f * f);
}
static float3 hemisphereImportanceSampleDggx(float2 u, float a) { // pdf = D(a) * cosTheta
const float phi = 2.0f * (float)F_PI * u.x;
// NOTE: (aa-1) == (a-1)(a+1) produces better fp accuracy
const float cosTheta2 = (1 - u.y) / (1 + (a + 1) * ((a - 1) * u.y));
const float cosTheta = std::sqrt(cosTheta2);
const float sinTheta = std::sqrt(1 - cosTheta2);
return { sinTheta * std::cos(phi), sinTheta * std::sin(phi), cosTheta };
}
inline math::float2 hammersley(uint32_t i, float iN) {
constexpr float tof = 0.5f / 0x80000000U;
uint32_t bits = i;
bits = (bits << 16u) | (bits >> 16u);
bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u);
bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u);
bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u);
bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u);
return { i * iN, bits * tof };
}
static float lodToPerceptualRoughness(float lod) noexcept {
// Inverse perceptualRoughness-to-LOD mapping:
// The LOD-to-perceptualRoughness mapping is a quadratic fit for
// log2(perceptualRoughness)+iblMaxMipLevel when iblMaxMipLevel is 4.
// We found empirically that this mapping works very well for a 256 cubemap with 5 levels used,
// but also scales well for other iblMaxMipLevel values.
const float a = 2.0f;
const float b = -1.0f;
return (lod != 0)
? saturate((std::sqrt(a * a + 4.0f * b * lod) - a) / (2.0f * b))
: 0.0f;
}
template<typename T>
static inline constexpr T log4(T x) {
return std::log2(x) * T(0.5);
}
IBLPrefilterContext::IBLPrefilterContext(Engine& engine)
: mEngine(engine) {
utils::EntityManager& em = utils::EntityManager::get();
mCameraEntity = em.create();
mFullScreenQuadEntity = em.create();
mIntegrationMaterial = Material::Builder().package(
IBLPREFILTER_MATERIALS_IBLPREFILTER_DATA,
IBLPREFILTER_MATERIALS_IBLPREFILTER_SIZE).build(engine);
mVertexBuffer = VertexBuffer::Builder()
.vertexCount(3)
.bufferCount(1)
.attribute(VertexAttribute::POSITION, 0,
VertexBuffer::AttributeType::FLOAT4, 0)
.build(engine);
mIndexBuffer = IndexBuffer::Builder()
.indexCount(3)
.bufferType(IndexBuffer::IndexType::USHORT)
.build(engine);
mVertexBuffer->setBufferAt(engine, 0,
{ sFullScreenTriangleVertices, sizeof(sFullScreenTriangleVertices) });
mIndexBuffer->setBuffer(engine,
{ sFullScreenTriangleIndices, sizeof(sFullScreenTriangleIndices) });
RenderableManager::Builder(1)
.geometry(0, RenderableManager::PrimitiveType::TRIANGLES, mVertexBuffer, mIndexBuffer)
.material(0, mIntegrationMaterial->getDefaultInstance())
.culling(false)
.castShadows(false)
.receiveShadows(false)
.build(engine, mFullScreenQuadEntity);
mView = engine.createView();
mScene = engine.createScene();
mRenderer = engine.createRenderer();
mCamera = engine.createCamera(mCameraEntity);
mScene->addEntity(mFullScreenQuadEntity);
View* const view = mView;
view->setCamera(mCamera);
view->setScene(mScene);
view->setScreenSpaceRefractionEnabled(false);
view->setShadowingEnabled(false);
view->setPostProcessingEnabled(false);
view->setFrustumCullingEnabled(false);
}
IBLPrefilterContext::~IBLPrefilterContext() noexcept {
utils::EntityManager& em = utils::EntityManager::get();
auto& engine = mEngine;
engine.destroy(mView);
engine.destroy(mScene);
engine.destroy(mRenderer);
engine.destroy(mVertexBuffer);
engine.destroy(mIndexBuffer);
engine.destroy(mIntegrationMaterial);
engine.destroy(mFullScreenQuadEntity);
engine.destroyCameraComponent(mCameraEntity);
em.destroy(mFullScreenQuadEntity);
}
IBLPrefilterContext::IBLPrefilterContext(IBLPrefilterContext&& rhs) noexcept
: mEngine(rhs.mEngine) {
this->operator=(std::move(rhs));
}
IBLPrefilterContext& IBLPrefilterContext::operator=(IBLPrefilterContext&& rhs) {
using std::swap;
if (this != & rhs) {
swap(mRenderer, rhs.mRenderer);
swap(mScene, rhs.mScene);
swap(mVertexBuffer, rhs.mVertexBuffer);
swap(mIndexBuffer, rhs.mIndexBuffer);
swap(mCamera, rhs.mCamera);
swap(mFullScreenQuadEntity, rhs.mFullScreenQuadEntity);
swap(mCameraEntity, rhs.mCameraEntity);
swap(mIntegrationMaterial, rhs.mIntegrationMaterial);
swap(mView, rhs.mView);
}
return *this;
}
// ------------------------------------------------------------------------------------------------
IBLPrefilterContext::EquirectangularToCubemap::EquirectangularToCubemap(
IBLPrefilterContext& context) : mContext(context) {
Engine& engine = mContext.mEngine;
mEquirectMaterial = Material::Builder().package(
IBLPREFILTER_MATERIALS_EQUIRECTTOCUBE_DATA,
IBLPREFILTER_MATERIALS_EQUIRECTTOCUBE_SIZE).build(engine);
}
IBLPrefilterContext::EquirectangularToCubemap::~EquirectangularToCubemap() noexcept {
Engine& engine = mContext.mEngine;
engine.destroy(mEquirectMaterial);
}
IBLPrefilterContext::EquirectangularToCubemap::EquirectangularToCubemap(
IBLPrefilterContext::EquirectangularToCubemap&& rhs) noexcept
: mContext(rhs.mContext) {
using std::swap;
swap(mEquirectMaterial, rhs.mEquirectMaterial);
}
IBLPrefilterContext::EquirectangularToCubemap&
IBLPrefilterContext::EquirectangularToCubemap::operator=(
IBLPrefilterContext::EquirectangularToCubemap&& rhs) {
using std::swap;
if (this != &rhs) {
swap(mEquirectMaterial, rhs.mEquirectMaterial);
}
return *this;
}
Texture* IBLPrefilterContext::EquirectangularToCubemap::operator()(
Texture const* equirect, Texture* outCube) {
SYSTRACE_CALL();
using namespace backend;
const TextureCubemapFace faces[2][3] = {
{ TextureCubemapFace::POSITIVE_X, TextureCubemapFace::POSITIVE_Y, TextureCubemapFace::POSITIVE_Z },
{ TextureCubemapFace::NEGATIVE_X, TextureCubemapFace::NEGATIVE_Y, TextureCubemapFace::NEGATIVE_Z }
};
Engine& engine = mContext.mEngine;
View* const view = mContext.mView;
Renderer* const renderer = mContext.mRenderer;
MaterialInstance* const mi = mEquirectMaterial->getDefaultInstance();
ASSERT_PRECONDITION(equirect != nullptr, "equirect is null!");
ASSERT_PRECONDITION(equirect->getTarget() == Texture::Sampler::SAMPLER_2D,
"equirect must be a 2D texture.");
UTILS_UNUSED_IN_RELEASE
const uint8_t maxLevelCount = uint8_t(std::log2(equirect->getWidth()) + 0.5f) + 1u;
ASSERT_PRECONDITION(equirect->getLevels() == maxLevelCount,
"equirect must have %u mipmap levels allocated.", +maxLevelCount);
if (outCube == nullptr) {
outCube = Texture::Builder()
.sampler(Texture::Sampler::SAMPLER_CUBEMAP)
.format(Texture::InternalFormat::R11F_G11F_B10F)
.usage(Texture::Usage::COLOR_ATTACHMENT | Texture::Usage::SAMPLEABLE)
.width(256).height(256).levels(0xFF)
.build(engine);
}
ASSERT_PRECONDITION(outCube->getTarget() == Texture::Sampler::SAMPLER_CUBEMAP,
"outCube must be a Cubemap texture.");
const uint32_t dim = outCube->getWidth();
RenderableManager& rcm = engine.getRenderableManager();
rcm.setMaterialInstanceAt(
rcm.getInstance(mContext.mFullScreenQuadEntity), 0, mi);
TextureSampler environmentSampler;
environmentSampler.setMagFilter(SamplerMagFilter::LINEAR);
environmentSampler.setMinFilter(SamplerMinFilter::LINEAR_MIPMAP_LINEAR);
environmentSampler.setAnisotropy(16.0f); // maybe make this an option
mi->setParameter("equirect", equirect, environmentSampler);
// We need mipmaps because we're sampling down
equirect->generateMipmaps(engine);
view->setViewport({ 0, 0, dim, dim });
RenderTarget::Builder builder;
builder.texture(RenderTarget::AttachmentPoint::COLOR0, outCube)
.texture(RenderTarget::AttachmentPoint::COLOR1, outCube)
.texture(RenderTarget::AttachmentPoint::COLOR2, outCube);
for (size_t i = 0; i < 2; i++) {
mi->setParameter("side", i == 0 ? 1.0f : -1.0f);
builder.face(RenderTarget::AttachmentPoint::COLOR0, faces[i][0])
.face(RenderTarget::AttachmentPoint::COLOR1, faces[i][1])
.face(RenderTarget::AttachmentPoint::COLOR2, faces[i][2]);
RenderTarget* const rt = builder.build(engine);
view->setRenderTarget(rt);
renderer->renderStandaloneView(view);
engine.destroy(rt);
}
return outCube;
}
// ------------------------------------------------------------------------------------------------
IBLPrefilterContext::SpecularFilter::SpecularFilter(IBLPrefilterContext& context, Config config)
: mContext(context) {
SYSTRACE_CALL();
using namespace backend;
Engine& engine = mContext.mEngine;
View* const view = mContext.mView;
Renderer* const renderer = mContext.mRenderer;
mSampleCount = std::min(config.sampleCount, uint16_t(2048));
mLevelCount = std::max(config.levelCount, uint8_t(1u));
mKernelMaterial = Material::Builder().package(
IBLPREFILTER_MATERIALS_GENERATEKERNEL_DATA,
IBLPREFILTER_MATERIALS_GENERATEKERNEL_SIZE).build(engine);
// { L.x, L.y, L.z, lod }
mKernelTexture = Texture::Builder()
.sampler(Texture::Sampler::SAMPLER_2D)
.format(Texture::InternalFormat::RGBA16F)
.usage(Texture::Usage::SAMPLEABLE | Texture::Usage::COLOR_ATTACHMENT)
.width(mLevelCount)
.height(mSampleCount)
.build(engine);
MaterialInstance* const mi = mKernelMaterial->getDefaultInstance();
mi->setParameter("size", uint2{ mLevelCount, mSampleCount });
mi->setParameter("sampleCount", float(mSampleCount));
mi->setParameter("oneOverLevelsMinusOne", 1.0f / (mLevelCount - 1.0f));
RenderableManager& rcm = engine.getRenderableManager();
rcm.setMaterialInstanceAt(
rcm.getInstance(mContext.mFullScreenQuadEntity), 0, mi);
RenderTarget* const rt = RenderTarget::Builder()
.texture(RenderTarget::AttachmentPoint::COLOR0, mKernelTexture)
.build(engine);
view->setRenderTarget(rt);
view->setViewport({ 0, 0, mLevelCount, mSampleCount });
renderer->renderStandaloneView(view);
engine.destroy(rt);
// the code below must match the shader in generateKernel.mat
// this is a little bit unfortunate that we have to compute the weightSum here, but it's
// not too heavy.
const uint32_t levelCount = mLevelCount;
const float sampleCount = mSampleCount;
mKernelWeightArray = new float[mLevelCount];
for (uint32_t lod = 0 ; lod < levelCount; lod++) {
SYSTRACE_NAME("computeFilterLOD");
const float perceptualRoughness = lodToPerceptualRoughness(saturate(lod / (levelCount - 1.0f)));
const float roughness = perceptualRoughness * perceptualRoughness;
const uint32_t effectiveSampleCount = (lod == 0) ? 1u : sampleCount;
float weight = 0.0f;
for (size_t i = 0; i < effectiveSampleCount; i++) {
const float2 u = hammersley(uint32_t(i), 1.0f / float(effectiveSampleCount));
const float3 H = hemisphereImportanceSampleDggx(u, roughness);
const float NoH2 = H.z * H.z;
const float NoL = saturate(2 * NoH2 - 1);
weight += NoL;
}
assert_invariant(lod < mLevelCount);
mKernelWeightArray[lod] = weight;
}
}
UTILS_NOINLINE
IBLPrefilterContext::SpecularFilter::SpecularFilter(IBLPrefilterContext& context)
: SpecularFilter(context, {}) {
}
IBLPrefilterContext::SpecularFilter::~SpecularFilter() noexcept {
Engine& engine = mContext.mEngine;
engine.destroy(mKernelTexture);
engine.destroy(mKernelMaterial);
delete [] mKernelWeightArray;
}
IBLPrefilterContext::SpecularFilter::SpecularFilter(SpecularFilter&& rhs) noexcept
: mContext(rhs.mContext) {
this->operator=(std::move(rhs));
}
IBLPrefilterContext::SpecularFilter& IBLPrefilterContext::SpecularFilter::operator=(SpecularFilter&& rhs) {
using std::swap;
if (this != & rhs) {
swap(mKernelTexture, rhs.mKernelTexture);
swap(mKernelWeightArray, rhs.mKernelWeightArray);
mSampleCount = rhs.mSampleCount;
mLevelCount = rhs.mLevelCount;
}
return *this;
}
Texture* IBLPrefilterContext::SpecularFilter::createReflectionsTexture() {
Engine& engine = mContext.mEngine;
const uint8_t levels = mLevelCount;
// default texture is 256 or larger to accommodate the level count requested
const uint32_t dim = std::max(256u, 1u << (levels - 1u));
Texture* const outCubemap = Texture::Builder()
.sampler(Texture::Sampler::SAMPLER_CUBEMAP)
.format(Texture::InternalFormat::R11F_G11F_B10F)
.usage(Texture::Usage::COLOR_ATTACHMENT | Texture::Usage::SAMPLEABLE)
.width(dim).height(dim).levels(levels)
.build(engine);
return outCubemap;
}
UTILS_NOINLINE
Texture* IBLPrefilterContext::SpecularFilter::operator()(
Texture const* environmentCubemap, Texture* outReflectionsTexture) {
return operator()({}, environmentCubemap, outReflectionsTexture);
}
Texture* IBLPrefilterContext::SpecularFilter::operator()(
IBLPrefilterContext::SpecularFilter::Options options,
Texture const* environmentCubemap, Texture* outReflectionsTexture) {
SYSTRACE_CALL();
using namespace backend;
ASSERT_PRECONDITION(environmentCubemap != nullptr, "environmentCubemap is null!");
ASSERT_PRECONDITION(environmentCubemap->getTarget() == Texture::Sampler::SAMPLER_CUBEMAP,
"environmentCubemap must be a cubemap.");
UTILS_UNUSED_IN_RELEASE
const uint8_t maxLevelCount = uint8_t(std::log2(environmentCubemap->getWidth()) + 0.5f) + 1u;
ASSERT_PRECONDITION(environmentCubemap->getLevels() == maxLevelCount,
"environmentCubemap must have %u mipmap levels allocated.", +maxLevelCount);
if (outReflectionsTexture == nullptr) {
outReflectionsTexture = createReflectionsTexture();
}
ASSERT_PRECONDITION(outReflectionsTexture->getTarget() == Texture::Sampler::SAMPLER_CUBEMAP,
"outReflectionsTexture must be a cubemap.");
ASSERT_PRECONDITION(mLevelCount <= outReflectionsTexture->getLevels(),
"outReflectionsTexture has %u levels but %u are requested.",
+outReflectionsTexture->getLevels(), +mLevelCount);
const TextureCubemapFace faces[2][3] = {
{ TextureCubemapFace::POSITIVE_X, TextureCubemapFace::POSITIVE_Y, TextureCubemapFace::POSITIVE_Z },
{ TextureCubemapFace::NEGATIVE_X, TextureCubemapFace::NEGATIVE_Y, TextureCubemapFace::NEGATIVE_Z }
};
Engine& engine = mContext.mEngine;
View* const view = mContext.mView;
Renderer* const renderer = mContext.mRenderer;
MaterialInstance* const mi = mContext.mIntegrationMaterial->getDefaultInstance();
RenderableManager& rcm = engine.getRenderableManager();
rcm.setMaterialInstanceAt(
rcm.getInstance(mContext.mFullScreenQuadEntity), 0, mi);
const uint32_t sampleCount = mSampleCount;
const float linear = options.hdrLinear;
const float compress = options.hdrMax;
const uint8_t levels = outReflectionsTexture->getLevels();
uint32_t dim = outReflectionsTexture->getWidth();
const float omegaP = (4.0f * f::PI) / float(6 * dim * dim);
TextureSampler environmentSampler;
environmentSampler.setMagFilter(SamplerMagFilter::LINEAR);
environmentSampler.setMinFilter(SamplerMinFilter::LINEAR_MIPMAP_LINEAR);
mi->setParameter("environment", environmentCubemap, environmentSampler);
mi->setParameter("kernel", mKernelTexture, TextureSampler{ SamplerMagFilter::NEAREST });
mi->setParameter("compress", float2{ linear, compress });
mi->setParameter("lodOffset", options.lodOffset - log4(omegaP));
if (options.generateMipmap) {
// We need mipmaps for prefiltering
environmentCubemap->generateMipmaps(engine);
}
RenderTarget::Builder builder;
builder.texture(RenderTarget::AttachmentPoint::COLOR0, outReflectionsTexture)
.texture(RenderTarget::AttachmentPoint::COLOR1, outReflectionsTexture)
.texture(RenderTarget::AttachmentPoint::COLOR2, outReflectionsTexture);
for (size_t lod = 0; lod < levels; lod++) {
SYSTRACE_NAME("executeFilterLOD");
mi->setParameter("sampleCount", uint32_t(lod == 0 ? 1u : sampleCount));
mi->setParameter("attachmentLevel", uint32_t(lod));
mi->setParameter("invKernelWeight", 1.0f / mKernelWeightArray[lod]);
if (lod == levels - 1) {
// this is the last lod, use a more agressive filtering because this level is also
// used for the diffuse brdf by filament, and we need it to be very smooth.
// So we set the lod offset to at least 2.
mi->setParameter("lodOffset", std::max(2.0f, options.lodOffset) - log4(omegaP));
}
builder.mipLevel(RenderTarget::AttachmentPoint::COLOR0, lod)
.mipLevel(RenderTarget::AttachmentPoint::COLOR1, lod)
.mipLevel(RenderTarget::AttachmentPoint::COLOR2, lod);
view->setViewport({ 0, 0, dim, dim });
for (size_t i = 0; i < 2; i++) {
mi->setParameter("side", i == 0 ? 1.0f : -1.0f);
builder.face(RenderTarget::AttachmentPoint::COLOR0, faces[i][0])
.face(RenderTarget::AttachmentPoint::COLOR1, faces[i][1])
.face(RenderTarget::AttachmentPoint::COLOR2, faces[i][2]);
RenderTarget* const rt = builder.build(engine);
view->setRenderTarget(rt);
renderer->renderStandaloneView(view);
engine.destroy(rt);
}
dim >>= 1;
}
return outReflectionsTexture;
}
| 38.090909 | 111 | 0.674722 | [
"geometry"
] |
e1a2b69e6c7b6ca0c3b261fd4b20bd0f88bd7ced | 20,115 | cpp | C++ | Project/Motor2D/j1Player.cpp | EnricGDV/Game_Development_Platformer | 7df4f7e21f649cabe4e8e134b2e99e665a069a1b | [
"Unlicense"
] | 1 | 2019-10-14T06:53:57.000Z | 2019-10-14T06:53:57.000Z | Project/Motor2D/j1Player.cpp | EnricGDV/Game_Development_Platformer | 7df4f7e21f649cabe4e8e134b2e99e665a069a1b | [
"Unlicense"
] | null | null | null | Project/Motor2D/j1Player.cpp | EnricGDV/Game_Development_Platformer | 7df4f7e21f649cabe4e8e134b2e99e665a069a1b | [
"Unlicense"
] | null | null | null | #include "p2Defs.h"
#include "p2Log.h"
#include "j1App.h"
#include "j1Map.h"
#include "j1Player.h"
#include "j1Input.h"
#include "j1Window.h"
#include "j1Textures.h"
#include "j1Scene.h"
#include "j1Audio.h"
#include "j1Render.h"
#include "ModuleCollision.h"
j1Player::j1Player() : j1Module()
{
name.create("player");
}
// Destructor
j1Player::~j1Player()
{}
bool j1Player::Awake(pugi::xml_node& config)
{
bool ret = true;
spritesheetN = config.child("spritesheetS").attribute("name").as_string();
pugi::xml_node animations;
for (animations = config.child("animations").first_child(); animations && ret; animations = animations.next_sibling("animation"))
{
p2SString temp(animations.attribute("name").as_string());
if (temp == "demon_idle")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.demon_idle.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.demon_idle.speed = animations.attribute("speed").as_float();
Player.demon_idle.loop = animations.attribute("loop").as_bool();
}
if (temp == "demon_moving")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.demon_moving.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.demon_moving.speed = animations.attribute("speed").as_float();
Player.demon_moving.loop = animations.attribute("loop").as_bool();
}
if (temp == "demon_jumping")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.demon_jumping.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.demon_jumping.speed = animations.attribute("speed").as_float();
Player.demon_jumping.loop = animations.attribute("loop").as_bool();
}
if (temp == "demon_falling")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.demon_falling.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.demon_falling.speed = animations.attribute("speed").as_float();
Player.demon_falling.loop = animations.attribute("loop").as_bool();
}
if (temp == "demon_idle_M")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.demon_idle_M.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.demon_idle_M.speed = animations.attribute("speed").as_float();
Player.demon_idle_M.loop = animations.attribute("loop").as_bool();
}
if (temp == "demon_moving_M")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.demon_moving_M.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.demon_moving_M.speed = animations.attribute("speed").as_float();
Player.demon_moving_M.loop = animations.attribute("loop").as_bool();
}
if (temp == "demon_jumping_M")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.demon_jumping_M.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.demon_jumping_M.speed = animations.attribute("speed").as_float();
Player.demon_jumping_M.loop = animations.attribute("loop").as_bool();
}
if (temp == "demon_falling_M")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.demon_falling_M.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.demon_falling_M.speed = animations.attribute("speed").as_float();
Player.demon_falling_M.loop = animations.attribute("loop").as_bool();
}
if (temp == "angel_idle")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.angel_idle.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.angel_idle.speed = animations.attribute("speed").as_float();
Player.angel_idle.loop = animations.attribute("loop").as_bool();
}
if (temp == "angel_moving")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.angel_moving.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.angel_moving.speed = animations.attribute("speed").as_float();
Player.angel_moving.loop = animations.attribute("loop").as_bool();
}
if (temp == "angel_jumping")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.angel_jumping.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.angel_jumping.speed = animations.attribute("speed").as_float();
Player.angel_jumping.loop = animations.attribute("loop").as_bool();
}
if (temp == "angel_falling")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.angel_falling.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.angel_falling.speed = animations.attribute("speed").as_float();
Player.angel_falling.loop = animations.attribute("loop").as_bool();
}
if (temp == "angel_idle_M")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.angel_idle_M.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.angel_idle_M.speed = animations.attribute("speed").as_float();
Player.angel_idle_M.loop = animations.attribute("loop").as_bool();
}
if (temp == "angel_moving_M")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.angel_moving_M.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.angel_moving_M.speed = animations.attribute("speed").as_float();
Player.angel_moving_M.loop = animations.attribute("loop").as_bool();
}
if (temp == "angel_jumping_M")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.angel_jumping_M.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.angel_jumping_M.speed = animations.attribute("speed").as_float();
Player.angel_jumping_M.loop = animations.attribute("loop").as_bool();
}
if (temp == "angel_falling_M")
{
for (pugi::xml_node frame = animations.child("frame"); frame && ret; frame = frame.next_sibling("frame"))
Player.angel_falling_M.PushBack({ frame.attribute("x").as_int() , frame.attribute("y").as_int(), frame.attribute("width").as_int(), frame.attribute("height").as_int() });
Player.angel_falling_M.speed = animations.attribute("speed").as_float();
Player.angel_falling_M.loop = animations.attribute("loop").as_bool();
}
}
//Player.current_animation = &Player.angel_idle;
Player.jumpSpeed.x = config.child("jumpSpeed").attribute("x").as_int();
Player.jumpSpeed.y = config.child("jumpSpeed").attribute("y").as_int();
Player.maxSpeed.x = config.child("maxSpeed").attribute("x").as_int();
Player.maxSpeed.y = config.child("maxSpeed").attribute("y").as_int();
Player.acceleration.x = config.child("acceleration").attribute("x").as_int();
Player.acceleration.y = config.child("acceleration").attribute("y").as_int();
Player.offSet.x = config.child("offSet").attribute("x").as_int();
Player.offSet.y = config.child("offSet").attribute("y").as_int();
Player.dashForce = config.child("dashForce").attribute("x").as_int();
Player.position.x = config.child("initPos").attribute("x").as_int();
Player.position.y = config.child("initPos").attribute("y").as_int();
Player.initPosition.x = config.child("initPos").attribute("x").as_int();
Player.initPosition.y = config.child("initPos").attribute("y").as_int();
Player.collider = App->collision->AddCollider({ config.child("position").attribute("x").as_int(), config.child("position").attribute("y").as_int(), config.child("col").attribute("w").as_int(), config.child("col").attribute("h").as_int() }, COLLIDER_PLAYER, this);
Player.colInit = { config.child("position").attribute("x").as_int(), config.child("position").attribute("y").as_int(), config.child("col").attribute("w").as_int(), config.child("col").attribute("h").as_int() };
jumpFX = config.child("jumpFX").attribute("source").as_string();
deathFX = config.child("deathFX").attribute("source").as_string();
landFX = config.child("landFX").attribute("source").as_string();
tranformationFX = config.child("transformationFX").attribute("source").as_string();
Player.map = config.child("map").attribute("value").as_int();
return ret;
}
bool j1Player::Start()
{
Player.speed = { 0,0 };
graphics = App->tex->Load(spritesheetN.GetString());
if (graphics == nullptr)
{
return false;
}
isAlive = true;
Player.isJumping = false;
Player.canDash = false;
Player.canDJump = true;
App->audio->LoadFx(jumpFX.GetString());
App->audio->LoadFx(deathFX.GetString());
App->audio->LoadFx(landFX.GetString());
App->audio->LoadFx(tranformationFX.GetString());
Player.iMaxSpeed = Player.maxSpeed;
Player.iSpeed = Player.speed;
Player.current_animation = &Player.angel_idle;
return true;
}
bool j1Player::PreUpdate()
{
return true;
}
bool j1Player::Update(float dt)
{
MirrorSprite();
if ((App->input->GetKey(SDL_SCANCODE_X) == KEY_DOWN) && Player.isDemon)
{
Player.isDemon = false;
}
else if ((App->input->GetKey(SDL_SCANCODE_X) == KEY_DOWN) && !Player.isDemon)
{
Player.isDemon = true;
}
if (!Player.godmode)
{
if (Player.isDemon)
{
Player.canDJump = false;
}
else
{
Player.canDash = false;
}
if ((Player.canDash) && (App->input->GetKey(SDL_SCANCODE_SPACE) == KEY_DOWN))
{
Dash();
}
if ((Player.isJumping && Player.canDJump) && (App->input->GetKey(SDL_SCANCODE_W) == KEY_DOWN))
{
DoubleJump();
}
if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT)
Player.xDirection = 1, SpeedUp();
else if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT)
Player.xDirection = -1, SpeedUp();
else
SpeedDown();
if (App->input->GetKey(SDL_SCANCODE_W) == KEY_DOWN && Player.onFloor)
{
App->audio->PlayFx(3,1);
Player.isJumping = true;
Player.maxSpeed.x += Player.jumpSpeed.x;
Player.speed.x = Player.jumpSpeed.x*Player.xDirection;
Player.speed.y = -Player.jumpSpeed.y;
Player.onFloor = false;
}
}
else if (Player.godmode)
{
if (App->input->GetKey(SDL_SCANCODE_W) == KEY_REPEAT)
Player.position.y -= 2;
if (App->input->GetKey(SDL_SCANCODE_A) == KEY_REPEAT)
Player.position.x -= 2;
if (App->input->GetKey(SDL_SCANCODE_S) == KEY_REPEAT)
Player.position.y += 2;
if (App->input->GetKey(SDL_SCANCODE_D) == KEY_REPEAT)
Player.position.x += 2;
}
if (App->input->GetKey(SDL_SCANCODE_F1) == KEY_DOWN)
{
if (App->scene->mapname != "map1.tmx")
{
p2SString map = "map1.tmx";
App->map->mapChange(&map);
App->scene->mapname = map;
App->map->DrawObjects();
Player.collider = App->collision->AddCollider(Player.colInit, COLLIDER_PLAYER, this);
}
ResetPlayer();
}
if (App->input->GetKey(SDL_SCANCODE_F2) == KEY_DOWN)
{
if (App->scene->mapname != "map2.tmx")
{
p2SString map = "map2.tmx";
App->map->mapChange(&map);
App->scene->mapname = map;
App->map->DrawObjects();
Player.collider = App->collision->AddCollider(Player.colInit, COLLIDER_PLAYER, this);
}
ResetPlayer();
}
if (App->input->GetKey(SDL_SCANCODE_F3) == KEY_DOWN)
{
Player.position = Player.initPosition;
}
if (App->input->GetKey(SDL_SCANCODE_F10) == KEY_DOWN)
{
if (Player.godmode)
Player.godmode = false;
else if (!Player.godmode)
{
Player.godmode = true;
Player.speed = { 0,0 };
}
}
if(!Player.godmode)
Player.speed = Gravity(Player.speed);
AnimChange();
PlayerMov();
Draw();
return true;
}
bool j1Player::PostUpdate()
{
return true;
}
bool j1Player::Clean()
{
LOG("Cleaning Player");
App->tex->UnLoad(graphics);
return true;
}
//Save Game
bool j1Player::Save(pugi::xml_node& data) const
{
data.append_child("position").append_attribute("x") = Player.position.x;
data.child("position").append_attribute("y") = Player.position.y;
data.append_child("speed").append_attribute("x") = Player.speed.x;
data.child("speed").append_attribute("y") = Player.speed.y;
data.append_child("col").append_attribute("width") = Player.collider->rect.w;
data.child("col").append_attribute("height") = Player.collider->rect.h;
data.child("col").append_attribute("x") = Player.collider->rect.x;
data.child("col").append_attribute("y") = Player.collider->rect.y;
data.append_child("onFloor").append_attribute("value") = Player.onFloor;
data.append_child("map").append_attribute("value") = Player.savedmap;
return true;
}
// Load Game
bool j1Player::Load(pugi::xml_node& data)
{
Player.position.x = data.child("position").attribute("x").as_int();
Player.position.y = data.child("position").attribute("y").as_int();
Player.speed.x = data.child("speed").attribute("x").as_int();
Player.speed.y = data.child("speed").attribute("y").as_int();
Player.collider->rect.w = data.child("col").attribute("width").as_int();
Player.collider->rect.h = data.child("col").attribute("height").as_int();
Player.collider->rect.x = data.child("col").attribute("x").as_int();
Player.collider->rect.y = data.child("col").attribute("y").as_int();
Player.onFloor = data.child("onFloor").attribute("value").as_bool();
Player.savedmap = data.child("map").attribute("value").as_bool();
return true;
}
void j1Player::MirrorSprite()
{
if (Player.speed.x < 0)
Player.mirror = true;
else if (Player.speed.x > 0)
Player.mirror = false;
}
void j1Player::SpeedUp()
{
Player.speed.x += Player.acceleration.x * Player.xDirection;
if (Player.xDirection > 0)
{
if (Player.speed.x > Player.maxSpeed.x)
Player.speed.x = Player.maxSpeed.x;
}
else
{
if (Player.speed.x < Player.xDirection*Player.maxSpeed.x)
Player.speed.x = Player.xDirection*Player.maxSpeed.x;
}
}
void j1Player::SpeedDown()
{
if (Player.speed.x != 0)
Player.speed.x -= Player.acceleration.x * Player.xDirection;
}
void j1Player::ArrivesFloor()
{
if (Player.isJumping)
{
Player.isJumping = false;
Player.maxSpeed.x -= Player.jumpSpeed.x;
Player.angel_jumping.Reset();
Player.angel_jumping_M.Reset();
}
Player.maxSpeed = Player.iMaxSpeed;
Player.angel_falling.Reset();
Player.angel_falling_M.Reset();
Player.canDJump = true;
Player.canDash = true;
Player.onFloor = true;
Player.angel_jumping.Reset();
}
void j1Player::DoubleJump()
{
Player.canDJump = false;
Player.isJumping = true;
//Player.maxSpeed.x += Player.jumpSpeed.x;
//Player.speed.x = Player.jumpSpeed.x*Player.xDirection;
Player.speed.y = -Player.jumpSpeed.y;
}
void j1Player::Dash()
{
if (!Player.mirror)
Player.position.x += Player.dashForce;
else
Player.position.x -= Player.dashForce;
Player.canDash = false;
}
void j1Player::AnimChange()
{
if (!Player.isDemon)
{
if (!Player.mirror)
{
if (Player.onFloor)
{
if (Player.speed.x == 0)
{
Player.current_animation = &Player.angel_idle;
}
else
{
Player.current_animation = &Player.angel_moving;
}
}
else if (Player.speed.y < 0)
{
Player.current_animation = &Player.angel_jumping;
}
else
{
Player.current_animation = &Player.angel_falling;
}
}
else
{
if (Player.onFloor)
{
if (Player.speed.x == 0)
{
Player.current_animation = &Player.angel_idle_M;
}
else
{
Player.current_animation = &Player.angel_moving_M;
}
}
else if (Player.speed.y < 0)
{
Player.current_animation = &Player.angel_jumping_M;
}
else
{
Player.current_animation = &Player.angel_falling_M;
}
}
}
else if(Player.isDemon)
{
if (!Player.mirror)
{
if (Player.onFloor)
{
if (Player.speed.x == 0)
{
Player.current_animation = &Player.demon_idle;
}
else
{
Player.current_animation = &Player.demon_moving;
}
}
else if (Player.speed.y < 0)
{
Player.current_animation = &Player.demon_jumping;
}
else
{
Player.current_animation = &Player.demon_falling;
}
}
else
{
if (Player.onFloor)
{
if (Player.speed.x == 0)
{
Player.current_animation = &Player.demon_idle_M;
}
else
{
Player.current_animation = &Player.demon_moving_M;
}
}
else if (Player.speed.y < 0)
{
Player.current_animation = &Player.demon_jumping_M;
}
else
{
Player.current_animation = &Player.demon_falling_M;
}
}
}
}
void j1Player::PlayerMov()
{
Player.position += Player.speed;
Player.collider->SetPos(Player.position.x + Player.offSet.x, Player.position.y + Player.offSet.y);
}
void j1Player::Draw()
{
App->render->Blit(graphics, Player.position.x, Player.position.y, &(Player.current_animation->GetCurrentFrame()), SDL_FLIP_HORIZONTAL, -1.0);
}
iPoint j1Player::Gravity(iPoint vec)
{
vec.y += Player.acceleration.y;
if (vec.y > Player.maxSpeed.y)
{
vec.y = Player.maxSpeed.y;
}
return vec;
}
void j1Player::ResetPlayer()
{
Player.maxSpeed = Player.iMaxSpeed;
Player.speed = Player.iSpeed;
Player.position = Player.initPosition;
Player.canDash = false;
Player.canDJump = true;
Player.isDemon = false;
Player.current_animation = &Player.angel_falling;
}
void j1Player::OnCollision(Collider* c1, Collider* c2)
{
if (c1->type == COLLIDER_PLAYER && c2->type == COLLIDER_WALL)
{
if (Player.speed.y >= 0 && c2->rect.y > c1->rect.y)
{
Player.position.y = c2->rect.y - c1->rect.h;
ArrivesFloor();
}
else if ((c2->rect.y + c2->rect.h) > c1->rect.y && c2->rect.y < c1->rect.y)
{
if (Player.speed.x > 0)
Player.position.x = c2->rect.x - 1;
else if (Player.speed.x < 0)
Player.position.x = c2->rect.x + c2->rect.w + 1;
}
}
else if (c1->type == COLLIDER_PLAYER && c2->type == COLLIDER_ENEMY)
{
if (App->scene->mapname == "map1.tmx")
{
p2SString map = "map2.tmx";
App->map->mapChange(&map);
Player.position = Player.initPosition;
App->scene->mapname = map;
App->map->DrawObjects();
Player.collider = App->collision->AddCollider(Player.colInit, COLLIDER_PLAYER, this);
}
else if (App->scene->mapname == "map2.tmx")
{
p2SString map = "map1.tmx";
App->map->mapChange(&map);
Player.position = Player.initPosition;
App->scene->mapname = map;
App->map->DrawObjects();
Player.collider = App->collision->AddCollider(Player.colInit, COLLIDER_PLAYER, this);
}
}
else if (c1->type == COLLIDER_PLAYER && c2->type == COLLIDER_ENEMY_SHOT)
{
Player.position = Player.initPosition;
}
} | 30.851227 | 264 | 0.676908 | [
"render"
] |
e1a72880b47b454481a101d895d3164d3e8d97a8 | 12,627 | cc | C++ | pmlc/dialect/pxa/transforms/stencil_gemm.cc | IsolatedMy/plaidml | 34538a9224e770fd79151105399d8d7ea08678c0 | [
"Apache-2.0"
] | null | null | null | pmlc/dialect/pxa/transforms/stencil_gemm.cc | IsolatedMy/plaidml | 34538a9224e770fd79151105399d8d7ea08678c0 | [
"Apache-2.0"
] | 65 | 2020-08-24T07:41:09.000Z | 2021-07-19T09:13:49.000Z | pmlc/dialect/pxa/transforms/stencil_gemm.cc | Flex-plaidml-team/plaidml | 1070411a87b3eb3d94674d4d041ed904be3e7d87 | [
"Apache-2.0"
] | null | null | null | // Copyright 2020 Intel Corporation
#include <string>
#include "mlir/Dialect/Affine/IR/AffineOps.h"
#include "mlir/Dialect/StandardOps/IR/Ops.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Support/DebugStringHelper.h"
#include "pmlc/dialect/pxa/analysis/strides.h"
#include "pmlc/dialect/pxa/ir/matchers.h"
#include "pmlc/dialect/pxa/ir/ops.h"
#include "pmlc/dialect/pxa/transforms/autotile.h"
#include "pmlc/dialect/pxa/transforms/passes.h"
#include "pmlc/dialect/pxa/transforms/stencil.h"
#include "pmlc/util/logging.h"
#include "pmlc/util/matchers.h"
#include "pmlc/util/tags.h"
using namespace mlir; // NOLINT
namespace pmlc::dialect::pxa {
struct GemmOperand {
Value memref;
AffineMap accessMap;
AffineMap tileMap;
template <typename TOp>
GemmOperand(TOp op, ArrayRef<BlockArgument> idxs,
SmallVectorImpl<Value> &mapOperands)
: memref(op.getMemRef()), accessMap(op.getAffineMap()),
tileMap(makeTileMap(op.getContext(), op.getAffineMap(),
op.getMapOperands(), idxs)) {
mapOperands.append(op.getMapOperands().begin(), op.getMapOperands().end());
}
};
// Requirements for additional reduction indices that do not appear in output
// tensor
static StencilIndexRequirement etcIdxReqs{
/*idxName=*/"etc", // this is unused
/*tilingGenerator=*/EvenTilingGenerator(), // this is unused
IndexStridePredicates{
[](int64_t stride) { return stride == 0; }, // output
[](int64_t stride) { return stride != 0; }, // input0
[](int64_t stride) { return stride != 0; }, // input1
}};
class StencilGEMM : public StencilBase {
private:
unsigned numThreads;
bool doBatch;
StencilCostFunction stencilCostFn;
Optional<StencilCapture> capture() {
using matchers::m_Any;
// Looking for load..load..mul..reduce..terminator
Value load1, load2, reduce;
Operation *yield = op.getBody()->getTerminator();
if (matchPattern(
yield,
m_Op<AffineYieldOp>(m_Capture(
&reduce, m_PxaReduceOp(
AtomicRMWKind::addf,
m_Op<MulFOp>(m_Capture(&load1, m_Op<PxaLoadOp>()),
m_Capture(&load2, m_Op<PxaLoadOp>())),
m_Any())))) ||
matchPattern(
yield,
m_Op<AffineYieldOp>(m_Capture(
&reduce, m_PxaReduceOp(
AtomicRMWKind::addi,
m_Op<MulIOp>(m_Capture(&load1, m_Op<PxaLoadOp>()),
m_Capture(&load2, m_Op<PxaLoadOp>())),
m_Any()))))) {
return StencilCapture{{reduce}, {load1, load2}};
}
return llvm::None;
}
double getCost(const StencilOption &stencil, ArrayRef<int64_t> tileSize) {
SmallVector<Type, 3> types;
for (const ValueStrideInfo &vsi : stencil.values) {
types.push_back(vsi.value.getType());
}
auto cost = stencilCostFn(tileSize, types);
if (cost.throughput == 0) {
return std::numeric_limits<double>::infinity();
}
// The middle idxs are the accumulation indexes, i.e. those used on loads
// but not stores
DenseMap<BlockArgument, unsigned> middleIdxs, outerIdxs;
for (const auto &kvp : stencil.values[1].strideInfo.strides) {
if (getBlockArgsAsSet().count(kvp.first)) {
IVLOG(6, "Based on first tensor, inserting middle index "
<< kvp.first.getArgNumber());
middleIdxs.insert(std::make_pair(kvp.first, getIdxRange(kvp.first)));
}
}
IVLOG(5, "Current size of middleIdxs = " << middleIdxs.size());
for (const auto &kvp : stencil.values[2].strideInfo.strides) {
if (getBlockArgsAsSet().count(kvp.first)) {
IVLOG(6, "Based on second tensor, inserting middle index "
<< kvp.first.getArgNumber());
middleIdxs.insert(std::make_pair(kvp.first, getIdxRange(kvp.first)));
}
}
IVLOG(5, "Current size of middleIdxs = " << middleIdxs.size());
for (const auto &kvp : stencil.values[0].strideInfo.strides) {
if (getBlockArgsAsSet().count(kvp.first)) {
auto it = middleIdxs.find(kvp.first);
if (it != middleIdxs.end()) {
IVLOG(6, "Based on output tensor, erasing middle index "
<< it->first.getArgNumber());
middleIdxs.erase(it);
}
outerIdxs.try_emplace(kvp.first, getIdxRange(kvp.first));
}
}
for (unsigned i = 0; i < getTiledIdxCount(); ++i) {
assert(getBlockArgsAsSet().count(stencil.indexes[i]) &&
"All tiled indexes must be introduced in current loop");
auto itMiddle = middleIdxs.find(stencil.indexes[i]);
if (itMiddle != middleIdxs.end()) {
itMiddle->second = llvm::divideCeil(itMiddle->second, tileSize[i]);
}
auto itOuter = outerIdxs.find(stencil.indexes[i]);
if (itOuter != outerIdxs.end()) {
itOuter->second = llvm::divideCeil(itOuter->second, tileSize[i]);
}
}
unsigned totOuterLoop = 1;
for (const auto &kvp : outerIdxs) {
totOuterLoop *= kvp.second;
}
unsigned totMiddleLoop = 1;
for (const auto &kvp : middleIdxs) {
totMiddleLoop *= kvp.second;
}
unsigned totInnerLoop = tileSize[0] * tileSize[1] * tileSize[2];
double innerTime = totInnerLoop / cost.throughput;
IVLOG(4, "Outer: loop = " << totOuterLoop);
if (VLOG_IS_ON(4)) {
for (auto &kvp : outerIdxs) {
if (kvp.second > 1) {
IVLOG(4, kvp.first.getArgNumber() << ": " << kvp.second);
}
}
}
unsigned outerBatches = (totOuterLoop - 1) / numThreads + 1;
double perf = outerBatches * totMiddleLoop * (cost.startupCost + innerTime);
IVLOG(3, "Tile Information:");
IVLOG(3, " tile: "
<< "[" << tileSize[0] << " " << tileSize[1] << " "
<< tileSize[2] << "]");
IVLOG(3, " outer count: " << outerBatches);
IVLOG(3, " middle count: " << totMiddleLoop);
IVLOG(3, " startup cost: " << cost.startupCost);
IVLOG(3, " inner time: " << innerTime);
return perf;
}
void transform(const StencilOption &stencil, ArrayRef<int64_t> tileSize) {
int64_t kBatches = 1;
int64_t kRange = getIdxRange(stencil.indexes[2]);
IVLOG(3, "kRange: " << kRange);
SmallVector<BlockArgument> tileEtcIdxs(stencil.indexes.begin(),
stencil.indexes.end());
SmallVector<int64_t> batches;
// Generate the GEMM op; select inputs based on permutation order
auto opC = cast<PxaReduceOp>(stencil.values[0].value.getDefiningOp());
auto opA = cast<PxaLoadOp>(stencil.values[1].value.getDefiningOp());
auto opB = cast<PxaLoadOp>(stencil.values[2].value.getDefiningOp());
// First, modify step size of all tiled indexes
SmallVector<int64_t, 8> steps = op.getSteps();
for (size_t i = 0; i < steps.size(); i++) {
BlockArgument idx = op.getBody()->getArgument(i);
int64_t idxRange = getIdxRange(idx);
bool foundBlockArg = false;
for (size_t j = 0; j < getTiledIdxCount(); j++) {
if (stencil.indexes[j] == idx) {
steps[i] *= tileSize[j];
foundBlockArg = true;
// K index (reduction dimension)
if (doBatch && j == 2) {
// We want to transform "regular" pxa.generic where kBatches is 1:
// affine.parallel (i, j, k) = (..., 0) to (..., kRange)
// step (kStep)
// pxa.generic C[i, j] = A[i, k], B[k, j]: [..., kStep], 1
//
// to
//
// affine.parallel (i, j, k) = (..., 0) to (..., kRange)
// step (kRange)
// pxa.generic C[i, j] = A[i, k], B[k, j]: [..., kStep],
// (kRange/64)
//
// where the number of batches of A and B matrices to multiply
// is the k loop's range divided by the original step size for
// the k loop.
//
// Subsequently, kStep is set to kRange. That is, in one step, a
// block of C is completely computed through reduction of
// batches of A and B matrix multiplies.
kBatches = kRange / steps[i];
steps[i] = kRange;
IVLOG(3, "steps[" << i << "] = " << steps[i]);
IVLOG(3, "kBatches: " << kBatches);
}
}
}
// Check for additional reduction indices with a range greater than 1
if (doBatch && !foundBlockArg && steps[i] == 1 && idxRange > 1 &&
etcIdxReqs.check(stencil.values, idx)) {
tileEtcIdxs.push_back(idx);
batches.emplace_back(idxRange);
foundBlockArg = true;
steps[i] = idxRange;
}
}
op.setSteps(steps);
// fullTileSizes always has the form: [m, n, k, kBatches, others...]
SmallVector<int64_t> fullTileSizes;
fullTileSizes.append(tileSize.begin(), tileSize.end());
if (!batches.empty()) {
fullTileSizes.push_back(kBatches);
fullTileSizes.append(batches.begin(), batches.end());
} else if (kBatches != 1) {
fullTileSizes.push_back(kBatches);
}
OpBuilder builder = op.getBodyBuilder();
SmallVector<Value> inputIndices, outputIndices;
GemmOperand c(opC, stencil.indexes, outputIndices);
GemmOperand a(opA, tileEtcIdxs, inputIndices);
GemmOperand b(opB, tileEtcIdxs, inputIndices);
ArrayAttr outputAccessMaps = builder.getAffineMapArrayAttr({c.accessMap});
ArrayAttr outputTileMaps = builder.getAffineMapArrayAttr({c.tileMap});
ArrayAttr inputAccessMaps =
builder.getAffineMapArrayAttr({a.accessMap, b.accessMap});
ArrayAttr inputTileMaps =
builder.getAffineMapArrayAttr({a.tileMap, b.tileMap});
ArrayAttr reductions =
builder.getI64ArrayAttr({static_cast<int64_t>(opC.agg())});
auto genericOp = builder.create<PxaGenericOp>(
op.getLoc(), c.memref.getType(),
/*inputs=*/ArrayRef<Value>{a.memref, b.memref},
/*outputs=*/ArrayRef<Value>{c.memref},
/*inputIndices=*/inputIndices,
/*outputIndices=*/outputIndices,
/*inputAccessMaps=*/inputAccessMaps,
/*inputTileMaps=*/inputTileMaps,
/*outputAccessMaps=*/outputAccessMaps,
/*outputTileMaps=*/outputTileMaps,
/*kernel=*/builder.getStringAttr("tpp_gemm"),
/*tile=*/builder.getI64ArrayAttr(fullTileSizes),
/*reductions=*/reductions);
opC.result().replaceAllUsesWith(genericOp.getResult(0));
opC.erase();
}
public:
StencilGEMM(AffineParallelOp op, unsigned numThreads, bool doBatch,
StencilCostFunction costFn)
: StencilBase(
op,
{
StencilIndexRequirement{
/*idxName=*/"gemm_m",
/*tilingGenerator=*/EvenTilingGenerator(),
IndexStridePredicates{
[](int64_t stride) { return stride != 0; }, // output
[](int64_t stride) { return stride != 0; }, // input0
[](int64_t stride) { return stride == 0; }, // input1
}},
StencilIndexRequirement{
/*idxName=*/"gemm_n",
/*tilingGenerator=*/EvenTilingGenerator(),
IndexStridePredicates{
[](int64_t stride) { return stride == 1; }, // output
[](int64_t stride) { return stride == 0; }, // input0
[](int64_t stride) { return stride == 1; }, // input1
}},
StencilIndexRequirement{
/*idxName=*/"gemm_k",
/*tilingGenerator=*/EvenTilingGenerator(),
IndexStridePredicates{
[](int64_t stride) { return stride == 0; }, // output
[](int64_t stride) { return stride == 1; }, // input0
[](int64_t stride) { return stride != 0; }, // input1
}},
}),
numThreads{numThreads}, doBatch{doBatch}, stencilCostFn(costFn) {}
};
LogicalResult applyStencilGEMM(AffineParallelOp op, unsigned numThreads,
bool doBatch, StencilCostFunction costFn) {
StencilGEMM stencil(op, numThreads, doBatch, costFn);
stencil.performStenciling();
return success();
}
} // namespace pmlc::dialect::pxa
| 38.263636 | 80 | 0.577097 | [
"transform"
] |
e1a7573881852724f9ea3054e439f497ca2c3cdf | 1,251 | cc | C++ | CPP/No684.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No684.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | CPP/No684.cc | hxz1998/funny_leetcode | 1d2c425af09b57a030fc018ddc1e1a5ffb966cd0 | [
"Apache-2.0"
] | null | null | null | /**
* Created by Xiaozhong on 2020/11/16.
* Copyright (c) 2020/11/16 Xiaozhong. All rights reserved.
*/
#include <vector>
#include <iostream>
#include <unordered_set>
#include <unordered_map>
using namespace std;
class Solution {
unordered_map<int, unordered_set<int>> adjacent;
bool check(const int from, const int prev, const int to) {
if (from == to) return true;
auto dists = adjacent[from];
for (auto dist : dists) {
if (dist == prev) continue;
if (check(dist, from, to)) return true;
}
return false;
}
public:
vector<int> findRedundantConnection(vector<vector<int>> &edges) {
int n = edges.size();
for (const auto &edge : edges) {
bool res = check(edge.front(), 0, edge.back());
if (res) return edge;
else {
int from = edge.front(), to = edge.back();
adjacent[from].insert(to);
adjacent[to].insert(from);
}
}
return {};
}
};
int main() {
Solution s;
vector<vector<int>> edges = {
{1, 2},
{1, 3},
{2, 3}
};
vector<int> ans = s.findRedundantConnection(edges);
return 0;
} | 25.02 | 69 | 0.533173 | [
"vector"
] |
e1a9f07d9a94350eb7ce709a45164427b61fcdcc | 3,886 | cpp | C++ | qtmultimedia/src/multimedia/controls/qmediaplaylistsourcecontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | 1 | 2020-04-30T15:47:35.000Z | 2020-04-30T15:47:35.000Z | qtmultimedia/src/multimedia/controls/qmediaplaylistsourcecontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | qtmultimedia/src/multimedia/controls/qmediaplaylistsourcecontrol.cpp | wgnet/wds_qt | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qmediaplaylistsourcecontrol_p.h"
#include "qmediacontrol_p.h"
QT_BEGIN_NAMESPACE
/*!
\class QMediaPlaylistSourceControl
\internal
\inmodule QtMultimedia
\ingroup multimedia_control
\brief The QMediaPlaylistSourceControl class provides access to the playlist playback
functionality of a QMediaService.
This control allows QMediaPlaylist to be passed directly to the service
instead of playing media sources one by one. This control should be
implemented if backend benefits from knowing the next media source to be
played, for example for preloading, cross fading or gap-less playback.
If QMediaPlaylistSourceControl is provided, the backend must listen for
current playlist item changes to load corresponding media source and
advance the playlist with QMediaPlaylist::next() when playback of the
current media is finished.
The interface name of QMediaPlaylistSourceControl is \c org.qt-project.qt.mediaplaylistsourcecontrol/5.0 as
defined in QMediaPlaylistSourceControl_iid.
\sa QMediaService::requestControl(), QMediaPlayer
*/
/*!
\macro QMediaPlaylistSourceControl_iid
\c org.qt-project.qt.mediaplaylistsourcecontrol/5.0
Defines the interface name of the QMediaPlaylistSourceControl class.
\relates QMediaPlaylistSourceControl
*/
/*!
Create a new playlist source control object with the given \a parent.
*/
QMediaPlaylistSourceControl::QMediaPlaylistSourceControl(QObject *parent):
QMediaControl(*new QMediaControlPrivate, parent)
{
}
/*!
Destroys the playlist control.
*/
QMediaPlaylistSourceControl::~QMediaPlaylistSourceControl()
{
}
/*!
\fn QMediaPlaylistSourceControl::playlist() const
Returns the current playlist.
Should return a null pointer if no playlist is assigned.
*/
/*!
\fn QMediaPlaylistSourceControl::setPlaylist(QMediaPlaylist *playlist)
Set the playlist of this media player to \a playlist.
If a null pointer is passed, the playlist source should be disabled.
The current media should be replaced with the current item of the media playlist.
*/
/*!
\fn QMediaPlaylistSourceControl::playlistChanged(QMediaPlaylist* playlist)
Signal emitted when the playlist has changed to \a playlist.
*/
#include "moc_qmediaplaylistsourcecontrol_p.cpp"
QT_END_NAMESPACE
| 32.115702 | 111 | 0.738806 | [
"object"
] |
e1aca30ca678117251e4590fae05d1711aafe9d1 | 6,397 | cpp | C++ | OPHD/States/MainMenuState.cpp | Daedeross/OPHD | 16c0c4bf44bd74fe2ef413e344d3ef5aeab6102c | [
"BSD-3-Clause"
] | 30 | 2018-03-31T19:16:45.000Z | 2019-10-15T03:12:17.000Z | OPHD/States/MainMenuState.cpp | Daedeross/OPHD | 16c0c4bf44bd74fe2ef413e344d3ef5aeab6102c | [
"BSD-3-Clause"
] | 149 | 2018-04-23T01:47:22.000Z | 2020-02-09T04:04:34.000Z | OPHD/States/MainMenuState.cpp | Daedeross/OPHD | 16c0c4bf44bd74fe2ef413e344d3ef5aeab6102c | [
"BSD-3-Clause"
] | 10 | 2018-04-28T14:59:07.000Z | 2020-01-26T19:54:36.000Z | #include "GameState.h"
#include "MapViewState.h"
#include "MainMenuState.h"
#include "PlanetSelectState.h"
#include "../Cache.h"
#include "../Constants/Strings.h"
#include "../Constants/UiConstants.h"
#include "../ShellOpenPath.h"
#include "../UI/MessageBox.h"
#include <NAS2D/Utility.h>
#include <NAS2D/Mixer/Mixer.h>
#include <NAS2D/Renderer/Renderer.h>
MainMenuState::MainMenuState() :
mBgImage{"sys/mainmenu.png"},
buttons{{
{constants::MainMenuNewGame, {this, &MainMenuState::onNewGame}},
{constants::MainMenuContinue, {this, &MainMenuState::onContinueGame}},
{constants::MainMenuHelp, {this, &MainMenuState::onHelp}},
{constants::MainMenuQuit, {this, &MainMenuState::onQuit}}
}},
lblVersion{constants::Version},
mReturnState{this}
{}
MainMenuState::~MainMenuState()
{
auto& eventHandler = NAS2D::Utility<NAS2D::EventHandler>::get();
eventHandler.windowResized().disconnect(this, &MainMenuState::onWindowResized);
eventHandler.keyDown().disconnect(this, &MainMenuState::onKeyDown);
NAS2D::Utility<NAS2D::Mixer>::get().stopAllAudio();
NAS2D::Utility<NAS2D::Renderer>::get().fadeComplete().disconnect(this, &MainMenuState::onFadeComplete);
}
/**
* Initialize function, called once when instantiated.
*/
void MainMenuState::initialize()
{
auto& eventHandler = NAS2D::Utility<NAS2D::EventHandler>::get();
eventHandler.windowResized().connect(this, &MainMenuState::onWindowResized);
eventHandler.keyDown().connect(this, &MainMenuState::onKeyDown);
for (auto& button : buttons)
{
button.fontSize(constants::FontPrimaryMedium);
button.size({200, 30});
}
mFileIoDialog.setMode(FileIo::FileOperation::Load);
mFileIoDialog.fileOperation().connect(this, &MainMenuState::onFileIoAction);
mFileIoDialog.anchored(false);
mFileIoDialog.hide();
const NAS2D::Font* tiny_font = &fontCache.load(constants::FONT_PRIMARY, constants::FontPrimaryNormal);
lblVersion.font(tiny_font);
lblVersion.color(NAS2D::Color::White);
positionButtons();
disableButtons();
auto& renderer = NAS2D::Utility<NAS2D::Renderer>::get();
renderer.fadeComplete().connect(this, &MainMenuState::onFadeComplete);
renderer.fadeOut(std::chrono::milliseconds{0});
renderer.fadeIn(constants::FadeSpeed);
renderer.showSystemPointer(true);
NAS2D::Mixer& mixer = NAS2D::Utility<NAS2D::Mixer>::get();
if (!mixer.musicPlaying()) { mixer.playMusic(*trackMars); }
}
/**
* Repositions buttons based on window size.
*/
void MainMenuState::positionButtons()
{
auto& renderer = NAS2D::Utility<NAS2D::Renderer>::get();
const auto center = renderer.center().to<int>();
auto buttonPosition = center - NAS2D::Vector{100, (35 * 4) / 2};
for (auto& button : buttons)
{
button.position(buttonPosition);
buttonPosition.y += 35;
}
mFileIoDialog.position(center - mFileIoDialog.size() / 2);
lblVersion.position(NAS2D::Point{0, 0} + renderer.size() - lblVersion.size());
}
/**
* Disables all buttons in the UI.
*/
void MainMenuState::disableButtons()
{
for (auto& button : buttons)
{
button.enabled(false);
}
}
/**
* Enables all buttons in the UI.
*/
void MainMenuState::enableButtons()
{
for (auto& button : buttons)
{
button.enabled(true);
}
}
/**
* Event handler for file I/O operations via the FileIO Window.
*/
void MainMenuState::onFileIoAction(const std::string& filePath, FileIo::FileOperation fileOp)
{
if (fileOp == FileIo::FileOperation::Save)
{
return;
}
if (filePath.empty())
{
return;
}
std::string filename = constants::SaveGamePath + filePath + ".xml";
try
{
checkSavegameVersion(filename);
GameState* gameState = new GameState();
MapViewState* mapview = new MapViewState(gameState->getMainReportsState(), filename);
mapview->_initialize();
mapview->activate();
gameState->mapviewstate(mapview);
mReturnState = gameState;
NAS2D::Utility<NAS2D::Renderer>::get().fadeOut(constants::FadeSpeed);
NAS2D::Utility<NAS2D::Mixer>::get().fadeOutMusic(constants::FadeSpeed);
}
catch (const std::exception& e)
{
mReturnState = this;
doNonFatalErrorMessage("Load Failed", e.what());
}
}
/**
* Key down event handler.
*/
void MainMenuState::onKeyDown(NAS2D::EventHandler::KeyCode /*key*/, NAS2D::EventHandler::KeyModifier /*mod*/, bool /*repeat*/)
{}
/**
* Window resize event handler.
*/
void MainMenuState::onWindowResized(NAS2D::Vector<int> /*newSize*/)
{
positionButtons();
}
/**
* Event handler for renderer fading.
*/
void MainMenuState::onFadeComplete()
{
if (NAS2D::Utility<NAS2D::Renderer>::get().isFaded()) { return; }
enableButtons();
}
/**
* Click handler for New Game button.
*/
void MainMenuState::onNewGame()
{
if (mFileIoDialog.visible()) { return; }
disableButtons();
mReturnState = new PlanetSelectState();
NAS2D::Utility<NAS2D::Renderer>::get().fadeOut(constants::FadeSpeed);
NAS2D::Utility<NAS2D::Mixer>::get().fadeOutMusic(constants::FadeSpeed);
}
/**
* Click handler for Continue button.
*/
void MainMenuState::onContinueGame()
{
if (mFileIoDialog.visible()) { return; }
mFileIoDialog.scanDirectory(constants::SaveGamePath);
mFileIoDialog.show();
}
/**
* Click handler for Options button.
*/
void MainMenuState::onOptions()
{
if (mFileIoDialog.visible()) { return; }
}
/**
* Click handler for the Help button.
*/
void MainMenuState::onHelp()
{
if (mFileIoDialog.visible()) { return; }
shellOpenPath("https://wiki.outpost2.net/doku.php?id=outposthd:how_to_play");
}
/**
* Click handler for Quit button.
*/
void MainMenuState::onQuit()
{
if (mFileIoDialog.visible()) { return; }
disableButtons();
NAS2D::postQuitEvent();
}
/**
* Update function -- called each frame.
*/
NAS2D::State* MainMenuState::update()
{
auto& renderer = NAS2D::Utility<NAS2D::Renderer>::get();
renderer.clearScreen();
renderer.drawImage(mBgImage, renderer.center() - mBgImage.size() / 2);
if (!mFileIoDialog.visible())
{
const auto padding = NAS2D::Vector{5, 5};
const auto menuRect = NAS2D::Rectangle<int>::Create(buttons.front().rect().startPoint() - padding, buttons.back().rect().endPoint() + padding);
renderer.drawBoxFilled(menuRect, NAS2D::Color{0, 0, 0, 150});
renderer.drawBox(menuRect, NAS2D::Color{0, 185, 0, 255});
for (auto& button : buttons)
{
button.update();
}
}
if (mFileIoDialog.visible())
{
mFileIoDialog.update();
}
lblVersion.update();
if (renderer.isFading())
{
return this;
}
return mReturnState;
}
| 22.134948 | 145 | 0.706269 | [
"vector"
] |
e1ad9f7a9d60aca912756343cdd457ac958d8d10 | 639 | cc | C++ | uva/00424.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 506 | 2018-08-22T10:30:38.000Z | 2022-03-31T10:01:49.000Z | uva/00424.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 13 | 2019-08-07T18:31:18.000Z | 2020-12-15T21:54:41.000Z | uva/00424.cc | Ashindustry007/competitive-programming | 2eabd3975c029d235abb7854569593d334acae2f | [
"WTFPL"
] | 234 | 2018-08-06T17:11:41.000Z | 2022-03-26T10:56:42.000Z | // https://uva.onlinejudge.org/external/4/424.pdf
#include<bits/stdc++.h>
using namespace std;
using vi=vector<int>;
using vvi=vector<vi>;
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
vvi a;
while(true){
string s;
cin>>s;
if(s=="0")break;
vi b(s.size());
for(int i=0;i<s.size();i++)b[i]=s[i]-'0';
reverse(b.begin(),b.end());
a.push_back(b);
}
vi r;
int c=0;
for(int i=0;i<105;i++){
for(vi &b:a)
if(b.size()>i)c+=b[i];
r.push_back(c%10);
c/=10;
}
while(r.size()>1&&r.back()==0){
r.pop_back();
}
reverse(r.begin(),r.end());
for(int k:r)cout<<k;
cout<<endl;
}
| 18.794118 | 49 | 0.536776 | [
"vector"
] |
e1b1be91857c0f407dc7950103229a58232fd2c2 | 16,445 | hpp | C++ | RX24T/icu.hpp | duybang140494/RX | 7fed06a9d8295f4504e8a08fa589d4a52792095f | [
"BSD-3-Clause"
] | 1 | 2020-01-16T03:38:30.000Z | 2020-01-16T03:38:30.000Z | RX24T/icu.hpp | duybang140494/RX | 7fed06a9d8295f4504e8a08fa589d4a52792095f | [
"BSD-3-Clause"
] | null | null | null | RX24T/icu.hpp | duybang140494/RX | 7fed06a9d8295f4504e8a08fa589d4a52792095f | [
"BSD-3-Clause"
] | null | null | null | #pragma once
//=====================================================================//
/*! @file
@brief RX24T グループ・ICUb 定義
@author 平松邦仁 (hira@rvf-rc45.net)
@copyright Copyright (C) 2016, 2018 Kunihito Hiramatsu @n
Released under the MIT license @n
https://github.com/hirakuni45/RX/blob/master/LICENSE
*/
//=====================================================================//
#include "common/io_utils.hpp"
namespace device {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief ICU 定義基底クラス
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
struct icu_t {
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief 通常ベクター型
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
enum class VECTOR {
NONE = 0, ///< none
BUSERR = 16, ///< BSC
FRDYI = 23, ///< FCU
SWINT = 27, ///< ICU
CMI0 = 28, ///< CMT0
CMI1 = 29, ///< CMT1
CMI2 = 30, ///< CMT2
CMI3 = 31, ///< CMT3
FERRF = 32, ///< CAC
MENDF = 33, ///< CAC
OVFF = 34, ///< CAC
ETGIN = 40, ///< GPT
ETGIP = 41, ///< GPT
SPEI0 = 44, ///< RSPI0
SPRI0 = 45, ///< RSPI0
SPTI0 = 46, ///< RSPI0
SPII0 = 47, ///< RSPI0
DOPCF = 57, ///< DOC
IRQ0 = 64, ///< ICU
IRQ1 = 65,
IRQ2 = 66,
IRQ3 = 67,
IRQ4 = 68,
IRQ5 = 69,
IRQ6 = 70,
IRQ7 = 71,
LVD1 = 88, ///< LVD
LVD2 = 89, ///< LVD
S12ADI = 102, ///< S12ADI
GBADI = 103, ///< S12AD
GCADI = 104, ///< S12AD
S12ADI1 = 105, ///< S12ADI1
GBADI1 = 106, ///< S12AD1
GCADI1 = 107, ///< S12AD1
CMPC0 = 108, ///< CMPC0
CMPC1 = 109, ///< CMPC1
CMPC2 = 110, ///< CMPC2
S12ADI2 = 111, ///< S12AD2
GBADI2 = 112, ///< S12AD2
GCADI2 = 113, ///< S12AD2
TGIA0 = 114, ///< MTU0
TGIB0 = 115, ///< MTU0
TGIC0 = 116, ///< MTU0
TGID0 = 117, ///< MTU0
TCIV0 = 118, ///< MTU0
TGIE0 = 119, ///< MTU0
TGIF0 = 120, ///< MTU0
TGIA1 = 121, ///< MTU1
TGIB1 = 122, ///< MTU1
TCIV1 = 123, ///< MTU1
TCIU1 = 124, ///< MTU1
TGIA2 = 125, ///< MTU2
TGIB2 = 126, ///< MTU2
TCIV2 = 127, ///< MTU2
TCIU2 = 128, ///< MTU2
TGIA3 = 129, ///< MTU3
TGIB3 = 130, ///< MTU3
TGIC3 = 131, ///< MTU3
TGID3 = 132, ///< MTU3
TCIV3 = 133, ///< MTU3
TGIA4 = 134, ///< MTU4
TGIB4 = 135, ///< MTU4
TGIC4 = 136, ///< MTU4
TGID4 = 137, ///< MTU4
TCIV4 = 138, ///< MTU4
TGIU5 = 139, ///< MTU5
TGIV5 = 140, ///< MTU5
TGIW5 = 141, ///< MTU5
TGIA6 = 142, ///< MTU6
TGIB6 = 143, ///< MTU6
TGIC6 = 144, ///< MTU6
TGID6 = 145, ///< MTU6
TCIV6 = 146, ///< MTU6
TGIA7 = 149, ///< MTU7
TGIB7 = 150, ///< MTU7
TGIC7 = 151, ///< MTU7
TGID7 = 152, ///< MTU7
TCIV7 = 153, ///< MTU7
TGIA9 = 159, ///< MTU9
TGIB9 = 160, ///< MTU9
TGIC9 = 161, ///< MTU9
TGID9 = 162, ///< MTU9
TCIV9 = 163, ///< MTU9
TGIE9 = 164, ///< MTU9
TGIF9 = 165, ///< MTU9
OEI1 = 168, ///< POE
OEI2 = 169, ///< POE
OEI3 = 170, ///< POE
OEI4 = 171, ///< POE
OEI5 = 172, ///< POE
CMPC3 = 173, ///< CMPC3
CMIA0 = 174, ///< TMR0: CMIA0
CMIB0 = 175, ///< TMR0: CMIB0
OVI0 = 176, ///< TMR0: OVI0
CMIA1 = 177, ///< TMR1: CMIA1
CMIB1 = 178, ///< TMR1: CMIB1
OVI1 = 179, ///< TMR1: OVI1
CMIA2 = 180, ///< TMR2: CMIA2
CMIB2 = 181, ///< TMR2: CMIB2
OVI2 = 182, ///< TMR2: OVI2
CMIA3 = 183, ///< TMR3: CMIA3
CMIB3 = 184, ///< TMR3: CMIB3
OVI3 = 185, ///< TMR3: OVI3
CMIA4 = 186, ///< TMR4: CMIA4
CMIB4 = 187, ///< TMR4: CMIB4
OVI4 = 188, ///< TMR4: OVI4
CMIA5 = 189, ///< TMR5: CMIA5
CMIB5 = 190, ///< TMR5: CMIB5
OVI5 = 191, ///< TMR5: OVI5
CMIA6 = 192, ///< TMR6: CMIA6
CMIB6 = 193, ///< TMR6: CMIB6
OVI6 = 194, ///< TMR6: OVI6
CMIA7 = 195, ///< TMR7: CMIA7
CMIB7 = 196, ///< TMR7: CMIB7
OVI7 = 197, ///< TMR7: OVI7
ERI1 = 218, ///< SCI1
RXI1 = 219, ///< SCI1
TXI1 = 220, ///< SCI1
TEI1 = 221, ///< SCI1
ERI5 = 222, ///< SCI5
RXI5 = 223, ///< SCI5
TXI5 = 224, ///< SCI5
TEI5 = 225, ///< SCI5
ERI6 = 226, ///< SCI6
RXI6 = 227, ///< SCI6
TXI6 = 228, ///< SCI6
TEI6 = 229, ///< SCI6
RIIC_EEI0 = 246, ///< RIIC0
RIIC_RXI0 = 247, ///< RIIC0
RIIC_TXI0 = 248, ///< RIIC0
RIIC_TEI0 = 249, ///< RIIC0
};
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief グループベクターの取得 @n
RX24T はグループベクターをサポートしない為「NONE」を返す
@param[in] VEC グループベクター型
@return グループベクター
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
static VECTOR get_group_vector(VECTOR ivec) noexcept {
return VECTOR::NONE;
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief IR レジスタ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t base>
struct ir_t {
rw8_t<base + 27> SWINT;
rw8_t<base + 28> CMI0;
rw8_t<base + 29> CMI1;
rw8_t<base + 30> CMI2;
rw8_t<base + 31> CMI3;
rw8_t<base + 44> SPEI0;
rw8_t<base + 45> SPRI0;
rw8_t<base + 46> SPTI0;
rw8_t<base + 47> SPII0;
rw8_t<base + 102> S12ADI;
rw8_t<base + 103> GBADI;
rw8_t<base + 104> GCADI;
rw8_t<base + 105> S12ADI1;
rw8_t<base + 106> GBADI1;
rw8_t<base + 107> GCADI1;
rw8_t<base + 108> CMPC0;
rw8_t<base + 109> CMPC1;
rw8_t<base + 110> CMPC2;
rw8_t<base + 111> S12ADI2;
rw8_t<base + 112> GBADI2;
rw8_t<base + 113> GCADI2;
rw8_t<base + 114> TGIA0;
rw8_t<base + 115> TGIB0;
rw8_t<base + 116> TGIC0;
rw8_t<base + 117> TGID0;
rw8_t<base + 118> TCIV0;
rw8_t<base + 119> TGIE0;
rw8_t<base + 120> TGIF0;
rw8_t<base + 121> TGIA1;
rw8_t<base + 122> TGIB1;
rw8_t<base + 123> TCIV1;
rw8_t<base + 124> TCIU1;
rw8_t<base + 125> TGIA2;
rw8_t<base + 126> TGIB2;
rw8_t<base + 127> TCIV2;
rw8_t<base + 128> TCIU2;
rw8_t<base + 129> TGIA3;
rw8_t<base + 130> TGIB3;
rw8_t<base + 131> TGIC3;
rw8_t<base + 132> TGID3;
rw8_t<base + 133> TCIV3;
rw8_t<base + 134> TGIA4;
rw8_t<base + 135> TGIB4;
rw8_t<base + 136> TGIC4;
rw8_t<base + 137> TGID4;
rw8_t<base + 138> TCIV4;
rw8_t<base + 139> TGIU5;
rw8_t<base + 140> TGIV5;
rw8_t<base + 141> TGIW5;
rw8_t<base + 142> TGIA6;
rw8_t<base + 143> TGIB6;
rw8_t<base + 144> TGIC6;
rw8_t<base + 145> TGID6;
rw8_t<base + 146> TCIV6;
rw8_t<base + 149> TGIA7;
rw8_t<base + 150> TGIB7;
rw8_t<base + 151> TGIC7;
rw8_t<base + 152> TGID7;
rw8_t<base + 153> TCIV7;
rw8_t<base + 159> TGIA9;
rw8_t<base + 160> TGIB9;
rw8_t<base + 161> TGIC9;
rw8_t<base + 162> TGID9;
rw8_t<base + 163> TCIV9;
rw8_t<base + 164> TGIE9;
rw8_t<base + 165> TGIF9;
rw8_t<base + 168> OEI1;
rw8_t<base + 169> OEI2;
rw8_t<base + 170> OEI3;
rw8_t<base + 171> OEI4;
rw8_t<base + 172> OEI5;
rw8_t<base + 174> CMIA0;
rw8_t<base + 175> CMIB0;
rw8_t<base + 176> OVI0;
rw8_t<base + 177> CMIA1;
rw8_t<base + 178> CMIB1;
rw8_t<base + 179> OVI1;
rw8_t<base + 180> CMIA2;
rw8_t<base + 181> CMIB2;
rw8_t<base + 182> OVI2;
rw8_t<base + 183> CMIA3;
rw8_t<base + 184> CMIB3;
rw8_t<base + 185> OVI3;
rw8_t<base + 186> CMIA4;
rw8_t<base + 187> CMIB4;
rw8_t<base + 188> OVI4;
rw8_t<base + 189> CMIA5;
rw8_t<base + 190> CMIB5;
rw8_t<base + 191> OVI5;
rw8_t<base + 192> CMIA6;
rw8_t<base + 193> CMIB6;
rw8_t<base + 194> OVI6;
rw8_t<base + 195> CMIA7;
rw8_t<base + 196> CMIB7;
rw8_t<base + 197> OVI7;
rw8_t<base + 218> ERI1;
rw8_t<base + 219> RXI1;
rw8_t<base + 220> TXI1;
rw8_t<base + 221> TEI1;
rw8_t<base + 222> ERI5;
rw8_t<base + 223> RXI5;
rw8_t<base + 224> TXI5;
rw8_t<base + 225> TEI5;
rw8_t<base + 226> ERI6;
rw8_t<base + 227> RXI6;
rw8_t<base + 228> TXI6;
rw8_t<base + 229> TEI6;
rw8_t<base + 246> RIIC_EEI0;
rw8_t<base + 247> RIIC_RXI0;
rw8_t<base + 248> RIIC_TXI0;
rw8_t<base + 249> RIIC_TEI0;
};
static ir_t<0x00087010> IR;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief IER レジスタ
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t base>
struct ier_t {
typedef rw8_t<base + 0x02> ier02;
bit_rw_t<ier02, bitpos::B0> BUSERR;
bit_rw_t<ier02, bitpos::B7> FRDYI;
typedef rw8_t<base + 0x03> ier03;
bit_rw_t<ier03, bitpos::B3> SWINT;
bit_rw_t<ier03, bitpos::B4> CMI0;
bit_rw_t<ier03, bitpos::B5> CMI1;
bit_rw_t<ier03, bitpos::B6> CMI2;
bit_rw_t<ier03, bitpos::B7> CMI3;
typedef rw8_t<base + 0x05> ier05;
bit_rw_t<ier03, bitpos::B4> SPEI0;
bit_rw_t<ier03, bitpos::B5> SPRI0;
bit_rw_t<ier03, bitpos::B6> SPTI0;
bit_rw_t<ier03, bitpos::B7> SPII0;
typedef rw8_t<base + 0x08> ier08;
bit_rw_t<ier08, bitpos::B0> IRQ0;
bit_rw_t<ier08, bitpos::B1> IRQ1;
bit_rw_t<ier08, bitpos::B2> IRQ2;
bit_rw_t<ier08, bitpos::B3> IRQ3;
bit_rw_t<ier08, bitpos::B4> IRQ4;
bit_rw_t<ier08, bitpos::B5> IRQ5;
bit_rw_t<ier08, bitpos::B6> IRQ6;
bit_rw_t<ier08, bitpos::B7> IRQ7;
typedef rw8_t<base + 0x0C> ier0c;
bit_rw_t<ier0c, bitpos::B6> S12ADI;
bit_rw_t<ier0c, bitpos::B7> GBADI;
typedef rw8_t<base + 0x0D> ier0d;
bit_rw_t<ier0d, bitpos::B0> GCADI;
bit_rw_t<ier0d, bitpos::B1> S12ADI1;
bit_rw_t<ier0d, bitpos::B2> GBADI1;
bit_rw_t<ier0d, bitpos::B3> GCADI1;
bit_rw_t<ier0d, bitpos::B4> CMPC0;
bit_rw_t<ier0d, bitpos::B5> CMPC1;
bit_rw_t<ier0d, bitpos::B6> CMPC2;
bit_rw_t<ier0d, bitpos::B7> S12ADI2;
typedef rw8_t<base + 0x0E> ier0e;
bit_rw_t<ier0e, bitpos::B0> GBADI2;
bit_rw_t<ier0e, bitpos::B1> GCADI2;
bit_rw_t<ier0e, bitpos::B2> TGIA0;
bit_rw_t<ier0e, bitpos::B3> TGIB0;
bit_rw_t<ier0e, bitpos::B4> TGIC0;
bit_rw_t<ier0e, bitpos::B5> TGID0;
bit_rw_t<ier0e, bitpos::B6> TCIV0;
bit_rw_t<ier0e, bitpos::B7> TGIE0;
typedef rw8_t<base + 0x0F> ier0f;
bit_rw_t<ier0f, bitpos::B0> TGIF0;
bit_rw_t<ier0f, bitpos::B1> TGIA1;
bit_rw_t<ier0f, bitpos::B2> TGIB1;
bit_rw_t<ier0f, bitpos::B3> TCIV1;
bit_rw_t<ier0f, bitpos::B4> TCIU1;
bit_rw_t<ier0f, bitpos::B5> TGIA2;
bit_rw_t<ier0f, bitpos::B6> TGIB2;
bit_rw_t<ier0f, bitpos::B7> TCIV2;
typedef rw8_t<base + 0x10> ier10;
bit_rw_t<ier10, bitpos::B0> TCIU2;
bit_rw_t<ier10, bitpos::B1> TGIA3;
bit_rw_t<ier10, bitpos::B2> TGIB3;
bit_rw_t<ier10, bitpos::B3> TGIC3;
bit_rw_t<ier10, bitpos::B4> TGID3;
bit_rw_t<ier10, bitpos::B5> TCIV3;
bit_rw_t<ier10, bitpos::B6> TGIA4;
bit_rw_t<ier10, bitpos::B7> TGIB4;
typedef rw8_t<base + 0x11> ier11;
bit_rw_t<ier11, bitpos::B0> TGIC4;
bit_rw_t<ier11, bitpos::B1> TGID4;
bit_rw_t<ier11, bitpos::B2> TCIV4;
bit_rw_t<ier11, bitpos::B3> TGIU5;
bit_rw_t<ier11, bitpos::B4> TGIV5;
bit_rw_t<ier11, bitpos::B5> TGIW5;
typedef rw8_t<base + 0x12> ier12;
bit_rw_t<ier11, bitpos::B6> TGIA6;
bit_rw_t<ier11, bitpos::B7> TGIB6;
bit_rw_t<ier12, bitpos::B0> TGIC6;
bit_rw_t<ier12, bitpos::B1> TGID6;
bit_rw_t<ier12, bitpos::B2> TCIV6;
bit_rw_t<ier12, bitpos::B5> TGIA7;
bit_rw_t<ier12, bitpos::B6> TGIB7;
bit_rw_t<ier12, bitpos::B7> TGIC7;
typedef rw8_t<base + 0x13> ier13;
bit_rw_t<ier13, bitpos::B0> TGID7;
bit_rw_t<ier13, bitpos::B1> TCIV7;
bit_rw_t<ier13, bitpos::B7> TGIA9;
typedef rw8_t<base + 0x14> ier14;
bit_rw_t<ier14, bitpos::B0> TGIB9;
bit_rw_t<ier14, bitpos::B1> TGIC9;
bit_rw_t<ier14, bitpos::B2> TGID9;
bit_rw_t<ier14, bitpos::B3> TCIV9;
bit_rw_t<ier14, bitpos::B4> TGIE9;
bit_rw_t<ier14, bitpos::B5> TGIF9;
typedef rw8_t<base + 0x15> ier15;
bit_rw_t<ier15, bitpos::B0> OEI1;
bit_rw_t<ier15, bitpos::B1> OEI2;
bit_rw_t<ier15, bitpos::B2> OEI3;
bit_rw_t<ier15, bitpos::B3> OEI4;
bit_rw_t<ier15, bitpos::B4> OEI5;
bit_rw_t<ier15, bitpos::B6> CMIA0;
bit_rw_t<ier15, bitpos::B7> CMIB0;
typedef rw8_t<base + 0x16> ier16;
bit_rw_t<ier16, bitpos::B0> OVI0;
bit_rw_t<ier16, bitpos::B1> CMIA1;
bit_rw_t<ier16, bitpos::B2> CMIB1;
bit_rw_t<ier16, bitpos::B3> OVI1;
bit_rw_t<ier16, bitpos::B4> CMIA2;
bit_rw_t<ier16, bitpos::B5> CMIB2;
bit_rw_t<ier16, bitpos::B6> OVI2;
bit_rw_t<ier16, bitpos::B7> CMIA3;
typedef rw8_t<base + 0x17> ier17;
bit_rw_t<ier17, bitpos::B0> CMIB3;
bit_rw_t<ier17, bitpos::B1> OVI3;
bit_rw_t<ier17, bitpos::B2> CMIA4;
bit_rw_t<ier17, bitpos::B3> CMIB4;
bit_rw_t<ier17, bitpos::B4> OVI4;
bit_rw_t<ier17, bitpos::B5> CMIA5;
bit_rw_t<ier17, bitpos::B6> CMIB5;
bit_rw_t<ier17, bitpos::B7> OVI5;
typedef rw8_t<base + 0x18> ier18;
bit_rw_t<ier18, bitpos::B0> CMIA6;
bit_rw_t<ier18, bitpos::B1> CMIB6;
bit_rw_t<ier18, bitpos::B2> OVI6;
bit_rw_t<ier18, bitpos::B3> CMIA7;
bit_rw_t<ier18, bitpos::B4> CMIB7;
bit_rw_t<ier18, bitpos::B5> OVI7;
typedef rw8_t<base + 0x1B> ier1b;
bit_rw_t<ier1b, bitpos::B2> ERI1;
bit_rw_t<ier1b, bitpos::B3> RXI1;
bit_rw_t<ier1b, bitpos::B4> TXI1;
bit_rw_t<ier1b, bitpos::B5> TEI1;
bit_rw_t<ier1b, bitpos::B6> ERI5;
bit_rw_t<ier1b, bitpos::B7> RXI5;
typedef rw8_t<base + 0x1C> ier1c;
bit_rw_t<ier1c, bitpos::B0> TXI5;
bit_rw_t<ier1c, bitpos::B1> TEI5;
bit_rw_t<ier1c, bitpos::B2> ERI6;
bit_rw_t<ier1c, bitpos::B3> RXI6;
bit_rw_t<ier1c, bitpos::B4> TXI6;
bit_rw_t<ier1c, bitpos::B5> TEI6;
typedef rw8_t<base + 0x1E> ier1e;
bit_rw_t<ier1e, bitpos::B6> RIIC_EEI0;
bit_rw_t<ier1e, bitpos::B7> RIIC_RXI0;
typedef rw8_t<base + 0x1F> ier1f;
bit_rw_t<ier1f, bitpos::B0> RIIC_TXI0;
bit_rw_t<ier1f, bitpos::B1> RIIC_TEI0;
};
static ier_t<0x00087200> IER;
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
/*!
@brief IPR レジスタ @n
全て、下位4ビットが有効
*/
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
template <uint32_t base>
struct ipr_t {
rw8_t<base + 3 > SWINT;
rw8_t<base + 4 > CMI0;
rw8_t<base + 5 > CMI1;
rw8_t<base + 6 > CMI2;
rw8_t<base + 7 > CMI3;
rw8_t<base + 44 > RSPI0;
rw8_t<base + 102> S12ADI; ///< S12AD
rw8_t<base + 103> GBADI;
rw8_t<base + 104> GCADI;
rw8_t<base + 105> S12ADI1; ///< S12AD1
rw8_t<base + 106> GBADI1;
rw8_t<base + 107> GCADI1;
rw8_t<base + 108> CMPC0;
rw8_t<base + 109> CMPC1;
rw8_t<base + 110> CMPC2;
rw8_t<base + 111> S12ADI2; ///< S12AD2
rw8_t<base + 112> GBADI2;
rw8_t<base + 113> GCADI2;
rw8_t<base + 114> MTU0_ABCD; ///< MTU0
rw8_t<base + 118> MTU0_VEF; ///< MTU0
rw8_t<base + 121> MTU1_AB; ///< MTU1
rw8_t<base + 123> MTU1_VU; ///< MTU1
rw8_t<base + 125> MTU2_AB; ///< MTU2
rw8_t<base + 127> MTU2_VU; ///< MTU2
rw8_t<base + 129> MTU3_ABCD; ///< MTU3
rw8_t<base + 133> MTU3_V; ///< MTU3
rw8_t<base + 134> MTU4_ABCD; ///< MTU4
rw8_t<base + 138> MTU4_V; ///< MTU4
rw8_t<base + 139> MTU5_UVW; ///< MTU5
rw8_t<base + 142> MTU6_ABCD; ///< MTU6
rw8_t<base + 146> MTU6_V; ///< MTU6
rw8_t<base + 149> MTU7_AB; ///< MTU7
rw8_t<base + 151> MTU7_CD; ///< MTU7
rw8_t<base + 153> MTU7_V; ///< MTU7
rw8_t<base + 159> MTU9_ABCD; ///< MTU9
rw8_t<base + 163> MTU9_VEF; ///< MTU9
rw8_t<base + 168> OEI1; ///< POE
rw8_t<base + 169> OEI2; ///< POE
rw8_t<base + 170> OEI3; ///< POE
rw8_t<base + 171> OEI4; ///< POE
rw8_t<base + 172> OEI5; ///< POE
rw8_t<base + 174> TMR0; ///< TMR0
rw8_t<base + 177> TMR1; ///< TMR1
rw8_t<base + 180> TMR2; ///< TMR2
rw8_t<base + 183> TMR3; ///< TMR3
rw8_t<base + 186> TMR4; ///< TMR4
rw8_t<base + 189> TMR5; ///< TMR5
rw8_t<base + 192> TMR6; ///< TMR6
rw8_t<base + 195> TMR7; ///< TMR7
rw8_t<base + 218> SCI1; ///< SCI1
rw8_t<base + 222> SCI5; ///< SCI5
rw8_t<base + 226> SCI6; ///< SCI6
rw8_t<base + 246> RIIC_EEI0; ///< RIIC0
rw8_t<base + 247> RIIC_RXI0;
rw8_t<base + 248> RIIC_TXI0;
rw8_t<base + 249> RIIC_TEI0;
};
static ipr_t<0x00087300> IPR;
};
typedef icu_t ICU;
}
| 27.967687 | 75 | 0.543205 | [
"vector"
] |
e1b1e0a9c8b5a1089b0b033b787de0bc9c1901e8 | 2,112 | cpp | C++ | tests/juliet/testcases/CWE761_Free_Pointer_Not_at_Start_of_Buffer/CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83_bad.cpp | RanerL/analyzer | a401da4680f163201326881802ee535d6cf97f5a | [
"MIT"
] | 28 | 2017-01-20T15:25:54.000Z | 2020-03-17T00:28:31.000Z | testcases/CWE761_Free_Pointer_Not_at_Start_of_Buffer/CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83_bad.cpp | mellowCS/cwe_checker_juliet_suite | ae604f6fd94964251fbe88ef04d5287f6c1ffbe2 | [
"MIT"
] | 1 | 2017-01-20T15:26:27.000Z | 2018-08-20T00:55:37.000Z | testcases/CWE761_Free_Pointer_Not_at_Start_of_Buffer/CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83_bad.cpp | mellowCS/cwe_checker_juliet_suite | ae604f6fd94964251fbe88ef04d5287f6c1ffbe2 | [
"MIT"
] | 2 | 2019-07-15T19:07:04.000Z | 2019-09-07T14:21:04.000Z | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83_bad.cpp
Label Definition File: CWE761_Free_Pointer_Not_at_Start_of_Buffer.label.xml
Template File: source-sinks-83_bad.tmpl.cpp
*/
/*
* @description
* CWE: 761 Free Pointer not at Start of Buffer
* BadSource: environment Read input from an environment variable
* Sinks:
* GoodSink: free() memory correctly at the start of the buffer
* BadSink : free() memory not at the start of the buffer
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83.h"
#define ENV_VARIABLE "ADD"
#ifdef _WIN32
#define GETENV getenv
#else
#define GETENV getenv
#endif
#define SEARCH_CHAR 'S'
namespace CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83
{
CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83_bad::CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83_bad(char * dataCopy)
{
data = dataCopy;
{
/* Append input from an environment variable to data */
size_t dataLen = strlen(data);
char * environment = GETENV(ENV_VARIABLE);
/* If there is data in the environment variable */
if (environment != NULL)
{
/* POTENTIAL FLAW: Read data from an environment variable */
strncat(data+dataLen, environment, 100-dataLen-1);
}
}
}
CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83_bad::~CWE761_Free_Pointer_Not_at_Start_of_Buffer__char_environment_83_bad()
{
/* FLAW: We are incrementing the pointer in the loop - this will cause us to free the
* memory block not at the start of the buffer */
for (; *data != '\0'; data++)
{
if (*data == SEARCH_CHAR)
{
printLine("We have a match!");
break;
}
}
free(data);
}
}
#endif /* OMITBAD */
| 32.492308 | 154 | 0.699811 | [
"object"
] |
e1b70ca3f45ec2fa3bee14ce6b23aa820d3f256b | 10,020 | cc | C++ | src/game/entities/moveable_component.cc | codeka/ravaged-planets | ab20247b3829414e71b58c9a6e926bddf41f1da5 | [
"Apache-2.0"
] | null | null | null | src/game/entities/moveable_component.cc | codeka/ravaged-planets | ab20247b3829414e71b58c9a6e926bddf41f1da5 | [
"Apache-2.0"
] | null | null | null | src/game/entities/moveable_component.cc | codeka/ravaged-planets | ab20247b3829414e71b58c9a6e926bddf41f1da5 | [
"Apache-2.0"
] | 3 | 2017-07-17T22:24:17.000Z | 2019-10-15T18:37:15.000Z | #include <boost/foreach.hpp>
#include <framework/misc.h>
#include <framework/colour.h>
#include <framework/logging.h>
#include <game/entities/entity.h>
#include <game/entities/entity_manager.h>
#include <game/entities/entity_factory.h>
#include <game/entities/entity_debug.h>
#include <game/entities/moveable_component.h>
#include <game/entities/pathing_component.h>
#include <game/entities/position_component.h>
#include <game/entities/selectable_component.h>
namespace ent {
// register the moveable component with the entity_factory
ENT_COMPONENT_REGISTER("Moveable", moveable_component);
moveable_component::moveable_component() :
_position_component(nullptr), _pathing_component(nullptr), _speed(3.0f), _turn_speed(1.0f),
_avoid_collisions(true), _is_moving(false) {
}
moveable_component::~moveable_component() {
}
void moveable_component::apply_template(luabind::object const &tmpl) {
for (luabind::iterator it(tmpl), end; it != end; ++it) {
if (it.key() == "Speed") {
_speed = luabind::object_cast<float>(*it);
} else if (it.key() == "TurnRadius") {
_turn_speed = 1.0f / luabind::object_cast<float>(*it);
} else if (it.key() == "AvoidCollisions") {
_avoid_collisions = luabind::object_cast<bool>(*it);
}
}
}
void moveable_component::initialize() {
std::shared_ptr<entity> entity(_entity);
_pathing_component = entity->get_component<pathing_component>();
_position_component = entity->get_component<position_component>();
_goal = _position_component->get_position();
_is_moving = false;
}
// TODO: skip_pathing is such a hack
void moveable_component::set_goal(fw::vector goal, bool skip_pathing /*= false*/) {
std::shared_ptr<entity> entity(_entity);
float world_width = entity->get_manager()->get_patch_manager()->get_world_width();
float world_length = entity->get_manager()->get_patch_manager()->get_world_length();
// make sure we constraining the goal to the bounds of the map
_goal = fw::vector(
fw::constrain(goal[0], world_width, 0.0f),
goal[1],
fw::constrain(goal[2], world_length, 0.0f));
if (skip_pathing || _pathing_component == nullptr) {
set_intermediate_goal(_goal);
} else {
_pathing_component->set_goal(_goal);
}
}
void moveable_component::set_intermediate_goal(fw::vector goal) {
std::shared_ptr<entity> entity(_entity);
float world_width = entity->get_manager()->get_patch_manager()->get_world_width();
float world_length = entity->get_manager()->get_patch_manager()->get_world_length();
// make sure we constraining the goal to the bounds of the map
_intermediate_goal = fw::vector(
fw::constrain(goal[0], world_width, 0.0f),
goal[1],
fw::constrain(goal[2], world_length, 0.0f));
_is_moving = true;
}
void moveable_component::stop() {
_is_moving = false;
if (_pathing_component != nullptr) {
_pathing_component->stop();
}
}
void moveable_component::update(float dt) {
if (!_is_moving) {
return;
}
fw::vector pos = _position_component->get_position();
fw::vector goal = _intermediate_goal;
fw::vector dir = _position_component->get_direction_to(goal);
float distance = dir.length();
if (distance < 0.1f) {
// we're close enough to the goal, so just stop!
_is_moving = false;
return;
}
std::shared_ptr<entity> entity(_entity);
bool show_steering = (entity->get_debug_view() != 0 && (entity->get_debug_flags() & debug_show_steering) != 0);
// if we're avoiding obstacles, we'll need to figure out what is the closest entity to us
if (_avoid_collisions) {
std::shared_ptr<ent::entity> obstacle = _position_component->get_nearest_entity().lock();
if (obstacle) {
fw::vector obstacle_dir = _position_component->get_direction_to(obstacle);
float obstacle_distance = obstacle_dir.length();
// only worry about the obstacle when it's in front of us
float d = cml::dot(cml::normalize(_position_component->get_direction()), cml::normalize(obstacle_dir));
// fw::debug << "cml::dot(_position_component->get_direction(), obstacle_dir) = " << d << std::endl;
if (d > 0.0f) {
// if they're selectable, reduce the distance by their selection radius - that's what we ACTUALLY want to
// avoid...
float obstacle_radius = 1.0f;
selectable_component *their_selectable = obstacle->get_component<selectable_component>();
if (their_selectable != nullptr) {
obstacle_radius = their_selectable->get_selection_radius();
obstacle_distance -= obstacle_radius;
}
// only worry about the obstacle if we're closer to it than to the goal...
if (obstacle_distance < (obstacle_radius * 2.0f) && obstacle_distance < distance) {
fw::vector obstacle_pos = pos + obstacle_dir;
if (show_steering) {
// draw a circle around whatever we're trying to avoid
entity->get_debug_view()->add_circle(obstacle_pos, obstacle_radius * 2.0f, fw::colour(1, 0, 0));
}
// temporarily adjust the "goal" so as to avoid the obstacle
fw::vector up = cml::cross(_position_component->get_direction(), obstacle_dir);
if (up.length_squared() < 0.01f) {
// if they're *directly* in front of us, just choose a random direction, left or right. we'll choose... left
up = fw::vector(0, 1, 0);
}
fw::vector avoid_dir = cml::cross(cml::normalize(_position_component->get_direction()), cml::normalize(up));
if (show_steering) {
// draw a blue line from the obstacle in the direction we're going to travel to avoid it.
entity->get_debug_view()->add_line(
obstacle_pos, obstacle_pos + (avoid_dir * (obstacle_radius * 2.0f)), fw::colour(0, 0, 1));
}
// our new goal is just in front of where we are now, but offset by what we're trying to avoid.
goal = _position_component->get_direction() + obstacle_pos + (avoid_dir * (obstacle_radius * 2.0f));
dir = _position_component->get_direction_to(goal);
distance = dir.length();
}
}
}
}
float speed = _speed;
float turn_speed = _turn_speed;
// adjust the speed and turn speed so that we slow down and turn faster when we get close
// (gives us a smaller turning circle, to ensure we don't overshoot the target)
float turn_radius = 1.0f / _turn_speed;
float scale_factor = distance / (turn_radius / 0.25f);
if (show_steering) {
// a line from us to the goal
entity->get_debug_view()->add_line(pos, goal, fw::colour(0, 1, 0));
}
if (scale_factor < 1.0f) {
speed *= (scale_factor < 0.75f ? 0.75f : scale_factor);
turn_speed *= 1.0f / (scale_factor < 0.25f ? 0.25f : scale_factor);
}
// turn towards the goal
dir = steer(_position_component->get_position(),
_position_component->get_direction(), dir, turn_speed * dt, show_steering);
// move in the direction we're facing
pos += (dir * dt * speed);
_position_component->set_direction(dir);
_position_component->set_position(pos);
}
// applies a steering factor to the "curr_direction" so that we slowly turn towards the goal_direction.
//
// if show_steering is true, we use the entity's debug_view (which we assume is non-NULL
// to display the relevent steering vectors.
fw::vector moveable_component::steer(fw::vector pos, fw::vector curr_direction, fw::vector goal_direction,
float turn_amount, bool show_steering) {
curr_direction.normalize();
goal_direction.normalize();
// If we're almost facing the right direction already, just point straight towards the goal, no steering.
if (cml::dot(curr_direction, goal_direction) > 0.95f) {
return goal_direction;
}
// so, to work out the steering factor, we start off by rotating the direction vector clockwise 90 degrees...
fw::vector up = cml::cross(curr_direction, goal_direction);
fw::matrix rotation = fw::rotate_axis_angle(up, static_cast<float>(M_PI / 2.0));
fw::vector steer = cml::transform_vector(rotation, curr_direction).normalize();
// now, if the angle between steer and the goal is greater than 90,
// we need to steer in the other direction.
steer = cml::dot(steer, goal_direction) < 0.0f ? steer * -1.0f : steer;
if (show_steering) {
std::shared_ptr<entity> entity(_entity);
entity_debug_view *edv = entity->get_debug_view();
// draw the current "up" and "forward" vectors
edv->add_line(pos, pos + up, fw::colour(1, 1, 1));
edv->add_line(pos, pos + curr_direction, fw::colour(1, 1, 1));
// draw the "steering" vector which is the direction we're going to steer in
entity->get_debug_view()->add_line(pos, pos + steer, fw::colour(0, 1, 1));
}
// adjust the amount of steering by the turn_amount. The higher the turn amount, the more we try to steer (we assume
// turn_amount is already scaled by the time delta for this frame)
steer *= turn_amount;
// adjust our current heading by applying a steering factor
fw::vector new_direction = (curr_direction + steer);
new_direction.normalize();
// if the new direction is on the other side of the goal_direction to the current
// direction, that means we'd be over-steering. rather than do that (and wobble), we'll
// just start heading straight for the goal.
fw::vector old_direction = curr_direction;
fw::vector rotated = cml::transform_vector(rotation, goal_direction).normalize();
float old_direction_dot = cml::dot(old_direction, rotated);
float new_direction_dot = cml::dot(new_direction, rotated);
if ((old_direction_dot < 0 && new_direction_dot > 0) || (old_direction_dot > 0 && new_direction_dot < 0)) {
return goal_direction;
} else {
return new_direction;
}
}
}
| 41.065574 | 121 | 0.673852 | [
"object",
"vector"
] |
e1b773229f0a2882866166172ab27b402295ae46 | 1,269 | cpp | C++ | src/fsm-editor/node.cpp | AsuMagic/centauri-fsm-editor | 0830969dd0c1548870ab71efa8b36a77fc40dbd4 | [
"MIT"
] | null | null | null | src/fsm-editor/node.cpp | AsuMagic/centauri-fsm-editor | 0830969dd0c1548870ab71efa8b36a77fc40dbd4 | [
"MIT"
] | null | null | null | src/fsm-editor/node.cpp | AsuMagic/centauri-fsm-editor | 0830969dd0c1548870ab71efa8b36a77fc40dbd4 | [
"MIT"
] | null | null | null | #include "node.hpp"
#include <algorithm>
#include "editor.hpp"
namespace fsme
{
Node::Node(FsmEditor& editor, ed::NodeId id) :
m_editor(&editor),
m_id(id)
{}
Node::~Node()
{
resize_pins(m_inputs, 0);
resize_pins(m_outputs, 0);
}
int Node::pin_index_or_default(ed::PinId needle, const std::vector<ed::PinId>& haystack, int if_not_found) const
{
const auto it = std::find(haystack.begin(), haystack.end(), needle);
return it != haystack.end() ? std::distance(haystack.begin(), it) : if_not_found;
}
int Node::input_pin_index(ed::PinId id) const
{
return pin_index_or_default(id, m_inputs);
}
int Node::output_pin_index(ed::PinId id) const
{
return pin_index_or_default(id, m_outputs);
}
void Node::resize_pins(std::vector<ed::PinId>& pins, std::size_t to_size)
{
const std::size_t old_size = pins.size();
// Unbind old IDs
for (std::size_t i = to_size; i < old_size; ++i)
{
m_editor->destroy_pin(pins[i]);
}
pins.resize(to_size);
// Allocate new IDs as required
for (std::size_t i = old_size; i < to_size; ++i)
{
pins[i] = m_editor->create_pin(node_id());
}
}
std::vector<ed::PinId>::iterator Node::erase_pin(std::vector<ed::PinId>& pins, std::vector<ed::PinId>::iterator it)
{
m_editor->destroy_pin(*it);
return pins.erase(it);
}
}
| 20.142857 | 115 | 0.688731 | [
"vector"
] |
e1bc2b3b4192082461b089a065de56f91393f62f | 4,465 | cpp | C++ | src/showsheets.cpp | DBHeise/ShowSheets | e73d818af244761a097aa72b63ea0cdd590f7800 | [
"MIT"
] | 12 | 2019-11-22T21:59:12.000Z | 2021-03-17T03:04:55.000Z | src/showsheets.cpp | DBHeise/ShowSheets | e73d818af244761a097aa72b63ea0cdd590f7800 | [
"MIT"
] | null | null | null | src/showsheets.cpp | DBHeise/ShowSheets | e73d818af244761a097aa72b63ea0cdd590f7800 | [
"MIT"
] | 1 | 2020-07-17T07:35:51.000Z | 2020-07-17T07:35:51.000Z |
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <fstream>
#include <string>
#include <vector>
#include "pole.h"
void showUsage() {
std::cout << "showsheets {file}" << std::endl;
}
enum class fileType : unsigned char {
OLESS,
ZIP,
Other
};
fileType ReadFileType(std::string file) {
std::ifstream stream(file, std::ios::binary | std::ios::ate);
if (stream.is_open()) {
char buffer[4];
stream.seekg(0, std::ios::beg);
stream.read(buffer, 4);
stream.close();
if (((unsigned char)buffer[0]) == 0xD0 && ((unsigned char)buffer[1]) == 0xCF && ((unsigned char)buffer[2]) == 0x11 && ((unsigned char)buffer[3]) == 0xE0) {
return fileType::OLESS;
} else if (((unsigned char)buffer[0]) == 0x50 && ((unsigned char)buffer[1]) == 0x4B) {
return fileType::ZIP;
}
}
return fileType::Other;
}
struct RecordHeader {
unsigned short Type;
unsigned short Length;
};
// see: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/b9ec509a-235d-424e-871d-f8e721106501
struct BoundSheetHeader {
unsigned int lbPlyPos;
unsigned short hsState : 2;
unsigned short unused1 : 6;
unsigned short dt : 8;
};
// see: https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-xls/05162858-0ca9-44cb-bb07-a720928f63f8
struct ShortXLUnicodeString {
unsigned char cch;
unsigned short fHighByte : 1;
unsigned short reserved1 : 7;
std::string rgb;
static ShortXLUnicodeString Read(const unsigned char* buffer, const unsigned int offset) {
ShortXLUnicodeString ans;
unsigned int index = offset;
ans.cch = buffer[index];
index += 1;
ans.fHighByte = buffer[index] & 128;
ans.reserved1 = buffer[index] & 127;
index++;
int byteCount = 0;
if (ans.fHighByte == 0x0) {
byteCount = ans.cch;
}
else {
byteCount = ans.cch * 2;
}
std::string name(reinterpret_cast<char const*>(buffer + index), byteCount);
ans.rgb = name;
return ans;
}
};
std::string GetVisibilityStr(unsigned short visibility) {
std::string ans;
switch (visibility) {
case 0x00: ans = "Visible"; break;
case 0x01: ans = "Hidden"; break;
case 0x02: ans = "Very Hidden"; break;
default: ans = "Unknown/Undocumented visiblitiy"; break;
}
return ans;
}
void makeSheetsVisible(std::string xlsFile) {
POLE::Storage* storage = new POLE::Storage(xlsFile.c_str());
storage->open(true, false);
if (storage->result() == POLE::Storage::Ok) {
std::list<std::string> entries;
entries = storage->entries("/");
std::list<std::string>::iterator it;
for (it = entries.begin(); it != entries.end(); it++) {
std::string name = *it;
if (name == "Workbook" || name == "Book" || name == "WorkBook") {
POLE::Stream* stream = new POLE::Stream(storage, "/" + name);
unsigned char recordHeader[4];
while (! stream->eof()) {
auto bytesRead = stream->read(recordHeader, 4);
if (bytesRead != 4) {
break;
}
else {
auto header = reinterpret_cast<RecordHeader*>(recordHeader);
unsigned char* block = new unsigned char[header->Length];
bytesRead = stream->read(block, header->Length);
if (bytesRead == header->Length) {
if (header->Type == 0x0085) { //BoundSheet
auto bs = reinterpret_cast<BoundSheetHeader*>(block);
auto name = ShortXLUnicodeString::Read(block, 6);
std::cout << "Sheet: \"" << name.rgb << "\", Visiblity: \"" << GetVisibilityStr(bs->hsState) << "\"" << std::endl;
if (bs->hsState != 0) {
bs->hsState = 0;
auto pos = stream->tell();
stream->seek(pos-(header->Length));
auto bytesWritten = stream->write(block, 6);
if (bytesWritten != 6) {
std::cout << "Could not write to stream!" << std::endl;
}
stream->seek(pos);
}
}
}
delete[] block;
}
}
stream->flush();
delete stream;
}
}
}
else {
std::cerr << "Could not open file as OLESS file for writing" << std::endl;
}
storage->close();
delete storage;
}
int main(int argc, char* argv[])
{
std::vector<std::string> arguments(argv + 1, argv + argc);
if (argc > 1) {
auto file = arguments[0];
auto ftype = ReadFileType(file);
if (ftype == fileType::OLESS) {
makeSheetsVisible(file);
} else if (ftype == fileType::ZIP) {
std::cerr << "I HAVEN'T DONE THIS WORK YET!!" << std::endl;
} else {
std::cerr << "Unsupported file type" << std::endl;
}
}
else {
showUsage();
}
return 0;
}
| 24.668508 | 157 | 0.62486 | [
"vector"
] |
e1bf9aecb392f48b5a622e3f981b3d70f2e7ac9a | 404 | cpp | C++ | chapters/3/3-23.cpp | Raymain1944/CPPLv1 | 96e5fd5347a336870fc868206ebfe44f88ce69eb | [
"Apache-2.0"
] | null | null | null | chapters/3/3-23.cpp | Raymain1944/CPPLv1 | 96e5fd5347a336870fc868206ebfe44f88ce69eb | [
"Apache-2.0"
] | null | null | null | chapters/3/3-23.cpp | Raymain1944/CPPLv1 | 96e5fd5347a336870fc868206ebfe44f88ce69eb | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using std::cin; using std::cout; using std::endl;
using std::string;
using std::vector;
int main()
{
vector<int> numbers(10, 3);
for (auto &x : numbers){
cout << x << endl;
}
for (auto it = numbers.begin(); it != numbers.end(); ++it){
*it *= 2;
}
for (auto &x : numbers){
cout << x << endl;
}
} | 19.238095 | 63 | 0.534653 | [
"vector"
] |
e1c6254a637a5d816ea2ae00f3a608513e0d1f6b | 406 | cpp | C++ | Notes/ZhangZhao/Code/test1.cpp | zyy1225/OSproject-miniprogram2020 | 4dc73c9ade682a9accc0e62d107ee0dae593cf01 | [
"Apache-2.0"
] | 3 | 2020-09-23T14:19:22.000Z | 2020-09-25T16:27:41.000Z | Notes/ZhangZhao/Code/test1.cpp | zyy1225/OSproject-miniprogram2020 | 4dc73c9ade682a9accc0e62d107ee0dae593cf01 | [
"Apache-2.0"
] | 1 | 2020-09-25T16:31:32.000Z | 2020-09-28T14:56:21.000Z | Notes/ZhangZhao/Code/test1.cpp | zyy1225/OSproject-miniprogram2020 | 4dc73c9ade682a9accc0e62d107ee0dae593cf01 | [
"Apache-2.0"
] | 2 | 2020-09-25T14:51:36.000Z | 2020-09-25T16:29:27.000Z | #include <iostream>
//#include <vector>
//#include <string>
//#include <algorithm>
using namespace std;
int main(){
int n;
scanf("%d", &n);
while(n > 0){
//vector<int> num(n, 0);
int sum = 0, Max = INT_MIN;
for(int i = 0; i < n; ++i){
int tmp;
cin >> tmp;
if(sum >= 0) sum += tmp;
else sum = tmp;
Max = max(Max, sum);
}
printf("%d\n", Max);
scanf("%d", &n);
}
return 0;
}
| 16.24 | 29 | 0.522167 | [
"vector"
] |
e1d7dc6aa99eb1da7ef743cbe01ac3697ee64444 | 33,789 | cpp | C++ | src/python.cpp | elkebir-group/OncoSim | 1707709c21f8f54ed7ebff9272f5b159f05a8ee5 | [
"BSD-3-Clause"
] | null | null | null | src/python.cpp | elkebir-group/OncoSim | 1707709c21f8f54ed7ebff9272f5b159f05a8ee5 | [
"BSD-3-Clause"
] | null | null | null | src/python.cpp | elkebir-group/OncoSim | 1707709c21f8f54ed7ebff9272f5b159f05a8ee5 | [
"BSD-3-Clause"
] | 3 | 2018-10-08T19:53:58.000Z | 2021-11-08T01:44:37.000Z | /*
* python.cpp
*
* Created on: 21-may-2018
* Author: M. El-Kebir
*/
#include <boost/scoped_array.hpp>
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <boost/python/args.hpp>
#include <boost/python/stl_iterator.hpp>
#include <armadillo>
#include <iostream>
#include <fstream>
#include "utils.h"
#include "simulation.h"
#include "mutclonetree.h"
#include "readmatrix.h"
#include "generatemixture.h"
#include "enumeratemutationtrees.h"
namespace p = boost::python;
template<typename T>
inline
std::vector< T > py_list_to_std_vector( const boost::python::object& iterable )
{
return std::vector< T >( boost::python::stl_input_iterator< T >( iterable ),
boost::python::stl_input_iterator< T >( ) );
}
void simulate(std::string outputDirectory = ".",
p::dict args = p::dict())
{
std::string filenameColorMap;
int seed = 0;
double carryingCapacity = 5e4;
double mutFreqThreshold = 0.05;
double migrationRate = 1e-6;
double mutationRate = 0.1;
double driverRate = 2e-7;
int maxNrAnatomicalSites = 3;
int migrationPattern = 0;
int nrTrials = -1;
int desiredNrMutationClusters = -1;
int sequencingDepth = 200;
int nrSamplesPerAnatomicalSite = 2;
int nrSamplesPrimary = 2;
double sequencingErrorRate = 0;
double purity = 1;
bool verbose = false;
for (const std::string& key : py_list_to_std_vector<std::string>(args.keys()))
{
if (key == "seed")
{
seed = p::extract<int>(args.get(key));
}
else if (key == "carryingCapacity")
{
carryingCapacity = p::extract<double>(args.get(key));
}
else if (key == "mutFreqThreshold")
{
mutFreqThreshold = p::extract<double>(args.get(key));
}
else if (key == "migrationRate")
{
migrationRate = p::extract<double>(args.get(key));
}
else if (key == "mutationRate")
{
mutationRate = p::extract<double>(args.get(key));
}
else if (key == "driverRate")
{
driverRate = p::extract<double>(args.get(key));
}
else if (key == "maxNrAnatomicalSites")
{
maxNrAnatomicalSites = p::extract<int>(args.get(key));
}
else if (key == "migrationPattern")
{
migrationPattern = p::extract<int>(args.get(key));
}
else if (key == "nrTrials")
{
nrTrials = p::extract<int>(args.get(key));
}
else if (key == "desiredNrMutationClusters")
{
desiredNrMutationClusters = p::extract<int>(args.get(key));
}
else if (key == "sequencingDepth")
{
sequencingDepth = p::extract<int>(args.get(key));
}
else if (key == "nrSamplesPerAnatomicalSite")
{
nrSamplesPerAnatomicalSite = p::extract<int>(args.get(key));
}
else if (key == "nrSamplesPrimary")
{
nrSamplesPrimary = p::extract<int>(args.get(key));
}
else if (key == "sequencingErrorRate")
{
sequencingErrorRate = p::extract<double>(args.get(key));
}
else if (key == "purity")
{
purity = p::extract<double>(args.get(key));
}
else if (key == "filenameColorMap")
{
filenameColorMap = p::extract<std::string>(args.get(key));
}
else if (key == "verbose")
{
verbose = p::extract<bool>(args.get(key));
}
}
Simulation::run(outputDirectory, filenameColorMap,
seed, carryingCapacity, mutFreqThreshold,
migrationRate, mutationRate, driverRate,
maxNrAnatomicalSites, migrationPattern,
nrTrials, desiredNrMutationClusters,
sequencingDepth, nrSamplesPerAnatomicalSite, nrSamplesPrimary,
sequencingErrorRate, purity, verbose);
}
std::string visualizeMigrationGraph(std::string filenameInGraph,
std::string filenameInColorMap = "")
{
std::ifstream inG(filenameInGraph);
if (!inG.good())
{
throw std::runtime_error("Error: could not open '"
+ filenameInGraph + "' for reading");
}
MigrationGraph G;
if (!G.read(inG))
{
throw std::runtime_error("Error: invalid format '"
+ filenameInGraph + "'");
}
StringToIntMap colorMap;
if (!filenameInColorMap.empty())
{
std::ifstream inColorMap(filenameInColorMap.c_str());
if (!inColorMap.good())
{
throw std::runtime_error("Error: could not open '"
+ filenameInColorMap + "' for reading");
}
if (!BaseTree::readColorMap(inColorMap, colorMap))
{
throw std::runtime_error("Error: error parsing '"
+ filenameInColorMap + "'");
}
}
else
{
colorMap = G.generateColorMap();
}
std::stringstream ss;
G.writeDOT(ss, colorMap);
return ss.str();
}
std::string visualizeCloneTree(std::string filenameInTree,
std::string filenameInColorMap = "",
std::string filenameInVertexLabeling = "")
{
std::ifstream inT(filenameInTree.c_str());
if (!inT.good())
{
throw std::runtime_error("Error: could not open '"
+ filenameInTree + "' for reading");
}
MutCloneTree T;
inT >> T;
StringToIntMap colorMap;
if (!filenameInColorMap.empty())
{
std::ifstream inColorMap(filenameInColorMap.c_str());
if (!inColorMap.good())
{
throw std::runtime_error("Error: could not open '"
+ filenameInColorMap + "' for reading");
}
if (!BaseTree::readColorMap(inColorMap, colorMap))
{
throw std::runtime_error("Error: error parsing '"
+ filenameInColorMap + "'");
}
}
else
{
colorMap = T.generateColorMap();
}
std::stringstream ss;
if (filenameInVertexLabeling.empty())
{
T.writeDOT(ss, colorMap);
}
else
{
std::ifstream inVertexLabeling(filenameInVertexLabeling.c_str());
if (!inVertexLabeling.good())
{
throw std::runtime_error("Error: could not open '"
+ filenameInVertexLabeling
+ "' for reading");
}
StringNodeMap lPlus(T.tree());
if (!T.readVertexLabeling(inVertexLabeling, T, lPlus))
{
throw std::runtime_error("Error: error parsing '"
+ filenameInVertexLabeling + "'");
}
T.writeDOT(ss, lPlus, colorMap);
}
return ss.str();
}
void mix(const std::string& filenameInTree,
const std::string& filenameOutTree,
int k,
bool partition,
int seed = 0)
{
std::ifstream inT(filenameInTree.c_str());
if (!inT.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTree + "' for reading");
}
MutCloneTree T;
inT >> T;
g_rng = std::mt19937(seed);
MutCloneTree sampledT = GenerateMixture(T).generate(k, partition);
std::ofstream outT(filenameOutTree.c_str());
outT << sampledT;
outT.close();
}
void downSample(const std::string& filenameInR,
const std::string& filenameOutR,
int nrSamplesPerAnatomicalSite,
int coverage,
int seed = 0,
double purity = 1,
double sequencingErrorRate = 0,
double fractionSNVs = 1)
{
ReadMatrix R;
std::ifstream inR(filenameInR.c_str());
if (!inR.good())
{
throw std::runtime_error("Error: failed to open '" + filenameInR + "' for reading");
}
inR >> R;
g_rng = std::mt19937(seed);
ReadMatrix newR = R.downSample(nrSamplesPerAnatomicalSite,
coverage,
purity,
sequencingErrorRate,
fractionSNVs);
std::ofstream outR(filenameOutR.c_str());
outR << newR;
outR.close();
}
void treeToFreqs(const std::string& filenameInTree,
const std::string& filenameOutFreqs)
{
std::ifstream inT(filenameInTree.c_str());
if (!inT.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTree + "' for reading");
}
MutCloneTree T;
inT >> T;
std::ofstream outF(filenameOutFreqs.c_str());
outF << T.getFrequencies();
outF.close();
}
void readsToFreqs(const std::string& filenameInReads,
const std::string& filenameOutFreqs,
double alpha)
{
std::ifstream inR(filenameInReads.c_str());
if (!inR.good())
{
throw std::runtime_error("Error: could not open '" + filenameInReads + "' for reading");
}
ReadMatrix R;
inR >> R;
inR.close();
std::ofstream outF(filenameOutFreqs.c_str());
outF << R.toFrequencyMatrix(alpha, 2);
outF.close();
}
void sequence(const std::string& filenameInTree,
const std::string& filenameOutReads,
int sequencingDepth,
int seed = 0,
int ploidy = 2,
double purity = 1.,
double sequencingErrorRate = 0.)
{
std::ifstream inT(filenameInTree.c_str());
if (!inT.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTree + "' for reading");
}
MutCloneTree T;
inT >> T;
g_rng = std::mt19937(seed);
std::ofstream outR(filenameOutReads.c_str());
outR << T.getReads(purity, sequencingDepth, sequencingErrorRate, ploidy, true, true);
outR.close();
}
void precluster(const std::string& filenameInFreqs,
const std::string& filenameInClustering,
const std::string& filenameOutFreqs)
{
std::ifstream inF(filenameInFreqs.c_str());
if (!inF.good())
{
throw std::runtime_error("Error: could not open '" + filenameInFreqs + "' for reading");
}
FrequencyMatrix F;
inF >> F;
inF.close();
std::ifstream inC(filenameInClustering.c_str());
if (!inC.good())
{
throw std::runtime_error("Error: could not open '" + filenameInClustering + "' for reading");
}
IntMatrix clustering = F.parseClustering(inC);
inC.close();
FrequencyMatrix newF = F.cluster(clustering);
std::ofstream outF(filenameOutFreqs);
outF << newF;
outF.close();
}
void enumerate(const std::string& filenameInFreqs,
const std::string& filenameOutTrees,
bool spanning,
int nrThreads,
int timeLimit,
bool dryRun)
{
std::ifstream inF(filenameInFreqs.c_str());
if (!inF.good())
{
throw std::runtime_error("Error: could not open '" + filenameInFreqs + "' for reading");
}
FrequencyMatrix F;
inF >> F;
inF.close();
VerbosityLevel oldVerbosity = g_verbosity;
g_verbosity = VERBOSE_NONE;
std::ofstream outT(filenameOutTrees.c_str());
EnumerateMutationTrees enumerate(F);
enumerate.enumerate("",
nrThreads,
-1,
timeLimit,
spanning,
dryRun,
outT);
g_verbosity = oldVerbosity;
outT.close();
}
double countSpanningTrees(const std::string& filenameInFreqs,
int root = 0)
{
std::ifstream inF(filenameInFreqs.c_str());
if (!inF.good())
{
throw std::runtime_error("Error: could not open '" + filenameInFreqs + "' for reading");
}
FrequencyMatrix F;
inF >> F;
inF.close();
EnumerateMutationTrees mutT(F);
const Digraph& G = mutT.getAncestryGraph().G();
lemon::DynArcLookUp<Digraph> arcLookUp(G);
arma::mat L(F.getNrCharacters() - 1, F.getNrCharacters() - 1);
for (int i = 0; i < F.getNrCharacters(); ++i)
{
for (int j = 0; j < F.getNrCharacters(); ++j)
{
if (i == root || j == root)
{
continue;
}
int ii = i > root ? i - 1 : i;
int jj = j > root ? j - 1 : j;
if (i == j)
{
Node v_j = mutT.getAncestryGraph().charStateToNode(j, 1);
L(ii, jj) = lemon::countInArcs(G, v_j) - 1;
}
else
{
Node v_i = mutT.getAncestryGraph().charStateToNode(i, 1);
Node v_j = mutT.getAncestryGraph().charStateToNode(j, 1);
if (arcLookUp(v_i, v_j) != lemon::INVALID)
{
L(ii, jj) = -1.;
}
else
{
L(ii, jj) = 0.;
}
}
}
}
// std::cout << L << std::endl;
return arma::det(L);
}
CloneTree parseNextTree(std::istream& in)
{
int nrEdges = -1;
std::string line;
std::stringstream ss;
getline(in, line);
ss.clear();
ss.str(line);
ss >> nrEdges;
if (nrEdges < 0)
{
throw std::runtime_error("Error: number of edges should be nonnegative");
}
ss.clear();
ss.str("");
for (int j = 0; j < nrEdges; ++j)
{
getline(in, line);
ss << line << std::endl;
}
CloneTree T;
if (!T.read(ss))
throw std::runtime_error("");
return T;
}
void filterSCS(const std::string& filenameInInferredTrees,
const std::string& filenameInTrueTree,
const std::string& filenameOutTrees,
int nrClones,
int seed)
{
// 0. parse true clone tree
std::ifstream inTrueTree(filenameInTrueTree.c_str());
if (!inTrueTree.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTrueTree + "' for reading");
}
MutCloneTree trueT;
inTrueTree >> trueT;
inTrueTree.close();
// 1. collect clones
std::vector<StringVector> clones;
for (Node leaf : trueT.leafSet())
{
clones.push_back(StringVector());
Node u = leaf;
while ((u = trueT.parent(u)) != trueT.root())
{
clones.back().push_back(trueT.label(u));
}
}
g_rng = std::mt19937(seed);
std::shuffle(clones.begin(), clones.end(), g_rng);
while (clones.size() > nrClones)
{
clones.pop_back();
}
// 2. parse enumerated trees
std::ifstream inTrees(filenameInInferredTrees.c_str());
if (!inTrees.good())
{
throw std::runtime_error("Error: could not open '" + filenameInInferredTrees + "' for reading");
}
int nrTrees = -1;
std::string line;
while (line.empty() || line[0] == '#')
{
getline(inTrees, line);
}
std::stringstream ss(line);
ss >> nrTrees;
if (nrTrees < 0)
{
throw std::runtime_error("Error: number of trees should be nonnegative");
}
std::ofstream outTrees(filenameOutTrees);
for (const StringVector& clone : clones)
{
outTrees << "#";
for (const std::string& mut : clone)
{
outTrees << " " << mut;
}
outTrees << std::endl;
}
for (int i = 0; i < nrTrees; ++i)
{
StringPairSet diff;
CloneTree T = parseNextTree(inTrees);
bool ok = true;
for (const StringVector& clone : clones)
{
Node u = T.getNodeByLabel(clone[0]);
int idx = 0;
while (u != lemon::INVALID && ok)
{
ok &= (idx < clone.size()) && (T.label(u) == clone[idx]);
u = T.parent(u);
++idx;
}
}
if (ok)
{
outTrees << lemon::countArcs(T.tree()) << " #edges" << std::endl;
T.write(outTrees);
}
}
outTrees.close();
}
void filterLR(const std::string& filenameInInferredTrees,
const std::string& filenameInTrueTree,
const std::string& filenameOutTrees,
int nrPairs,
int seed)
{
// 0. parse true clone tree
std::ifstream inTrueTree(filenameInTrueTree.c_str());
if (!inTrueTree.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTrueTree + "' for reading");
}
MutCloneTree trueT;
inTrueTree >> trueT;
inTrueTree.close();
// 1. collect clones
StringPairSet ancestralPairSet = trueT.getAncestralPairsNoRoot();
std::vector<StringPair> vec(ancestralPairSet.begin(), ancestralPairSet.end());
g_rng = std::mt19937(seed);
std::shuffle(vec.begin(), vec.end(), g_rng);
while (vec.size() > nrPairs)
{
vec.pop_back();
}
ancestralPairSet = StringPairSet(vec.begin(), vec.end());
// 2. parse enumerated trees
std::ifstream inTrees(filenameInInferredTrees.c_str());
if (!inTrees.good())
{
throw std::runtime_error("Error: could not open '" + filenameInInferredTrees + "' for reading");
}
int nrTrees = -1;
std::string line;
while (line.empty() || line[0] == '#')
{
getline(inTrees, line);
}
std::stringstream ss(line);
ss >> nrTrees;
if (nrTrees < 0)
{
throw std::runtime_error("Error: number of trees should be nonnegative");
}
std::ofstream outTrees(filenameOutTrees);
for (const StringPair& pair : ancestralPairSet)
{
outTrees << "# " << pair.first << " " << pair.second << std::endl;
}
for (int i = 0; i < nrTrees; ++i)
{
StringPairSet diff;
CloneTree T = parseNextTree(inTrees);
StringPairSet ancestralPairSetT = T.getAncestralPairs();
std::set_difference(ancestralPairSet.begin(), ancestralPairSet.end(),
ancestralPairSetT.begin(), ancestralPairSetT.end(),
std::inserter(diff, diff.begin()));
if (diff.empty())
{
outTrees << lemon::countArcs(T.tree()) << " #edges" << std::endl;
T.write(outTrees);
}
}
outTrees.close();
}
void computeRecall(const std::string& filenameInInferredTrees,
const std::string& filenameInTrueTree,
const std::string& filenameOutRecall)
{
std::ifstream inTrueTree(filenameInTrueTree.c_str());
if (!inTrueTree.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTrueTree + "' for reading");
}
CloneTree trueT;
if (!trueT.read(inTrueTree))
{
throw std::runtime_error("Parse error: '" + filenameInTrueTree + "'");
}
inTrueTree.close();
StringPairSet trueParental = trueT.getParentalPairs();
StringPairSet trueAncestral = trueT.getAncestralPairs();
StringPairSet trueIncomparable = trueT.getIncomparablePairs();
std::ifstream inTrees(filenameInInferredTrees.c_str());
if (!inTrees.good())
{
throw std::runtime_error("Error: could not open '" + filenameInInferredTrees + "' for reading");
}
int nrTrees = -1;
std::string line;
while (line.empty() || line[0] == '#')
{
getline(inTrees, line);
}
std::stringstream ss(line);
ss >> nrTrees;
if (nrTrees < 0)
{
throw std::runtime_error("Error: number of trees should be nonnegative");
}
std::ofstream outRecall(filenameOutRecall);
outRecall << "solution\tancestral\tparental\tincomparable" << std::endl;
for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)
{
CloneTree T = parseNextTree(inTrees);
StringPairSet inferredParental = T.getParentalPairs();
StringPairSet inferredAncestral = T.getAncestralPairs();
StringPairSet inferredIncomparable = T.getIncomparablePairs();
outRecall << treeIdx << "\t"
<< BaseTree::recall(inferredAncestral, trueAncestral)
<< "\t"
<< BaseTree::recall(inferredParental, trueParental)
<< "\t"
<< BaseTree::recall(inferredIncomparable, trueIncomparable)
<< std::endl;
}
inTrees.close();
outRecall.close();
}
double getFractionOfIncomparablePairs(const std::string& filenameInFreqs)
{
std::ifstream inF(filenameInFreqs.c_str());
if (!inF.good())
{
throw std::runtime_error("Error: could not open '" + filenameInFreqs + "' for reading");
}
FrequencyMatrix F;
inF >> F;
inF.close();
return EnumerateMutationTrees(F).getAncestryGraph().fracOfIncomparablePairs();
}
void summarize(const std::string& filenameInAllTrees,
const std::string& filenameInSampledTree,
const std::string& filenameOutSummary)
{
// 1. Parse sampled trees
std::map<StringPairSet, int> sampledTreeHistogram;
std::ifstream inTrees(filenameInSampledTree.c_str());
if (!inTrees.good())
{
throw std::runtime_error("Error: could not open '" + filenameInSampledTree + "' for reading");
}
int nrTrees = -1;
std::string line;
while (line.empty() || line[0] == '#')
{
getline(inTrees, line);
}
std::stringstream ss(line);
ss >> nrTrees;
if (nrTrees < 0)
{
throw std::runtime_error("Error: number of trees should be nonnegative");
}
for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)
{
CloneTree T = parseNextTree(inTrees);
StringPairSet edges;
for (ArcIt a(T.tree()); a != lemon::INVALID; ++a)
{
Node u = T.tree().source(a);
Node v = T.tree().target(a);
edges.insert(StringPair(T.label(u), T.label(v)));
}
if (sampledTreeHistogram.count(edges) == 0)
{
sampledTreeHistogram[edges] = 1;
}
else
{
++sampledTreeHistogram[edges];
}
}
inTrees.close();
// 2. Parse all trees
std::map<StringPairSet, int> allTreeIndex;
inTrees = std::ifstream(filenameInAllTrees.c_str());
if (!inTrees.good())
{
throw std::runtime_error("Error: could not open '" + filenameInAllTrees + "' for reading");
}
nrTrees = -1;
line.clear();
while (line.empty() || line[0] == '#')
{
getline(inTrees, line);
}
ss.clear();
ss.str(line);
ss >> nrTrees;
if (nrTrees < 0)
{
throw std::runtime_error("Error: number of trees should be nonnegative");
}
for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)
{
CloneTree T = parseNextTree(inTrees);
StringPairSet edges;
for (ArcIt a(T.tree()); a != lemon::INVALID; ++a)
{
Node u = T.tree().source(a);
Node v = T.tree().target(a);
edges.insert(StringPair(T.label(u), T.label(v)));
}
if (allTreeIndex.count(edges) > 0)
{
throw std::runtime_error("Error: duplicate tree");
}
allTreeIndex[edges] = treeIdx;
}
inTrees.close();
std::ofstream outSum(filenameOutSummary);
int incorrect = 0;
outSum << "index\tcount" << std::endl;
for (const auto& kv : sampledTreeHistogram)
{
if (allTreeIndex.count(kv.first) == 0)
{
outSum << --incorrect << "\t" << kv.second << std::endl;
}
else
{
outSum << allTreeIndex[kv.first] << "\t" << kv.second << std::endl;
}
}
for (const auto& kv : allTreeIndex)
{
if (sampledTreeHistogram.count(kv.first) == 0)
{
outSum << kv.second << "\t" << 0 << std::endl;
}
}
outSum.close();
}
int rejectionSample(const std::string& filenameInFreqs,
const std::string& filenameOutTrees,
int count,
int seed = 0)
{
g_rng = std::mt19937(seed);
std::ifstream inF(filenameInFreqs.c_str());
if (!inF.good())
{
throw std::runtime_error("Error: could not open '" + filenameInFreqs + "' for reading");
}
FrequencyMatrix F;
inF >> F;
inF.close();
const int n = F.getNrCharacters();
const int k = F.getNrSamples();
RealTensor FF(2, k, n);
for (int p = 0; p < k; ++p)
{
FF.setRowLabel(p, F.indexToSample(p));
for (int i = 0; i < n; ++i)
{
if (p == 0)
{
FF.setColLabel(i, F.indexToCharacter(i));
}
FF.set(1, p, i, F.min(p, i));
FF.set(0, p, i, 1 - F.max(p, i));
}
}
StateTreeVector S(F.getNrCharacters(), StateTree({-1, 0}));
gm::RootedCladisticAncestryGraph G(FF, S);
G.init();
std::ofstream outTrees(filenameOutTrees);
outTrees << count << " #trees" << std::endl;
StringPairSet tree;
int sampleCount = 0;
while (count > 0)
{
++sampleCount;
if (G.sample(tree))
{
outTrees << tree.size() << " #edges" << std::endl;
for (const StringPair& edge : tree)
{
outTrees << edge.first << " " << edge.second << std::endl;
}
--count;
}
}
return sampleCount;
}
std::string visualizeEnumeratedCloneTree(const std::string& filenameInFreqs,
const std::string& filenameInTrees,
int index,
bool showCharacterLabels = false,
int offset = 1,
bool showFrequencies = false)
{
std::ifstream inF(filenameInFreqs.c_str());
if (!inF.good())
{
throw std::runtime_error("Error: could not open '" + filenameInFreqs + "' for reading");
}
FrequencyMatrix F;
inF >> F;
inF.close();
std::ifstream inTrees(filenameInTrees.c_str());
if (!inTrees.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTrees + "' for reading");
}
int nrTrees = -1;
std::string line;
while (line.empty() || line[0] == '#')
{
getline(inTrees, line);
}
std::stringstream ss(line);
ss >> nrTrees;
if (nrTrees < 0)
{
throw std::runtime_error("Error: number of trees should be nonnegative");
}
if (!(0 <= index && index < nrTrees))
{
throw std::runtime_error("Error: invalid index");
}
std::stringstream ssOut;
for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)
{
CloneTree T = parseNextTree(inTrees);
if (index == treeIdx)
{
ssOut << "digraph T_" << index << " {" << std::endl;
for (NodeIt v(T.tree()); v != lemon::INVALID; ++v)
{
ssOut << " " << T.tree().id(v) << " [label=\"";
const std::string& label_v = T.label(v);
if (showCharacterLabels)
ssOut << label_v;
else
ssOut << F.characterToIndex(label_v) + offset;
if (showFrequencies)
{
for (int p = 0; p < F.getNrSamples(); ++p)
{
ssOut << "\\n" << F.min(p, F.characterToIndex(label_v)) << " " << F.max(p, F.characterToIndex(label_v));
}
}
ssOut << "\"]" << std::endl;
}
for (ArcIt a(T.tree()); a != lemon::INVALID; ++a)
{
Node u = T.tree().source(a);
Node v = T.tree().target(a);
ssOut << " " << T.tree().id(u) << " -> " << T.tree().id(v) << std::endl;
}
ssOut << "}" << std::endl;
break;
}
}
inTrees.close();
return ssOut.str();
}
int identifySolution(const std::string& filenameInTrees,
const std::string& filenameInTree)
{
std::ifstream inTrueTree(filenameInTree.c_str());
if (!inTrueTree.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTree + "' for reading");
}
CloneTree trueT;
if (!trueT.read(inTrueTree))
{
throw std::runtime_error("Parse error: '" + filenameInTree + "'");
}
inTrueTree.close();
StringPairSet edgesTrueT = trueT.getEdgeSet();
std::ifstream inTrees(filenameInTrees.c_str());
if (!inTrees.good())
{
throw std::runtime_error("Error: could not open '" + filenameInTrees + "' for reading");
}
int nrTrees = -1;
std::string line;
while (line.empty() || line[0] == '#')
{
getline(inTrees, line);
}
std::stringstream ss(line);
ss >> nrTrees;
if (nrTrees < 0)
{
throw std::runtime_error("Error: number of trees should be nonnegative");
}
int res = -1;
for (int treeIdx = 0; treeIdx < nrTrees; ++treeIdx)
{
CloneTree T = parseNextTree(inTrees);
if (T.getEdgeSet() == edgesTrueT)
{
res = treeIdx;
break;
}
}
inTrees.close();
return res;
}
BOOST_PYTHON_FUNCTION_OVERLOADS(sequence_overloads, sequence, 3, 7);
BOOST_PYTHON_FUNCTION_OVERLOADS(downSample_overloads, downSample, 4, 8);
BOOST_PYTHON_FUNCTION_OVERLOADS(visualizeCloneTree_overloads, visualizeCloneTree, 1, 3);
BOOST_PYTHON_FUNCTION_OVERLOADS(visualizeEnumeratedCloneTree_overloads, visualizeEnumeratedCloneTree, 3, 6);
BOOST_PYTHON_FUNCTION_OVERLOADS(visualizeMigrationGraph_overloads, visualizeMigrationGraph, 1, 2);
BOOST_PYTHON_FUNCTION_OVERLOADS(simulate_overloads, simulate, 0, 2);
BOOST_PYTHON_FUNCTION_OVERLOADS(countSpanningTrees_overloads, countSpanningTrees, 1, 2);
BOOST_PYTHON_FUNCTION_OVERLOADS(mix_overloads, mix, 4, 5);
BOOST_PYTHON_FUNCTION_OVERLOADS(rejectionSample_overloads, rejectionSample, 3, 4);
BOOST_PYTHON_MODULE(oncolib)
{
p::def("sequence", sequence,
sequence_overloads(p::args("filenameInTree",
"filenameOutReads",
"sequencingDepth",
"seed=0",
"ploidy=2",
"purity=1.",
"sequencingErrorRate=0."),
"Generate NGS reads from clone tree"));
p::def("simulate", simulate, simulate_overloads(p::args("outputDirectory='.'",
"args={'filenameColorMap:'', "\
"'seed':0, "\
"'carryingCapacity':5e4, "\
"'mutFreqThreshold':0.05, "\
"'migrationRate':1e-6, "\
"'mutationRate':0.1, "\
"'driverRate':2e-7, "\
"'maxNrAnatomicalSites':3, "\
"'migrationPattern':0, "\
"'nrTrials':-1, "\
"'desiredNrMutationClusters':-1, "
"'sequencingDepth':200, "\
"'nrSamplesPerAnatomicalSite':2, "\
"'nrSamplesPrimary':2, "\
"'sequencingErrorRate':0, "\
"'purity':1., "\
"'verbose':False}"),
"Simulate a metastatic tumor"));
p::def("tree2dot", visualizeCloneTree,
visualizeCloneTree_overloads(p::args("filenameInTree",
"filenameInColorMap=''",
"filenameInVertexLabeling=''"),
"Visualize clone tree in DOT format"));
p::def("enumeratedtree2dot", visualizeEnumeratedCloneTree,
visualizeEnumeratedCloneTree_overloads(p::args("filenameInFreqs",
"filenameInTrees",
"index",
"showCharacterLabels=False",
"offset=1",
"showFrequencies=False"),
"Visualize enumerated clone tree in DOT format"));
p::def("graph2dot", visualizeMigrationGraph,
visualizeMigrationGraph_overloads(p::args("filenameInTree",
"filenameInColorMap=''"),
"Visualize clone tree in DOT format"));
p::def("downsample", downSample,
downSample_overloads(p::args("filenameInR",
"filenameOutR",
"nrSamplesPerAnatomicalSite",
"coverage",
"seed=0",
"purity=1.",
"sequencingErrorRate=0.",
"fractionSNVs=1."),
"Down sample reads"));
p::def("mix", mix, mix_overloads(p::args("filenameInTree",
"filenameOutTree",
"k",
"partition",
"seed=0"),
"Generate mixture of clone tree leaves"));
p::def("tree2freqs", treeToFreqs, "Extract mutation frequencies from clone tree");
p::def("reads2freqs", readsToFreqs, "Extract mutation frequencies from reads");
p::def("precluster", precluster, "Cluster mutation frequencies given clustering");
p::def("enumerate", enumerate, "Enumerate mutation trees");
p::def("countSpanningTrees", countSpanningTrees,
countSpanningTrees_overloads(p::args("filenameInF",
"root=0"),
"Compute number of spanning arborescence in ancestry graph"));
p::def("computeRecall", computeRecall, "Compute recall");
p::def("getFractionOfIncomparablePairs", getFractionOfIncomparablePairs,
"Compute fraction of incomparable pairs");
p::def("filterSCS", filterSCS, "Include SCS information");
p::def("filterLR", filterLR, "Include long read information");
p::def("summarize", summarize, "Compute histogram of sampled trees w.r.t. all trees");
p::def("identifySolution", identifySolution, "Determine whether specified tree occurs in specified trees");
p::def("rejectionSample", rejectionSample,
rejectionSample_overloads(p::args("filenameInFreqs",
"filenameOutTrees",
"count",
"seed=0"),
"Rejection sampling of spanning trees satisfying SC"));
}
| 28.251672 | 116 | 0.553168 | [
"object",
"vector"
] |
e1d991877ff581c35d6c454afaed891cc2df2517 | 3,903 | cc | C++ | tests/nnfw_api/src/one_op_tests/Select.cc | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | 255 | 2020-05-22T07:45:29.000Z | 2022-03-29T23:58:22.000Z | tests/nnfw_api/src/one_op_tests/Select.cc | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | 5,102 | 2020-05-22T07:48:33.000Z | 2022-03-31T23:43:39.000Z | tests/nnfw_api/src/one_op_tests/Select.cc | juitem/ONE | 8c6a4b7738074573b6ac5c82dcf1f6697520d1ed | [
"Apache-2.0"
] | 120 | 2020-05-22T07:51:08.000Z | 2022-02-16T19:08:05.000Z | /*
* Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "GenModelTest.h"
TEST_F(GenModelTest, OneOp_Select)
{
CircleGen cgen;
std::vector<uint8_t> cond_data{1, 1, 0, 1};
uint32_t cond_buf = cgen.addBuffer(cond_data);
int cond = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_BOOL, cond_buf});
int in_true = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
int in_false = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
int out = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
cgen.addOperatorSelect({{cond, in_true, in_false}, {out}});
cgen.setInputsAndOutputs({in_true, in_false}, {out});
_context = std::make_unique<GenModelTestContext>(cgen.finish());
_context->addTestCase(uniformTCD<float>({{0, 1, 2, 3}, {4, 5, 6, 7}}, {{0, 1, 6, 3}}));
_context->setBackends({"cpu"});
SUCCEED();
}
TEST_F(GenModelTest, OneOp_SelectV2_Broadcast)
{
CircleGen cgen;
std::vector<uint8_t> cond_data{1, 0};
uint32_t cond_buf = cgen.addBuffer(cond_data);
int cond = cgen.addTensor({{1, 2, 1, 1}, circle::TensorType::TensorType_BOOL, cond_buf});
int in_true = cgen.addTensor({{1, 1, 2, 1}, circle::TensorType::TensorType_FLOAT32});
int in_false = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
int out = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
cgen.addOperatorSelectV2({{cond, in_true, in_false}, {out}});
cgen.setInputsAndOutputs({in_true, in_false}, {out});
_context = std::make_unique<GenModelTestContext>(cgen.finish());
_context->addTestCase(uniformTCD<float>({{0, 1}, {4, 5, 6, 7}}, {{0, 1, 6, 7}}));
_context->setBackends({"cpu"});
SUCCEED();
}
TEST_F(GenModelTest, neg_OneOp_Select_InputType)
{
CircleGen cgen;
std::vector<uint8_t> cond_data{1, 1, 0, 1};
uint32_t cond_buf = cgen.addBuffer(cond_data);
int cond = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_BOOL, cond_buf});
int in_true = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
int in_false = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_INT32});
int out = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
cgen.addOperatorSelect({{cond, in_true, in_false}, {out}});
cgen.setInputsAndOutputs({in_true, in_false}, {out});
_context = std::make_unique<GenModelTestContext>(cgen.finish());
_context->setBackends({"cpu"});
_context->expectFailModelLoad();
SUCCEED();
}
TEST_F(GenModelTest, neg_OneOp_Select_CondType)
{
CircleGen cgen;
std::vector<uint8_t> cond_data{1, 1, 0, 1};
uint32_t cond_buf = cgen.addBuffer(cond_data);
int cond = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_UINT8, cond_buf});
int in_true = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
int in_false = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
int out = cgen.addTensor({{1, 2, 2, 1}, circle::TensorType::TensorType_FLOAT32});
cgen.addOperatorSelect({{cond, in_true, in_false}, {out}});
cgen.setInputsAndOutputs({in_true, in_false}, {out});
_context = std::make_unique<GenModelTestContext>(cgen.finish());
_context->setBackends({"cpu"});
_context->expectFailModelLoad();
SUCCEED();
}
| 41.521277 | 92 | 0.702024 | [
"vector"
] |
e1db1534177ae698273cc82c9b9102adc4573b04 | 5,292 | cpp | C++ | src/backend/gporca/libnaucrates/src/md/CDXLBucket.cpp | Tylarb/gpdb | 15e1341cfbac7f70d2086a9a1d46149a82765b5e | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2020-11-27T07:30:05.000Z | 2020-11-27T07:30:05.000Z | src/backend/gporca/libnaucrates/src/md/CDXLBucket.cpp | Tylarb/gpdb | 15e1341cfbac7f70d2086a9a1d46149a82765b5e | [
"PostgreSQL",
"Apache-2.0"
] | 6 | 2020-06-24T18:56:06.000Z | 2022-02-26T08:53:11.000Z | src/backend/gporca/libnaucrates/src/md/CDXLBucket.cpp | Tylarb/gpdb | 15e1341cfbac7f70d2086a9a1d46149a82765b5e | [
"PostgreSQL",
"Apache-2.0"
] | 1 | 2022-03-22T18:45:41.000Z | 2022-03-22T18:45:41.000Z | //---------------------------------------------------------------------------
// Greenplum Database
// Copyright (C) 2012 EMC Corp.
//
// @filename:
// CDXLBucket.cpp
//
// @doc:
// Implementation of the class for representing buckets in DXL column stats
//---------------------------------------------------------------------------
#include "gpos/string/CWStringDynamic.h"
#include "naucrates/md/CDXLBucket.h"
#include "naucrates/dxl/xml/CXMLSerializer.h"
#include "naucrates/dxl/CDXLUtils.h"
using namespace gpdxl;
using namespace gpmd;
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::CDXLBucket
//
// @doc:
// Constructor
//
//---------------------------------------------------------------------------
CDXLBucket::CDXLBucket
(
CDXLDatum *dxl_datum_lower,
CDXLDatum *dxl_datum_upper,
BOOL is_lower_closed,
BOOL is_upper_closed,
CDouble frequency,
CDouble distinct
)
:
m_lower_bound_dxl_datum(dxl_datum_lower),
m_upper_bound_dxl_datum(dxl_datum_upper),
m_is_lower_closed(is_lower_closed),
m_is_upper_closed(is_upper_closed),
m_frequency(frequency),
m_distinct(distinct)
{
GPOS_ASSERT(NULL != dxl_datum_lower);
GPOS_ASSERT(NULL != dxl_datum_upper);
GPOS_ASSERT(m_frequency >= 0.0 && m_frequency <= 1.0);
GPOS_ASSERT(m_distinct >= 0);
}
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::~CDXLBucket
//
// @doc:
// Destructor
//
//---------------------------------------------------------------------------
CDXLBucket::~CDXLBucket()
{
m_lower_bound_dxl_datum->Release();
m_upper_bound_dxl_datum->Release();
}
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::GetDXLDatumLower
//
// @doc:
// Returns the lower bound for the bucket
//
//---------------------------------------------------------------------------
const CDXLDatum *
CDXLBucket::GetDXLDatumLower() const
{
return m_lower_bound_dxl_datum;
}
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::GetDXLDatumUpper
//
// @doc:
// Returns the upper bound for the bucket
//
//---------------------------------------------------------------------------
const CDXLDatum *
CDXLBucket::GetDXLDatumUpper() const
{
return m_upper_bound_dxl_datum;
}
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::GetFrequency
//
// @doc:
// Returns the frequency for this bucket
//
//---------------------------------------------------------------------------
CDouble
CDXLBucket::GetFrequency() const
{
return m_frequency;
}
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::GetNumDistinct
//
// @doc:
// Returns the number of distinct in this bucket
//
//---------------------------------------------------------------------------
CDouble
CDXLBucket::GetNumDistinct() const
{
return m_distinct;
}
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::Serialize
//
// @doc:
// Serialize bucket in DXL format
//
//---------------------------------------------------------------------------
void
CDXLBucket::Serialize
(
CXMLSerializer *xml_serializer
)
const
{
xml_serializer->OpenElement(CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix),
CDXLTokens::GetDXLTokenStr(EdxltokenColumnStatsBucket));
xml_serializer->AddAttribute(CDXLTokens::GetDXLTokenStr(EdxltokenStatsFrequency), m_frequency);
xml_serializer->AddAttribute(CDXLTokens::GetDXLTokenStr(EdxltokenStatsDistinct), m_distinct);
SerializeBoundaryValue(xml_serializer, CDXLTokens::GetDXLTokenStr(EdxltokenStatsBucketLowerBound), m_lower_bound_dxl_datum, m_is_lower_closed);
SerializeBoundaryValue(xml_serializer, CDXLTokens::GetDXLTokenStr(EdxltokenStatsBucketUpperBound), m_upper_bound_dxl_datum, m_is_upper_closed);
xml_serializer->CloseElement(CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix),
CDXLTokens::GetDXLTokenStr(EdxltokenColumnStatsBucket));
GPOS_CHECK_ABORT;
}
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::Serialize
//
// @doc:
// Serialize the bucket boundary
//
//---------------------------------------------------------------------------
void
CDXLBucket::SerializeBoundaryValue
(
CXMLSerializer *xml_serializer,
const CWStringConst *elem_str,
CDXLDatum *dxl_datum,
BOOL is_bound_closed
)
const
{
xml_serializer->OpenElement(CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix), elem_str);
xml_serializer->AddAttribute(CDXLTokens::GetDXLTokenStr(EdxltokenStatsBoundClosed), is_bound_closed);
dxl_datum->Serialize(xml_serializer);
xml_serializer->CloseElement(CDXLTokens::GetDXLTokenStr(EdxltokenNamespacePrefix), elem_str);
}
#ifdef GPOS_DEBUG
//---------------------------------------------------------------------------
// @function:
// CDXLBucket::DebugPrint
//
// @doc:
// Debug print of the bucket object
//
//---------------------------------------------------------------------------
void
CDXLBucket::DebugPrint
(
IOstream & //os
)
const
{
// TODO: - Feb 13, 2012; implement
}
#endif // GPOS_DEBUG
// EOF
| 26.328358 | 144 | 0.53647 | [
"object"
] |
e1dbede33ea69ecb0eec90d81bb20f2891e53647 | 11,634 | cpp | C++ | src/Data_Generation.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 4 | 2021-02-26T10:30:36.000Z | 2021-03-17T01:49:18.000Z | src/Data_Generation.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 7 | 2021-02-09T16:32:05.000Z | 2022-02-03T09:20:08.000Z | src/Data_Generation.cpp | temken/DaMaSCUS-SUN | 6dc10d7e707c20bb1d5aea58249515b00e225b58 | [
"MIT"
] | 1 | 2022-01-03T03:54:24.000Z | 2022-01-03T03:54:24.000Z | #include "Data_Generation.hpp"
#include <algorithm>
#include <chrono>
#include <mpi.h>
#include "libphysica/Natural_Units.hpp"
#include "libphysica/Special_Functions.hpp"
#include "libphysica/Utilities.hpp"
#include "obscura/Astronomy.hpp"
namespace DaMaSCUS_SUN
{
using namespace libphysica::natural_units;
Simulation_Data::Simulation_Data(unsigned int sample_size, double u_min, unsigned int iso_rings)
: min_sample_size_above_threshold(sample_size), minimum_speed_threshold(u_min), isoreflection_rings(iso_rings), number_of_trajectories(0), number_of_free_particles(0), number_of_reflected_particles(0), number_of_captured_particles(0), average_number_of_scatterings(0.0), computing_time(0.0), number_of_data_points(std::vector<unsigned long int>(iso_rings, 0)), data(iso_rings, std::vector<libphysica::DataPoint>())
{
MPI_Comm_size(MPI_COMM_WORLD, &mpi_processes);
MPI_Comm_rank(MPI_COMM_WORLD, &mpi_rank);
}
void Simulation_Data::Configure(double initial_radius, unsigned int min_scattering, unsigned int max_scattering, unsigned long int max_free_steps)
{
initial_and_final_radius = initial_radius;
minimum_number_of_scatterings = min_scattering;
maximum_number_of_scatterings = max_scattering;
maximum_free_time_steps = max_free_steps;
}
void Simulation_Data::Generate_Data(obscura::DM_Particle& DM, Solar_Model& solar_model, obscura::DM_Distribution& halo_model, unsigned int fixed_seed)
{
auto time_start = std::chrono::system_clock::now();
//MPI ring communication
int mpi_source = (mpi_rank == 0) ? mpi_processes - 1 : mpi_rank - 1;
int mpi_destination = (mpi_rank == mpi_processes - 1) ? 0 : mpi_rank + 1;
int mpi_tag = 0;
MPI_Status mpi_status;
MPI_Request mpi_request;
// Configure the simulator
Trajectory_Simulator simulator(solar_model, maximum_free_time_steps, maximum_number_of_scatterings, initial_and_final_radius);
// simulator.Toggle_Trajectory_Saving(50);
if(fixed_seed != 0)
simulator.Fix_PRNG_Seed(fixed_seed);
//Get the MPI ring communication started by sending the data counters
std::vector<unsigned long int> local_counter_new(isoreflection_rings, 0);
if(mpi_rank == 0)
MPI_Isend(&number_of_data_points.front(), isoreflection_rings, MPI_UNSIGNED_LONG, mpi_destination, mpi_tag, MPI_COMM_WORLD, &mpi_request);
MPI_Barrier(MPI_COMM_WORLD);
unsigned int smallest_sample_size = 0;
while(smallest_sample_size < min_sample_size_above_threshold)
{
Event IC = Initial_Conditions(halo_model, solar_model, simulator.PRNG);
Hyperbolic_Kepler_Shift(IC, initial_and_final_radius);
Trajectory_Result trajectory = simulator.Simulate(IC, DM);
number_of_trajectories++;
average_number_of_scatterings = 1.0 / number_of_trajectories * ((number_of_trajectories - 1) * average_number_of_scatterings + trajectory.number_of_scatterings);
if(trajectory.Particle_Captured())
number_of_captured_particles++;
else
{
if(trajectory.Particle_Free())
number_of_free_particles++;
else if(trajectory.Particle_Reflected())
number_of_reflected_particles++;
Hyperbolic_Kepler_Shift(trajectory.final_event, 1.0 * AU);
double v_final = trajectory.final_event.Speed();
if(trajectory.number_of_scatterings >= minimum_number_of_scatterings && v_final > KDE_boundary_correction_factor * minimum_speed_threshold)
{
unsigned int isoreflection_ring = (isoreflection_rings == 1) ? 0 : trajectory.final_event.Isoreflection_Ring(obscura::Sun_Velocity(), isoreflection_rings);
if(v_final > minimum_speed_threshold)
local_counter_new[isoreflection_ring]++;
data[isoreflection_ring].push_back(libphysica::DataPoint(v_final));
}
//Check if data counters arrived.
int mpi_flag;
MPI_Iprobe(mpi_source, MPI_ANY_TAG, MPI_COMM_WORLD, &mpi_flag, &mpi_status);
if(mpi_flag)
{
//Receive and increment the data counters
MPI_Recv(&number_of_data_points.front(), isoreflection_rings, MPI_UNSIGNED_LONG, mpi_source, MPI_ANY_TAG, MPI_COMM_WORLD, &mpi_status);
unsigned long int smallest_sample_size_old = *std::min_element(std::begin(number_of_data_points), std::end(number_of_data_points));
for(unsigned int i = 0; i < isoreflection_rings; i++)
{
number_of_data_points[i] += local_counter_new[i];
local_counter_new[i] = 0;
}
smallest_sample_size = *std::min_element(std::begin(number_of_data_points), std::end(number_of_data_points));
//Check if we are done
if(smallest_sample_size_old < min_sample_size_above_threshold && smallest_sample_size >= min_sample_size_above_threshold)
mpi_tag = mpi_source + 1;
else if(smallest_sample_size_old >= min_sample_size_above_threshold)
mpi_tag = mpi_status.MPI_TAG;
//Progress bar
if(smallest_sample_size_old < smallest_sample_size && mpi_rank % 10 == 0)
{
double time = 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - time_start).count();
libphysica::Print_Progress_Bar(1.0 * smallest_sample_size / min_sample_size_above_threshold, 0, 44, time);
}
//Pass on the counters, unless you are the very last process.
if(mpi_tag != (mpi_rank + 1))
MPI_Isend(&number_of_data_points.front(), isoreflection_rings, MPI_UNSIGNED_LONG, mpi_destination, mpi_tag, MPI_COMM_WORLD, &mpi_request);
}
}
}
auto time_end = std::chrono::system_clock::now();
computing_time = 1e-6 * std::chrono::duration_cast<std::chrono::microseconds>(time_end - time_start).count();
libphysica::Print_Progress_Bar(1.0, mpi_rank, 44, computing_time);
if(mpi_rank == 0)
std::cout << std::endl;
MPI_Barrier(MPI_COMM_WORLD);
Perform_MPI_Reductions();
}
void Simulation_Data::Perform_MPI_Reductions()
{
average_number_of_scatterings *= number_of_trajectories;
MPI_Allreduce(MPI_IN_PLACE, &number_of_trajectories, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &number_of_free_particles, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &number_of_reflected_particles, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &number_of_captured_particles, 1, MPI_UNSIGNED_LONG, MPI_SUM, MPI_COMM_WORLD);
MPI_Allreduce(MPI_IN_PLACE, &average_number_of_scatterings, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD);
average_number_of_scatterings /= number_of_trajectories;
MPI_Datatype mpi_datapoint;
MPI_Type_contiguous(2, MPI_DOUBLE, &mpi_datapoint);
MPI_Type_commit(&mpi_datapoint);
std::vector<std::vector<libphysica::DataPoint>> global_data;
for(unsigned int i = 0; i < isoreflection_rings; i++)
{
// 1. How many data points did this worker gather?
unsigned long int local_number_of_data_points = data[i].size();
// 2. Every worker needs to know how much every worker did.
std::vector<unsigned long int> data_points_of_workers(mpi_processes);
MPI_Allgather(&local_number_of_data_points, 1, MPI_UNSIGNED_LONG, data_points_of_workers.data(), 1, MPI_UNSIGNED_LONG, MPI_COMM_WORLD);
// 3. How many data points did all workers gather in total?
number_of_data_points[i] = std::accumulate(data_points_of_workers.begin(), data_points_of_workers.end(), 0);
//4. Collect info on the data packages to be received.
std::vector<int> receive_counter(mpi_processes);
std::vector<int> receive_displacements(mpi_processes);
for(int j = 0; j < mpi_processes; j++)
{
receive_counter[j] = data_points_of_workers[j];
receive_displacements[j] = (j == 0) ? 0 : receive_displacements[j - 1] + data_points_of_workers[j - 1];
}
// 5. Gather data packages
std::vector<libphysica::DataPoint> ring_data(number_of_data_points[i]);
MPI_Allgatherv(&data[i].front(), local_number_of_data_points, mpi_datapoint, &ring_data.front(), receive_counter.data(), receive_displacements.data(), mpi_datapoint, MPI_COMM_WORLD);
global_data.push_back(ring_data);
}
data = global_data;
MPI_Allreduce(MPI_IN_PLACE, &computing_time, 1, MPI_DOUBLE, MPI_MAX, MPI_COMM_WORLD);
}
double Simulation_Data::Free_Ratio() const
{
return 1.0 * number_of_free_particles / number_of_trajectories;
}
double Simulation_Data::Capture_Ratio() const
{
return 1.0 * number_of_captured_particles / number_of_trajectories;
}
double Simulation_Data::Reflection_Ratio(int isoreflection_ring) const
{
if(isoreflection_ring < 0)
return 1.0 * number_of_reflected_particles / number_of_trajectories;
else
return 1.0 * data[isoreflection_ring].size() / number_of_trajectories;
}
double Simulation_Data::Minimum_Speed() const
{
return KDE_boundary_correction_factor * minimum_speed_threshold;
}
double Simulation_Data::Lowest_Speed(unsigned int iso_ring) const
{
return (*std::min_element(data[iso_ring].begin(), data[iso_ring].end())).value;
}
double Simulation_Data::Highest_Speed(unsigned int iso_ring) const
{
return (*std::max_element(data[iso_ring].begin(), data[iso_ring].end())).value;
}
void Simulation_Data::Print_Summary(unsigned int mpi_rank)
{
if(mpi_rank == 0)
{
unsigned long int number_of_data_points_tot = std::accumulate(number_of_data_points.begin(), number_of_data_points.end(), 0);
std::cout << SEPARATOR
<< "Simulation data summary" << std::endl
<< std::endl
<< "Configuration:" << std::endl
<< "DM speed threshold [km/sec]:\t" << libphysica::Round(In_Units(minimum_speed_threshold, km / sec)) << std::endl
<< "Minimum sample size:\t\t" << min_sample_size_above_threshold << std::endl
<< "Isoreflection rings:\t\t" << isoreflection_rings << std::endl
<< std::endl
<< "Results:" << std::endl
<< "Simulated trajectories:\t\t" << number_of_trajectories << std::endl
<< "Generated data points (total):\t" << number_of_data_points_tot << std::endl
<< "Average # of scatterings:\t" << libphysica::Round(average_number_of_scatterings) << std::endl
<< "Free particles [%]:\t\t" << libphysica::Round(100.0 * Free_Ratio()) << std::endl
<< "Reflected particles [%]:\t" << libphysica::Round(100.0 * Reflection_Ratio()) << std::endl
<< "Captured particles [%]:\t\t" << libphysica::Round(100.0 * Capture_Ratio()) << std::endl;
if(isoreflection_rings > 1)
{
std::cout << std::endl
<< "Ring\tData points\tRelative [%]\t<u> [km/sec]\tu_max [km/sec]" << std::endl;
for(unsigned int i = 0; i < isoreflection_rings; i++)
{
double rel_number_of_data_points = 100.0 * number_of_data_points[i] / number_of_data_points_tot;
std::vector<double> u_average = libphysica::Weighted_Average(data[i]);
double u_max = Highest_Speed(i);
std::cout << i + 1 << "\t" << number_of_data_points[i] << "\t\t" << libphysica::Round(rel_number_of_data_points) << "\t\t" << libphysica::Round(In_Units(u_average[0], km / sec)) << " +- " << libphysica::Round(In_Units(u_average[1], km / sec)) << "\t" << libphysica::Round(In_Units(u_max, km / sec)) << std::endl;
}
}
else
{
std::vector<double> u_average = libphysica::Weighted_Average(data[0]);
double u_max = Highest_Speed();
std::cout << "<u> [km/sec]:\t\t\t" << libphysica::Round(In_Units(u_average[0], km / sec)) << " +- " << libphysica::Round(In_Units(u_average[1], km / sec)) << std::endl
<< "u_max [km/sec]:\t\t\t" << libphysica::Round(In_Units(u_max, km / sec)) << std::endl;
}
std::cout << std::endl
<< "Trajectory rate [1/s]:\t\t" << libphysica::Round(1.0 * number_of_trajectories / computing_time) << std::endl
<< "Data generation rate [1/s]:\t" << libphysica::Round(1.0 * number_of_data_points_tot / computing_time) << std::endl
<< "Simulation time:\t\t" << libphysica::Time_Display(computing_time) << std::endl;
std::cout << SEPARATOR << std::endl;
}
}
} // namespace DaMaSCUS_SUN | 47.485714 | 414 | 0.745229 | [
"vector"
] |
e1dcc63c1e3fe54785022ca676fd80e256bbd051 | 2,823 | cpp | C++ | src/logger/logger.cpp | hihi-dev/linphone | 45814404943a0c8a4e341dbebf5da71fc6e44b67 | [
"BSD-2-Clause"
] | null | null | null | src/logger/logger.cpp | hihi-dev/linphone | 45814404943a0c8a4e341dbebf5da71fc6e44b67 | [
"BSD-2-Clause"
] | null | null | null | src/logger/logger.cpp | hihi-dev/linphone | 45814404943a0c8a4e341dbebf5da71fc6e44b67 | [
"BSD-2-Clause"
] | null | null | null | /*
* logger.cpp
* Copyright (C) 2010-2018 Belledonne Communications SARL
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <chrono>
#include <bctoolbox/logging.h>
#include "object/base-object-p.h"
#include "logger.h"
// =============================================================================
using namespace std;
LINPHONE_BEGIN_NAMESPACE
// -----------------------------------------------------------------------------
class LoggerPrivate : public BaseObjectPrivate {
public:
Logger::Level level;
ostringstream os;
};
// -----------------------------------------------------------------------------
Logger::Logger (Level level) : BaseObject(*new LoggerPrivate) {
L_D();
d->level = level;
}
Logger::~Logger () {
L_D();
const string str = d->os.str();
switch (d->level) {
case Debug:
#if DEBUG_LOGS
bctbx_debug("%s", str.c_str());
#endif // if DEBUG_LOGS
break;
case Info:
bctbx_message("%s", str.c_str());
break;
case Warning:
bctbx_warning("%s", str.c_str());
break;
case Error:
bctbx_error("%s", str.c_str());
break;
case Fatal:
bctbx_fatal("%s", str.c_str());
break;
}
}
ostringstream &Logger::getOutput () {
L_D();
return d->os;
}
// -----------------------------------------------------------------------------
class DurationLoggerPrivate : public BaseObjectPrivate {
public:
unique_ptr<Logger> logger;
chrono::high_resolution_clock::time_point start;
};
// -----------------------------------------------------------------------------
DurationLogger::DurationLogger (const string &label, Logger::Level level) : BaseObject(*new DurationLoggerPrivate) {
L_D();
d->logger.reset(new Logger(level));
d->logger->getOutput() << "Duration of [" + label + "]: ";
d->start = chrono::high_resolution_clock::now();
Logger(level).getOutput() << "Start measurement of [" + label + "].";
}
DurationLogger::~DurationLogger () {
L_D();
chrono::high_resolution_clock::time_point end = chrono::high_resolution_clock::now();
d->logger->getOutput() << chrono::duration_cast<chrono::milliseconds>(end - d->start).count() << "ms.";
}
LINPHONE_END_NAMESPACE
| 25.899083 | 116 | 0.598654 | [
"object"
] |
e1eefaf5f14d51eca00a4f32a7b8cb88d27ce9af | 4,371 | hpp | C++ | cuarma/tools/matrix_generation.hpp | yangxianpku/cuarma | 404f20b5b3fa74e5e27338e89343450f8853024c | [
"X11",
"MIT"
] | null | null | null | cuarma/tools/matrix_generation.hpp | yangxianpku/cuarma | 404f20b5b3fa74e5e27338e89343450f8853024c | [
"X11",
"MIT"
] | null | null | null | cuarma/tools/matrix_generation.hpp | yangxianpku/cuarma | 404f20b5b3fa74e5e27338e89343450f8853024c | [
"X11",
"MIT"
] | null | null | null | #pragma once
/* =========================================================================
Copyright (c) 2015-2017, COE of Peking University, Shaoqiang Tang.
-----------------
cuarma - COE of Peking University, Shaoqiang Tang.
-----------------
Author Email yangxianpku@pku.edu.cn
Code Repo https://github.com/yangxianpku/cuarma
License: MIT (X11) License
============================================================================= */
/** @file cuarma/tools/matrix_generation.hpp
* @encoding:UTF-8 文档编码
@brief Helper routines for generating sparse matrices
*/
#include <string>
#include <fstream>
#include <sstream>
#include "cuarma/forwards.h"
#include "cuarma/meta/result_of.hpp"
#include "cuarma/tools/adapter.hpp"
#include <vector>
#include <map>
namespace cuarma
{
namespace tools
{
/** @brief Generates a sparse matrix obtained from a simple finite-difference discretization of the Laplace equation on the unit square (2d).
*
* @tparam MatrixType An uBLAS-compatible matrix type supporting .clear(), .resize(), and operator()-access
* @param A A sparse matrix object from cuarma, total number of unknowns will be points_x*points_y
* @param points_x Number of points in x-direction
* @param points_y Number of points in y-direction
*/
template<typename MatrixType>
void generate_fdm_laplace(MatrixType & A, arma_size_t points_x, arma_size_t points_y)
{
arma_size_t total_unknowns = points_x * points_y;
A.clear();
A.resize(total_unknowns, total_unknowns, false);
for (arma_size_t i=0; i<points_x; ++i)
{
for (arma_size_t j=0; j<points_y; ++j)
{
arma_size_t row = i + j * points_x;
A(row, row) = 4.0;
if (i > 0)
{
arma_size_t col = (i-1) + j * points_x;
A(row, col) = -1.0;
}
if (j > 0)
{
arma_size_t col = i + (j-1) * points_x;
A(row, col) = -1.0;
}
if (i < points_x-1)
{
arma_size_t col = (i+1) + j * points_x;
A(row, col) = -1.0;
}
if (j < points_y-1)
{
arma_size_t col = i + (j+1) * points_x;
A(row, col) = -1.0;
}
}
}
}
template<typename NumericT>
void generate_fdm_laplace(cuarma::compressed_matrix<NumericT> & A, arma_size_t points_x, arma_size_t points_y)
{
// Assemble into temporary matrix on CPU, then copy over:
std::vector< std::map<unsigned int, NumericT> > temp_A;
cuarma::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A);
generate_fdm_laplace(adapted_A, points_x, points_y);
cuarma::copy(temp_A, A);
}
template<typename NumericT>
void generate_fdm_laplace(cuarma::coordinate_matrix<NumericT> & A, arma_size_t points_x, arma_size_t points_y)
{
// Assemble into temporary matrix on CPU, then copy over:
std::vector< std::map<unsigned int, NumericT> > temp_A;
cuarma::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A);
generate_fdm_laplace(adapted_A, points_x, points_y);
cuarma::copy(temp_A, A);
}
template<typename NumericT>
void generate_fdm_laplace(cuarma::ell_matrix<NumericT> & A, arma_size_t points_x, arma_size_t points_y)
{
// Assemble into temporary matrix on CPU, then copy over:
std::vector< std::map<unsigned int, NumericT> > temp_A;
cuarma::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A);
generate_fdm_laplace(adapted_A, points_x, points_y);
cuarma::copy(temp_A, A);
}
template<typename NumericT>
void generate_fdm_laplace(cuarma::sliced_ell_matrix<NumericT> & A, arma_size_t points_x, arma_size_t points_y)
{
// Assemble into temporary matrix on CPU, then copy over:
std::vector< std::map<unsigned int, NumericT> > temp_A;
cuarma::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A);
generate_fdm_laplace(adapted_A, points_x, points_y);
cuarma::copy(temp_A, A);
}
template<typename NumericT>
void generate_fdm_laplace(cuarma::hyb_matrix<NumericT> & A, arma_size_t points_x, arma_size_t points_y)
{
// Assemble into temporary matrix on CPU, then copy over:
std::vector< std::map<unsigned int, NumericT> > temp_A;
cuarma::tools::sparse_matrix_adapter<NumericT> adapted_A(temp_A);
generate_fdm_laplace(adapted_A, points_x, points_y);
cuarma::copy(temp_A, A);
}
} //namespace tools
} //namespace cuarma | 31.221429 | 141 | 0.654084 | [
"object",
"vector"
] |
e1f48013fc294fa427e674eb16a53b131b706c06 | 6,616 | cpp | C++ | example/console-example/main.cpp | domenn/WinToast | 3646723366bddfca509599cadbafdae5230f6def | [
"MIT"
] | 446 | 2016-11-07T19:03:42.000Z | 2022-03-31T21:14:52.000Z | example/console-example/main.cpp | domenn/WinToast | 3646723366bddfca509599cadbafdae5230f6def | [
"MIT"
] | 51 | 2017-05-09T14:42:36.000Z | 2022-02-16T06:30:08.000Z | example/console-example/main.cpp | domenn/WinToast | 3646723366bddfca509599cadbafdae5230f6def | [
"MIT"
] | 104 | 2016-11-21T00:23:51.000Z | 2022-03-15T04:07:23.000Z | #include "wintoastlib.h"
#include <string> // std::string, std::stoi
using namespace WinToastLib;
class CustomHandler : public IWinToastHandler {
public:
void toastActivated() const {
std::wcout << L"The user clicked in this toast" << std::endl;
exit(0);
}
void toastActivated(int actionIndex) const {
std::wcout << L"The user clicked on action #" << actionIndex << std::endl;
exit(16 + actionIndex);
}
void toastDismissed(WinToastDismissalReason state) const {
switch (state) {
case UserCanceled:
std::wcout << L"The user dismissed this toast" << std::endl;
exit(1);
break;
case TimedOut:
std::wcout << L"The toast has timed out" << std::endl;
exit(2);
break;
case ApplicationHidden:
std::wcout << L"The application hid the toast using ToastNotifier.hide()" << std::endl;
exit(3);
break;
default:
std::wcout << L"Toast not activated" << std::endl;
exit(4);
break;
}
}
void toastFailed() const {
std::wcout << L"Error showing current toast" << std::endl;
exit(5);
}
};
enum Results {
ToastClicked, // user clicked on the toast
ToastDismissed, // user dismissed the toast
ToastTimeOut, // toast timed out
ToastHided, // application hid the toast
ToastNotActivated, // toast was not activated
ToastFailed, // toast failed
SystemNotSupported, // system does not support toasts
UnhandledOption, // unhandled option
MultipleTextNotSupported, // multiple texts were provided
InitializationFailure, // toast notification manager initialization failure
ToastNotLaunched // toast could not be launched
};
#define COMMAND_ACTION L"--action"
#define COMMAND_AUMI L"--aumi"
#define COMMAND_APPNAME L"--appname"
#define COMMAND_APPID L"--appid"
#define COMMAND_EXPIREMS L"--expirems"
#define COMMAND_TEXT L"--text"
#define COMMAND_HELP L"--help"
#define COMMAND_IMAGE L"--image"
#define COMMAND_SHORTCUT L"--only-create-shortcut"
#define COMMAND_AUDIOSTATE L"--audio-state"
#define COMMAND_ATTRIBUTE L"--attribute"
void print_help() {
std::wcout << "WinToast Console Example [OPTIONS]" << std::endl;
std::wcout << "\t" << COMMAND_ACTION << L" : Set the actions in buttons" << std::endl;
std::wcout << "\t" << COMMAND_AUMI << L" : Set the App User Model Id" << std::endl;
std::wcout << "\t" << COMMAND_APPNAME << L" : Set the default appname" << std::endl;
std::wcout << "\t" << COMMAND_APPID << L" : Set the App Id" << std::endl;
std::wcout << "\t" << COMMAND_EXPIREMS << L" : Set the default expiration time" << std::endl;
std::wcout << "\t" << COMMAND_TEXT << L" : Set the text for the notifications" << std::endl;
std::wcout << "\t" << COMMAND_IMAGE << L" : set the image path" << std::endl;
std::wcout << "\t" << COMMAND_ATTRIBUTE << L" : set the attribute for the notification" << std::endl;
std::wcout << "\t" << COMMAND_SHORTCUT << L" : create the shortcut for the app" << std::endl;
std::wcout << "\t" << COMMAND_AUDIOSTATE << L" : set the audio state: Default = 0, Silent = 1, Loop = 2" << std::endl;
std::wcout << "\t" << COMMAND_HELP << L" : Print the help description" << std::endl;
}
int wmain(int argc, LPWSTR *argv)
{
if (argc == 1) {
print_help();
return 0;
}
if (!WinToast::isCompatible()) {
std::wcerr << L"Error, your system in not supported!" << std::endl;
return Results::SystemNotSupported;
}
LPWSTR appName = L"Console WinToast Example",
appUserModelID = L"WinToast Console Example",
text = NULL,
imagePath = NULL,
attribute = L"default";
std::vector<std::wstring> actions;
INT64 expiration = 0;
bool onlyCreateShortcut = false;
WinToastTemplate::AudioOption audioOption = WinToastTemplate::AudioOption::Default;
int i;
for (i = 1; i < argc; i++)
if (!wcscmp(COMMAND_IMAGE, argv[i]))
imagePath = argv[++i];
else if (!wcscmp(COMMAND_ACTION, argv[i]))
actions.push_back(argv[++i]);
else if (!wcscmp(COMMAND_EXPIREMS, argv[i]))
expiration = wcstol(argv[++i], NULL, 10);
else if (!wcscmp(COMMAND_APPNAME, argv[i]))
appName = argv[++i];
else if (!wcscmp(COMMAND_AUMI, argv[i]) || !wcscmp(COMMAND_APPID, argv[i]))
appUserModelID = argv[++i];
else if (!wcscmp(COMMAND_TEXT, argv[i]))
text = argv[++i];
else if (!wcscmp(COMMAND_ATTRIBUTE, argv[i]))
attribute = argv[++i];
else if (!wcscmp(COMMAND_SHORTCUT, argv[i]))
onlyCreateShortcut = true;
else if (!wcscmp(COMMAND_AUDIOSTATE, argv[i]))
audioOption = static_cast<WinToastTemplate::AudioOption>(std::stoi(argv[++i]));
else if (!wcscmp(COMMAND_HELP, argv[i])) {
print_help();
return 0;
} else {
std::wcerr << L"Option not recognized: " << argv[i] << std::endl;
return Results::UnhandledOption;
}
WinToast::instance()->setAppName(appName);
WinToast::instance()->setAppUserModelId(appUserModelID);
if (onlyCreateShortcut) {
if (imagePath || text || actions.size() > 0 || expiration) {
std::wcerr << L"--only-create-shortcut does not accept images/text/actions/expiration" << std::endl;
return 9;
}
enum WinToast::ShortcutResult result = WinToast::instance()->createShortcut();
return result ? 16 + result : 0;
}
if (!text)
text = L"Hello, world!";
if (!WinToast::instance()->initialize()) {
std::wcerr << L"Error, your system in not compatible!" << std::endl;
return Results::InitializationFailure;
}
bool withImage = (imagePath != NULL);
WinToastTemplate templ( withImage ? WinToastTemplate::ImageAndText02 : WinToastTemplate::Text02);
templ.setTextField(text, WinToastTemplate::FirstLine);
templ.setAudioOption(audioOption);
templ.setAttributionText(attribute);
for (auto const &action : actions)
templ.addAction(action);
if (expiration)
templ.setExpiration(expiration);
if (withImage)
templ.setImagePath(imagePath);
if (WinToast::instance()->showToast(templ, new CustomHandler()) < 0) {
std::wcerr << L"Could not launch your toast notification!";
return Results::ToastFailed;
}
// Give the handler a chance for 15 seconds (or the expiration plus 1 second)
Sleep(expiration ? (DWORD)expiration + 1000 : 15000);
exit(2);
}
| 35.762162 | 122 | 0.621826 | [
"vector",
"model"
] |
e1f9c4587758f59606c3e9903a5eb2266e2a3784 | 24,065 | cpp | C++ | fractals/mandel_quadtree/server/server.cpp | MS-DOS-stuff/reenigne | 0a113990aef398550c6f14d1c7a33af1cb091887 | [
"Unlicense"
] | 1 | 2021-05-24T05:18:10.000Z | 2021-05-24T05:18:10.000Z | fractals/mandel_quadtree/server/server.cpp | MS-DOS-stuff/reenigne | 0a113990aef398550c6f14d1c7a33af1cb091887 | [
"Unlicense"
] | null | null | null | fractals/mandel_quadtree/server/server.cpp | MS-DOS-stuff/reenigne | 0a113990aef398550c6f14d1c7a33af1cb091887 | [
"Unlicense"
] | null | null | null | // Fractal computation server.
//
// Because the networking overhead should be small compared to the computation
// time, we only use a single thread for IO. A more network-bound server would
// want to do IO completion processing on multiple threads.
#include "def.h"
#include "../long_fixed.cpp"
#include "socket.h"
#include "linkedlist.h"
#include "vectors.h"
#include <vector>
#include "complex.h"
class Server : public Mutex
{
class BoxEntry
{
public:
Digit* zx() { return reinterpret_cast<Digit*>(this + 1); }
Digit* zy(int precision) { return zx() + precision; }
Digit* zSx(int precision) { return zy(precision) + precision; }
Digit* zSy(int precision) { return zSx(precision) + precision; }
static int bytes(int precision)
{
return sizeof(BoxEntry) + 4*precision*sizeof(Digit);
}
Vector _texel;
int _iterations;
// Data follows in "struct hack" fashion:
// _precision words for z.x value
// _precision words for z.y value
// _precision words for zS.x value
// _precision words for zS.y value
};
class AcceptSocket;
friend class AcceptSocket;
class Box : public LinkedListMember<Box>
{
public:
Digit* cx() { return reinterpret_cast<Digit*>(this + 1); }
Digit* cy() { return cx() + _precision; }
BoxEntry* entry(int n)
{
return &reinterpret_cast<BoxEntry*>(cy() + _precision)[n];
}
int bytes()
{
return (7 + _precision*2 + _points*(3 + 4*_precision))*4;
}
char* buffer() { return reinterpret_cast<char*>(&_points); }
// Our boxes need to be big enough to hold a single point at
// maximum precision.
static int bufferSize() { return (1024*6 + 10)*4; }
bool valid()
{
return _points > 0 && _points <= (bufferSize() - 9*4)/(7*4) &&
_precision > 0 && _precision <= 1024 &&
bytes() <= bufferSize();
}
Server::AcceptSocket* _socket;
int _points;
int _precision; // ignored in outgoing boxes
int _pointGeneration; // Not actually used by server, just passed back
int _bailoutRadius2; // ignored in outgoing boxes
int _logDelta; // ignored in outgoing boxes
int _maximumIterations; // client should use value returned by server
int _logUnitsPerTexel; // ignored in outgoing boxes
// Data follows in "struct hack" fashion:
// _precision words for c.x value at texel 0, 0 (ignored in outgoing)
// _precision words for c.y value at texel 0, 0 (ignored in outgoing)
// _points BoxEntry objects
};
class AcceptSocket
: public Socket, public LinkedListMember<AcceptSocket>
{
class BoxCompletion : public IOCompletion
{
public:
void setSocket(AcceptSocket* socket) { _socket = socket; }
virtual void process(DWORD bytesTransferred,
OVERLAPPED* overlapped, bool success)
{
_socket->boxCompleted();
}
private:
AcceptSocket* _socket;
};
class AcceptCompletion : public IOCompletion
{
public:
void setSocket(AcceptSocket* socket) { _socket = socket; }
virtual void process(DWORD bytesTransferred,
OVERLAPPED* overlapped, bool success)
{
_socket->acceptCompleted(bytesTransferred, overlapped,
success);
}
private:
AcceptSocket* _socket;
};
public:
AcceptSocket(Server* server)
: Socket(&server->_addressInformation),
_addressInformation(&server->_addressInformation),
_server(server),
_buffer(2*(_addressInformation->addressLength() + 16))
{
_acceptCompletion.setSocket(this);
_boxCompletion.setSocket(this);
ZeroMemory(&_acceptOverlapped, sizeof(OVERLAPPED));
ZeroMemory(&_sendOverlapped, sizeof(OVERLAPPED));
}
void accept()
{
// Set zero TCP stack receive and send buffer, so that the TCP
// stack will perform IO directly into/out of our buffers.
int bufferSize = 0;
IF_NONZERO_THROW(setsockopt(*this, SOL_SOCKET, SO_SNDBUF,
reinterpret_cast<char*>(&bufferSize), sizeof(bufferSize)));
IF_NONZERO_THROW(setsockopt(*this, SOL_SOCKET, SO_RCVBUF,
reinterpret_cast<char*>(&bufferSize), sizeof(bufferSize)));
// We give a receive buffer size here of 0 so that we are notified
// as soon as a connection occurs, in order that we can start
// another accept immediately. We could get slightly better
// performance by specifying enough buffer for an initial box as
// well, but then we would need extra code to guard against a
// hostile client that connects but then sends no data (this can be
// done by calling WSAEventSelect() to register for FD_ACCEPT
// events). The complexity is not worth the insignificant
// performance improvement for this application.
BOOL result = _server->_acceptEx(_server->_listenSocket, *this,
&_buffer[0], 0, _addressInformation->addressLength() + 16,
_addressInformation->addressLength() + 16, &_bytesReceived,
&_acceptOverlapped);
if (result == FALSE)
if (GetLastError() != ERROR_IO_PENDING)
handleError();
}
void moveToOutgoing(Box* box)
{
_outgoingBoxes.add(box);
_server->_ioCompletionPort.post(&_boxCompletion);
}
void initiateReceive()
{
// Each time a box is iterated and there are insufficient boxes
// queued up, we'll download at most a couple of boxes. If we only
// downloaded one there would be no chance of getting the queue
// filled.
_boxesToReceive += 2;
extract();
}
private:
bool checkClose()
{
if (!_closing)
return false;
if (!_sending && !_receiving) {
open();
_server->moveToReserve(this);
}
return true;
}
bool handleError()
{
DWORD error = GetLastError();
if (error == WSAECONNABORTED || error == WSAECONNRESET ||
error == WSAEDISCON || error == WSAENETDOWN ||
error == WSAENETRESET || error == WSAETIMEDOUT ||
error == WSA_OPERATION_ABORTED) {
_accepted = false;
_closing = true;
return checkClose();
}
IF_FALSE_THROW(false);
// TODO: retry on WSAEINPROGRESS, WSAENOBUFS and WSAEWOUDLBLOCK?
// TODO: tear down socket on WSAENOTCONN?
}
void acceptCompleted(DWORD bytesTransferred, OVERLAPPED* overlapped,
bool success)
{
if (overlapped == &_sendOverlapped) {
_sending = false;
if (checkClose())
return;
if (!success)
handleError();
else
sendNextBox();
return;
}
if (_accepted) {
// Must have been a receive
_receiving = false;
if (checkClose())
return;
_receiveOffset += bytesTransferred;
if (!success)
handleError();
else
extract();
return;
}
if (!success) {
handleError();
return;
}
// Allow other clients to connect.
_server->openNewConnection();
// Inherit socket properties from the listening socket.
IF_NONZERO_THROW(setsockopt(*this, SOL_SOCKET,
SO_UPDATE_ACCEPT_CONTEXT,
reinterpret_cast<char *>(&_server->_listenSocket._handle),
sizeof(SOCKET)));
// Associate this socket with the IO completion port.
_server->_ioCompletionPort.associate(this, &_acceptCompletion);
// Start things moving
_boxesToReceive = 0;
_receiveOffset = 0;
_incomingBox = _server->getEmptyBox();
_incomingBox->_socket = this;
_server->startThreads();
_sending = false;
_receiving = false;
_accepted = true;
}
void boxCompleted()
{
if (!_sending)
sendNextBox();
}
// Attempt to extract boxes from the buffer until we've extracted
// enough. If we run out of buffered data, initiate a receive.
void extract()
{
while (_boxesToReceive > 0) {
if (_receiveOffset >= 8) {
// We have enough to determine the expected size of the box
if (!_incomingBox->valid()) {
// TODO: close connection? Break up box into smaller
// ones?
}
int bytes = _incomingBox->bytes();
if (_receiveOffset >= bytes) {
// Received the entire box.
--_boxesToReceive;
Box* box = _incomingBox;
_incomingBox = _server->getEmptyBox();
_incomingBox->_socket = this;
// Move any residual data to the new incoming box.
_receiveOffset -= bytes;
memcpy(_incomingBox->buffer(), box->buffer(),
_receiveOffset);
_server->moveToUniterated(box);
continue;
}
}
// Insufficient data - kick off another read
WSABUF bufferDescriptor;
bufferDescriptor.len = Box::bufferSize() - _receiveOffset;
bufferDescriptor.buf = _incomingBox->buffer() + _receiveOffset;
BOOL result = WSARecv(*this, &bufferDescriptor, 1, NULL, 0,
&_acceptOverlapped, 0);
if (result != 0)
if (GetLastError() != WSA_IO_PENDING)
handleError();
// Success case and delayed failure case will be handled by
// the completion routine.
}
}
void sendNextBox()
{
Box* box = _outgoingBoxes.getNext();
if (box == 0)
return;
WSABUF bufferDescriptor;
bufferDescriptor.len = box->bytes();
bufferDescriptor.buf = box->buffer();
int result = WSASend(*this, &bufferDescriptor, 1, NULL, 0,
&_sendOverlapped, 0);
if (result != 0)
if (GetLastError() != WSA_IO_PENDING)
handleError();
_sending = true;
}
AddressInformation* _addressInformation;
Box* _incomingBox;
LinkedList<Box> _outgoingBoxes;
Server* _server;
AcceptCompletion _acceptCompletion;
BoxCompletion _boxCompletion;
std::vector<Byte> _buffer;
OVERLAPPED _acceptOverlapped;
OVERLAPPED _sendOverlapped;
DWORD _bytesReceived;
int _receiveOffset;
int _boxesToReceive;
bool _sending;
bool _receiving;
bool _accepted;
bool _closing;
};
class CalculationThread : public Thread
{
public:
CalculationThread(Server* server)
: _server(server),
_ending(false),
_failed(false),
_running(false),
_box(0)
{
_ready.reset();
_finished.reset();
}
// Signals the thread to come to an end.
void end() { _ending = true; _ready.set(); }
bool running() const { return _running; }
// Start the thread.
void go()
{
_finished.reset();
_ready.set();
}
private:
int doubleIterate()
{
Complex<double> z;
z.x = doubleFromFixed(_zx, 0, _precision);
z.y = doubleFromFixed(_zy, 0, _precision);
Complex<double> zS;
zS.x = doubleFromFixed(_zSx, 0, _precision);
zS.y = doubleFromFixed(_zSy, 0, _precision);
Complex<double> c;
c.x = doubleFromFixed(_t[4], 0, _precision);
c.y = doubleFromFixed(_t[5], 0, _precision);
int maximumIterations = _maximumIterations;
double delta = ldexp(1.0, _logDelta);
double bailoutRadius2 = ldexp(static_cast<double>(_bailoutRadius2),
intBits - bitsPerDigit);
for (int i = 0; i < maximumIterations; i += 2) {
double zr2 = z.x*z.x;
double zi2 = z.y*z.y;
z = Complex<double>(zr2 - zi2 + c.x, 2*z.x*z.y + c.y);
if (zr2 + zi2 > bailoutRadius2)
return i + 1;
zr2 = z.x*z.x;
zi2 = z.y*z.y;
z = Complex<double>(zr2 - zi2 + c.x, 2*z.x*z.y + c.y);
if (zr2 + zi2 > bailoutRadius2)
return i + 2;
zr2 = zS.x*zS.x;
zi2 = zS.y*zS.y;
zS = Complex<double>(zr2 - zi2 + c.x, 2*zS.x*zS.y + c.y);
Complex<double> d = z - zS;
if (abs(d.x) < delta && abs(d.y) < delta)
return -(i + 2);
}
fixedFromDouble(_zx, z.x, 0, _precision);
fixedFromDouble(_zy, z.y, 0, _precision);
fixedFromDouble(_zSx, zS.x, 0, _precision);
fixedFromDouble(_zSy, zS.y, 0, _precision);
return -1;
}
int longFixedIterate()
{
int p = _precision;
fixedFromDouble(_t[3], 1.0, _logDelta, p);
int maximumIterations = _maximumIterations;
for (int i = 0; i < maximumIterations; i += 2) {
multiply(_t[0], _zx, _zx, _t[6], p);
multiply(_t[1], _zy, _zy, _t[6], p);
add(_t[2], _t[0], _t[1], p);
if (static_cast<SignedDigit>(_t[2][p - 1]) > _bailoutRadius2)
return i + 1;
multiply(_t[2], _zx, _zy, _t[6], p, intBits + 1);
add(_zx, _t[0], _t[4], p);
sub(_zx, _zx, _t[1], p);
add(_zy, _t[2], _t[5], p);
multiply(_t[0], _zx, _zx, _t[6], p);
multiply(_t[1], _zy, _zy, _t[6], p);
add(_t[2], _t[0], _t[1], p);
if (static_cast<SignedDigit>(_t[2][p - 1]) > _bailoutRadius2)
return i + 2;
multiply(_t[2], _zx, _zy, _t[6], p, intBits + 1);
add(_zx, _t[0], _t[4], p);
sub(_zx, _zx, _t[1], p);
add(_zy, _t[2], _t[5], p);
multiply(_t[0], _zSx, _zSx, _t[6], p);
multiply(_t[1], _zSy, _zSy, _t[6], p);
multiply(_t[2], _zSx, _zSy, _t[6], p, intBits + 1);
add(_zSx, _t[0], _t[4], p);
sub(_zSx, _zSx, _t[1], p);
add(_zSy, _t[2], _t[5], p);
sub(_t[0], _zSx, _zx, p);
abs(_t[0], _t[0], p);
if (lessThan(_t[0], _t[3], p)) {
sub(_t[0], _zSy, _zy, p);
abs(_t[0], _t[0], p);
if (lessThan(_t[0], _t[3], p))
return -(i + 2);
}
}
return -1;
}
bool processOneBox()
{
{
Lock lock(_server);
if (_box != 0)
_box->_socket->moveToOutgoing(_box);
_box = _server->getUniteratedBox();
if (_box == 0)
return false;
}
_precision = _box->_precision;
// Server may also use its own preferred value for
// _maximumIterations, as long as it returns in the box the same
// value that it uses.
_maximumIterations = _box->_maximumIterations;
_logDelta = _box->_logDelta;
_bailoutRadius2 = _box->_bailoutRadius2;
// Setup up temporary buffers
_buffer.ensureLength(10*_precision);
Digit* t = _buffer;
for (int i = 0; i < 7; ++i) {
_t[i] = t;
t += _precision;
}
for (int i = 0; i < _box->_points; ++i) {
BoxEntry* entry = _box->entry(i);
fixedFromDouble(_t[4], entry->_point.x,
_box->_logUnitsPerPoint, _precision);
add(_t[4], _t[4], _box->cx(), _precision);
fixedFromDouble(_t[5], entry->_point.y,
_box->_logUnitsPerPoint, _precision);
add(_t[5], _t[5], _box->cy(), _precision);
_zx = entry->zx();
_zy = entry->zy(_precision);
_zSx = entry->zSx(_precision);
_zSy = entry->zSy(_precision);
if (_precision <= 2)
entry->_iterations = doubleIterate();
else
entry->_iterations = longFixedIterate();
}
return true;
}
void threadProc()
{
BEGIN_CHECKED {
do {
_ready.wait();
_ready.reset();
while (processOneBox())
;
_finished.set();
} while (!_ending);
} END_CHECKED(Exception& e) {
_exception = e;
_failed = true;
_finished.set();
}
}
// Wait for a thread to finish if it hasn't already and rethrow the
// exception on the main thread if it failed.
void check()
{
_finished.wait();
_finished.reset();
if (_failed)
throw _exception;
}
Exception _exception;
Box* _box;
int _precision;
int _maximumIterations;
int _logDelta;
SignedDigit _bailoutRadius2;
volatile bool _failed;
volatile bool _ending;
volatile bool _running;
Event _ready;
Event _finished;
Server* _server;
DigitBuffer _buffer;
Digit* _t[7];
Digit* _zx;
Digit* _zy;
Digit* _zSx;
Digit* _zSy;
};
void openNewConnection()
{
AcceptSocket* socket = getSocket();
socket->accept();
}
public:
Server(const char* port)
: _addressInformation(port),
_listenSocket(&_addressInformation),
_uniteratedCount(0),
_threadCount(0)
{
_listenSocket.bind();
_listenSocket.listen();
LPFN_ACCEPTEX acceptEx = 0;
DWORD bytes;
GUID guidAcceptEx = WSAID_ACCEPTEX;
IF_NONZERO_THROW(WSAIoctl(_listenSocket,
SIO_GET_EXTENSION_FUNCTION_POINTER,
&guidAcceptEx,
sizeof(guidAcceptEx),
&_acceptEx,
sizeof(_acceptEx),
&bytes,
NULL,
NULL));
openNewConnection();
// Count available threads
DWORD_PTR pam, sam;
IF_ZERO_THROW(GetProcessAffinityMask(GetCurrentProcess(), &pam, &sam));
for (DWORD_PTR p = 1; p != 0; p <<= 1)
if ((pam&p) != 0)
++_threadCount;
_threads.resize(_threadCount, 0);
for (int i = 0; i < _threadCount; ++i) {
CalculationThread* thread = new CalculationThread(this);
thread->setPriority(THREAD_PRIORITY_BELOW_NORMAL);
_threads[i] = thread;
thread->start();
}
}
~Server()
{
// Tell the threads to stop what they're doing.
for (int i = 0; i < _threadCount; ++i) {
CalculationThread* thread = _threads[i];
if (thread != 0)
thread->end();
}
// Wait for them all to actually stop and delete them. Don't rethrow
// any exceptions here.
for (int i = 0; i < _threadCount; ++i) {
CalculationThread* thread = _threads[i];
if (thread != 0) {
thread->join();
delete thread;
}
}
// Delete all the sockets.
for (auto& socket : _reserveSockets) {
socket.remove();
delete &socket;
}
// Delete all the boxes.
for (auto& box : _emptyBoxes) {
box.remove();
free(&box);
}
}
void loop()
{
while (true)
_ioCompletionPort.process();
}
AcceptSocket* getSocket()
{
AcceptSocket* socket = _reserveSockets.getNext();
if (socket == 0)
socket = new AcceptSocket(this);
else
socket->remove();
_activeSockets.add(socket);
return socket;
}
void moveToReserve(AcceptSocket* socket)
{
socket->remove();
_reserveSockets.add(socket);
}
Box* getEmptyBox()
{
Box* box = _emptyBoxes.getNext();
if (box == 0)
box = static_cast<Box*>(malloc(Box::bufferSize()));
else
box->remove();
return box;
}
Box* getUniteratedBox()
{
Box* box = _uniteratedBoxes.getNext();
if (box != 0)
box->remove();
--_uniteratedCount;
// Use a higher multiple of _threadCount below if we end up with idle
// threads.
if (_uniteratedCount < _threadCount) {
// Give each client a chance to give us another box.
for (auto& socket : _activeSockets)
socket.initiateReceive();
}
return box;
}
void moveToEmpty(Box* box) { _emptyBoxes.add(box); }
void startThreads()
{
for (int i = 0; i < _threadCount; ++i) {
CalculationThread* thread = _threads[i];
if (!thread->running())
thread->go();
}
}
void moveToUniterated(Box* box)
{
_uniteratedBoxes.add(box);
++_uniteratedCount;
// Now we have some work to do - make sure we have some threads to do
// it.
startThreads();
}
private:
WindowsSockets _windowsSockets;
IOCompletionPort _ioCompletionPort;
AddressInformation _addressInformation;
Socket _listenSocket;
int _threadCount;
LinkedList<AcceptSocket> _reserveSockets;
LinkedList<AcceptSocket> _activeSockets;
LinkedList<Box> _emptyBoxes;
LinkedList<Box> _uniteratedBoxes;
int _uniteratedCount;
LPFN_ACCEPTEX _acceptEx;
std::vector<CalculationThread*> _threads;
};
INT APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR lpCmdLine, INT)
{
const char* port = "24448";
if (lpCmdLine[0] != 0)
port = lpCmdLine;
do {
BEGIN_CHECKED {
Server server(port);
server.loop();
} END_CHECKED(Exception&) {
// Wait a couple of seconds before restarting so that a persistent
// failure doesn't cause us to peg the CPU.
Sleep(2000);
// Ignore exception and restart server.
}
} while (true);
}
| 33.846695 | 79 | 0.505631 | [
"vector"
] |
e1fbc65c8ed76685fd0a7092efe7cb274734caf1 | 462 | cpp | C++ | DevRookies/DevRookies/GUIImage.cpp | DevRookies/Development | 6ed89ccbe1bb265271299bc9e8196879727aa430 | [
"MIT"
] | null | null | null | DevRookies/DevRookies/GUIImage.cpp | DevRookies/Development | 6ed89ccbe1bb265271299bc9e8196879727aa430 | [
"MIT"
] | null | null | null | DevRookies/DevRookies/GUIImage.cpp | DevRookies/Development | 6ed89ccbe1bb265271299bc9e8196879727aa430 | [
"MIT"
] | null | null | null | #include "DevRookiesApp.h"
#include "GUIImage.h"
#include "p2Log.h"
#include "Textures.h"
#include "Render.h"
GUIImage::GUIImage(iPoint pos, SDL_Rect rect, SDL_Texture* texture): GUIElement(pos, GUI_Type::IMAGE, false, parent)
{
this->position = pos;
this->rect = rect;
this->texture = texture;
}
GUIImage::~GUIImage()
{
}
bool GUIImage::PostUpdate()
{
bool ret = false;
App->render->Blit(texture, position.x, position.y, &rect,0.0f);
return ret;
}
| 16.5 | 116 | 0.694805 | [
"render"
] |
c001899780c4be5078a81fe9b8fdec962a81972e | 921 | cpp | C++ | codes/tree/centroid.cpp | arunrajora/algorithms | 3590deefbf94382e10ebd16692118328fc9b538a | [
"MIT"
] | 1 | 2017-08-20T20:35:53.000Z | 2017-08-20T20:35:53.000Z | codes/tree/centroid.cpp | arunrajora/algorithms | 3590deefbf94382e10ebd16692118328fc9b538a | [
"MIT"
] | null | null | null | codes/tree/centroid.cpp | arunrajora/algorithms | 3590deefbf94382e10ebd16692118328fc9b538a | [
"MIT"
] | 1 | 2017-06-10T18:51:56.000Z | 2017-06-10T18:51:56.000Z |
// centroid of a tree
// subtree of centroid has size <=(N/2)
#include<iostream>
#include<vector>
#include<queue>
#include<algorithm>
using namespace std;
#define N 100005
vector<int> tree[N];
int rec_centroid(int u,int parent,int n){
int count=1;
bool isGoodCenter=true;
for(int i=0;i<tree[u].size();i++){
if(tree[u][i]==parent){
continue;
}
int val=rec_centroid(tree[u][i],u,n);
if(val>=0){
return val;
}
isGoodCenter&=(-val)<=(n/2);
count-=val;
}
isGoodCenter&=(n-count)<=(n/2);
return isGoodCenter?u:-count;
}
int centroidOfTree(int n){
return rec_centroid(0,-1,n);
}
int main(){
tree[0].push_back(1);
tree[1].push_back(0);
tree[1].push_back(2);
tree[1].push_back(4);
tree[2].push_back(1);
tree[2].push_back(3);
tree[3].push_back(2);
tree[3].push_back(5);
tree[4].push_back(1);
tree[5].push_back(3);
tree[5].push_back(6);
tree[6].push_back(5);
cout<<centroidOfTree(7);
}
| 18.058824 | 41 | 0.652552 | [
"vector"
] |
c00eeb05268d012790344b8b148fd28e0cc060f5 | 3,756 | cpp | C++ | Gems/SceneProcessing/Code/Source/Config/SettingsObjects/SoftNameSetting.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-09-13T00:01:12.000Z | 2021-09-13T00:01:12.000Z | Gems/SceneProcessing/Code/Source/Config/SettingsObjects/SoftNameSetting.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | null | null | null | Gems/SceneProcessing/Code/Source/Config/SettingsObjects/SoftNameSetting.cpp | aaarsene/o3de | 37e3b0226958974defd14dd6d808e8557dcd7345 | [
"Apache-2.0",
"MIT"
] | 1 | 2021-07-20T11:07:25.000Z | 2021-07-20T11:07:25.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzCore/Serialization/EditContext.h>
#include <AzCore/std/sort.h>
#include <SceneAPI/SceneCore/Events/GraphMetaInfoBus.h>
#include <Config/SettingsObjects/SoftNameSetting.h>
namespace AZ
{
namespace SceneProcessingConfig
{
SoftNameSetting::SoftNameSetting(const char* pattern, SceneAPI::SceneCore::PatternMatcher::MatchApproach approach,
const char* virtualType)
: m_pattern(pattern, approach)
, m_virtualType(virtualType)
{
}
SoftNameSetting::~SoftNameSetting() = default;
Crc32 SoftNameSetting::GetVirtualTypeHash() const
{
if (m_virtualTypeHash == Crc32())
{
m_virtualTypeHash = Crc32(m_virtualType.c_str());
}
return m_virtualTypeHash;
}
const AZStd::string& SoftNameSetting::GetVirtualType() const
{
return m_virtualType;
}
void SoftNameSetting::Reflect(ReflectContext* context)
{
SerializeContext* serialize = azrtti_cast<SerializeContext*>(context);
if (serialize)
{
serialize->Class<SoftNameSetting>()
->Version(1)
->Field("pattern", &SoftNameSetting::m_pattern)
->Field("virtualType", &SoftNameSetting::m_virtualType);
EditContext* editContext = serialize->GetEditContext();
if (editContext)
{
editContext->Class<SoftNameSetting>("Soft name setting", "A pattern matcher to setup project specific naming conventions.")
->ClassElement(Edit::ClassElements::EditorData, "")
->Attribute(Edit::Attributes::AutoExpand, true)
->Attribute(Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20))
->DataElement(Edit::UIHandlers::Default, &SoftNameSetting::m_pattern, "Pattern",
"The pattern the matcher will check against.")
->Attribute(Edit::Attributes::Visibility, AZ_CRC("PropertyVisibility_ShowChildrenOnly", 0xef428f20))
->DataElement(Edit::UIHandlers::ComboBox, &SoftNameSetting::m_virtualType, "Virtual Type",
"The node(s) will be converted to this type after their pattern matches.")
->Attribute(Edit::Attributes::StringList, &SoftNameSetting::GetAllVirtualTypes);
}
}
}
AZStd::vector<AZStd::string> SoftNameSetting::GetAllVirtualTypes() const
{
using namespace SceneAPI::Events;
AZStd::set<Crc32> virtualTypes;
GraphMetaInfoBus::Broadcast(&GraphMetaInfoBus::Events::GetAllVirtualTypes, virtualTypes);
AZStd::vector<AZStd::string> result;
for (Crc32 virtualType : virtualTypes)
{
AZStd::string virtualTypeName;
GraphMetaInfoBus::Broadcast(&GraphMetaInfoBus::Events::GetVirtualTypeName, virtualTypeName, virtualType);
AZ_Assert(!virtualTypeName.empty(), "No name found for virtual type with hash %i.", static_cast<u32>(virtualType));
result.emplace_back(AZStd::move(virtualTypeName));
}
AZStd::sort(result.begin(), result.end());
return result;
}
} // namespace SceneProcessingConfig
} // namespace AZ
| 41.733333 | 158 | 0.602236 | [
"vector",
"3d"
] |
c00eeb8803400b720c4d85b1e155db9fbf6672a3 | 14,463 | cpp | C++ | src/modules/hip/hip_color_model_conversions.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 26 | 2019-09-04T17:48:41.000Z | 2022-02-23T17:04:24.000Z | src/modules/hip/hip_color_model_conversions.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 57 | 2019-09-06T21:37:34.000Z | 2022-03-09T02:13:46.000Z | src/modules/hip/hip_color_model_conversions.cpp | shobana-mcw/rpp | e4a5eb622b9abd0a5a936bf7174a84a5e2470b59 | [
"MIT"
] | 24 | 2019-09-04T23:12:07.000Z | 2022-03-30T02:06:22.000Z | #include "hip/hip_runtime_api.h"
#include "hip_declarations.hpp"
#include "kernel/rpp_hip_host_decls.hpp"
/******************** color_temperature ********************/
RppStatus
color_temperature_hip(Rpp8u* srcPtr, RppiSize srcSize, Rpp8u* dstPtr, Rpp32s adjustmentValue, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{(srcSize.width + 31) & ~31, (srcSize.height + 31) & ~31, 1};
handle.AddKernel("", "", "color_temperature.cpp", "temperature_planar", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel,
adjustmentValue);
}
else
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{(srcSize.width + 31) & ~31, (srcSize.height + 31) & ~31, 1};
handle.AddKernel("", "", "color_temperature.cpp", "temperature_packed", vld, vgd, "")(srcPtr,
dstPtr,
srcSize.height,
srcSize.width,
channel,
adjustmentValue);
}
return RPP_SUCCESS;
}
RppStatus
color_temperature_hip_batch(Rpp8u* srcPtr, Rpp8u* dstPtr, rpp::Handle& handle, RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_color_temperature_batch(srcPtr, dstPtr, handle, chnFormat, channel, plnpkdind, max_height, max_width);
return RPP_SUCCESS;
}
/******************** vignette ********************/
RppStatus
vignette_hip(Rpp8u* srcPtr, RppiSize srcSize, Rpp8u* dstPtr, float stdDev, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
return RPP_SUCCESS;
}
RppStatus
vignette_hip_batch(Rpp8u* srcPtr, Rpp8u* dstPtr, rpp::Handle& handle, RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_vignette_batch(srcPtr, dstPtr, handle, chnFormat, channel, plnpkdind, max_height, max_width);
return RPP_SUCCESS;
}
/******************** channel_extract ********************/
RppStatus
channel_extract_hip(Rpp8u* srcPtr, RppiSize srcSize, Rpp8u* dstPtr, Rpp32u extractChannelNumber, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
return RPP_SUCCESS;
}
RppStatus
channel_extract_hip_batch(Rpp8u* srcPtr, Rpp8u* dstPtr, rpp::Handle& handle, RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_channel_extract_batch(srcPtr, dstPtr, handle, chnFormat, channel, plnpkdind, max_height, max_width);
return RPP_SUCCESS;
}
/******************** channel_combine ********************/
RppStatus
channel_combine_hip(Rpp8u* srcPtr1, Rpp8u* srcPtr2, Rpp8u* srcPtr3, RppiSize srcSize, Rpp8u* dstPtr, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
if (chnFormat == RPPI_CHN_PLANAR)
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{(srcSize.width + 31) & ~31, (srcSize.height + 31) & ~31, 1};
handle.AddKernel("", "", "channel_combine.cpp", "channel_combine_pln", vld, vgd, "")(srcPtr1,
srcPtr2,
srcPtr3,
dstPtr,
srcSize.height,
srcSize.width,
channel);
}
else
{
std::vector<size_t> vld{32, 32, 1};
std::vector<size_t> vgd{(srcSize.width + 31) & ~31, (srcSize.height + 31) & ~31, 1};
handle.AddKernel("", "", "channel_combine.cpp", "channel_combine_pkd", vld, vgd, "")(srcPtr1,
srcPtr2,
srcPtr3,
dstPtr,
srcSize.height,
srcSize.width,
channel);
}
return RPP_SUCCESS;
}
RppStatus
channel_combine_hip_batch(Rpp8u* srcPtr1, Rpp8u* srcPtr2, Rpp8u* srcPtr3, Rpp8u* dstPtr,rpp::Handle& handle, RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_channel_combine_batch(srcPtr1, srcPtr2, srcPtr3, dstPtr, handle, chnFormat, channel, plnpkdind, max_height, max_width);
return RPP_SUCCESS;
}
/******************** hueRGB ********************/
RppStatus
hueRGB_hip(Rpp8u* srcPtr,RppiSize srcSize, Rpp8u* dstPtr, float hue_factor, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
float sat = 0.0;
std::vector<size_t> vld{16, 16, 1};
std::vector<size_t> vgd{((srcSize.width + 15)/16) * 16, ((srcSize.height + 15)/16) * 16, 1};
if (chnFormat == RPPI_CHN_PLANAR)
{
handle.AddKernel("", "", "hue.cpp", "huergb_pln", vld, vgd, "")(srcPtr,
dstPtr,
hue_factor,
sat,
srcSize.height,
srcSize.width);
}
else
{
handle.AddKernel("", "", "hue.cpp", "huergb_pkd", vld, vgd, "")(srcPtr,
dstPtr,
hue_factor,
sat,
srcSize.height,
srcSize.width);
}
return RPP_SUCCESS;
}
RppStatus
hueRGB_hip_batch(Rpp8u* srcPtr, Rpp8u* dstPtr, rpp::Handle& handle, RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_hueRGB_batch(srcPtr, dstPtr, handle, plnpkdind, max_height, max_width);
return RPP_SUCCESS;
}
/******************** saturationRGB ********************/
RppStatus
saturationRGB_hip(Rpp8u* srcPtr,RppiSize srcSize, Rpp8u* dstPtr, float sat, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
float hue_factor = 0.0;
std::vector<size_t> vld{16, 16, 1};
std::vector<size_t> vgd{((srcSize.width + 15)/16) * 16, ((srcSize.height + 15)/16) * 16, 1};
if (chnFormat == RPPI_CHN_PLANAR)
{
handle.AddKernel("", "", "hue.cpp", "huergb_pln", vld, vgd, "")(srcPtr,
dstPtr,
hue_factor,
sat,
srcSize.height,
srcSize.width);
}
else
{
handle.AddKernel("", "", "hue.cpp", "huergb_pkd", vld, vgd, "")(srcPtr,
dstPtr,
hue_factor,
sat,
srcSize.height,
srcSize.width);
}
return RPP_SUCCESS;
}
RppStatus
saturationRGB_hip_batch(Rpp8u* srcPtr, Rpp8u* dstPtr, rpp::Handle& handle, RppiChnFormat chnFormat, unsigned int channel)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_saturationRGB_batch(srcPtr, dstPtr, handle, plnpkdind, max_height, max_width);
return RPP_SUCCESS;
}
/******************** color_convert ********************/
RppStatus
color_convert_hip_batch_u8_fp32(Rpp8u* srcPtr, Rpp32f* dstPtr, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_convert_batch_rgb_hsv(srcPtr, dstPtr, handle, plnpkdind, max_width, max_height);
return RPP_SUCCESS;
}
RppStatus
color_convert_hip_batch_fp32_u8(Rpp32f* srcPtr, Rpp8u* dstPtr, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_convert_batch_hsv_rgb(srcPtr, dstPtr, handle, plnpkdind, max_width, max_height);
return RPP_SUCCESS;
}
/******************** look_up_table ********************/
RppStatus
look_up_table_hip(Rpp8u* srcPtr, RppiSize srcSize, Rpp8u* dstPtr,Rpp8u* lutPtr, RppiChnFormat chnFormat, unsigned int channel, rpp::Handle& handle)
{
return RPP_SUCCESS;
}
RppStatus
look_up_table_hip_batch(Rpp8u* srcPtr, Rpp8u* dstPtr, Rpp8u* lutPtr,rpp::Handle& handle, RppiChnFormat chnFormat, unsigned int channel)
{
Rpp8u* hipLutPtr;
hipMalloc(&hipLutPtr, sizeof(Rpp8u) * 256 * channel * handle.GetBatchSize());
hipMemcpy(hipLutPtr, lutPtr, sizeof(Rpp8u) * 256 * channel * handle.GetBatchSize(), hipMemcpyHostToDevice);
int plnpkdind;
if(chnFormat == RPPI_CHN_PLANAR)
plnpkdind = 1;
else
plnpkdind = 3;
Rpp32u max_height, max_width;
max_size(handle.GetInitHandle()->mem.mgpu.csrcSize.height, handle.GetInitHandle()->mem.mgpu.csrcSize.width, handle.GetBatchSize(), &max_height, &max_width);
hip_exec_look_up_table_batch(srcPtr, dstPtr, hipLutPtr, handle, chnFormat, channel, plnpkdind, max_height, max_width);
hipFree(&hipLutPtr);
return RPP_SUCCESS;
}
/******************** tensor_look_up_table ********************/
RppStatus
tensor_look_up_table_hip(Rpp32u tensorDimension, Rpp32u* tensorDimensionValues, Rpp8u* srcPtr, Rpp8u* dstPtr, Rpp8u* lutPtr, rpp::Handle& handle)
{
Rpp8u* hipLutPtr;
hipMalloc(&hipLutPtr, sizeof(Rpp8u) * 256);
hipMemcpy(hipLutPtr, lutPtr, sizeof(Rpp8u) * 256, hipMemcpyHostToDevice);
size_t gDim3[3];
if(tensorDimension == 1)
{
gDim3[0] = tensorDimensionValues[0];
gDim3[1] = 1;
gDim3[2] = 1;
}
else if(tensorDimension == 2)
{
gDim3[0] = tensorDimensionValues[0];
gDim3[1] = tensorDimensionValues[1];
gDim3[2] = 1;
}
else
{
gDim3[0] = tensorDimensionValues[0];
gDim3[1] = tensorDimensionValues[1];
int value = 1;
for(int i = 2 ; i < tensorDimension ; i++)
{
value *= tensorDimensionValues[i];
}
gDim3[2] = value;
}
unsigned int dim1,dim2,dim3;
dim1 = gDim3[0];
dim2 = gDim3[1];
dim3 = gDim3[2];
hip_exec_tensor_look_up_table_batch(tensorDimension, srcPtr, dstPtr, hipLutPtr, handle, dim1, dim2, dim3);
return RPP_SUCCESS;
} | 41.921739 | 168 | 0.511166 | [
"vector"
] |
c00f36b9efbf748b756c9fb660bacedeb05a2ca4 | 3,730 | cpp | C++ | patches/llvm/src/lib/Transforms/Utils/NameStringLiterals.cpp | systems-nuts/popcorn-compiler-alpine | 5c225c7d3055db83dc654b6b5525c34bbdacded1 | [
"Linux-OpenIB"
] | 30 | 2019-04-07T14:58:31.000Z | 2021-05-24T19:07:20.000Z | patches/llvm/src/lib/Transforms/Utils/NameStringLiterals.cpp | XRDevIEEE/popcorn-compiler | 2cb2eccc0c75b5963d9fec26ad80a7b881316b1d | [
"Linux-OpenIB"
] | 11 | 2018-07-24T19:31:26.000Z | 2020-09-03T08:56:23.000Z | patches/llvm/src/lib/Transforms/Utils/NameStringLiterals.cpp | XRDevIEEE/popcorn-compiler | 2cb2eccc0c75b5963d9fec26ad80a7b881316b1d | [
"Linux-OpenIB"
] | 17 | 2018-08-26T12:43:15.000Z | 2022-03-18T12:08:40.000Z | #include <algorithm>
#include <cctype>
#include "llvm/Pass.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "name-string-literals"
#define CHARS_FOR_NAME 10
using namespace llvm;
namespace
{
/**
* Generate unique name for private anonymous string literals. Uses the
* filename, LLVM's temporary name and (up to) the first 10 characters of the
* string. Converts non-alphanumeric characters to underscores.
*/
std::string UniquifySymbol(const Module &M, GlobalVariable &Sym)
{
std::string newName;
std::string::size_type loc;
auto filter = [](char c){ return !isalnum(c); };
newName = M.getName();
loc = newName.find_last_of('.');
newName = newName.substr(0, loc) + "_" + Sym.getName().str() + "_";
std::replace_if(newName.begin(), newName.end(), filter, '_');
// Check if it's a string, and if so use string content to uniquify
if(Sym.hasInitializer()) {
Constant *Initializer = Sym.getInitializer();
if(isa<ConstantDataSequential>(Initializer)) {
ConstantDataSequential *CDS = cast<ConstantDataSequential>(Initializer);
if(CDS->isString()) {
std::string data = CDS->getAsString().substr(0, CHARS_FOR_NAME);
std::replace_if(data.begin(), data.end(), filter, '_');
newName += data;
}
}
}
return newName;
}
/**
* This pass searches for anonymous read-only data for which there is no symbol
* and generates a symbol for the data. This is required by the Popcorn
* compiler in order to align the data at link-time.
*/
class NameStringLiterals : public ModulePass
{
public:
static char ID;
NameStringLiterals() : ModulePass(ID) {}
~NameStringLiterals() {}
/* ModulePass virtual methods */
virtual void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); }
virtual bool runOnModule(Module &M)
{
bool modified = false;
std::string newName;
Module::global_iterator gl, gle; // for global variables
DEBUG(errs() << "\n********** Begin NameStringLiterals **********\n"
<< "********** Module: " << M.getName() << " **********\n\n");
// Iterate over all globals and generate symbol for anonymous string
// literals in each module
for(gl = M.global_begin(), gle = M.global_end(); gl != gle; gl++) {
// DONT NEED TO CHANGE NAME PER-SE just change type
// PrivateLinkage does NOT show up in any symbol table in the object file!
if(gl->getLinkage() == GlobalValue::PrivateLinkage) {
//change Linkage
//FROM private unnamed_addr constant [num x i8]
//TO global [num x i8]
gl->setLinkage(GlobalValue::ExternalLinkage);
// Make the global's name unique so we don't clash when linking with
// other files
newName = UniquifySymbol(M, *gl);
gl->setName(newName);
// Also REMOVE unnamed_addr value
if(gl->hasUnnamedAddr()) {
gl->setUnnamedAddr(false);
}
modified = true;
DEBUG(errs() << "New anonymous string name: " << newName << "\n";);
} else {
DEBUG(errs() << "> " << *gl << ", linkage: "
<< gl->getLinkage() << "\n");
}
}
return modified;
}
virtual const char *getPassName() const { return "Name string literals"; }
};
} /* end anonymous namespace */
char NameStringLiterals::ID = 0;
INITIALIZE_PASS(NameStringLiterals, "name-string-literals",
"Generate symbols for anonymous string literals", false, false)
namespace llvm {
ModulePass *createNameStringLiteralsPass() { return new NameStringLiterals(); }
}
| 31.083333 | 82 | 0.647989 | [
"object"
] |
c00f57035d25648b42f806f217f24616e3d8e251 | 1,114 | cpp | C++ | src/remove/linefit/linefit.cpp | mangosroom/mvk-nodes | 0ec3a7853e949d192ee54daeaf25875cd3cb6d18 | [
"Apache-2.0"
] | 5 | 2021-12-24T10:18:46.000Z | 2022-03-15T14:11:04.000Z | src/remove/linefit/linefit.cpp | mangosroom/mvk-nodes | 0ec3a7853e949d192ee54daeaf25875cd3cb6d18 | [
"Apache-2.0"
] | null | null | null | src/remove/linefit/linefit.cpp | mangosroom/mvk-nodes | 0ec3a7853e949d192ee54daeaf25875cd3cb6d18 | [
"Apache-2.0"
] | 1 | 2021-03-30T07:34:26.000Z | 2021-03-30T07:34:26.000Z |
/**
* @file linefit.cpp
* @brief 直线拟合源文件
* @details 基于最小二乘、huber、tukey等方法拟合直线
* @author 芒果
* @date 2020-4-10
* @version 1.0.0
*/
#include "linefit.h"
#include <cassert>
namespace mvp
{
std::shared_ptr<LineFit> LineFit::CreateLineFitTool()
{
return std::make_shared<LineFit>();
}
int LineFit::SetParam(const std::string& json_str)
{
return 0;
}
int LineFit::SetInputPointArray(const std::vector<cv::Point_>& point_array)
{
return 0;
}
int LineFit::Run()
{
RunRansac();
return 0;
}
int LineFit::SampleMnimumData()
{
return 0;
}
int LineFit::FitModel()
{
return 0;
}
int LineFit::ComputeCurrentInliers()
{
return 0;
}
int LineFit::RecordBestModel()
{
return 0;
}
int LineFit::IsGoodEnough()
{
return 0;
}
int LineFit::SetOutliersDistanceThreshold(const double& threshold)
{
return 0;
}
int LineFit::SetForceRemoveRatio(const double& ratio)
{
return 0;
}
int LineFit::SetForceRemoveNum(const int& num)
{
return 0;
}
int LineFit::SetMaxIterNum(const int& num)
{
return 0;
}
}//namespace mvp
| 11.978495 | 76 | 0.640036 | [
"vector"
] |
84fd825c39908a4c00bd66bb5759f24e639d59fb | 4,172 | cpp | C++ | src/plugins/azoth/plugins/murm/vcarddialog.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/plugins/azoth/plugins/murm/vcarddialog.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | src/plugins/azoth/plugins/murm/vcarddialog.cpp | MellonQ/leechcraft | 71cbb238d2dade56b3865278a6a8e6a58c217fc5 | [
"BSL-1.0"
] | null | null | null | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#include "vcarddialog.h"
#include <util/xpc/util.h>
#include <interfaces/core/ientitymanager.h>
#include "structures.h"
#include "photostorage.h"
#include "georesolver.h"
namespace LeechCraft
{
namespace Azoth
{
namespace Murm
{
VCardDialog::VCardDialog (const UserInfo& info, PhotoStorage *storage,
GeoResolver *geo, ICoreProxy_ptr proxy, QWidget *parent)
: QDialog (parent)
, Proxy_ (proxy)
, Info_ (info)
, Storage_ (storage)
{
Ui_.setupUi (this);
setAttribute (Qt::WA_DeleteOnClose);
Ui_.FirstName_->setText (info.FirstName_);
Ui_.LastName_->setText (info.LastName_);
Ui_.Nickname_->setText (info.Nick_);
Ui_.Birthday_->setDate (info.Birthday_);
Ui_.Birthday_->setDisplayFormat (info.Birthday_.year () != 1800 ? "dd MMMM yyyy" : "dd MMMM");
if (info.Gender_)
Ui_.Gender_->setText (info.Gender_ == 1 ? tr ("female") : tr ("male"));
Ui_.HomePhone_->setText (info.HomePhone_);
Ui_.MobilePhone_->setText (info.MobilePhone_);
auto timezoneText = QString::number (info.Timezone_) + " GMT";
if (info.Timezone_ > 0)
timezoneText.prepend ('+');
Ui_.Timezone_->setText (timezoneText);
QPointer<VCardDialog> safeThis (this);
if (info.Country_ > 0)
geo->GetCountry (info.Country_,
[safeThis, this] (const QString& country)
{
if (safeThis)
Ui_.Country_->setText (country);
});
if (info.City_ > 0)
geo->GetCity (info.City_,
[safeThis, this] (const QString& country)
{
if (safeThis)
Ui_.City_->setText (country);
});
if (!info.BigPhoto_.isValid ())
return;
const auto& image = storage->GetImage (info.BigPhoto_);
if (image.isNull ())
connect (storage,
SIGNAL (gotImage (QUrl)),
this,
SLOT (handleImage (QUrl)));
else
Ui_.PhotoLabel_->setPixmap (QPixmap::fromImage (image)
.scaled (Ui_.PhotoLabel_->size (),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
}
void VCardDialog::handleImage (const QUrl& url)
{
if (url != Info_.BigPhoto_)
return;
const auto& image = Storage_->GetImage (url);
Ui_.PhotoLabel_->setPixmap (QPixmap::fromImage (image)
.scaled (Ui_.PhotoLabel_->size (),
Qt::KeepAspectRatio,
Qt::SmoothTransformation));
}
void VCardDialog::on_OpenVKPage__released ()
{
const auto& pageUrlStr = "http://vk.com/id" + QString::number (Info_.ID_);
const auto& e = Util::MakeEntity (QUrl (pageUrlStr),
QString (), FromUserInitiated | OnlyHandle);
Proxy_->GetEntityManager ()->HandleEntity (e);
}
}
}
}
| 33.111111 | 96 | 0.682167 | [
"object"
] |
84fe672d774f49c43577a765ebe7a08fb5fabcde | 3,900 | cpp | C++ | Test/RhythmPatternTest.cpp | Tomasito665/mtv-rhythm-generator | 6cdfbdcdd745148d477ce3b7599912dc36cd2848 | [
"MIT"
] | null | null | null | Test/RhythmPatternTest.cpp | Tomasito665/mtv-rhythm-generator | 6cdfbdcdd745148d477ce3b7599912dc36cd2848 | [
"MIT"
] | null | null | null | Test/RhythmPatternTest.cpp | Tomasito665/mtv-rhythm-generator | 6cdfbdcdd745148d477ce3b7599912dc36cd2848 | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
#include "RhythmPattern.h"
#include <bitset>
template <int N>
static PatternId createPattern(const std::string& str)
{
// LSB in pattern id represents first step, therefore we reverse the str
std::string strRev(str.rbegin(), str.rend());
std::bitset<N> patternBitset(strRev, 0, strRev.size(), '-', 'x');
return patternBitset.to_ullong();
}
TEST(RhythmPatternTests, StepCount)
{
RhythmPattern r(TimeSignature(6, 8), Unit::SEMIQUAVER);
ASSERT_EQ(12, r.getNSteps());
}
TEST(RhythmPatternTests, StartsEmpty)
{
RhythmPattern r;
const int N = r.getNSteps();
for (int i = 0; i < N; ++i)
ASSERT_FALSE(r[i]);
}
TEST(RhythmPatternTests, ConstructorPatternId)
{
PatternId patternId = createPattern<8>("xx-x-xx-");
RhythmPattern r(TimeSignature(4, 4), Unit::QUAVER, patternId);
std::vector<int> expectedPattern = { 1, 1, 0, 1, 0, 1, 1, 0 };
std::vector<int> actualPattern(8);
for (int i = 0; i < 8; ++i)
actualPattern[i] = (int)r[i];
ASSERT_EQ(expectedPattern, actualPattern);
}
TEST(RhythmPatternTests, AsMusicalEvents)
{
PatternId patternId = createPattern<16>("x--x---x--x-x---"); // rumba clave
RhythmPattern r(TimeSignature(4, 4), Unit::SEMIQUAVER, patternId);
MusicalEventList expectedEvents = {
MusicalEvent(MusicalEventType::NOTE, 0, 2),
MusicalEvent(MusicalEventType::TIED_NOTE, 2, 1),
MusicalEvent(MusicalEventType::NOTE, 3, 1),
MusicalEvent(MusicalEventType::TIED_NOTE, 4, 2),
MusicalEvent(MusicalEventType::REST, 6, 1),
MusicalEvent(MusicalEventType::NOTE, 7, 1),
MusicalEvent(MusicalEventType::TIED_NOTE, 8, 2),
MusicalEvent(MusicalEventType::NOTE, 10, 2),
MusicalEvent(MusicalEventType::NOTE, 12, 4)
};
MusicalEventList actualEvents = r.asMusicalEvents(false, false);
ASSERT_EQ(expectedEvents, actualEvents);
}
TEST(RhythmPatternTests, AsMusicalEventsCyclicTrim)
{
PatternId patternId = createPattern<4>("---x"); // rumba clave
RhythmPattern r(TimeSignature(4, 4), Unit::CROTCHET, patternId);
MusicalEventList expectedEvents = {
MusicalEvent(MusicalEventType::TIED_NOTE, 0, 1),
MusicalEvent(MusicalEventType::REST, 1, 1),
MusicalEvent(MusicalEventType::REST, 2, 1),
MusicalEvent(MusicalEventType::NOTE, 3, 1)
};
MusicalEventList actualEvents = r.asMusicalEvents(true, true);
ASSERT_EQ(expectedEvents, actualEvents);
}
TEST(RhythmPatternTests, AsMusicalEventsNoCyclicTrim)
{
PatternId patternId = createPattern<4>("---x"); // rumba clave
RhythmPattern r(TimeSignature(4, 4), Unit::CROTCHET, patternId);
MusicalEventList expectedEvents = {
MusicalEvent(MusicalEventType::REST, 0, 1),
MusicalEvent(MusicalEventType::REST, 1, 1),
MusicalEvent(MusicalEventType::REST, 2, 1),
MusicalEvent(MusicalEventType::NOTE, 3, 1)
};
MusicalEventList actualEvents = r.asMusicalEvents(false, true);
ASSERT_EQ(expectedEvents, actualEvents);
}
TEST(RhythmPatternTests, AsMusicalEventsCyclicNoTrim)
{
PatternId patternId = createPattern<4>("---x"); // rumba clave
RhythmPattern r(TimeSignature(4, 4), Unit::CROTCHET, patternId);
MusicalEventList expectedEvents = {
MusicalEvent(MusicalEventType::TIED_NOTE, 0, 2),
MusicalEvent(MusicalEventType::REST, 2, 1),
MusicalEvent(MusicalEventType::NOTE, 3, 1)
};
MusicalEventList actualEvents = r.asMusicalEvents(true, false);
ASSERT_EQ(expectedEvents, actualEvents);
}
TEST(RhythmPatternTests, AsMusicalEventsNoCyclicNoTrim)
{
PatternId patternId = createPattern<4>("---x"); // rumba clave
RhythmPattern r(TimeSignature(4, 4), Unit::CROTCHET, patternId);
MusicalEventList expectedEvents = {
MusicalEvent(MusicalEventType::REST, 0, 2),
MusicalEvent(MusicalEventType::REST, 2, 1),
MusicalEvent(MusicalEventType::NOTE, 3, 1)
};
MusicalEventList actualEvents = r.asMusicalEvents(false, false);
ASSERT_EQ(expectedEvents, actualEvents);
}
| 31.2 | 78 | 0.721026 | [
"vector"
] |
17000c92c7eae7801d6045ae4867cfd354fa83bc | 5,827 | cpp | C++ | sdk/rms_sdk/RestClients/RestHttpClient.cpp | AzureAD/rms-sdk-for-cpp | 0e5d54a030008c5c0f70d8d3d0695fa0722b6ab6 | [
"MIT"
] | 30 | 2015-06-22T23:59:02.000Z | 2021-09-12T05:51:34.000Z | sdk/rms_sdk/RestClients/RestHttpClient.cpp | AnthonyCSheehy/rms-sdk-for-cpp | 42985c0b5d93da5bef6bd6c847ddced4be008843 | [
"MIT"
] | 115 | 2015-06-22T18:26:34.000Z | 2022-03-24T16:57:46.000Z | sdk/rms_sdk/RestClients/RestHttpClient.cpp | AnthonyCSheehy/rms-sdk-for-cpp | 42985c0b5d93da5bef6bd6c847ddced4be008843 | [
"MIT"
] | 32 | 2015-06-22T08:39:29.000Z | 2022-03-24T16:49:20.000Z | /*
* ======================================================================
* Copyright (c) Microsoft Open Technologies, Inc. All rights reserved.
* Licensed under the MIT License.
* See LICENSE.md in the project root for license information.
* ======================================================================
*/
#include <numeric>
#include "RestHttpClient.h"
#include "AuthenticationHandler.h"
#include "../Common/tools.h"
#include "../Platform/Http/IHttpClient.h"
#include "../Platform/Settings/ILanguageSettings.h"
#include "../Platform/Logger/Logger.h"
using namespace std;
using namespace rmscore::common;
using namespace rmscore::modernapi;
using namespace rmscore::platform::http;
using namespace rmscore::platform::settings;
using namespace rmscore::platform::logger;
namespace rmscore {
namespace restclients {
RestHttpClient::Result RestHttpClient::Get(const std::string& sUrl,
const AuthenticationHandler::AuthenticationHandlerParameters& authParams,
IAuthenticationCallbackImpl& authenticationCallback,
std::shared_ptr<std::atomic<bool>> cancelState)
{
// Performance latency should exclude the time it takes in Authentication and
// consent operations
auto accessToken = AuthenticationHandler::GetAccessTokenForUrl(sUrl,
authParams,
authenticationCallback,
cancelState);
Logger::Hidden("access token %s", accessToken.c_str());
auto parameters = HttpRequestParameters {
HTTP_GET, // type
string(sUrl), // Url
common::ByteArray(), // requestBody
accessToken, // accessToken
cancelState };
// call the DoHttpRequest() and abandon the call when the cancel event is
// signalled (for Office scenarios)
return RestHttpClient::DoHttpRequest(move(parameters));
}
RestHttpClient::Result RestHttpClient::Post(const string& sUrl,
ByteArray&& requestBody,
IAuthenticationCallbackImpl& authenticationCallback,
std::shared_ptr<std::atomic<bool>> cancelState)
{
// Performance latency should exclude the time it takes in Authentication and
// consent operations
// empty not needed at the moment for post.
auto accessToken = AuthenticationHandler::GetAccessTokenForUrl(sUrl,
move(requestBody), // requestBody
authenticationCallback,
cancelState);
auto parameters = HttpRequestParameters {
HTTP_POST, // type
string(sUrl), // Url
move(requestBody), // requestBody
accessToken, // accessToken
cancelState };
// call the DoHttpRequest() and abandon the call when the cancel event is
// signalled (for Office scenarios)
return RestHttpClient::DoHttpRequest(move(parameters));
}
RestHttpClient::Result RestHttpClient::DoHttpRequest(const HttpRequestParameters& parameters)
{
shared_ptr<IHttpClient> pHttpClient = IHttpClient::Create();
// generate a request id (i.e., a new ScenarioId and a new CorrelationId)
string requestId = GenerateRequestId();
// Add headers
pHttpClient->AddAcceptMediaTypeHeader("application/json");
pHttpClient->AddHeader("content-type", "application/json");
pHttpClient->AddAcceptLanguageHeader(ConstructLanguageHeader());
pHttpClient->AddAuthorizationHeader(ConstructAuthTokenHeader(parameters.accessToken));
pHttpClient->AddHeader("x-ms-rms-request-id", requestId);
// x-ms-rms-platform-id header consists of AppName, AppVersion, SDKVersion,
// AppPublisherId, AppPublisherName, UniqueClientID
if (m_sPlatformIdHeaderCache.size() == 0)
{
m_sPlatformIdHeaderCache = GetPlatformIdHeader();
}
pHttpClient->AddHeader("x-ms-rms-platform-id", m_sPlatformIdHeaderCache);
Result result;
switch (parameters.type)
{
case HTTP_POST:
{
Logger::Hidden("RestHttpClient::DoHttpRequest doing http POST to %s, Request-ID: %s",
parameters.requestUrl.c_str(),
requestId.c_str());
result.status = pHttpClient->Post(parameters.requestUrl,
parameters.requestBody, std::string("application/json"),
result.responseBody,
parameters.cancelState);
}
break;
case HTTP_GET:
{
Logger::Hidden("RestHttpClient::DoHttpRequest doing http GET to %s, Request-ID: %s",
parameters.requestUrl.c_str(),
requestId.c_str());
result.status = pHttpClient->Get(parameters.requestUrl, result.responseBody, parameters.cancelState);
}
break;
}
Logger::Hidden("RestHttpClient::DoHttpRequest returned status code: %d", (int)result.status);
return result;
}
string RestHttpClient::ConstructAuthTokenHeader(const string& accessToken)
{
// prefix with "Bearer "
return "Bearer " + accessToken;
}
string RestHttpClient::ConstructLanguageHeader()
{
shared_ptr<ILanguageSettings> pLanguageSettings = ILanguageSettings::Create();
// get the ordered list of the languages supported by the app
vector<string> appLanguages = pLanguageSettings->GetAppLanguages();
// construct the header
return accumulate(begin(appLanguages), end(appLanguages), string(),
[](const string& str1, const string& str2) -> string
{
// join with comma
return str1.empty() ? str2 : str1 + ", " + str2;
});
}
string RestHttpClient::GenerateRequestId()
{
return GenerateAGuid() + ";" + GenerateAGuid();
}
string RestHttpClient::GetPlatformIdHeader()
{
string platformId(
"AppName=rmscore;AppVersion=1.0;DevicePlatform=WindowsStore;SDKVersion=4.1;");
return platformId;
}
string RestHttpClient::m_sPlatformIdHeaderCache = GetPlatformIdHeader();
} // namespace restclients
} // namespace rmscore
| 33.682081 | 113 | 0.675819 | [
"vector"
] |
170d558236199153bcd248a55fe862098397beda | 15,386 | cc | C++ | wrspice/bin/multidec.cc | wrcad/xictools | f46ba6d42801426739cc8b2940a809b74f1641e2 | [
"Apache-2.0"
] | 73 | 2017-10-26T12:40:24.000Z | 2022-03-02T16:59:43.000Z | wrspice/bin/multidec.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 12 | 2017-11-01T10:18:22.000Z | 2022-03-20T19:35:36.000Z | wrspice/bin/multidec.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 34 | 2017-10-06T17:04:21.000Z | 2022-02-18T16:22:03.000Z |
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, *
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES *
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, *
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE *
* USE OR OTHER DEALINGS IN THE SOFTWARE. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* multidec -- Lossy transmission line decomposition tool. *
* *
*========================================================================*
$Id:$
*========================================================================*/
/**********
Copyright 1990 Regents of the University of California. All rights reserved.
Author: 1990 Jaijeet Roychowdury
**********/
#include <stdio.h>
#include <math.h>
#include "misc.h"
#include "ttyio.h"
#include "sparse/spmatrix.h"
#define THRSH 0.01
#define ABS_THRSH 0
#define DIAG_PIVOTING 1
#undef DEBUG_LEVEL1
// Interface to the TTY. The sparse package is built for WRspice.
// and uses the TTYio system. We have to supply a trivial interface.
//
bool sTTYioIF::isInteractive() { return (false); }
int sTTYioIF::getchar() { return (0); }
bool sTTYioIF::getWaiting() { return (false); }
void sTTYioIF::setWaiting(bool) { }
wordlist *sTTYioIF::getWordlist() { return (0); }
void sTTYioIF::stripList(wordlist*) { }
sTTYioIF TTYif;
extern void usage(char**);
extern void comments(double, double, double, double, double, double, double,
double, char*, int, double);
extern double phi(int, double);
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
#ifdef WIN32
int optind = 1;
char *optarg;
int
getopt(int ac, char* const *av, const char *optstring)
{
int ochar = EOF;
for ( ; optind < ac && av[optind]; optind++) {
if (*av[optind] != '-')
continue;
char *t = strchr(optstring, av[optind][1]);
if (!t)
continue;
ochar = av[optind][1];
optind++;
if (t[1] == ':' && optind < ac) {
optarg = av[optind];
optind++;
}
else
optarg = 0;
}
return (ochar);
}
#endif
int
main (int argc, char **argv)
{
extern char *optarg;
int errflg=0, i, j;
char *options;
int num, node;
char *name = 0;
double l, c, ctot, r=0.0, g=0.0, k=0.0, lm=0.0, cm=0.0, len;
unsigned gotl=0, gotc=0, gotlen=0;
unsigned gotname = 0, gotnum = 0;
int ch;
while ((ch = getopt(argc, argv, "ul:c:r:g:k:n:o:x:L:")) != EOF) {
switch (ch) {
case 'o':
name = new char[strlen(optarg) + 1];
strcpy(name, optarg);
gotname = 1;
break;
case 'l':
sscanf(optarg,"%lf", &l);
gotl = 1;
break;
case 'c':
sscanf(optarg,"%lf", &c);
gotc = 1;
break;
case 'r':
sscanf(optarg,"%lf", &r);
break;
case 'g':
sscanf(optarg,"%lf", &g);
break;
case 'k':
sscanf(optarg,"%lf", &k);
break;
case 'x':
sscanf(optarg,"%lf", &cm);
break;
case 'L':
sscanf(optarg,"%lf", &len);
gotlen = 1;
break;
case 'n':
sscanf(optarg,"%d", &num);
gotnum = 1;
break;
case 'u':
usage(argv);
exit(1);
break;
case '?':
errflg++;
}
}
if (errflg) {
usage(argv);
exit (2);
}
if (gotl + gotc + gotname + gotnum + gotlen < 5) {
fprintf(stderr,
"l, c, model_name, number_of_conductors and length must be specified.\n");
fprintf(stderr,"%s -u for details.\n",argv[0]);
fflush(stdout);
exit(1);
}
if ( (k<0.0?-k:k) >= 1.0 ) {
fprintf(stderr,"Error: |k| must be less than 1.0\n");
fflush(stderr);
exit(1);
}
if (num == 1) {
fprintf(stdout,"* single conductor line\n");
fflush(stdout);
exit(1);
}
lm = l*k;
switch (num) {
case 1:
ctot = c;
break;
case 2:
ctot = c + cm;
break;
default:
ctot = c + 2*cm;
break;
}
comments(r, l, g, c, ctot, cm, lm, k, name, num, len);
double **matrix = new double*[num + 1];
double **inverse = new double*[num + 1];
double *tpeigenvalues = new double[num + 1];
for (i = 1; i <= num; i++) {
matrix[i] = new double[num + 1];
inverse[i] = new double[num + 1];
}
for (i = 1; i <= num; i++) {
tpeigenvalues[i] = -2.0 * cos(M_PI*i/(num+1));
}
for (i = 1; i<= num; i++) {
for (j = 1; j <= num; j++) {
matrix[i][j] = phi(i-1, tpeigenvalues[j]);
}
}
double *gammaj = new double[num + 1];
for (j = 1; j<= num; j++) {
gammaj[j] = 0.0;
for (i = 1; i <= num; i++) {
gammaj[j] += matrix[i][j] * matrix[i][j];
}
gammaj[j] = sqrt(gammaj[j]);
}
for (j = 1; j <= num; j++) {
for (i = 1; i <= num; i++) {
matrix[i][j] /= gammaj[j];
}
}
delete [] gammaj;
// matrix = M set up
{
double *rhs = new double[num + 1];
double *irhs = new double[num + 1];
double *solution = new double[num + 1];
double *isolution = new double[num + 1];
spMatrixFrame *othermatrix =
new spMatrixFrame(num, SP_NO_KLU | SP_NO_SORT);
for (i = 1; i <= num; i++) {
for (j = 1; j <= num; j++) {
double *elptr = othermatrix->spGetElement(i, j);
*elptr = matrix[i][j];
}
}
#ifdef DEBUG_LEVEL1
spPrint(othermatrix,0,1,0);
#endif
for (i = 1; i <= num; i++)
rhs[i] = 0.0;
rhs[1] = 1.0;
int err = othermatrix->spOrderAndFactor(rhs,
THRSH, ABS_THRSH, DIAG_PIVOTING);
othermatrix->spErrorMessage(stderr, 0);
int singular_row, singular_col;
switch (err) {
case spNO_MEMORY:
fprintf(stderr,"No memory in spOrderAndFactor\n");
fflush(stderr);
exit(1);
case spSINGULAR:
othermatrix->spWhereSingular(&singular_row, &singular_col);
fprintf(stderr,
"Singular matrix: problem in row %d and col %d\n",
singular_row, singular_col);
fflush(stderr);
exit(1);
case spSMALL_PIVOT:
fprintf(stderr,"* Warning: matrix is illconditioned.\n");
fflush(stderr);
break;
default: break;
}
for (i = 1; i <= num; i++) {
for (j = 1; j <= num; j++) {
rhs[j] = (j==i ? 1.0 : 0.0);
irhs[j] = 0.0;
}
othermatrix->spSolveTransposed(rhs, solution, irhs, isolution);
for (j = 1; j <= num;j++) {
inverse[i][j] = solution[j];
}
}
delete [] rhs;
delete [] solution;
}
// inverse = M^{-1} set up
fprintf(stdout, "\n");
fprintf(stdout, "* Lossy line models\n");
options = new char[256];
strcpy(options, "rel=1.2 nocontrol");
for (i = 1; i <= num; i++) {
fprintf(stdout,
".model mod%d_%s ltra %s r=%0.12g l=%0.12g g=%0.12g c=%0.12g len=%0.12g\n",
i, name, options, r, l+tpeigenvalues[i]*lm, g,
ctot-tpeigenvalues[i]*cm, len);
//i, name, options, r, l+tpeigenvalues[i]*lm, g, ctot+tpeigenvalues[i]*cm, len);
}
fprintf(stdout, "\n");
fprintf(stdout,
"* subcircuit m_%s - modal transformation network for %s\n",
name, name);
fprintf(stdout, ".subckt m_%s", name);
for (i = 1; i <= 2*num; i++) {
fprintf(stdout, " %d", i);
}
fprintf(stdout, "\n");
for (j = 1; j <= num; j++)
fprintf(stdout, "v%d %d 0 0v\n", j, j+2*num);
for (j = 1; j <= num; j++) {
for (i = 1; i <= num; i++) {
fprintf(stdout, "f%d 0 %d v%d %0.12g\n",
(j-1)*num+i, num+j, i, inverse[j][i]);
}
}
node = 3*num+1;
for (j = 1; j <= num; j++) {
fprintf(stdout,"e%d %d %d %d 0 %0.12g\n", (j-1)*num+1,
node, 2*num+j, num+1, matrix[j][1]);
node++;
for (i = 2; i < num; i++) {
fprintf(stdout,"e%d %d %d %d 0 %0.12g\n", (j-1)*num+i,
node, node-1, num+i, matrix[j][i]);
node++;
}
fprintf(stdout,"e%d %d %d %d 0 %0.12g\n", j*num, j, node-1,
2*num,matrix[j][num]);
}
fprintf(stdout, ".ends m_%s\n", name);
fprintf(stdout, "\n");
fprintf(stdout, "* Subckt %s\n", name);
fprintf(stdout, ".subckt %s", name);
for (i = 1; i <= 2*num; i++) {
fprintf(stdout, " %d", i);
}
fprintf(stdout, "\n");
fprintf(stdout, "x1");
for (i = 1; i <= num; i++)
fprintf(stdout, " %d", i);
for (i = 1; i <= num; i++)
fprintf(stdout, " %d", 2*num+i);
fprintf(stdout, " m_%s\n", name);
for (i = 1; i <= num; i++)
fprintf(stdout, "o%d %d 0 %d 0 mod%d_%s\n", i, 2*num+i, 3*num+i,
i, name);
fprintf(stdout, "x2");
for (i = 1; i <= num; i++)
fprintf(stdout, " %d", num+i);
for (i = 1; i <= num; i++)
fprintf(stdout, " %d", 3*num+i);
fprintf(stdout, " m_%s\n", name);
fprintf(stdout, ".ends %s\n", name);
delete [] tpeigenvalues;
for (i = 1; i <= num; i++) {
delete [] matrix[i];
delete [] inverse[i];
}
delete [] matrix;
delete [] inverse;
delete [] name;
delete [] options;
return (0);
}
void
usage(char **argv)
{
fprintf(stderr,"Purpose: make subckt. for coupled lines using uncoupled simple lossy lines\n");
fprintf(stderr,"Usage: %s -l<line-inductance> -c<line-capacitance>\n",argv[0]);
fprintf(stderr," -r<line-resistance> -g<line-conductance> \n");
fprintf(stderr," -k<inductive coeff. of coupling> \n");
fprintf(stderr," -x<line-to-line capacitance> -o<subckt-name> \n");
fprintf(stderr," -n<number of conductors> -L<length> -u\n");
fprintf(stderr,"Example: %s -n4 -l9e-9 -c20e-12 -r5.3 -x5e-12 -k0.7 -otest -L5.4\n\n",argv[0]);
fprintf(stderr,"See \"Efficient Transient Simulation of Lossy Interconnect\",\n");
fprintf(stderr,"J.S. Roychowdhury and D.O. Pederson, Proc. DAC 91 for details\n");
fprintf(stderr,"\n");
fflush(stderr);
}
void
comments(double r, double l, double g, double c, double ctot, double cm,
double lm, double k, char *name, int num, double len)
{
fprintf(stdout,"* Subcircuit %s\n",name);
fprintf(stdout,"* %s is a subcircuit that models a %d-conductor transmission line with\n",name,num);
fprintf(stdout,"* the following parameters: l=%g, c=%g, r=%g, g=%g,\n",l,c,r,g);
fprintf(stdout,"* inductive_coeff_of_coupling k=%g, inter-line capacitance cm=%g,\n",k,cm);
fprintf(stdout,"* length=%g. Derived parameters are: lm=%g, ctot=%g.\n",len,lm,ctot);
fprintf(stdout,"* \n");
fprintf(stdout,"* It is important to note that the model is a simplified one - the\n");
fprintf(stdout,"* following assumptions are made: 1. The self-inductance l, the\n");
fprintf(stdout,"* self-capacitance ctot (note: not c), the series resistance r and the\n");
fprintf(stdout,"* parallel capacitance g are the same for all lines, and 2. Each line\n");
fprintf(stdout,"* is coupled only to the two lines adjacent to it, with the same\n");
fprintf(stdout,"* coupling parameters cm and lm. The first assumption implies that edge\n");
fprintf(stdout,"* effects have to be neglected. The utility of these assumptions is\n");
fprintf(stdout,"* that they make the sL+R and sC+G matrices symmetric, tridiagonal and\n");
fprintf(stdout,"* Toeplitz, with useful consequences (see \"Efficient Transient\n");
fprintf(stdout,"* Simulation of Lossy Interconnect\", by J.S. Roychowdhury and\n");
fprintf(stdout,"* D.O Pederson, Proc. DAC 91).\n\n");
fprintf(stdout,"* It may be noted that a symmetric two-conductor line is\n");
fprintf(stdout,"* represented accurately by this model.\n\n");
fprintf(stdout,"* Subckt node convention:\n");
fprintf(stdout,"* \n");
fprintf(stdout,"* |--------------------------|\n");
fprintf(stdout,"* 1-----| |-----n+1\n");
fprintf(stdout,"* 2-----| |-----n+2\n");
fprintf(stdout,"* : | n-wire multiconductor | :\n");
fprintf(stdout,"* : | line | :\n");
fprintf(stdout,"* n-1-----|(node 0=common gnd plane) |-----2n-1\n");
fprintf(stdout,"* n-----| |-----2n\n");
fprintf(stdout,"* |--------------------------|\n\n");
fflush(stdout);
}
double
phi(int i, double arg)
{
double rval;
switch (i) {
case 0:
rval = 1.0;
break;
case 1:
rval = arg;
break;
default:
rval = arg*phi(i-1,arg) - phi(i-2,arg);
}
return rval;
}
void
fatal(int x)
{
exit(x);
}
| 32.459916 | 100 | 0.488886 | [
"model"
] |
171329a615798a54850ff3c1a5fd08f61af1a0ba | 826 | hpp | C++ | Engine/Public/Ryme/Mesh.hpp | WhoBrokeTheBuild/Ryme | 945c4ab135dbe411f43787cbf222589b13420d4b | [
"MIT"
] | null | null | null | Engine/Public/Ryme/Mesh.hpp | WhoBrokeTheBuild/Ryme | 945c4ab135dbe411f43787cbf222589b13420d4b | [
"MIT"
] | null | null | null | Engine/Public/Ryme/Mesh.hpp | WhoBrokeTheBuild/Ryme | 945c4ab135dbe411f43787cbf222589b13420d4b | [
"MIT"
] | null | null | null | #ifndef RYME_MESH_HPP
#define RYME_MESH_HPP
#include <Ryme/Config.hpp>
#include <Ryme/Asset.hpp>
#include <Ryme/Path.hpp>
#include <Ryme/Containers.hpp>
#include <Ryme/JSON.hpp>
#include <Ryme/ThirdParty/vulkan.hpp>
namespace ryme {
class Primitive;
class RYME_API Mesh : public Asset
{
public:
Mesh(const Path& path, bool search = true);
virtual ~Mesh();
bool LoadFromFile(const Path& path, bool search = true);
void Free() override;
bool Reload() override;
bool CanReload() const override {
return true;
}
private:
bool LoadGLTF(const Path& path, bool search);
bool LoadOBJ(const Path& path, bool search);
Path _path;
// List<Primitive> _primitiveList;
vk::DescriptorSet _descriptorSet;
}; // class mesh
} // namespace ryme
#endif // RYME_MESH_HPP | 16.196078 | 60 | 0.682809 | [
"mesh"
] |
1716c1e0dae4190b6b16cce38c6305748e0e8ac3 | 51,812 | cpp | C++ | src/game/client/tf/tf_hud_building_status.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/game/client/tf/tf_hud_building_status.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/game/client/tf/tf_hud_building_status.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z | //========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: HUD Target ID element
//
// $NoKeywords: $
//=============================================================================
#include "cbase.h"
#include "hud.h"
#include "iclientmode.h"
#include "c_baseobject.h"
#include "c_tf_player.h"
#include "ienginevgui.h"
#include "vgui/ILocalize.h"
#include "vgui/ISurface.h"
#include <vgui/IVGui.h>
#include <vgui_controls/ProgressBar.h>
#include <vgui_controls/AnimationController.h>
#include "game_controls/IconPanel.h"
#include "teamplay_round_timer.h"
#include "tf_hud_building_status.h"
#include "c_obj_sentrygun.h"
#include "c_obj_dispenser.h"
#include "c_obj_teleporter.h"
#include "c_obj_sapper.h"
#include "tf_gamerules.h"
#include "tf_logic_halloween_2014.h"
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
class C_ObjectSentrygun;
extern CUtlVector<int> g_TeamRoundTimers;
using namespace vgui;
ConVar tf_hud_num_building_alert_beeps( "tf_hud_num_building_alert_beeps", "2", FCVAR_ARCHIVE, "Number of times to play warning sound when a new alert displays on building hud objects", true, 0, false, 0 );
//============================================================================
DECLARE_BUILD_FACTORY( CBuildingHealthBar );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBuildingHealthBar::CBuildingHealthBar(Panel *parent, const char *panelName) : vgui::ProgressBar( parent, panelName )
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingHealthBar::Paint()
{
if ( _progress < 0.5 )
{
SetFgColor( m_cLowHealthColor );
}
else
{
SetFgColor( m_cHealthColor );
}
BaseClass::Paint();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingHealthBar::PaintBackground()
{
// save progress and real fg color
float flProgress = _progress;
Color fgColor = GetFgColor();
// stuff our fake info
_progress = 1.0;
SetFgColor( GetBgColor() );
BaseClass::Paint();
// restore actual progress / color
_progress = flProgress;
SetFgColor( fgColor );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingHealthBar::ApplySchemeSettings(vgui::IScheme *pScheme)
{
BaseClass::ApplySchemeSettings(pScheme);
SetBgColor(GetSchemeColor("BuildingHealthBar.BgColor", pScheme));
m_cHealthColor = GetSchemeColor("BuildingHealthBar.Health", pScheme);
m_cLowHealthColor = GetSchemeColor("BuildingHealthBar.LowHealth", pScheme);
SetBorder(NULL);
}
//============================================================================
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBuildingStatusItem::CBuildingStatusItem( Panel *parent, const char *szLayout, int iObjectType, int iObjectMode=0 ) :
BaseClass( parent, "BuildingStatusItem" )
{
SetProportional( true );
// Save our layout file for re-loading
Q_strncpy( m_szLayout, szLayout, sizeof(m_szLayout) );
// load control settings...
LoadControlSettings( szLayout );
SetPositioned( false );
m_pObject = NULL;
m_iObjectType = iObjectType;
m_iObjectMode = iObjectMode;
m_pBuiltPanel = new vgui::EditablePanel( this, "BuiltPanel" );
m_pNotBuiltPanel = new vgui::EditablePanel( this, "NotBuiltPanel" );
// sub panels
m_pBuildingPanel = new vgui::EditablePanel( m_pBuiltPanel, "BuildingPanel" );
m_pRunningPanel = new vgui::EditablePanel( m_pBuiltPanel, "RunningPanel" );
// Shared between All sub panels
m_pBackground = new CIconPanel( this, "Background" );
// Running and Building sub panels only
m_pHealthBar = new CBuildingHealthBar( m_pBuiltPanel, "Health" );
m_pHealthBar->SetSegmentInfo( YRES(1), YRES(3) );
m_pHealthBar->SetProgressDirection( ProgressBar::PROGRESS_NORTH );
m_pHealthBar->SetBarInset( 0 );
m_pBuildingProgress = new vgui::ContinuousProgressBar( m_pBuildingPanel, "BuildingProgress" );
m_pAlertTray = new CBuildingStatusAlertTray( m_pBuiltPanel, "AlertTray" );
m_pWrenchIcon = new CIconPanel( m_pBuiltPanel, "WrenchIcon" );
m_pSapperIcon = new CIconPanel( m_pBuiltPanel, "SapperIcon" );
m_pUpgradeIcons[0] = new CIconPanel( m_pBuiltPanel, "Icon_Upgrade_1" );
m_pUpgradeIcons[1] = new CIconPanel( m_pBuiltPanel, "Icon_Upgrade_2" );
m_pUpgradeIcons[2] = new CIconPanel( m_pBuiltPanel, "Icon_Upgrade_3" );
m_iUpgradeLevel = 1;
vgui::ivgui()->AddTickSignal( GetVPanel() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem::ApplySchemeSettings( IScheme *pScheme )
{
// This lets us use hud_reloadscheme to reload the status items
int x, y;
GetPos( x, y );
LoadControlSettings( m_szLayout );
SetPos( x, y );
BaseClass::ApplySchemeSettings( pScheme );
}
//-----------------------------------------------------------------------------
// Purpose: Calc visibility of subpanels
//-----------------------------------------------------------------------------
void CBuildingStatusItem::PerformLayout( void )
{
BaseClass::PerformLayout();
C_BaseObject *pObj = m_pObject.Get();
m_bActive = ( pObj != NULL );
m_pHealthBar->SetVisible( m_bActive );
m_pNotBuiltPanel->SetVisible( !m_bActive );
m_pBuiltPanel->SetVisible( m_bActive );
if ( pObj )
{
// redo the background
m_pBackground->SetIcon( GetBackgroundImage() );
if ( pObj->IsBuilding() )
{
m_pBuildingPanel->SetVisible( true );
m_pRunningPanel->SetVisible( false );
m_pUpgradeIcons[0]->SetVisible( false );
m_pUpgradeIcons[1]->SetVisible( false );
m_pUpgradeIcons[2]->SetVisible( false );
}
else
{
m_pBuildingPanel->SetVisible( false );
m_pRunningPanel->SetVisible( true );
int iUpgradeLevel = pObj->GetUpgradeLevel();
Assert( iUpgradeLevel >= 1 && iUpgradeLevel <= 3 );
m_pUpgradeIcons[0]->SetVisible( false );
m_pUpgradeIcons[1]->SetVisible( false );
m_pUpgradeIcons[2]->SetVisible( false );
// show the correct upgrade level icon
if ( !pObj->IsMiniBuilding() )
{
m_pUpgradeIcons[iUpgradeLevel-1]->SetVisible( true );
}
}
}
else
{
// redo the background
m_pBackground->SetIcon( GetInactiveBackgroundImage() );
if ( m_pAlertTray->IsTrayOut() )
{
m_pAlertTray->HideTray();
m_pWrenchIcon->SetVisible( false );
m_pSapperIcon->SetVisible( false );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Setup
//-----------------------------------------------------------------------------
void CBuildingStatusItem::LevelInit( void )
{
if ( m_pAlertTray )
m_pAlertTray->LevelInit();
}
//-----------------------------------------------------------------------------
// Purpose: Setup
//-----------------------------------------------------------------------------
void CBuildingStatusItem::SetObject( C_BaseObject *pObj )
{
m_pObject = pObj;
Assert( !pObj || ( pObj && !pObj->IsMarkedForDeletion() ) );
if ( !pObj )
{
m_pAlertTray->HideTray();
m_pWrenchIcon->SetVisible( false );
m_pSapperIcon->SetVisible( false );
m_pAlertTray->SetAlertType( BUILDING_HUD_ALERT_NONE );
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem::Paint( void )
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem::PaintBackground( void )
{
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBuildingStatusItem::GetBackgroundImage( void )
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
const char *pResult = "obj_status_background_blue";
if ( !pLocalPlayer )
{
Assert( 0 );
return pResult;
}
switch( pLocalPlayer->GetTeamNumber() )
{
case TF_TEAM_BLUE:
pResult = "obj_status_background_blue";
break;
case TF_TEAM_RED:
pResult = "obj_status_background_red";
break;
default:
break;
}
return pResult;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBuildingStatusItem::GetInactiveBackgroundImage( void )
{
return "obj_status_background_disabled";
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem::OnTick()
{
// We only tick while active and with a valid built object
C_BaseObject *pObj = GetRepresentativeObject();
if ( !pObj ) // implies not active
{
if ( m_bActive )
{
// we lost our object. force relayout to inactive mode
InvalidateLayout();
// tell our parent that we're gone
IGameEvent *event = gameeventmanager->CreateEvent( "building_info_changed" );
if ( event )
{
event->SetInt( "building_type", GetRepresentativeObjectType() );
event->SetInt( "object_mode", GetRepresentativeObjectMode() );
gameeventmanager->FireEventClientSide( event );
}
}
// We don't want to tick while inactive regardless
return;
}
float flHealth = (float)pObj->GetHealth() / (float)pObj->GetMaxHealth();
m_pHealthBar->SetProgress( flHealth );
if ( pObj->IsBuilding() )
{
m_pBuildingPanel->SetVisible( true );
m_pRunningPanel->SetVisible( false );
m_pBuildingProgress->SetProgress( pObj->GetPercentageConstructed() );
}
else
{
m_pBuildingPanel->SetVisible( false );
m_pRunningPanel->SetVisible( true );
}
// what is our current alert state?
BuildingHudAlert_t alertLevel = pObj->GetBuildingAlertLevel();
if ( alertLevel <= BUILDING_HUD_ALERT_NONE )
{
// if the tray is out, hide it
if ( m_pAlertTray->IsTrayOut() )
{
m_pAlertTray->HideTray();
m_pWrenchIcon->SetVisible( false );
m_pSapperIcon->SetVisible( false );
}
}
else
{
m_pWrenchIcon->SetVisible( false );
m_pSapperIcon->SetVisible( false );
bool bShowAlertTray = false;
bool bAlertTrayFullyDeployed = m_pAlertTray->GetPercentDeployed() >= 1.0f;
switch( alertLevel )
{
// show low ammo for normal sentry and mini-sentry
case BUILDING_HUD_ALERT_LOW_AMMO:
case BUILDING_HUD_ALERT_VERY_LOW_AMMO:
bShowAlertTray = true;
m_pWrenchIcon->SetVisible( bAlertTrayFullyDeployed );
break;
// do not show low health for mini-sentry
case BUILDING_HUD_ALERT_LOW_HEALTH:
case BUILDING_HUD_ALERT_VERY_LOW_HEALTH:
bShowAlertTray = pObj->IsMiniBuilding() == false;
m_pWrenchIcon->SetVisible( bAlertTrayFullyDeployed && bShowAlertTray );
break;
// always show when being sapped
case BUILDING_HUD_ALERT_SAPPER:
bShowAlertTray = true;
m_pSapperIcon->SetVisible( bAlertTrayFullyDeployed );
break;
default:
bShowAlertTray = false;
break;
}
if ( bShowAlertTray && !pObj->IsDisposableBuilding() )
{
if ( !m_pAlertTray->IsTrayOut() )
{
m_pAlertTray->ShowTray();
}
m_pAlertTray->SetAlertType( alertLevel );
}
else
{
if ( m_pAlertTray->IsTrayOut() )
{
m_pAlertTray->HideTray();
}
m_pAlertTray->SetAlertType( BUILDING_HUD_ALERT_NONE );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
C_BaseObject *CBuildingStatusItem::GetRepresentativeObject( void )
{
if ( !m_bActive )
{
return NULL;
}
else
{
return m_pObject.Get();
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CBuildingStatusItem::GetRepresentativeObjectType( void )
{
return m_iObjectType;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CBuildingStatusItem::GetRepresentativeObjectMode( void )
{
return m_iObjectMode;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
int CBuildingStatusItem::GetObjectPriority( void )
{
int nPriority = GetObjectInfo( GetRepresentativeObjectType() )->m_iDisplayPriority;
// MvM hack to sort buildings properly since we can have more than one sentry via upgrades
if ( GetRepresentativeObjectType() == OBJ_SENTRYGUN && GetRepresentativeObjectMode() == MODE_SENTRYGUN_DISPOSABLE )
{
nPriority = 0;
}
return nPriority;
}
//============================================================================
DECLARE_BUILD_FACTORY( CBuildingStatusAlertTray );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBuildingStatusAlertTray::CBuildingStatusAlertTray(Panel *parent, const char *panelName) : BaseClass( parent, panelName )
{
m_pAlertPanelMaterial = NULL;
m_flAlertDeployedPercent = 0.0f;
m_bIsTrayOut = false;
m_pAlertPanelHudTexture = NULL;
m_pAlertPanelMaterial = NULL;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusAlertTray::ApplySettings( KeyValues *inResourceData )
{
m_pAlertPanelHudTexture = gHUD.GetIcon( inResourceData->GetString( "icon", "" ) );
if ( m_pAlertPanelHudTexture )
{
m_pAlertPanelMaterial = materials->FindMaterial( m_pAlertPanelHudTexture->szTextureFile, TEXTURE_GROUP_VGUI );
}
BaseClass::ApplySettings( inResourceData );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusAlertTray::Paint( void )
{
// Paint the alert tray
if ( !m_pAlertPanelMaterial || !m_pAlertPanelHudTexture )
{
return;
}
int x = 0;
int y = 0;
ipanel()->GetAbsPos(GetVPanel(), x,y );
int iWidth = GetWide();
int iHeight = GetTall();
// Position the alert panel image based on the deployed percent
float flXa = m_pAlertPanelHudTexture->texCoords[0];
float flXb = m_pAlertPanelHudTexture->texCoords[2];
float flYa = m_pAlertPanelHudTexture->texCoords[1];
float flYb = m_pAlertPanelHudTexture->texCoords[3];
float flMaskXa = flXa;
float flMaskXb = flXb;
float flMaskYa = flYa;
float flMaskYb = flYb;
float flFrameDelta = ( flXb - flXa ) * ( 1.0 - m_flAlertDeployedPercent );
flXa += flFrameDelta;
flXb += flFrameDelta;
CMatRenderContextPtr pRenderContext( materials );
pRenderContext->Bind( m_pAlertPanelMaterial );
IMesh* pMesh = pRenderContext->GetDynamicMesh( true );
int r, g, b, a;
r = a = 255;
switch( m_lastAlertType )
{
case BUILDING_HUD_ALERT_VERY_LOW_AMMO:
case BUILDING_HUD_ALERT_VERY_LOW_HEALTH:
g = b = (int)( 127.0f + 127.0f * cos( gpGlobals->curtime * 2.0f * M_PI * 0.5 ) );
break;
case BUILDING_HUD_ALERT_SAPPER:
g = b = (int)( 127.0f + 127.0f * cos( gpGlobals->curtime * 2.0f * M_PI * 1.5 ) );
break;
case BUILDING_HUD_ALERT_LOW_AMMO:
case BUILDING_HUD_ALERT_LOW_HEALTH:
case BUILDING_HUD_ALERT_NONE:
default:
g = b = 255;
break;
}
CMeshBuilder meshBuilder;
meshBuilder.Begin( pMesh, MATERIAL_QUADS, 1 );
meshBuilder.Position3f( x, y, 0.0f );
meshBuilder.TexCoord2f( 0, flXa, flYa );
meshBuilder.TexCoord2f( 1, flMaskXa, flMaskYa );
meshBuilder.Color4ub( r, g, b, a );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( x + iWidth, y, 0.0f );
meshBuilder.TexCoord2f( 0, flXb, flYa );
meshBuilder.TexCoord2f( 1, flMaskXb, flMaskYa );
meshBuilder.Color4ub( r, g, b, a );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( x + iWidth, y + iHeight, 0.0f );
meshBuilder.TexCoord2f( 0, flXb, flYb );
meshBuilder.TexCoord2f( 1, flMaskXb, flMaskYb );
meshBuilder.Color4ub( r, g, b, a );
meshBuilder.AdvanceVertex();
meshBuilder.Position3f( x, y + iHeight, 0.0f );
meshBuilder.TexCoord2f( 0, flXa, flYb );
meshBuilder.TexCoord2f( 1, flMaskXa, flMaskYb );
meshBuilder.Color4ub( r, g, b, a );
meshBuilder.AdvanceVertex();
meshBuilder.End();
pMesh->Draw();
}
void CBuildingStatusAlertTray::PaintBackground( void )
{
}
void CBuildingStatusAlertTray::ShowTray( void )
{
if ( m_bIsTrayOut == false )
{
m_flAlertDeployedPercent = 0.0;
g_pClientMode->GetViewportAnimationController()->RunAnimationCommand( this, "deployed", 1.0, 0.0, 0.3, AnimationController::INTERPOLATOR_LINEAR );
m_bIsTrayOut = true;
}
}
void CBuildingStatusAlertTray::HideTray( void )
{
if ( m_bIsTrayOut == true )
{
m_flAlertDeployedPercent = 1.0;
g_pClientMode->GetViewportAnimationController()->RunAnimationCommand( this, "deployed", 0.0, 0.0, 0.3, AnimationController::INTERPOLATOR_LINEAR );
m_bIsTrayOut = false;
}
}
//-----------------------------------------------------------------------------
// Purpose: Setup
//-----------------------------------------------------------------------------
void CBuildingStatusAlertTray::LevelInit( void )
{
m_bIsTrayOut = false;
m_flAlertDeployedPercent = 0.0f;
}
void CBuildingStatusAlertTray::SetAlertType( BuildingHudAlert_t alertLevel )
{
m_lastAlertType = alertLevel;
}
//============================================================================
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBuildingStatusItem_SentryGun::CBuildingStatusItem_SentryGun( Panel *parent ) :
CBuildingStatusItem( parent, "resource/UI/hud_obj_sentrygun.res", OBJ_SENTRYGUN, MODE_SENTRYGUN_NORMAL )
{
m_pShellsProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Shells" );
m_pRocketsProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Rockets" );
m_pUpgradeProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Upgrade" );
m_pRocketIcon = new vgui::ImagePanel( GetRunningPanel(), "RocketIcon" );
m_pUpgradeIcon = new CIconPanel( GetRunningPanel(), "UpgradeIcon" );
m_pSentryIcons[0] = new CIconPanel( this, "Icon_Sentry_1" );
m_pSentryIcons[1] = new CIconPanel( this, "Icon_Sentry_2" );
m_pSentryIcons[2] = new CIconPanel( this, "Icon_Sentry_3" );
m_iUpgradeLevel = 1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_SentryGun::ApplySchemeSettings( vgui::IScheme *scheme )
{
BaseClass::ApplySchemeSettings( scheme );
m_cLowAmmoColor = scheme->GetColor( "LowHealthRed", Color(255,0,0,255) );
m_cNormalAmmoColor = scheme->GetColor( "ProgressOffWhite", Color(255,255,255,255) );
}
//-----------------------------------------------------------------------------
// Purpose: Calc visibility of subpanels
//-----------------------------------------------------------------------------
void CBuildingStatusItem_SentryGun::PerformLayout( void )
{
BaseClass::PerformLayout();
C_ObjectSentrygun *pSentrygun = dynamic_cast<C_ObjectSentrygun *>( GetRepresentativeObject() );
if ( !pSentrygun || ( pSentrygun && pSentrygun->IsDisposableBuilding() ) )
{
return;
}
GetRunningPanel()->SetDialogVariable( "numkills", pSentrygun->GetKills() );
GetRunningPanel()->SetDialogVariable( "numassists", pSentrygun->GetAssists() );
int iShells, iMaxShells;
int iRockets, iMaxRockets;
pSentrygun->GetAmmoCount( iShells, iMaxShells, iRockets, iMaxRockets );
// Shells label
float flShells = (float)iShells / (float)iMaxShells;
m_pShellsProgress->SetProgress( flShells );
if ( flShells < 0.25f )
{
m_pShellsProgress->SetFgColor( m_cLowAmmoColor );
}
else
{
m_pShellsProgress->SetFgColor( m_cNormalAmmoColor );
}
// Rockets label
float flRockets = (float)iRockets / (float)SENTRYGUN_MAX_ROCKETS;
m_pRocketsProgress->SetProgress( flRockets );
if ( flRockets < 0.25f )
{
m_pRocketsProgress->SetFgColor( m_cLowAmmoColor );
}
else
{
m_pRocketsProgress->SetFgColor( m_cNormalAmmoColor );
}
int iUpgradeLevel = pSentrygun->GetUpgradeLevel();
Assert( iUpgradeLevel >= 1 && iUpgradeLevel <= 3 );
// show the correct icon
m_pSentryIcons[0]->SetVisible( false );
m_pSentryIcons[1]->SetVisible( false );
m_pSentryIcons[2]->SetVisible( false );
m_pSentryIcons[iUpgradeLevel-1]->SetVisible( true );
// upgrade progress
int iMetal = pSentrygun->GetUpgradeMetal();
int iMetalRequired = pSentrygun->GetUpgradeMetalRequired();
float flUpgrade = (float)iMetal / (float)iMetalRequired;
m_pUpgradeProgress->SetProgress( flUpgrade );
// upgrade label only in 1 or 2
m_pUpgradeIcon->SetVisible( iUpgradeLevel < 3 );
m_pUpgradeProgress->SetVisible( iUpgradeLevel < 3 );
// rockets label only in 3
m_pRocketIcon->SetVisible( iUpgradeLevel == 3 );
m_pRocketsProgress->SetVisible( iUpgradeLevel == 3 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_SentryGun::OnTick()
{
BaseClass::OnTick();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBuildingStatusItem_SentryGun::GetBackgroundImage( void )
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
const char *pResult = "obj_status_background_tall_blue";
if ( !pLocalPlayer )
{
return pResult;
}
switch( pLocalPlayer->GetTeamNumber() )
{
case TF_TEAM_BLUE:
pResult = "obj_status_background_tall_blue";
break;
case TF_TEAM_RED:
pResult = "obj_status_background_tall_red";
break;
default:
break;
}
return pResult;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBuildingStatusItem_SentryGun::GetInactiveBackgroundImage( void )
{
return "obj_status_background_tall_disabled";
}
//============================================================================
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBuildingStatusItem_SentryGun_Disposable::CBuildingStatusItem_SentryGun_Disposable( Panel *parent ) :
CBuildingStatusItem( parent, "resource/UI/hud_obj_sentrygun_disp.res", OBJ_SENTRYGUN, MODE_SENTRYGUN_DISPOSABLE )
{
m_pShellsProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Shells" );
m_pUpgradeIcon = new CIconPanel( GetRunningPanel(), "UpgradeIcon" );
m_pSentryIcons[0] = new CIconPanel( this, "Icon_Sentry_1" );
m_pSentryIcons[1] = new CIconPanel( this, "Icon_Sentry_2" );
m_pSentryIcons[2] = new CIconPanel( this, "Icon_Sentry_3" );
m_iUpgradeLevel = 1;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_SentryGun_Disposable::ApplySchemeSettings( vgui::IScheme *scheme )
{
BaseClass::ApplySchemeSettings( scheme );
m_cLowAmmoColor = scheme->GetColor( "LowHealthRed", Color(255,0,0,255) );
m_cNormalAmmoColor = scheme->GetColor( "ProgressOffWhite", Color(255,255,255,255) );
}
//-----------------------------------------------------------------------------
// Purpose: Calc visibility of subpanels
//-----------------------------------------------------------------------------
void CBuildingStatusItem_SentryGun_Disposable::PerformLayout( void )
{
BaseClass::PerformLayout();
C_ObjectSentrygun *pSentrygun = dynamic_cast<C_ObjectSentrygun *>( GetRepresentativeObject() );
if ( !pSentrygun || ( pSentrygun && !pSentrygun->IsDisposableBuilding() ) )
{
return;
}
GetRunningPanel()->SetDialogVariable( "numkills", pSentrygun->GetKills() );
GetRunningPanel()->SetDialogVariable( "numassists", pSentrygun->GetAssists() );
int iShells, iMaxShells;
int iRockets, iMaxRockets;
pSentrygun->GetAmmoCount( iShells, iMaxShells, iRockets, iMaxRockets );
// Shells label
float flShells = (float)iShells / (float)iMaxShells;
m_pShellsProgress->SetProgress( flShells );
if ( flShells < 0.25f )
{
m_pShellsProgress->SetFgColor( m_cLowAmmoColor );
}
else
{
m_pShellsProgress->SetFgColor( m_cNormalAmmoColor );
}
int iUpgradeLevel = pSentrygun->GetUpgradeLevel();
Assert( iUpgradeLevel >= 1 && iUpgradeLevel <= 3 );
// show the correct icon
m_pSentryIcons[0]->SetVisible( false );
m_pSentryIcons[1]->SetVisible( false );
m_pSentryIcons[2]->SetVisible( false );
m_pSentryIcons[iUpgradeLevel-1]->SetVisible( true );
m_pUpgradeIcon->SetEnabled( false );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_SentryGun_Disposable::OnTick()
{
BaseClass::OnTick();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBuildingStatusItem_SentryGun_Disposable::GetBackgroundImage( void )
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
const char *pResult = "obj_status_background_tall_blue";
if ( !pLocalPlayer )
{
return pResult;
}
switch( pLocalPlayer->GetTeamNumber() )
{
case TF_TEAM_BLUE:
pResult = "obj_status_background_blue";
break;
case TF_TEAM_RED:
pResult = "obj_status_background_red";
break;
default:
break;
}
return pResult;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
const char *CBuildingStatusItem_SentryGun_Disposable::GetInactiveBackgroundImage( void )
{
return "obj_status_background_disabled";
}
//============================================================================
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBuildingStatusItem_Dispenser::CBuildingStatusItem_Dispenser( Panel *parent ) :
CBuildingStatusItem( parent, "resource/UI/hud_obj_dispenser.res", OBJ_DISPENSER )
{
m_pAmmoProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Ammo" );
m_pUpgradeProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Upgrade" );
m_pUpgradeIcon = new CIconPanel( GetRunningPanel(), "UpgradeIcon" );
}
//-----------------------------------------------------------------------------
// Purpose: Calc visibility of subpanels
//-----------------------------------------------------------------------------
void CBuildingStatusItem_Dispenser::PerformLayout( void )
{
BaseClass::PerformLayout();
C_ObjectDispenser *pDispenser = static_cast<C_ObjectDispenser*>(GetRepresentativeObject());
if ( !pDispenser )
{
return;
}
int iAmmo = pDispenser->GetMetalAmmoCount();
float flMaxMetal = pDispenser->IsMiniBuilding() ? MINI_DISPENSER_MAX_METAL : DISPENSER_MAX_METAL_AMMO;
float flProgress = (float)iAmmo / flMaxMetal;
m_pAmmoProgress->SetProgress( flProgress );
int iUpgradeLevel = pDispenser->GetUpgradeLevel();
Assert( iUpgradeLevel >= 1 && iUpgradeLevel <= 3 );
// upgrade progress
int iMetal = pDispenser->GetUpgradeMetal();
int iMetalRequired = pDispenser->GetUpgradeMetalRequired();
flProgress = (float)iMetal / (float)iMetalRequired;
m_pUpgradeProgress->SetProgress( flProgress );
// upgrade label only in 1 or 2
bool bShowUpgradeInfo = iUpgradeLevel < 3;
m_pUpgradeIcon->SetVisible( bShowUpgradeInfo );
m_pUpgradeProgress->SetVisible( bShowUpgradeInfo );
}
//============================================================================
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBuildingStatusItem_TeleporterEntrance::CBuildingStatusItem_TeleporterEntrance( Panel *parent ) :
CBuildingStatusItem( parent, "resource/UI/hud_obj_tele_entrance.res", OBJ_TELEPORTER, MODE_TELEPORTER_ENTRANCE )
{
// Panel and children when we are charging
m_pChargingPanel = new vgui::EditablePanel( GetRunningPanel(), "ChargingPanel" );
m_pRechargeTimer = new vgui::ContinuousProgressBar( m_pChargingPanel, "Recharge" );
// Panel and children when we are fully charged
m_pFullyChargedPanel = new vgui::EditablePanel( GetRunningPanel(), "FullyChargedPanel" );
m_iTimesUsed = -1; // force first update of 0
m_iTeleporterState = -1;
m_pUpgradeProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Upgrade" );
m_pUpgradeIcon = new CIconPanel( GetRunningPanel(), "UpgradeIcon" );
vgui::ivgui()->AddTickSignal( GetVPanel() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_TeleporterEntrance::OnTick( void )
{
// We only tick while active and with a valid built object
C_ObjectTeleporter *pTeleporter = static_cast<C_ObjectTeleporter*>(GetRepresentativeObject());
if ( pTeleporter && IsActive() )
{
if ( pTeleporter->GetState() == TELEPORTER_STATE_RECHARGING )
{
// Update the recharge
float flMaxRecharge = pTeleporter->GetCurrentRechargeDuration();
float flChargeTime = pTeleporter->GetChargeTime();
m_pRechargeTimer->SetProgress( 1.0 - ( flChargeTime / flMaxRecharge ) );
}
}
BaseClass::OnTick();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_TeleporterEntrance::PerformLayout( void )
{
BaseClass::PerformLayout();
// We only tick while active and with a valid built object
C_ObjectTeleporter *pTeleporter = static_cast<C_ObjectTeleporter*>(GetRepresentativeObject());
if ( !IsActive() || !pTeleporter )
{
return;
}
bool bRecharging = ( pTeleporter->GetState() == TELEPORTER_STATE_RECHARGING );
m_pChargingPanel->SetVisible( bRecharging );
m_pFullyChargedPanel->SetVisible( !bRecharging );
// How many times has this teleporter been used?
m_pFullyChargedPanel->SetDialogVariable( "timesused", pTeleporter->GetTimesUsed() );
int iUpgradeLevel = pTeleporter->GetUpgradeLevel();
Assert( iUpgradeLevel >= 1 && iUpgradeLevel <= 3 );
// upgrade progress
int iMetal = pTeleporter->GetUpgradeMetal();
int iMetalRequired = pTeleporter->GetUpgradeMetalRequired();
float flUpgrade = (float)iMetal / (float)iMetalRequired;
m_pUpgradeProgress->SetProgress( flUpgrade );
// upgrade label only in 1 or 2
m_pUpgradeIcon->SetVisible( iUpgradeLevel < 3 );
m_pUpgradeProgress->SetVisible( iUpgradeLevel < 3 );
}
//============================================================================
CBuildingStatusItem_TeleporterExit::CBuildingStatusItem_TeleporterExit( Panel *parent ) :
CBuildingStatusItem( parent, "resource/UI/hud_obj_tele_exit.res", OBJ_TELEPORTER, MODE_TELEPORTER_EXIT )
{
m_pUpgradeProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Upgrade" );
m_pUpgradeIcon = new CIconPanel( GetRunningPanel(), "UpgradeIcon" );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_TeleporterExit::PerformLayout( void )
{
BaseClass::PerformLayout();
// We only tick while active and with a valid built object
C_ObjectTeleporter *pTeleporter = static_cast<C_ObjectTeleporter*>(GetRepresentativeObject());
if ( !IsActive() || !pTeleporter )
{
return;
}
int iUpgradeLevel = pTeleporter->GetUpgradeLevel();
Assert( iUpgradeLevel >= 1 && iUpgradeLevel <= 3 );
// upgrade progress
int iMetal = pTeleporter->GetUpgradeMetal();
int iMetalRequired = pTeleporter->GetUpgradeMetalRequired();
float flUpgrade = (float)iMetal / (float)iMetalRequired;
m_pUpgradeProgress->SetProgress( flUpgrade );
// upgrade label only in 1 or 2
m_pUpgradeIcon->SetVisible( iUpgradeLevel < 3 );
m_pUpgradeProgress->SetVisible( iUpgradeLevel < 3 );
}
#ifdef STAGING_ONLY
//============================================================================
CBuildingStatusItem_TeleporterSpeed::CBuildingStatusItem_TeleporterSpeed( Panel *parent, int ETeleporterMode ) :
CBuildingStatusItem( parent, "resource/UI/hud_obj_tele_speedpad.res", OBJ_TELEPORTER, ETeleporterMode )
{
// Panel and children when we are charging
m_pChargingPanel = new vgui::EditablePanel( GetRunningPanel(), "ChargingPanel" );
m_pRechargeTimer = new vgui::ContinuousProgressBar( m_pChargingPanel, "Recharge" );
// Panel and children when we are fully charged
m_pFullyChargedPanel = new vgui::EditablePanel( GetRunningPanel(), "FullyChargedPanel" );
m_iTimesUsed = -1; // force first update of 0
m_iTeleporterState = -1;
m_pUpgradeProgress = new vgui::ContinuousProgressBar( GetRunningPanel(), "Upgrade" );
m_pUpgradeIcon = new CIconPanel( GetRunningPanel(), "UpgradeIcon" );
vgui::ivgui()->AddTickSignal( GetVPanel() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_TeleporterSpeed::OnTick( void )
{
// We only tick while active and with a valid built object
C_ObjectTeleporter *pTeleporter = static_cast<C_ObjectTeleporter*>( GetRepresentativeObject() );
if ( pTeleporter && IsActive() )
{
if ( pTeleporter->GetState() == TELEPORTER_STATE_RECHARGING )
{
// Update the recharge
float flMaxRecharge = pTeleporter->GetCurrentRechargeDuration();
float flChargeTime = pTeleporter->GetChargeTime();
m_pRechargeTimer->SetProgress( 1.0 - ( flChargeTime / flMaxRecharge ) );
}
}
BaseClass::OnTick();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CBuildingStatusItem_TeleporterSpeed::PerformLayout( void )
{
BaseClass::PerformLayout();
// We only tick while active and with a valid built object
C_ObjectTeleporter *pTeleporter = static_cast<C_ObjectTeleporter*>( GetRepresentativeObject() );
if ( !IsActive() || !pTeleporter )
{
return;
}
bool bRecharging = ( pTeleporter->GetState() == TELEPORTER_STATE_RECHARGING );
m_pChargingPanel->SetVisible( bRecharging );
m_pFullyChargedPanel->SetVisible( !bRecharging );
// How many times has this teleporter been used?
m_pFullyChargedPanel->SetDialogVariable( "timesused", pTeleporter->GetTimesUsed() );
int iUpgradeLevel = pTeleporter->GetUpgradeLevel();
Assert( iUpgradeLevel >= 1 && iUpgradeLevel <= 3 );
// upgrade progress
int iMetal = pTeleporter->GetUpgradeMetal();
int iMetalRequired = pTeleporter->GetUpgradeMetalRequired();
float flUpgrade = (float)iMetal / (float)iMetalRequired;
m_pUpgradeProgress->SetProgress( flUpgrade );
// upgrade label only in 1 or 2
m_pUpgradeIcon->SetVisible( iUpgradeLevel < 3 );
m_pUpgradeProgress->SetVisible( iUpgradeLevel < 3 );
}
#endif
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CBuildingStatusItem_Sapper::CBuildingStatusItem_Sapper( Panel *parent ) :
CBuildingStatusItem( parent, "resource/UI/hud_obj_sapper.res", OBJ_ATTACHMENT_SAPPER )
{
// health of target building
m_pTargetHealthBar = new ContinuousProgressBar( GetRunningPanel(), "TargetHealth" );
// image of target building
m_pTargetIcon = new CIconPanel( GetRunningPanel(), "TargetIcon" );
// force first think to set the icon
m_iTargetType = -1;
}
void CBuildingStatusItem_Sapper::PerformLayout( void )
{
BaseClass::PerformLayout();
// We only tick while active and with a valid built object
C_ObjectSapper *pSapper = static_cast<C_ObjectSapper*>(GetRepresentativeObject());
// only visible
SetVisible( pSapper != NULL );
if ( !IsActive() || !pSapper )
{
return;
}
C_BaseObject *pTarget = pSapper->GetParentObject();
if ( pTarget )
{
float flHealth = (float)pTarget->GetHealth() / (float)pTarget->GetMaxHealth();
m_pTargetHealthBar->SetProgress( flHealth );
int iTargetType = pTarget->GetType();
if ( m_iTargetType != iTargetType )
{
m_pTargetIcon->SetIcon( pTarget->GetHudStatusIcon() );
m_iTargetType = iTargetType;
}
}
else
{
m_pTargetHealthBar->SetProgress( 0.0f );
}
}
//============================================================================
DECLARE_HUDELEMENT( CHudBuildingStatusContainer_Spy );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CHudBuildingStatusContainer_Spy::CHudBuildingStatusContainer_Spy( const char *pElementName ) :
BaseClass( "BuildingStatus_Spy" )
{
AddBuildingPanel( OBJ_ATTACHMENT_SAPPER );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CHudBuildingStatusContainer_Spy::ShouldDraw( void )
{
// Don't draw in freezecam
C_TFPlayer *pPlayer = CTFPlayer::GetLocalTFPlayer();
if ( !pPlayer || !pPlayer->IsPlayerClass( TF_CLASS_SPY ) || pPlayer->GetObserverMode() == OBS_MODE_FREEZECAM )
{
return false;
}
if ( pPlayer->GetTeamNumber() <= TEAM_SPECTATOR )
{
return false;
}
return CHudElement::ShouldDraw();
}
//============================================================================
DECLARE_HUDELEMENT( CHudBuildingStatusContainer_Engineer );
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CHudBuildingStatusContainer_Engineer::CHudBuildingStatusContainer_Engineer( const char *pElementName ) :
BaseClass( "BuildingStatus_Engineer" )
{
AddBuildingPanel( OBJ_SENTRYGUN, MODE_SENTRYGUN_NORMAL );
AddBuildingPanel( OBJ_DISPENSER );
AddBuildingPanel( OBJ_TELEPORTER, MODE_TELEPORTER_ENTRANCE );
AddBuildingPanel( OBJ_TELEPORTER, MODE_TELEPORTER_EXIT );
AddBuildingPanel( OBJ_SENTRYGUN, MODE_SENTRYGUN_DISPOSABLE );
#ifdef STAGING_ONLY
AddBuildingPanel( OBJ_TELEPORTER, MODE_TELEPORTER_SPEED );
AddBuildingPanel( OBJ_TELEPORTER, MODE_TELEPORTER_SPEED2 );
#endif
vgui::ivgui()->AddTickSignal( GetVPanel(), 500 );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CHudBuildingStatusContainer_Engineer::ShouldDraw( void )
{
// Don't draw in freezecam
C_TFPlayer *pPlayer = CTFPlayer::GetLocalTFPlayer();
if ( !pPlayer || !pPlayer->IsPlayerClass( TF_CLASS_ENGINEER ) || pPlayer->GetObserverMode() == OBS_MODE_FREEZECAM )
return false;
if ( pPlayer->GetTeamNumber() <= TEAM_SPECTATOR )
return false;
if ( CTFMinigameLogic::GetMinigameLogic() && CTFMinigameLogic::GetMinigameLogic()->GetActiveMinigame() )
return false;
if ( TFGameRules() && TFGameRules()->ShowMatchSummary() )
return false;
return CHudElement::ShouldDraw();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudBuildingStatusContainer_Engineer::OnTick()
{
BaseClass::OnTick();
if ( !ShouldDraw() )
return;
C_TFPlayer *pLocalPlayer = CTFPlayer::GetLocalTFPlayer();
if ( pLocalPlayer )
{
bool bDisposableSentriesVisible = false;
if ( TFGameRules() && TFGameRules()->GameModeUsesUpgrades() )
{
int nDisposableSentries = 0;
CALL_ATTRIB_HOOK_INT_ON_OTHER( pLocalPlayer, nDisposableSentries, engy_disposable_sentries );
if ( nDisposableSentries )
{
bDisposableSentriesVisible = true;
}
}
#ifdef STAGING_ONLY
int iSpeedPad = 0;
CALL_ATTRIB_HOOK_INT_ON_OTHER( pLocalPlayer, iSpeedPad, teleporter_is_speedpad );
#endif // STAGING_ONLY
for ( int i = 0 ; i < m_BuildingPanels.Count() ; i++ )
{
CBuildingStatusItem *pItem = m_BuildingPanels.Element( i );
if ( pItem && ( pItem->GetRepresentativeObjectType() == OBJ_SENTRYGUN ) && ( pItem->GetRepresentativeObjectMode() == MODE_SENTRYGUN_DISPOSABLE ) )
{
if ( pItem->IsVisible() != bDisposableSentriesVisible )
{
pItem->SetVisible( bDisposableSentriesVisible );
}
#ifndef STAGING_ONLY
break;
#endif // !STAGING_ONLY
}
#ifdef STAGING_ONLY
// Disable entrance and exit
if ( pItem && ( pItem->GetRepresentativeObjectType() == OBJ_TELEPORTER ) )
{
if ( pItem->GetRepresentativeObjectMode() == MODE_TELEPORTER_SPEED || pItem->GetRepresentativeObjectMode() == MODE_TELEPORTER_SPEED2 )
{
pItem->SetVisible( iSpeedPad );
}
else
{
pItem->SetVisible( !(bool)(iSpeedPad) );
}
}
#endif // STAGING_ONLY
}
}
}
//============================================================================
// order the buildings in our m_BuildingsList by their object priority
typedef CBuildingStatusItem *BUILDINGSTATUSITEM_PTR;
static bool BuildingOrderLessFunc( const BUILDINGSTATUSITEM_PTR &left, const BUILDINGSTATUSITEM_PTR &right )
{
return ( left->GetObjectPriority() <= right->GetObjectPriority() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CHudBuildingStatusContainer::CHudBuildingStatusContainer( const char *pElementName ) :
CHudElement( pElementName ), BaseClass( NULL, pElementName )
{
vgui::Panel *pParent = g_pClientMode->GetViewport();
SetParent( pParent );
SetHiddenBits( HIDEHUD_MISCSTATUS );
SetProportional(true);
ListenForGameEvent( "building_info_changed" );
m_BuildingPanels.SetLessFunc( BuildingOrderLessFunc );
m_AlertLevel = BUILDING_HUD_ALERT_NONE;
m_flNextBeep = 0;
m_iNumBeepsToBeep = 0;
// for beeping
vgui::ivgui()->AddTickSignal( GetVPanel() );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
bool CHudBuildingStatusContainer::ShouldDraw( void )
{
// Don't draw in freezecam
C_TFPlayer *pPlayer = CTFPlayer::GetLocalTFPlayer();
if ( pPlayer && pPlayer->GetObserverMode() == OBS_MODE_FREEZECAM )
return false;
return CHudElement::ShouldDraw();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudBuildingStatusContainer::LevelInit( void )
{
CHudElement::LevelInit();
for ( int i = 0; i < m_BuildingPanels.Count(); i++ )
{
CBuildingStatusItem *pItem = m_BuildingPanels.Element(i);
if ( pItem )
{
pItem->LevelInit();
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Create the appropriate info panel for the object
//-----------------------------------------------------------------------------
CBuildingStatusItem *CHudBuildingStatusContainer::CreateItemPanel( int iObjectType, int iObjectMode )
{
CBuildingStatusItem *pBuildingItem = NULL;
switch( iObjectType )
{
case OBJ_SENTRYGUN:
if ( iObjectMode == 0 )
{
pBuildingItem = new CBuildingStatusItem_SentryGun( this );
}
else
{
pBuildingItem = new CBuildingStatusItem_SentryGun_Disposable( this );
}
break;
case OBJ_DISPENSER:
pBuildingItem = new CBuildingStatusItem_Dispenser( this );
break;
case OBJ_TELEPORTER:
if ( iObjectMode == 0 )
{
pBuildingItem = new CBuildingStatusItem_TeleporterEntrance( this );
}
else if ( iObjectMode == 1 )
{
pBuildingItem = new CBuildingStatusItem_TeleporterExit( this );
}
#ifdef STAGING_ONLY
else if ( iObjectMode == 2 )
{
pBuildingItem = new CBuildingStatusItem_TeleporterSpeed( this, MODE_TELEPORTER_SPEED );
}
else
{
pBuildingItem = new CBuildingStatusItem_TeleporterSpeed( this, MODE_TELEPORTER_SPEED2 );
}
#endif
break;
case OBJ_ATTACHMENT_SAPPER:
pBuildingItem = new CBuildingStatusItem_Sapper( this );
break;
default:
pBuildingItem = NULL;
break;
}
Assert( pBuildingItem );
return pBuildingItem;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudBuildingStatusContainer::AddBuildingPanel( int iObjectType, int iObjectMode )
{
CBuildingStatusItem *pBuildingItem = CreateItemPanel( iObjectType, iObjectMode );
Assert( pBuildingItem );
pBuildingItem->SetPos( 0, 0 );
pBuildingItem->InvalidateLayout();
m_BuildingPanels.Insert( pBuildingItem );
RepositionObjectPanels();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudBuildingStatusContainer::UpdateAllBuildings( void )
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pLocalPlayer )
return;
for ( int i = 0; i < m_BuildingPanels.Count(); i++ )
{
CBuildingStatusItem *pItem = m_BuildingPanels.Element(i);
if ( pItem )
{
// find the item that represents this building type
C_BaseObject *pObj = NULL;
if ( pObj )
{
// find the object
pObj = pLocalPlayer->GetObjectOfType( pItem->GetRepresentativeObjectType(), pItem->GetRepresentativeObjectMode() );
pItem->SetObject( pObj );
pItem->InvalidateLayout( true );
RecalculateAlertState();
}
}
}
}
void CHudBuildingStatusContainer::OnBuildingChanged( int iBuildingType, int iBuildingMode, bool bBuildingIsDead )
{
bool bFound = false;
for ( int i = 0; i < m_BuildingPanels.Count() && !bFound; i++ )
{
CBuildingStatusItem *pItem = m_BuildingPanels.Element(i);
if ( pItem && pItem->GetRepresentativeObjectType() == iBuildingType && pItem->GetRepresentativeObjectMode() == iBuildingMode )
{
// find the item that represents this building type
C_BaseObject *pObj = NULL;
// find the object
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( pLocalPlayer )
{
pObj = pLocalPlayer->GetObjectOfType( iBuildingType, iBuildingMode );
pItem->SetObject( pObj );
pItem->InvalidateLayout( true );
bFound = true;
RecalculateAlertState();
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudBuildingStatusContainer::ApplySchemeSettings( vgui::IScheme *scheme )
{
BaseClass::ApplySchemeSettings( scheme );
SetPaintBackgroundEnabled( false );
RepositionObjectPanels();
}
//-----------------------------------------------------------------------------
// Purpose: Contents of object list has changed, reposition the panels
//-----------------------------------------------------------------------------
void CHudBuildingStatusContainer::RepositionObjectPanels( void )
{
float flXPos = XRES(9);
float flYPos = YRES(9);
float flTeleEntranceY = YRES(9);
float flTeleExitY = YRES(9);
// Regular Panels
for ( int i = 0; i < m_BuildingPanels.Count(); i++ )
{
CBuildingStatusItem *pItem = m_BuildingPanels.Element(i);
if ( pItem )
{
// set position directly
pItem->SetPos( flXPos, flYPos );
// do not increment for speed pad (this is a minor hack)
// OBJ_TELEPORTER, MODE_TELEPORTER_SPEED
if ( pItem->GetRepresentativeObjectType() == OBJ_TELEPORTER )
{
switch ( pItem->GetRepresentativeObjectMode() )
{
case MODE_TELEPORTER_ENTRANCE:
flTeleEntranceY = flYPos;
flYPos += pItem->GetTall();
break;
case MODE_TELEPORTER_EXIT:
flTeleExitY = flYPos;
flYPos += pItem->GetTall();
break;
#ifdef STAGING_ONLY
case MODE_TELEPORTER_SPEED:
pItem->SetPos( flXPos, flTeleEntranceY );
break;
case MODE_TELEPORTER_SPEED2:
pItem->SetPos( flXPos, flTeleExitY );
break;
#endif
}
}
else
{
flYPos += pItem->GetTall(); // the fade around the panels gives a gap
}
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CHudBuildingStatusContainer::FireGameEvent( IGameEvent *event )
{
const char * type = event->GetName();
if ( Q_strcmp(type, "building_info_changed" ) == 0 )
{
int iBuildingType = event->GetInt( "building_type" );
int iBuildingMode = event->GetInt( "object_mode" );
if ( iBuildingType >= 0 )
{
bool bRemove = ( event->GetInt( "remove" ) > 0 );
OnBuildingChanged( iBuildingType, iBuildingMode, bRemove );
}
else
{
UpdateAllBuildings();
}
}
else
{
CHudElement::FireGameEvent( event );
}
}
void CHudBuildingStatusContainer::RecalculateAlertState( void )
{
BuildingHudAlert_t maxAlertLevel = BUILDING_HUD_ALERT_NONE;
// find our highest warning level
for ( int i = 0; i < m_BuildingPanels.Count(); i++ )
{
CBuildingStatusItem *pItem = m_BuildingPanels.Element(i);
C_BaseObject * pObj = pItem->GetRepresentativeObject();
if ( pObj )
{
BuildingHudAlert_t alertLevel = pObj->GetBuildingAlertLevel();
if ( alertLevel > maxAlertLevel )
{
if ( pObj->IsMiniBuilding() && alertLevel != BUILDING_HUD_ALERT_LOW_HEALTH && alertLevel != BUILDING_HUD_ALERT_VERY_LOW_HEALTH && alertLevel != BUILDING_HUD_ALERT_SAPPER )
continue;
maxAlertLevel = alertLevel;
}
}
}
if ( maxAlertLevel != m_AlertLevel )
{
if ( maxAlertLevel >= BUILDING_HUD_ALERT_VERY_LOW_AMMO )
{
m_flNextBeep = gpGlobals->curtime; // beep asap
m_iNumBeepsToBeep = tf_hud_num_building_alert_beeps.GetInt();
}
m_AlertLevel = maxAlertLevel;
}
}
void CHudBuildingStatusContainer::OnTick( void )
{
if ( m_AlertLevel >= BUILDING_HUD_ALERT_VERY_LOW_AMMO &&
gpGlobals->curtime >= m_flNextBeep &&
m_iNumBeepsToBeep > 0 )
{
C_TFPlayer *pLocalPlayer = C_TFPlayer::GetLocalTFPlayer();
if ( !pLocalPlayer )
return;
pLocalPlayer->EmitSound( "Hud.Warning" );
switch( m_AlertLevel )
{
case BUILDING_HUD_ALERT_VERY_LOW_AMMO:
case BUILDING_HUD_ALERT_VERY_LOW_HEALTH:
m_flNextBeep = gpGlobals->curtime + 2.0f;
m_iNumBeepsToBeep--;
break;
case BUILDING_HUD_ALERT_SAPPER:
m_flNextBeep = gpGlobals->curtime + 1.0f;
// don't decrement beeps, we want them to go on forever
break;
}
}
} | 30.123256 | 206 | 0.58996 | [
"object"
] |
1725975c054b9c841e46409d4fb5ba04c010023e | 3,194 | cpp | C++ | src/shader.cpp | wilfriedE/VelaSynth | 0c0ad22abe8a0169ba9dd77e67be12b3f505f0a5 | [
"CC0-1.0"
] | 1 | 2018-05-26T23:03:46.000Z | 2018-05-26T23:03:46.000Z | src/shader.cpp | wilfriedE/VelaSynth | 0c0ad22abe8a0169ba9dd77e67be12b3f505f0a5 | [
"CC0-1.0"
] | null | null | null | src/shader.cpp | wilfriedE/VelaSynth | 0c0ad22abe8a0169ba9dd77e67be12b3f505f0a5 | [
"CC0-1.0"
] | null | null | null | #include "shader.hpp"
Shader::Shader(){
}
Shader::Shader(string vertexShader, string fragmentShader){
vertexShaderID = loadShader(vertexShader, GL_VERTEX_SHADER);
fragmentShaderID = loadShader(fragmentShader, GL_FRAGMENT_SHADER);
//create a program and attach the shader objects
programID = glCreateProgram();
glAttachShader(programID, vertexShaderID);
glAttachShader(programID, fragmentShaderID);
//Link the shader program and verify
glLinkProgram(programID);
GLint linked;
glGetProgramiv(programID, GL_LINK_STATUS, &linked);
if(!linked){
cerr << "Error linking program with shaders " << vertexShader
<< " and " << fragmentShader << endl;
}
}
void Shader::startShader(){
glUseProgram(programID);
}
void Shader::stopShader(){
glUseProgram(0);
}
GLuint Shader::getProgram(){
return programID;
}
void Shader::setUniform1i(string identifier, GLint value){
glUniform1i(glGetUniformLocation(programID, identifier.c_str()),value);
}
void Shader::setUniform1f(string identifier, GLfloat value){
glUniform1f(glGetUniformLocation(programID, identifier.c_str()),value);
}
void Shader::cleanUpShader(){
stopShader();
glDetachShader(programID, vertexShaderID);
glDetachShader(programID, fragmentShaderID);
glDeleteShader(vertexShaderID);
glDeleteShader(fragmentShaderID);
glDeleteProgram(programID);
}
GLuint Shader::loadShader(string sourceFileName, GLenum type){
ifstream infile;
infile.open(sourceFileName);
if(infile){
string shader = "", line;
// concatenate each line into a single string
while(getline(infile, line)){
shader += line;
shader += "\n";
}
//Create a shader object to attach the source shader string to and compile
GLuint shaderID = glCreateShader(type);
if(shaderID != 0){
const char* c_str = shader.c_str();
glShaderSource(shaderID, 1, &c_str, NULL);
glCompileShader(shaderID);
GLint compiled;
glGetShaderiv(shaderID, GL_COMPILE_STATUS, &compiled);
if(!compiled){
cerr << sourceFileName << " failed to compile" << endl;
GLint eLogSize;
//Query for the current size of the error log
glGetShaderiv(shaderID, GL_INFO_LOG_LENGTH, &eLogSize);
char* infoLog = new char[eLogSize];
glGetShaderInfoLog(shaderID, eLogSize, NULL, infoLog);
cerr << infoLog << endl;
delete [] infoLog;
exit(EXIT_FAILURE);
}
}else{
cerr << "Error occurred creating shader of type " << type << endl;
exit(EXIT_FAILURE);
}
return shaderID;
}else{
cerr << "Shader file " << sourceFileName << " could not be found!" << endl;
exit(EXIT_FAILURE);
}
}
Shader::~Shader(){
stopShader();
glDetachShader(programID, vertexShaderID);
glDetachShader(programID, fragmentShaderID);
glDeleteShader(vertexShaderID);
glDeleteShader(fragmentShaderID);
glDeleteProgram(programID);
}
| 27.067797 | 84 | 0.639324 | [
"object"
] |
172a2b6776cecf8e88b37027b2d28dd16ae75212 | 12,241 | hpp | C++ | include/ulib/uprop.hpp | syntheticgio/fda-hive | 5e645c6a5b76b5a437635631819a1c934c7fd7fc | [
"Unlicense",
"MIT"
] | null | null | null | include/ulib/uprop.hpp | syntheticgio/fda-hive | 5e645c6a5b76b5a437635631819a1c934c7fd7fc | [
"Unlicense",
"MIT"
] | null | null | null | include/ulib/uprop.hpp | syntheticgio/fda-hive | 5e645c6a5b76b5a437635631819a1c934c7fd7fc | [
"Unlicense",
"MIT"
] | null | null | null | /*
* ::718604!
*
* Copyright(C) November 20, 2014 U.S. Food and Drug Administration
* Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al
* Affiliation: Food and Drug Administration (1), George Washington University (2)
*
* All rights Reserved.
*
* The MIT License (MIT)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#pragma once
#ifndef sLib_usrprop_h
#define sLib_usrprop_h
#include <slib/core/dic.hpp>
#include <slib/core/id.hpp>
#include <slib/core/var.hpp>
#include <slib/core/vec.hpp>
#include <slib/std/variant.hpp>
#include <slib/utils/json/printer.hpp>
#include <ulib/usr.hpp>
#include <ulib/utype2.hpp>
namespace slib {
class sUsrObjPropsTree;
class sUsrObjPropsNode {
public:
enum FindStatus {
eFindError = -1,
eFindStop = 0,
eFindContinue,
eFindPrune
};
typedef FindStatus (*FindConstCallback)(const sUsrObjPropsNode &node, void *param);
typedef FindStatus (*FindCallback)(sUsrObjPropsNode &node, void *param);
protected:
sUsrObjPropsTree * _tree;
idx _row;
idx _name;
sStr _path;
struct Navigation {
idx self;
idx parent;
idx prev_sib;
idx next_sib;
idx first_child;
idx last_child;
idx dim;
idx depth;
Navigation()
{
self = parent = prev_sib = next_sib = first_child = last_child = -1;
dim = depth = 0;
}
} _nav;
FindStatus find(const char * field_name, const sUsrObjPropsNode ** firstFound, bool backwards, FindConstCallback callback, void * callbackParam) const;
FindStatus find(const char * field_name, sUsrObjPropsNode ** firstFound, bool backwards, FindCallback callback, void * callbackParam);
public:
sUsrObjPropsNode(): _tree(0), _row(-1), _name(-1), _path(sMex::fExactSize) {}
virtual ~sUsrObjPropsNode() {}
const sUsrTypeField * field() const;
const char * name() const;
idx namecmp(const char * s) const;
const char * path() const { return _path.ptr(); }
idx treeIndex() const { return _nav.self; }
//! depth from root (including array row virtual nodes)
idx depth() const { return _nav.depth; }
sUsrTypeField::EType type() const;
// value of a leaf node
bool hasValue() const { return _tree && _row >= 0; }
bool value(sVariant &var) const;
const char * value(const char * fallback=0) const;
idx ivalue(idx fallback=0) const;
udx uvalue(udx fallback=0) const;
bool boolvalue(bool fallback=false) const;
real rvalue(real fallback=0.) const;
bool hiveidvalue(sHiveId & val) const;
// flat list of values in a container node
idx values(const char * field_name, sVariant &out) const;
const char * values00(const char * field_name, sStr &out00) const;
idx ivalues(const char * field_name, sVec<idx> &out) const;
idx uvalues(const char * field_name, sVec<udx> &out) const;
idx boolvalues(const char * field_name, sVec<bool> &out) const;
idx boolvalues(const char * field_name, sVec<idx> &out) const;
idx rvalues(const char * field_name, sVec<real> &out) const;
idx hiveidvalues(const char * field_name, sVec<sHiveId> &out) const;
// structured representation of value(s) (as scalar, list, dic, whatever is more
// appropriate) in a container node, derived from flattened type field tree
idx structured(const char * field_name, sVariant &out, const sUsrObjPropsNode ** out_outer_list = 0) const;
// retrieve a dictionary variant of all available structured values
idx allStructured(sVariant &out) const;
// json output
/* ! \param into_object Print into an existing JSON object; do not open or close top-level braces
\param flatten Omit intermediate decorative nodes (ones which serve only for visual grouping of fields)\
\warning into_object can *only* be used on inner nodes that would normally print as an object of keys/values;
it is an error to use into_object on leaf nodes */
bool printJSON(sJSONPrinter & out, bool into_object = false, bool flatten = false) const;
// navigation
idx dim(const char * field_name=0) const;
bool isRoot() const;
const sUsrObjPropsNode * find(const char * field_name=0, FindConstCallback callback=0, void * callbackParam=0) const;
const sUsrObjPropsNode * findBackwards(const char * field_name=0, FindConstCallback callback=0, void * callbackParam=0) const;
const sUsrObjPropsNode * firstChild(const char * field_name=0) const;
const sUsrObjPropsNode * lastChild(const char * field_name=0) const;
const sUsrObjPropsNode * previousSibling(const char * field_name=0) const;
const sUsrObjPropsNode * nextSibling(const char * field_name=0) const;
const sUsrObjPropsNode * parentNode() const;
sUsrObjPropsNode * find(const char * field_name=0, FindCallback callback=0, void * callbackParam=0);
sUsrObjPropsNode * findBackwards(const char * field_name=0, FindCallback callback=0, void * callbackParam=0);
inline sUsrObjPropsNode * firstChild(const char * field_name=0) { return const_cast<sUsrObjPropsNode*>(static_cast<const sUsrObjPropsNode&>(*this).firstChild(field_name)); }
inline sUsrObjPropsNode * lastChild(const char * field_name=0) { return const_cast<sUsrObjPropsNode*>(static_cast<const sUsrObjPropsNode&>(*this).lastChild(field_name)); }
inline sUsrObjPropsNode * previousSibling(const char * field_name=0) { return const_cast<sUsrObjPropsNode*>(static_cast<const sUsrObjPropsNode&>(*this).previousSibling(field_name)); }
inline sUsrObjPropsNode * nextSibling(const char * field_name=0) { return const_cast<sUsrObjPropsNode*>(static_cast<const sUsrObjPropsNode&>(*this).nextSibling(field_name)); }
inline sUsrObjPropsNode * parentNode(const char * field_name=0) { return const_cast<sUsrObjPropsNode*>(static_cast<const sUsrObjPropsNode&>(*this).parentNode()); }
const char * findValue(const char * field_name, const char * fallback=0) const;
bool findValue(const char * field_name, sVariant & val) const;
idx findIValue(const char * field_name, idx fallback=0) const;
udx findUValue(const char * field_name, udx fallback=0) const;
bool findBoolValue(const char * field_name, bool fallback=false) const;
real findRValue(const char * field_name, real fallback=0.) const;
bool findHiveIdValue(const char * field_name, sHiveId & val) const;
const char * findValueOrDefault(const char * field_name) const;
bool findValueOrDefault(const char * field_name, sVariant & val) const;
idx findIValueOrDefault(const char * field_name) const;
udx findUValueOrDefault(const char * field_name) const;
bool findBoolValueOrDefault(const char * field_name) const;
real findRValueOrDefault(const char * field_name) const;
bool findHiveIdValueOrDefault(const char * field_name, sHiveId & val) const;
// modify data
bool set(sVariant &val);
bool set(const char * val=0, idx len=0);
bool set(const sHiveId & val);
bool iset(idx val);
bool uset(udx val);
bool rset(real val);
// append to containers. Creates intermediate container nodes automatically if needed.
const sUsrObjPropsNode * push(const char * field_name, sVariant &val);
const sUsrObjPropsNode * push(const char * field_name, const char * val=0);
const sUsrObjPropsNode * push(const char * field_name, const sHiveId & val);
const sUsrObjPropsNode * ipush(const char * field_name, idx ival);
const sUsrObjPropsNode * upush(const char * field_name, udx uval);
const sUsrObjPropsNode * rpush(const char * field_name, real rval);
#ifdef _DEBUG
virtual const char * printDump(sStr & out, bool onlySelf=false) const;
#endif
friend class sUsrObjPropsTree;
};
class sUsrObjPropsTree: public sUsrObjPropsNode {
protected:
const sUsr& _usr;
sHiveId _type_id; // guaranteed to be zero or a valid type id
sVarSet _table;
sVarSet * _ptable;
sVec<sUsrObjPropsNode> _nodes;
sDic<char> _namesPrintable;
sDic<sDic<idx> > _pathMap; // path => name => node index
void init(const sUsrType2 * obj_type, const sHiveId * obj_type_id);
bool addPathMapEntry(const char * field_name, const char * path, idx index);
idx getPathMapEntry(const char * field_name, const char * path) const;
sUsrObjPropsNode * addNode(const char * field_name, const char * path);
void linkNodeParentSiblings(idx index, idx parent_index);
bool linkNode(idx index);
bool parseTable(const sVarSet & table, idx first_row, sVec<idx> * rows_push, const char * filter);
idx pushHelper(idx node_index, const char * field_name, sVariant &val);
idx pushHelper(idx node_index, const char * field_name, const char * value);
const char * findIdString(sStr & buf) const;
public:
sUsrObjPropsTree(const sUsr& usr, const sUsrType2 * obj_type);
sUsrObjPropsTree(const sUsr& usr, const char * obj_type_name);
sUsrObjPropsTree(const sUsr& usr, const sUsrType2 * obj_type, sVarSet & table);
sUsrObjPropsTree(const sUsr& usr, const char * obj_type_name, sVarSet & table);
sUsrObjPropsTree(const sUsr& usr, const sUsrType2 * obj_type, const sVar & form);
sUsrObjPropsTree(const sUsr& usr, const char * obj_type_name, const sVar & form);
bool initialized() const;
const char * objTypeName() const;
const sUsrType2 * objType() const;
void empty(bool empty_table);
virtual ~sUsrObjPropsTree();
sVarSet& getTable() { return *_ptable; }
const sVarSet& getTable() const { return *_ptable; }
bool useTable(sVarSet & table, const char * filter=0);
bool addTable(const sVarSet & table, const char * filter=0);
bool useForm(const sVar & form, const char * filter=0);
bool addForm(const sVar & form, const char * filter=0);
const sUsrObjPropsNode * getNodeByIndex(idx i) const;
inline sUsrObjPropsNode * getNodeByIndex(idx i) { return const_cast<sUsrObjPropsNode*>(static_cast<const sUsrObjPropsTree&>(*this).getNodeByIndex(i)); }
idx dimTree() const { return _nodes.dim(); }
#if 0 // TODO
// set a value with a specific path
bool setValueAt(const char * path, const char * field_name, const sVariant &val);
bool setValueAt(const char * path, const char * field_name, const char * val=0);
#endif
bool valid(sStr * log = 0) const;
bool complete(sStr * log = 0) const;
#ifdef _DEBUG
virtual const char * printDump(sStr & out, bool onlySelf=false) const;
#endif
friend class sUsrObjPropsNode;
};
};
#endif
| 48.192913 | 191 | 0.67421 | [
"object"
] |
172bc939d1a5711a423a080d04fbed4c0a4763e0 | 26,699 | cpp | C++ | src/model/ZonePropertyUserViewFactorsBySurfaceName.cpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 354 | 2015-01-10T17:46:11.000Z | 2022-03-29T10:00:00.000Z | src/model/ZonePropertyUserViewFactorsBySurfaceName.cpp | muehleisen/OpenStudio | 3bfe89f6c441d1e61e50b8e94e92e7218b4555a0 | [
"blessing"
] | 3,243 | 2015-01-02T04:54:45.000Z | 2022-03-31T17:22:22.000Z | src/model/ZonePropertyUserViewFactorsBySurfaceName.cpp | jmarrec/OpenStudio | 5276feff0d8dbd6c8ef4e87eed626bc270a19b14 | [
"blessing"
] | 157 | 2015-01-07T15:59:55.000Z | 2022-03-30T07:46:09.000Z | /***********************************************************************************************************************
* OpenStudio(R), Copyright (c) 2008-2021, Alliance for Sustainable Energy, LLC, and other contributors. All rights reserved.
*
* 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 name of the copyright holder nor the names of any contributors may be used to endorse or promote products
* derived from this software without specific prior written permission from the respective party.
*
* (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative works
* may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without specific prior
* written permission from Alliance for Sustainable Energy, LLC.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND ANY 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(S), ANY CONTRIBUTORS, THE UNITED STATES GOVERNMENT, OR THE UNITED
* STATES DEPARTMENT OF ENERGY, NOR ANY OF THEIR EMPLOYEES, BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***********************************************************************************************************************/
#include <vector>
#include <string>
#include "ZonePropertyUserViewFactorsBySurfaceName.hpp"
#include "ZonePropertyUserViewFactorsBySurfaceName_Impl.hpp"
#include "ThermalZone.hpp"
#include "ThermalZone_Impl.hpp"
#include "Surface.hpp"
#include "Surface_Impl.hpp"
#include "SubSurface.hpp"
#include "SubSurface_Impl.hpp"
#include "InternalMass.hpp"
#include "InternalMass_Impl.hpp"
#include "Space.hpp"
#include "Space_Impl.hpp"
#include "Model.hpp"
#include "Model_Impl.hpp"
#include "ModelExtensibleGroup.hpp"
#include <utilities/idd/IddEnums.hxx>
#include <utilities/idd/OS_ZoneProperty_UserViewFactors_BySurfaceName_FieldEnums.hxx>
#include "../utilities/core/Assert.hpp"
#include <algorithm>
namespace openstudio {
namespace model {
/*****************************************************************************************************************************************************
* V I E W F A C T O R W R A P P E R *
*****************************************************************************************************************************************************/
ViewFactor::ViewFactor(const ModelObject& fromSurface, const ModelObject& toSurface, double viewFactor)
: m_from_surface(fromSurface), m_to_surface(toSurface), m_view_factor(viewFactor) {
// Matches the maximum value in IDD
if (m_view_factor > 1) {
LOG_AND_THROW("Unable to create view factor, factor of " << m_view_factor << " more than 1");
}
// Note JM 2019-09-13: E+ will issue a Warning if you don't have numSurfaces^2 viewFactors in HeatBalanceIntRadExchange::GetInputViewFactorsbyName
// and set them to zero (which is probably what you want). In order to avoid this warning, I'll allow toSurface == fromSurface
if (fromSurface.handle() == toSurface.handle()) {
// LOG_AND_THROW("Cannot create a viewFactor when fromSurface and toSurface are the same: " << fromSurface.briefDescription());
// Issue a warning if viewFactor isn't zero though, it's unusual for a surface to view itself
if (viewFactor != 0.0) {
LOG(Warn, "You are creating a viewFactor with a value of "
<< viewFactor << " while fromSurface and toSurface are the same: " << fromSurface.briefDescription());
}
}
// Check the IDD types to ensure they are ok
IddObjectType fromIddType = fromSurface.iddObjectType();
if ((fromIddType != IddObjectType::OS_Surface) && (fromIddType != IddObjectType::OS_SubSurface)
&& (fromIddType != IddObjectType::OS_InternalMass)) {
LOG_AND_THROW("fromSurface can be only of type Surface, SubSurface or InternalMass, not " << fromIddType.value());
}
IddObjectType toIddType = toSurface.iddObjectType();
if ((toIddType != IddObjectType::OS_Surface) && (toIddType != IddObjectType::OS_SubSurface) && (toIddType != IddObjectType::OS_InternalMass)) {
LOG_AND_THROW("toSurface can be only of type Surface, SubSurface or InternalMass, not " << toIddType.value());
}
}
ModelObject ViewFactor::fromSurface() const {
return m_from_surface;
}
ModelObject ViewFactor::toSurface() const {
return m_to_surface;
}
double ViewFactor::viewFactor() const {
return m_view_factor;
}
std::ostream& operator<<(std::ostream& out, const openstudio::model::ViewFactor& viewFactor) {
out << "(from " << viewFactor.fromSurface().iddObject().name() << "='" << viewFactor.fromSurface().nameString() << "', "
<< "to " << viewFactor.toSurface().iddObject().name() << "='" << viewFactor.toSurface().nameString() << "', "
<< "view factor=" << viewFactor.viewFactor() << ")";
return out;
}
/*****************************************************************************************************************************************************
* Z O N E P R O P E R T Y U S E R V I E W F A C T O R S B Y S U R F A C E N A M E *
*****************************************************************************************************************************************************/
namespace detail {
ZonePropertyUserViewFactorsBySurfaceName_Impl::ZonePropertyUserViewFactorsBySurfaceName_Impl(const IdfObject& idfObject, Model_Impl* model,
bool keepHandle)
: ModelObject_Impl(idfObject, model, keepHandle) {
OS_ASSERT(idfObject.iddObject().type() == ZonePropertyUserViewFactorsBySurfaceName::iddObjectType());
}
ZonePropertyUserViewFactorsBySurfaceName_Impl::ZonePropertyUserViewFactorsBySurfaceName_Impl(
const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle)
: ModelObject_Impl(other, model, keepHandle) {
OS_ASSERT(other.iddObject().type() == ZonePropertyUserViewFactorsBySurfaceName::iddObjectType());
}
ZonePropertyUserViewFactorsBySurfaceName_Impl::ZonePropertyUserViewFactorsBySurfaceName_Impl(
const ZonePropertyUserViewFactorsBySurfaceName_Impl& other, Model_Impl* model, bool keepHandle)
: ModelObject_Impl(other, model, keepHandle) {}
const std::vector<std::string>& ZonePropertyUserViewFactorsBySurfaceName_Impl::outputVariableNames() const {
static const std::vector<std::string> result;
return result;
}
IddObjectType ZonePropertyUserViewFactorsBySurfaceName_Impl::iddObjectType() const {
return ZonePropertyUserViewFactorsBySurfaceName::iddObjectType();
}
ModelObject ZonePropertyUserViewFactorsBySurfaceName_Impl::clone(Model model) const {
LOG_AND_THROW("Cloning isn't allowed for ZonePropertyUserViewFactorsBySurfaceName in order to guarantee that every "
"ZonePropertyUserViewFactorsBySurfaceName has a thermal zone, and"
"that a thermal zone must have only one ZonePropertyUserViewFactorsBySurfaceName.");
}
ThermalZone ZonePropertyUserViewFactorsBySurfaceName_Impl::thermalZone() const {
boost::optional<ThermalZone> thermalZone =
getObject<ModelObject>().getModelObjectTarget<ThermalZone>(OS_ZoneProperty_UserViewFactors_BySurfaceNameFields::ThermalZoneName);
OS_ASSERT(thermalZone);
return thermalZone.get();
}
unsigned int ZonePropertyUserViewFactorsBySurfaceName_Impl::numberofViewFactors() const {
return numExtensibleGroups();
}
boost::optional<unsigned> ZonePropertyUserViewFactorsBySurfaceName_Impl::viewFactorIndex(const ViewFactor& t_viewFactor) const {
boost::optional<unsigned> result;
// Find with custom predicate, checking handle equality between the toSurface and the fromSurface pairs
// We do it with extensibleGroups() (rather than viewFactors()) and getString to avoid overhead
// of manipulating actual model objects (getTarget, then create a ViewFactor wrapper, get handle convert to string...) and speed up the routine
auto egs = castVector<WorkspaceExtensibleGroup>(extensibleGroups());
auto from = toString(t_viewFactor.fromSurface().handle());
auto to = toString(t_viewFactor.toSurface().handle());
auto it = std::find_if(egs.begin(), egs.end(), [&](const WorkspaceExtensibleGroup& eg) {
return ((eg.getField(OS_ZoneProperty_UserViewFactors_BySurfaceNameExtensibleFields::FromSurfaceName).get() == from)
&& (eg.getField(OS_ZoneProperty_UserViewFactors_BySurfaceNameExtensibleFields::ToSurfaceName).get() == to));
});
// If found, we compute the index by using std::distance between the start of vector and the iterator returned by std::find_if
if (it != egs.end()) {
result = std::distance(egs.begin(), it);
}
return result;
}
boost::optional<ViewFactor> ZonePropertyUserViewFactorsBySurfaceName_Impl::getViewFactor(unsigned groupIndex) const {
boost::optional<ViewFactor> result;
if (groupIndex >= numberofViewFactors()) {
LOG(Error, "Asked to get ViewFactor with index " << groupIndex << ", but " << briefDescription() << " has just " << numberofViewFactors()
<< " ViewFactors.");
return result;
}
ModelExtensibleGroup group = getExtensibleGroup(groupIndex).cast<ModelExtensibleGroup>();
boost::optional<ModelObject> _toSurface =
group.getModelObjectTarget<ModelObject>(OS_ZoneProperty_UserViewFactors_BySurfaceNameExtensibleFields::FromSurfaceName);
boost::optional<ModelObject> _fromSurface =
group.getModelObjectTarget<ModelObject>(OS_ZoneProperty_UserViewFactors_BySurfaceNameExtensibleFields::ToSurfaceName);
boost::optional<double> value = group.getDouble(OS_ZoneProperty_UserViewFactors_BySurfaceNameExtensibleFields::ViewFactor);
if (!_toSurface) {
LOG(Error, "Could not retrieve FromSurfaceName for extensible group " << group.groupIndex() << ".");
}
if (!_fromSurface) {
LOG(Error, "Could not retrieve ToSurfaceName for extensible group " << group.groupIndex() << ".");
}
if (!value) {
LOG(Error, "Could not retrieve ViewFactor for extensible group " << group.groupIndex() << ".");
}
result = ViewFactor(_toSurface.get(), _fromSurface.get(), value.get());
return result;
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const ViewFactor& viewFactor) {
bool result = false;
// This the only place we need to cast, in order to check if the actual to/from stuff is part of our zone
// This lambda checks that the InternalMass/Surface/SubSurface is part of the ThermalZone referenced by this object
auto checkIfInThermalZone = [this](const ModelObject& modelObject) {
bool result = false;
boost::optional<Space> _space;
if (boost::optional<Surface> _fromSurfaceAsSurface = modelObject.optionalCast<Surface>()) {
_space = _fromSurfaceAsSurface->space();
} else if (boost::optional<SubSurface> _fromSurfaceAsSubSurface = modelObject.optionalCast<SubSurface>()) {
_space = _fromSurfaceAsSubSurface->space();
} else if (boost::optional<InternalMass> _fromSurfaceAsInternalMass = modelObject.optionalCast<InternalMass>()) {
_space = _fromSurfaceAsInternalMass->space();
} else {
// This can't happen, ViewFactor shouldn't accept anything else
OS_ASSERT(false);
}
if (_space) {
if (boost::optional<ThermalZone> _zone = _space->thermalZone()) {
if (_zone->handle() == this->thermalZone().handle()) {
result = true;
}
}
}
return result;
};
ModelObject fromSurface = viewFactor.fromSurface();
if (!checkIfInThermalZone(fromSurface)) {
LOG(Error, "Cannot add ViewFactor to " << briefDescription() << " because fromSurface=" << fromSurface.briefDescription()
<< "'is not part of the ThermalZone.");
return false;
}
ModelObject toSurface = viewFactor.toSurface();
if (!checkIfInThermalZone(toSurface)) {
LOG(Error, "Cannot add ViewFactor to " << briefDescription() << " because toSurface=" << toSurface.briefDescription()
<< "'is not part of the ThermalZone.");
return false;
}
// Check if viewFactor already exists
boost::optional<unsigned> _existingIndex = viewFactorIndex(viewFactor);
if (_existingIndex) {
boost::optional<ViewFactor> _viewFactor = getViewFactor(_existingIndex.get());
OS_ASSERT(_viewFactor);
LOG(Warn, "For " << briefDescription() << ", ViewFactor already exists, will be modified in place from " << _viewFactor.get() << " to "
<< viewFactor << ".");
}
// If existing, get it, otherwise Push an extensible group. ModelExtensibleGroup cannot be default-constructed, so use a ternary operator
// Given that we will potentially push many extensible groups
// (number of viewFactors to add in a Zone = x^2 where x is number of surfaces + subsurfaces + internalMass)
// we will suffer from going through the internal checks in WorkspaceObject, especially in setPointer,
// and performance will be roughly O(n^2) when adding viewFactors.
// So to improve the performance we pushExtensible group without validity check, and call setPointer without validity check (`isValid`)
std::vector<std::string> temp;
ModelExtensibleGroup eg = (_existingIndex ? getExtensibleGroup(_existingIndex.get()).cast<ModelExtensibleGroup>()
: pushExtensibleGroup(temp, false).cast<ModelExtensibleGroup>());
bool from = eg.setPointer(OS_ZoneProperty_UserViewFactors_BySurfaceNameExtensibleFields::FromSurfaceName, fromSurface.handle(), false);
if (!from) {
LOG(Error, "Unable to add View Factor which has an incompatible fromSurface object to " << briefDescription());
OS_ASSERT(false);
}
bool to = eg.setPointer(OS_ZoneProperty_UserViewFactors_BySurfaceNameExtensibleFields::ToSurfaceName, toSurface.handle(), false);
if (!to) {
LOG(Error, "Unable to add View Factor which has an incompatible toSurface object to " << briefDescription());
OS_ASSERT(false);
}
bool value = eg.setDouble(OS_ZoneProperty_UserViewFactors_BySurfaceNameExtensibleFields::ViewFactor, viewFactor.viewFactor());
if (from && to && value) {
result = true;
} else {
// Something went wrong
// So erase the new extensible group
getObject<ModelObject>().eraseExtensibleGroup(eg.groupIndex());
result = false;
}
return result;
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const Surface& fromSurface, const Surface& toSurface, double value) {
ViewFactor viewFactor(fromSurface, toSurface, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const Surface& fromSurface, const SubSurface& toSubSurface, double value) {
ViewFactor viewFactor(fromSurface, toSubSurface, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const Surface& fromSurface, const InternalMass& toInternalMass, double value) {
ViewFactor viewFactor(fromSurface, toInternalMass, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const SubSurface& fromSubSurface, const SubSurface& toSubSurface,
double value) {
ViewFactor viewFactor(fromSubSurface, toSubSurface, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const SubSurface& fromSubSurface, const Surface& toSurface, double value) {
ViewFactor viewFactor(fromSubSurface, toSurface, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const SubSurface& fromSubSurface, const InternalMass& toInternalMass,
double value) {
ViewFactor viewFactor(fromSubSurface, toInternalMass, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const InternalMass& fromInternalMass, const InternalMass& toSubSurface,
double value) {
ViewFactor viewFactor(fromInternalMass, toSubSurface, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const InternalMass& fromInternalMass, const Surface& toSurface, double value) {
ViewFactor viewFactor(fromInternalMass, toSurface, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactor(const InternalMass& fromInternalMass, const SubSurface& toSubSurface,
double value) {
ViewFactor viewFactor(fromInternalMass, toSubSurface, value);
return addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::removeViewFactor(unsigned groupIndex) {
bool result = false;
unsigned int num = numberofViewFactors();
if (groupIndex < num) {
getObject<ModelObject>().eraseExtensibleGroup(groupIndex);
result = true;
}
return result;
}
void ZonePropertyUserViewFactorsBySurfaceName_Impl::removeAllViewFactors() {
getObject<ModelObject>().clearExtensibleGroups();
}
std::vector<ViewFactor> ZonePropertyUserViewFactorsBySurfaceName_Impl::viewFactors() const {
std::vector<ViewFactor> result;
for (unsigned i = 0; i < numberofViewFactors(); ++i) {
boost::optional<ViewFactor> _viewFactor = getViewFactor(i);
// getViewFactor is responsible for handling error and issuing Error log messages.
// Here we add it to the result array if it worked, and if it didn't, we keep going
// We just issue a message about index so user can delete it easily
if (_viewFactor) {
result.push_back(_viewFactor.get());
} else {
LOG(Error, briefDescription() << " has an invalid ViewFactor group at index " << i);
}
}
return result;
}
bool ZonePropertyUserViewFactorsBySurfaceName_Impl::addViewFactors(const std::vector<ViewFactor>& viewFactors) {
bool result = true;
for (const ViewFactor& viewFactor : viewFactors) {
bool thisResult = addViewFactor(viewFactor);
if (!thisResult) {
LOG(Error, "Could not add viewFactor " << viewFactor << " to " << briefDescription() << ". Continuing with others.");
// OS_ASSERT(false);
// result = false;
}
}
return result;
}
} // namespace detail
ZonePropertyUserViewFactorsBySurfaceName::ZonePropertyUserViewFactorsBySurfaceName(const ThermalZone& thermalZone)
: ModelObject(ZonePropertyUserViewFactorsBySurfaceName::iddObjectType(), thermalZone.model()) {
std::vector<ZonePropertyUserViewFactorsBySurfaceName> zoneProps =
thermalZone.getModelObjectSources<ZonePropertyUserViewFactorsBySurfaceName>(ZonePropertyUserViewFactorsBySurfaceName::iddObjectType());
if (!zoneProps.empty()) {
remove();
LOG_AND_THROW(thermalZone.briefDescription() << " already has a ZonePropertyUserViewFactorsBySurfaceName, cannot create a new one. Use "
"ThermalZone::getZonePropertyUserViewFactorsBySurfaceName() instead.");
}
OS_ASSERT(getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>());
bool ok = setPointer(OS_ZoneProperty_UserViewFactors_BySurfaceNameFields::ThermalZoneName, thermalZone.handle());
OS_ASSERT(ok);
}
IddObjectType ZonePropertyUserViewFactorsBySurfaceName::iddObjectType() {
return IddObjectType(IddObjectType::OS_ZoneProperty_UserViewFactors_BySurfaceName);
}
ThermalZone ZonePropertyUserViewFactorsBySurfaceName::thermalZone() const {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->thermalZone();
}
unsigned int ZonePropertyUserViewFactorsBySurfaceName::numberofViewFactors() const {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->numberofViewFactors();
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const ViewFactor& viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const Surface& fromSurface, const Surface& toSurface, double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromSurface, toSurface, viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const Surface& fromSurface, const SubSurface& toSubSurface, double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromSurface, toSubSurface, viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const Surface& fromSurface, const InternalMass& toInternalMass, double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromSurface, toInternalMass, viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const SubSurface& fromSubSurface, const SubSurface& toSubSurface, double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromSubSurface, toSubSurface, viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const SubSurface& fromSubSurface, const Surface& toSurface, double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromSubSurface, toSurface, viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const SubSurface& fromSubSurface, const InternalMass& toInternalMass,
double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromSubSurface, toInternalMass, viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const InternalMass& fromInternalMass, const InternalMass& toInternalMass,
double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromInternalMass, toInternalMass, viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const InternalMass& fromInternalMass, const Surface& toSurface, double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromInternalMass, toSurface, viewFactor);
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactor(const InternalMass& fromInternalMass, const SubSurface& toSubSurface,
double viewFactor) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactor(fromInternalMass, toSubSurface, viewFactor);
}
boost::optional<unsigned> ZonePropertyUserViewFactorsBySurfaceName::viewFactorIndex(const ViewFactor& viewFactor) const {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->viewFactorIndex(viewFactor);
}
boost::optional<ViewFactor> ZonePropertyUserViewFactorsBySurfaceName::getViewFactor(unsigned groupIndex) const {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->getViewFactor(groupIndex);
}
void ZonePropertyUserViewFactorsBySurfaceName::removeViewFactor(int groupIndex) {
getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->removeViewFactor(groupIndex);
}
void ZonePropertyUserViewFactorsBySurfaceName::removeAllViewFactors() {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->removeAllViewFactors();
}
std::vector<ViewFactor> ZonePropertyUserViewFactorsBySurfaceName::viewFactors() const {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->viewFactors();
}
bool ZonePropertyUserViewFactorsBySurfaceName::addViewFactors(const std::vector<ViewFactor>& viewFactors) {
return getImpl<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl>()->addViewFactors(viewFactors);
}
/// @cond
ZonePropertyUserViewFactorsBySurfaceName::ZonePropertyUserViewFactorsBySurfaceName(
std::shared_ptr<detail::ZonePropertyUserViewFactorsBySurfaceName_Impl> impl)
: ModelObject(std::move(impl)) {}
/// @endcond
} // namespace model
} // namespace openstudio
| 52.764822 | 152 | 0.690625 | [
"object",
"vector",
"model"
] |
1735dc75b499a7c204216f352cdfb6118f229af3 | 16,391 | cpp | C++ | pdfium_lib/pdfium/core/fxge/cfx_pathdata.cpp | qingqibing/vs_pdfium | 6d009d478c3e761fac49b357d81532c3ed7aad9f | [
"BSD-3-Clause"
] | null | null | null | pdfium_lib/pdfium/core/fxge/cfx_pathdata.cpp | qingqibing/vs_pdfium | 6d009d478c3e761fac49b357d81532c3ed7aad9f | [
"BSD-3-Clause"
] | null | null | null | pdfium_lib/pdfium/core/fxge/cfx_pathdata.cpp | qingqibing/vs_pdfium | 6d009d478c3e761fac49b357d81532c3ed7aad9f | [
"BSD-3-Clause"
] | 1 | 2020-04-04T17:23:01.000Z | 2020-04-04T17:23:01.000Z | // Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "core/fxge/cfx_pathdata.h"
#include "core/fxcrt/fx_system.h"
#include "third_party/base/numerics/safe_math.h"
namespace {
void UpdateLineEndPoints(CFX_FloatRect* rect,
const CFX_PointF& start_pos,
const CFX_PointF& end_pos,
float hw) {
if (start_pos.x == end_pos.x) {
if (start_pos.y == end_pos.y) {
rect->UpdateRect(end_pos + CFX_PointF(hw, hw));
rect->UpdateRect(end_pos - CFX_PointF(hw, hw));
return;
}
float point_y;
if (end_pos.y < start_pos.y)
point_y = end_pos.y - hw;
else
point_y = end_pos.y + hw;
rect->UpdateRect(CFX_PointF(end_pos.x + hw, point_y));
rect->UpdateRect(CFX_PointF(end_pos.x - hw, point_y));
return;
}
if (start_pos.y == end_pos.y) {
float point_x;
if (end_pos.x < start_pos.x)
point_x = end_pos.x - hw;
else
point_x = end_pos.x + hw;
rect->UpdateRect(CFX_PointF(point_x, end_pos.y + hw));
rect->UpdateRect(CFX_PointF(point_x, end_pos.y - hw));
return;
}
CFX_PointF diff = end_pos - start_pos;
float ll = FXSYS_sqrt2(diff.x, diff.y);
float mx = end_pos.x + hw * diff.x / ll;
float my = end_pos.y + hw * diff.y / ll;
float dx1 = hw * diff.y / ll;
float dy1 = hw * diff.x / ll;
rect->UpdateRect(CFX_PointF(mx - dx1, my + dy1));
rect->UpdateRect(CFX_PointF(mx + dx1, my - dy1));
}
void UpdateLineJoinPoints(CFX_FloatRect* rect,
const CFX_PointF& start_pos,
const CFX_PointF& mid_pos,
const CFX_PointF& end_pos,
float half_width,
float miter_limit) {
float start_k = 0;
float start_c = 0;
float end_k = 0;
float end_c = 0;
float start_len = 0;
float start_dc = 0;
float end_len = 0;
float end_dc = 0;
float one_twentieth = 1.0f / 20;
bool bStartVert = fabs(start_pos.x - mid_pos.x) < one_twentieth;
bool bEndVert = fabs(mid_pos.x - end_pos.x) < one_twentieth;
if (bStartVert && bEndVert) {
int start_dir = mid_pos.y > start_pos.y ? 1 : -1;
float point_y = mid_pos.y + half_width * start_dir;
rect->UpdateRect(CFX_PointF(mid_pos.x + half_width, point_y));
rect->UpdateRect(CFX_PointF(mid_pos.x - half_width, point_y));
return;
}
if (!bStartVert) {
CFX_PointF start_to_mid = start_pos - mid_pos;
start_k = (mid_pos.y - start_pos.y) / (mid_pos.x - start_pos.x);
start_c = mid_pos.y - (start_k * mid_pos.x);
start_len = FXSYS_sqrt2(start_to_mid.x, start_to_mid.y);
start_dc =
static_cast<float>(fabs(half_width * start_len / start_to_mid.x));
}
if (!bEndVert) {
CFX_PointF end_to_mid = end_pos - mid_pos;
end_k = end_to_mid.y / end_to_mid.x;
end_c = mid_pos.y - (end_k * mid_pos.x);
end_len = FXSYS_sqrt2(end_to_mid.x, end_to_mid.y);
end_dc = static_cast<float>(fabs(half_width * end_len / end_to_mid.x));
}
if (bStartVert) {
CFX_PointF outside(start_pos.x, 0);
if (end_pos.x < start_pos.x)
outside.x += half_width;
else
outside.x -= half_width;
if (start_pos.y < (end_k * start_pos.x) + end_c)
outside.y = (end_k * outside.x) + end_c + end_dc;
else
outside.y = (end_k * outside.x) + end_c - end_dc;
rect->UpdateRect(outside);
return;
}
if (bEndVert) {
CFX_PointF outside(end_pos.x, 0);
if (start_pos.x < end_pos.x)
outside.x += half_width;
else
outside.x -= half_width;
if (end_pos.y < (start_k * end_pos.x) + start_c)
outside.y = (start_k * outside.x) + start_c + start_dc;
else
outside.y = (start_k * outside.x) + start_c - start_dc;
rect->UpdateRect(outside);
return;
}
if (fabs(start_k - end_k) < one_twentieth) {
int start_dir = mid_pos.x > start_pos.x ? 1 : -1;
int end_dir = end_pos.x > mid_pos.x ? 1 : -1;
if (start_dir == end_dir)
UpdateLineEndPoints(rect, mid_pos, end_pos, half_width);
else
UpdateLineEndPoints(rect, start_pos, mid_pos, half_width);
return;
}
float start_outside_c = start_c;
if (end_pos.y < (start_k * end_pos.x) + start_c)
start_outside_c += start_dc;
else
start_outside_c -= start_dc;
float end_outside_c = end_c;
if (start_pos.y < (end_k * start_pos.x) + end_c)
end_outside_c += end_dc;
else
end_outside_c -= end_dc;
float join_x = (end_outside_c - start_outside_c) / (start_k - end_k);
float join_y = start_k * join_x + start_outside_c;
rect->UpdateRect(CFX_PointF(join_x, join_y));
}
} // namespace
FX_PATHPOINT::FX_PATHPOINT() = default;
FX_PATHPOINT::FX_PATHPOINT(const CFX_PointF& point, FXPT_TYPE type, bool close)
: m_Point(point), m_Type(type), m_CloseFigure(close) {}
FX_PATHPOINT::FX_PATHPOINT(const FX_PATHPOINT& other) = default;
FX_PATHPOINT::~FX_PATHPOINT() = default;
CFX_PathData::CFX_PathData() = default;
CFX_PathData::CFX_PathData(const CFX_PathData& src) = default;
CFX_PathData::CFX_PathData(CFX_PathData&& src) = default;
CFX_PathData::~CFX_PathData() = default;
void CFX_PathData::Clear() {
m_Points.clear();
}
void CFX_PathData::ClosePath() {
if (m_Points.empty())
return;
m_Points.back().m_CloseFigure = true;
}
void CFX_PathData::Append(const CFX_PathData* pSrc, const CFX_Matrix* pMatrix) {
if (pSrc->m_Points.empty())
return;
size_t cur_size = m_Points.size();
m_Points.insert(m_Points.end(), pSrc->m_Points.begin(), pSrc->m_Points.end());
if (!pMatrix)
return;
for (size_t i = cur_size; i < m_Points.size(); i++)
m_Points[i].m_Point = pMatrix->Transform(m_Points[i].m_Point);
}
void CFX_PathData::AppendPoint(const CFX_PointF& point,
FXPT_TYPE type,
bool closeFigure) {
m_Points.push_back(FX_PATHPOINT(point, type, closeFigure));
}
void CFX_PathData::AppendLine(const CFX_PointF& pt1, const CFX_PointF& pt2) {
if (m_Points.empty() || fabs(m_Points.back().m_Point.x - pt1.x) > 0.001 ||
fabs(m_Points.back().m_Point.y - pt1.y) > 0.001) {
AppendPoint(pt1, FXPT_TYPE::MoveTo, false);
}
AppendPoint(pt2, FXPT_TYPE::LineTo, false);
}
void CFX_PathData::AppendRect(const CFX_FloatRect& rect) {
return AppendRect(rect.left, rect.bottom, rect.right, rect.top);
}
void CFX_PathData::AppendRect(float left,
float bottom,
float right,
float top) {
CFX_PointF left_bottom(left, bottom);
CFX_PointF left_top(left, top);
CFX_PointF right_top(right, top);
CFX_PointF right_bottom(right, bottom);
AppendLine(left_bottom, left_top);
AppendLine(left_top, right_top);
AppendLine(right_top, right_bottom);
AppendLine(right_bottom, left_bottom);
ClosePath();
}
CFX_FloatRect CFX_PathData::GetBoundingBox() const {
if (m_Points.empty())
return CFX_FloatRect();
CFX_FloatRect rect;
rect.InitRect(m_Points[0].m_Point);
for (size_t i = 1; i < m_Points.size(); i++)
rect.UpdateRect(m_Points[i].m_Point);
return rect;
}
CFX_FloatRect CFX_PathData::GetBoundingBox(float line_width,
float miter_limit) const {
CFX_FloatRect rect(100000.0f, 100000.0f, -100000.0f, -100000.0f);
size_t iPoint = 0;
float half_width = line_width;
int iStartPoint = 0;
int iEndPoint = 0;
int iMiddlePoint = 0;
bool bJoin;
while (iPoint < m_Points.size()) {
if (m_Points[iPoint].IsTypeAndOpen(FXPT_TYPE::MoveTo)) {
if (iPoint + 1 == m_Points.size())
break;
iStartPoint = iPoint + 1;
iEndPoint = iPoint;
bJoin = false;
} else {
if (m_Points[iPoint].IsTypeAndOpen(FXPT_TYPE::BezierTo)) {
rect.UpdateRect(m_Points[iPoint].m_Point);
rect.UpdateRect(m_Points[iPoint + 1].m_Point);
iPoint += 2;
}
if (iPoint == m_Points.size() - 1 ||
m_Points[iPoint + 1].IsTypeAndOpen(FXPT_TYPE::MoveTo)) {
iStartPoint = iPoint - 1;
iEndPoint = iPoint;
bJoin = false;
} else {
iStartPoint = iPoint - 1;
iMiddlePoint = iPoint;
iEndPoint = iPoint + 1;
bJoin = true;
}
}
CFX_PointF start_pos = m_Points[iStartPoint].m_Point;
CFX_PointF end_pos = m_Points[iEndPoint].m_Point;
if (bJoin) {
CFX_PointF mid_pos = m_Points[iMiddlePoint].m_Point;
UpdateLineJoinPoints(&rect, start_pos, mid_pos, end_pos, half_width,
miter_limit);
} else {
UpdateLineEndPoints(&rect, start_pos, end_pos, half_width);
}
iPoint++;
}
return rect;
}
void CFX_PathData::Transform(const CFX_Matrix& matrix) {
for (auto& point : m_Points)
point.m_Point = matrix.Transform(point.m_Point);
}
bool CFX_PathData::GetZeroAreaPath(const CFX_Matrix* pMatrix,
bool bAdjust,
CFX_PathData* NewPath,
bool* bThin,
bool* setIdentity) const {
*setIdentity = false;
if (m_Points.size() < 3)
return false;
if (m_Points.size() == 3 && m_Points[0].m_Type == FXPT_TYPE::MoveTo &&
m_Points[1].m_Type == FXPT_TYPE::LineTo &&
m_Points[2].m_Type == FXPT_TYPE::LineTo &&
m_Points[0].m_Point == m_Points[2].m_Point) {
for (size_t i = 0; i < 2; i++) {
CFX_PointF point = m_Points[i].m_Point;
if (bAdjust) {
if (pMatrix)
point = pMatrix->Transform(point);
point = CFX_PointF(static_cast<int>(point.x) + 0.5f,
static_cast<int>(point.y) + 0.5f);
}
NewPath->AppendPoint(
point, i == 0 ? FXPT_TYPE::MoveTo : FXPT_TYPE::LineTo, false);
}
if (bAdjust && pMatrix)
*setIdentity = true;
// Note, they both have to be not equal.
if (m_Points[0].m_Point.x != m_Points[1].m_Point.x &&
m_Points[0].m_Point.y != m_Points[1].m_Point.y) {
*bThin = true;
}
return true;
}
if (((m_Points.size() > 3) && (m_Points.size() % 2))) {
int mid = m_Points.size() / 2;
bool bZeroArea = false;
CFX_PathData t_path;
for (int i = 0; i < mid; i++) {
if (!(m_Points[mid - i - 1].m_Point == m_Points[mid + i + 1].m_Point &&
m_Points[mid - i - 1].m_Type != FXPT_TYPE::BezierTo &&
m_Points[mid + i + 1].m_Type != FXPT_TYPE::BezierTo)) {
bZeroArea = true;
break;
}
t_path.AppendPoint(m_Points[mid - i].m_Point, FXPT_TYPE::MoveTo, false);
t_path.AppendPoint(m_Points[mid - i - 1].m_Point, FXPT_TYPE::LineTo,
false);
}
if (!bZeroArea) {
NewPath->Append(&t_path, nullptr);
*bThin = true;
return true;
}
}
int startPoint = 0;
int next = 0;
for (size_t i = 0; i < m_Points.size(); i++) {
FXPT_TYPE point_type = m_Points[i].m_Type;
if (point_type == FXPT_TYPE::MoveTo) {
startPoint = i;
} else if (point_type == FXPT_TYPE::LineTo) {
next = (i + 1 - startPoint) % (m_Points.size() - startPoint) + startPoint;
if (m_Points[next].m_Type != FXPT_TYPE::BezierTo &&
m_Points[next].m_Type != FXPT_TYPE::MoveTo) {
if ((m_Points[i - 1].m_Point.x == m_Points[i].m_Point.x &&
m_Points[i].m_Point.x == m_Points[next].m_Point.x) &&
((m_Points[i].m_Point.y - m_Points[i - 1].m_Point.y) *
(m_Points[i].m_Point.y - m_Points[next].m_Point.y) >
0)) {
int pre = i;
if (fabs(m_Points[i].m_Point.y - m_Points[i - 1].m_Point.y) <
fabs(m_Points[i].m_Point.y - m_Points[next].m_Point.y)) {
pre--;
next--;
}
NewPath->AppendPoint(m_Points[pre].m_Point, FXPT_TYPE::MoveTo, false);
NewPath->AppendPoint(m_Points[next].m_Point, FXPT_TYPE::LineTo,
false);
} else if ((m_Points[i - 1].m_Point.y == m_Points[i].m_Point.y &&
m_Points[i].m_Point.y == m_Points[next].m_Point.y) &&
((m_Points[i].m_Point.x - m_Points[i - 1].m_Point.x) *
(m_Points[i].m_Point.x - m_Points[next].m_Point.x) >
0)) {
int pre = i;
if (fabs(m_Points[i].m_Point.x - m_Points[i - 1].m_Point.x) <
fabs(m_Points[i].m_Point.x - m_Points[next].m_Point.x)) {
pre--;
next--;
}
NewPath->AppendPoint(m_Points[pre].m_Point, FXPT_TYPE::MoveTo, false);
NewPath->AppendPoint(m_Points[next].m_Point, FXPT_TYPE::LineTo,
false);
} else if (m_Points[i - 1].m_Type == FXPT_TYPE::MoveTo &&
m_Points[next].m_Type == FXPT_TYPE::LineTo &&
m_Points[i - 1].m_Point == m_Points[next].m_Point &&
m_Points[next].m_CloseFigure) {
NewPath->AppendPoint(m_Points[i - 1].m_Point, FXPT_TYPE::MoveTo,
false);
NewPath->AppendPoint(m_Points[i].m_Point, FXPT_TYPE::LineTo, false);
*bThin = true;
}
}
} else if (point_type == FXPT_TYPE::BezierTo) {
i += 2;
continue;
}
}
size_t new_path_size = NewPath->GetPoints().size();
if (m_Points.size() > 3 && new_path_size > 0)
*bThin = true;
return new_path_size != 0;
}
bool CFX_PathData::IsRect() const {
if (m_Points.size() != 5 && m_Points.size() != 4)
return false;
if ((m_Points.size() == 5 && m_Points[0].m_Point != m_Points[4].m_Point) ||
m_Points[0].m_Point == m_Points[2].m_Point ||
m_Points[1].m_Point == m_Points[3].m_Point) {
return false;
}
// Note, both x,y have to not equal.
if (m_Points[0].m_Point.x != m_Points[3].m_Point.x &&
m_Points[0].m_Point.y != m_Points[3].m_Point.y) {
return false;
}
for (int i = 1; i < 4; i++) {
if (m_Points[i].m_Type != FXPT_TYPE::LineTo)
return false;
// Note, both x,y have to not equal.
if (m_Points[i].m_Point.x != m_Points[i - 1].m_Point.x &&
m_Points[i].m_Point.y != m_Points[i - 1].m_Point.y) {
return false;
}
}
return m_Points.size() == 5 || m_Points[3].m_CloseFigure;
}
bool CFX_PathData::IsRect(const CFX_Matrix* pMatrix,
CFX_FloatRect* pRect) const {
if (!pMatrix) {
if (!IsRect())
return false;
if (pRect) {
pRect->left = m_Points[0].m_Point.x;
pRect->right = m_Points[2].m_Point.x;
pRect->bottom = m_Points[0].m_Point.y;
pRect->top = m_Points[2].m_Point.y;
pRect->Normalize();
}
return true;
}
if (m_Points.size() != 5 && m_Points.size() != 4)
return false;
if ((m_Points.size() == 5 && m_Points[0].m_Point != m_Points[4].m_Point) ||
m_Points[1].m_Point == m_Points[3].m_Point) {
return false;
}
// Note, both x,y not equal.
if (m_Points.size() == 4 && m_Points[0].m_Point.x != m_Points[3].m_Point.x &&
m_Points[0].m_Point.y != m_Points[3].m_Point.y) {
return false;
}
CFX_PointF points[5];
for (size_t i = 0; i < m_Points.size(); i++) {
points[i] = pMatrix->Transform(m_Points[i].m_Point);
if (i == 0)
continue;
if (m_Points[i].m_Type != FXPT_TYPE::LineTo)
return false;
if (points[i].x != points[i - 1].x && points[i].y != points[i - 1].y)
return false;
}
if (pRect) {
pRect->left = points[0].x;
pRect->right = points[2].x;
pRect->bottom = points[0].y;
pRect->top = points[2].y;
pRect->Normalize();
}
return true;
}
CFX_RetainablePathData::CFX_RetainablePathData() = default;
// Note: can't default the copy constructor since Retainable<> has a deleted
// copy constructor (as it should). Instead, we want the default Retainable<>
// constructor to be invoked so as to create a copy with a ref-count of 1 as
// of the time it is created, then populate the remainder of the members from
// the |src| object.
CFX_RetainablePathData::CFX_RetainablePathData(
const CFX_RetainablePathData& src)
: CFX_PathData(src) {}
CFX_RetainablePathData::~CFX_RetainablePathData() = default;
| 32.013672 | 80 | 0.601245 | [
"object",
"transform"
] |
173d2b90baf3e9b1fbd298d031334c423812537f | 7,603 | cpp | C++ | henry-omp/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 58 | 2020-08-06T18:53:44.000Z | 2021-10-01T07:59:46.000Z | henry-omp/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 2 | 2020-12-04T12:35:02.000Z | 2021-03-04T22:49:25.000Z | henry-omp/main.cpp | BeauJoh/HeCBench | 594b845171d686dc951971ce36ed59cf114dd2b4 | [
"BSD-3-Clause"
] | 13 | 2020-08-19T13:44:18.000Z | 2021-09-08T04:25:34.000Z | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <map>
#include <string>
#include <fstream>
#include <sstream>
#include <omp.h>
#define NUMTHREADS 256 // number of threads per GPU block
// data for atom of crystal structure
// Unit cell of crystal structure can then be stored
// as pointer array of StructureAtom's
struct StructureAtom {
// Cartesian position, units: A
double x;
double y;
double z;
// Lennard-Jones epsilon parameter with adsorbate
double epsilon; // units: K
// Lennard-Jones sigma parameter with adsorbate
double sigma; // units: A
};
#pragma omp declare target
// temperature, Kelvin
const double T = 298.0;
// Universal gas constant, m3 - Pa / (K - mol)
const double R = 8.314;
// Generate a random number
double LCG_random_double(uint64_t * seed)
{
const uint64_t m = 9223372036854775808ULL; // 2^63
const uint64_t a = 2806196910506780709ULL;
const uint64_t c = 1ULL;
*seed = (a * (*seed) + c) % m;
return (double) (*seed) / (double) m;
}
// Compute the Boltzmann factor of methane at point (x, y, z) inside structure
// Loop over all atoms of unit cell of crystal structure
// Find nearest image to methane at point (x, y, z) for application of periodic boundary conditions
// Compute energy contribution due to this atom via the Lennard-Jones potential
double compute(double x, double y, double z,
const StructureAtom * __restrict__ structureAtoms,
double natoms, double L)
{
// (x, y, z) : Cartesian coords of methane molecule
// structureAtoms : pointer array storing info on unit cell of crystal structure
// natoms : number of atoms in crystal structure
// L : box length
// returns Boltzmann factor e^{-E/(RT)}
double E = 0.0; // energy (K)
// loop over atoms in crystal structure
for (int i = 0; i < natoms; i++) {
// Compute distance in each coordinate from (x, y, z) to this structure atom
double dx = x - structureAtoms[i].x;
double dy = y - structureAtoms[i].y;
double dz = z - structureAtoms[i].z;
// apply nearest image convention for periodic boundary conditions
const double boxupper = 0.5 * L;
const double boxlower = -boxupper;
dx = (dx > boxupper) ? dx-L : dx;
dx = (dx > boxupper) ? dx-L : dx;
dy = (dy > boxupper) ? dy-L : dy;
dy = (dy <= boxlower) ? dy-L : dy;
dz = (dz <= boxlower) ? dz-L : dz;
dz = (dz <= boxlower) ? dz-L : dz;
// compute inverse distance
double rinv = 1.0 / sqrt(dx*dx + dy*dy + dz*dz);
// Compute contribution to energy of adsorbate at (x, y, z) due to this atom
// Lennard-Jones potential (this is the efficient way to compute it)
double sig_ovr_r = rinv * structureAtoms[i].sigma;
double sig_ovr_r6 = pow(sig_ovr_r, 6.0);
double sig_ovr_r12 = sig_ovr_r6 * sig_ovr_r6;
E += 4.0 * structureAtoms[i].epsilon * (sig_ovr_r12 - sig_ovr_r6);
}
return exp(-E / (R * T)); // return Boltzmann factor
}
#pragma omp end declare target
int main(int argc, char *argv[]) {
// take in number of MC insertions as argument
if (argc != 3) {
printf("Usage: ./%s <material file> ninsertions\n", argv[0]);
exit(EXIT_FAILURE);
}
// Import unit cell of nanoporous material IRMOF-1
StructureAtom *structureAtoms; // store atoms in pointer array here
// open crystal structure file
std::ifstream materialfile(argv[1]);
if (materialfile.fail()) {
printf("Failed to import file %s.\n", argv[1]);
exit(EXIT_FAILURE);
}
const int ncycles = atoi(argv[2]); // Number of Monte Carlo insertions
// Energetic model for interactions of methane molecule with atoms of framework
// pairwise Lennard-Jones potentials
// Epsilon parameters for Lennard-Jones potential (K)
std::map<std::string, double> epsilons;
epsilons["Zn"] = 96.152688;
epsilons["O"] = 66.884614;
epsilons["C"] = 88.480032;
epsilons["H"] = 57.276566;
// Sigma parameters for Lennard-Jones potential (A)
std::map<std::string, double> sigmas;
sigmas["Zn"] = 3.095775;
sigmas["O"] = 3.424075;
sigmas["C"] = 3.580425;
sigmas["H"] = 3.150565;
// read cubic box dimensions
std::string line;
getline(materialfile, line);
std::istringstream istream(line);
double L; // dimension of cube
istream >> L;
printf("L = %f\n", L);
// waste line
getline(materialfile, line);
// get number of atoms of a material
getline(materialfile, line);
int natoms; // e.g. number of atoms in unit cell of IRMOF-1
istream.str(line);
istream.clear();
istream >> natoms;
printf("%d atoms\n", natoms);
// waste line
getline(materialfile, line);
// Allocate space for material atoms and epsilons/sigmas
structureAtoms = (StructureAtom *) malloc(natoms * sizeof(StructureAtom));
// read atom coordinates
for (int i = 0; i < natoms; i++) {
// read atoms from .cssr file
getline(materialfile, line);
istream.str(line);
istream.clear();
int atomno;
double xf, yf, zf; // fractional coordinates
std::string element;
istream >> atomno >> element >> xf >> yf >> zf;
// load structureAtoms with Cartesian coordinates of this atom
structureAtoms[i].x = L * xf;
structureAtoms[i].y = L * yf;
structureAtoms[i].z = L * zf;
// store epsilon and sigma Lennard-Jones parameters as well, for ease of computation on device
structureAtoms[i].epsilon = epsilons[element];
structureAtoms[i].sigma = sigmas[element];
}
// calculate number of MC insertions
const int nBlocks = 1024;
const int insertionsPerCycle = nBlocks * NUMTHREADS;
const int ninsertions = ncycles * insertionsPerCycle;
double * boltzmannFactors = (double*) malloc (insertionsPerCycle * sizeof(double));
#pragma omp target data map(to: structureAtoms[0:natoms]) \
map(alloc: boltzmannFactors[0:insertionsPerCycle])
{
// Compute the Henry coefficient
// KH = < e^{-E/(kB * T)} > / (R * T)
// Brackets denote average over space
double KH = 0.0; // will be Henry coefficient
for (int cycle = 0; cycle < ncycles; cycle++) {
// Inserts a methane molecule at a random position inside the structure
// Calls function to compute Boltzmann factor at this point
// Stores Boltzmann factor computed at this thread in boltzmannFactors
#pragma omp target teams distribute parallel for thread_limit(NUMTHREADS)
for (int id = 0; id < insertionsPerCycle; id++) {
// random seed for each thread
uint64_t seed = id;
// Generate random position inside the cubic unit cell of the structure
double x = L * LCG_random_double(&seed);
double y = L * LCG_random_double(&seed);
double z = L * LCG_random_double(&seed);
// Compute Boltzmann factor, store in boltzmannFactors
boltzmannFactors[id] = compute(x, y, z, structureAtoms, natoms, L);
}
#pragma omp target update from (boltzmannFactors[0:insertionsPerCycle])
// Compute Henry coefficient from the sampled Boltzmann factors
for(int i = 0; i < insertionsPerCycle; i++)
KH += boltzmannFactors[i];
}
// average Boltzmann factor: < e^{-E/(kB/T)} >
KH = KH / ninsertions;
KH = KH / (R * T); // divide by RT
printf("Used %d blocks with %d thread each\n", nBlocks, NUMTHREADS);
printf("Henry constant = %e mol/(m3 - Pa)\n", KH);
printf("Number of actual insertions: %d\n", ninsertions);
printf("Number of times we called the device kernel: %d\n", ncycles);
}
free(structureAtoms);
free(boltzmannFactors);
return EXIT_SUCCESS;
}
| 32.91342 | 101 | 0.660529 | [
"model"
] |
1741073a5c610f0402f970d823bb9cbdb92adedb | 5,533 | cc | C++ | python/jittor/src/memory_profiler.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 2,571 | 2020-03-20T03:38:35.000Z | 2022-03-31T08:20:05.000Z | python/jittor/src/memory_profiler.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 197 | 2020-03-20T04:11:47.000Z | 2022-03-31T10:14:24.000Z | python/jittor/src/memory_profiler.cc | Exusial/jittor | eca21d5bba5098bce4f492fa44908677b6e76588 | [
"Apache-2.0"
] | 284 | 2020-03-20T03:53:15.000Z | 2022-03-28T07:20:32.000Z | // ***************************************************************
// Copyright (c) 2021 Jittor. All Rights Reserved.
// Maintainers:
// Guoye Yang <498731903@qq.com>
// Dun Liang <randonlang@gmail.com>.
//
// This file is subject to the terms and conditions defined in
// file 'LICENSE.txt', which is part of this source code package.
// ***************************************************************
#include "memory_profiler.h"
#include "graph.h"
#include "var_holder.h"
#include "var.h"
#include "mem/allocator/sfrl_allocator.h"
#include <iomanip>
#include <algorithm>
#include <sstream>
#include "pybind/py_var_tracer.h"
namespace jittor {
//TODO reuse from mem_info.cc
struct FloatOutput_ {
double value;
string scale;
int base;
string suffix;
int p=4;
};
inline std::ostream& operator<<(std::ostream& os, const FloatOutput_& o) {
int w = 8;
os << std::setw(w-2-o.suffix.size());
os << std::setprecision(o.p);
uint i=0;
double k = o.value;
for (; i+1<o.scale.size(); i++) {
if (k<o.base) break;
k /= o.base;
}
os << k << o.scale[i];
return os << o.suffix;
}
MemoryProfiler memory_profiler;
DEFINE_FLAG(int, profile_memory_enable, 0, "Enable memory profiler.");
MemoryProfiler::MemoryProfiler() {
clear();
}
void MemoryProfiler::clear() {
allocations.clear();
max_memory_size = 0;
max_used_memory_size = 0;
}
std::pair<size_t, size_t> MemoryProfiler::get_memory_info() {
ASSERT(profile_memory_enable == 1);
size_t used = 0;
size_t unused = 0;
//TODO add mssfrl allocator
for (auto& a : SFRLAllocator::sfrl_allocators) {
used += a->used_memory;
unused += a->unused_memory;
}
return std::make_pair(used, unused);
}
void MemoryProfiler::check() {
ASSERT(profile_memory_enable == 1);
std::pair<size_t, size_t> mem_info = get_memory_info();
if (mem_info.first > max_used_memory_size) {
max_used_memory_size = mem_info.first;
allocations.clear();
size_t memory_size = 0;
std::vector<std::pair<std::pair<string, vector<Stack>>, size_t>> live_vars;
vector<Node*> queue;
auto t = ++Node::tflag_count;
for (auto& vh : hold_vars)
if (vh->var->tflag != t) {
vh->var->tflag = t;
queue.push_back(vh->var);
}
bfs_both(queue, [](Node*){return true;});
for (Node* node : queue) {
if (node->is_var()) {
Var* var = (Var*)node;
if (var->mem_ptr != nullptr) {
vector<Stack> stacks = get_node_trace(var);
if (stacks.size() == 0) {
stacks.push_back(Stack());
}
std::stringstream stream;
stream << var;
live_vars.push_back(std::make_pair(std::make_pair(stream.str(), stacks), var->size));
if (!allocations.count(var->mem_ptr)) {
allocations[var->mem_ptr] = 1;
memory_size += var->size;
}
}
}
}
max_live_vars = live_vars;
max_memory_size = memory_size;
}
}
bool MemoryProfiler::cmp(const std::pair<std::pair<string, vector<Stack>>, size_t>& a, const std::pair<std::pair<string, vector<Stack>>, size_t>& b) {
return a.second > b.second;
}
void MemoryProfiler::display_max_memory_info() {
ASSERT(profile_memory_enable == 1);
Log log("", 'i', 0);
std::sort(max_live_vars.begin(), max_live_vars.end(), cmp);
log << "\n=====display_max_memory_info=====\n";
log << "max used memory" << FloatOutput_{(double)max_used_memory_size, " KMG", 1024, "B"} << "\n";
log << "max var memory" << FloatOutput_{(double)max_memory_size, " KMG", 1024, "B"} << "\n\n";
log << "[Size]" << "[Percent]" << "[Var Info]" << "\n";
for (int i = 0; i < max_live_vars.size(); ++i) {
log << FloatOutput_{(double)max_live_vars[i].second, " KMG", 1024, "B"}
<< double(max_live_vars[i].second) / max_memory_size * 100 << "%"
<< max_live_vars[i].first.first
<< max_live_vars[i].first.second[0].file_path + ":" + std::to_string(max_live_vars[i].first.second[0].lineno)
<< "\n\n";
}
log << "=========================\n";
log.end();
}
void display_max_memory_info() {
ASSERT(profile_memory_enable == 1);
memory_profiler.display_max_memory_info();
}
string MemoryProfiler::get_max_memory_info() {
ASSERT(profile_memory_enable == 1);
std::stringstream out;
string div1 = "[!@#div1!@#]";
string div2 = "[!@#div2!@#]";
string div3 = "[!@#div3!@#]";
std::sort(max_live_vars.begin(), max_live_vars.end(), cmp);
out << max_memory_size;
for (int i = 0; i < max_live_vars.size(); ++i) {
out << div1;
out << max_live_vars[i].first.first << div2;
out << max_live_vars[i].second << div2;
for (int j = 0; j < max_live_vars[i].first.second.size(); ++j) {
out << max_live_vars[i].first.second[j].file_path + ":" + std::to_string(max_live_vars[i].first.second[j].lineno) << div3
<< max_live_vars[i].first.second[j].module_name << div3
<< max_live_vars[i].first.second[j].module_type << div2;
}
}
return out.str();
}
string get_max_memory_info() {
ASSERT(profile_memory_enable == 1);
return memory_profiler.get_max_memory_info();
}
} // jittor | 33.331325 | 150 | 0.563347 | [
"vector"
] |
17493a39cb5e15b7dc237122e1fdccd7fbdb37ce | 23,012 | cpp | C++ | src/unity/lib/unity_sarray_binary_operations.cpp | fossabot/turicreate | a500d5e52143ad15ebdf771d9f74198982c7c45c | [
"BSD-3-Clause"
] | 1 | 2019-04-16T19:51:18.000Z | 2019-04-16T19:51:18.000Z | src/unity/lib/unity_sarray_binary_operations.cpp | tashby/turicreate | 7f07ce795833d0c56c72b3a1fb9339bed6d178d1 | [
"BSD-3-Clause"
] | 3 | 2021-09-08T02:18:00.000Z | 2022-03-12T00:39:44.000Z | src/unity/lib/unity_sarray_binary_operations.cpp | tashby/turicreate | 7f07ce795833d0c56c72b3a1fb9339bed6d178d1 | [
"BSD-3-Clause"
] | 1 | 2020-10-21T17:46:28.000Z | 2020-10-21T17:46:28.000Z | /* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#include <string>
#include <cmath>
#include <functional>
#include <flexible_type/flexible_type.hpp>
#include <unity/lib/unity_sarray_binary_operations.hpp>
namespace turi {
namespace unity_sarray_binary_operations {
void check_operation_feasibility(flex_type_enum left,
flex_type_enum right,
std::string op) {
bool operation_is_feasible = false;
if (op == "+" || op == "-" || op == "*" || op == "/") {
if (left == flex_type_enum::DATETIME && right == flex_type_enum::DATETIME && op == "-") {
operation_is_feasible = true;
} else {
operation_is_feasible = flex_type_has_binary_op(left, right, op[0]) ||
((left == flex_type_enum::FLOAT
|| left == flex_type_enum::INTEGER
|| left == flex_type_enum::VECTOR)
&& (right == flex_type_enum::FLOAT
|| right == flex_type_enum::INTEGER
|| right == flex_type_enum::VECTOR));
}
} else if (op == "%") {
operation_is_feasible = left == flex_type_enum::INTEGER &&
right == flex_type_enum::INTEGER;
} else if (op == "**" || op == "//") {
operation_is_feasible = (
(left == flex_type_enum::FLOAT
|| left == flex_type_enum::INTEGER
|| left == flex_type_enum::VECTOR)
&& (right == flex_type_enum::FLOAT
|| right == flex_type_enum::INTEGER
|| right == flex_type_enum::VECTOR));
} else if (op == "<" || op == ">" || op == "<=" || op == ">=") {
// the comparison operators are all compatible. we just need to check
// the < operator
operation_is_feasible = flex_type_has_binary_op(left, right, '<');
} else if (op == "==" || op == "!=") {
// equality comparison is always feasible
operation_is_feasible = true;
} else if (op == "&" || op == "|") {
// boolean operations are always feasible
operation_is_feasible = true;
} else if (op == "in") {
// note that while the op is "in", the direction of the operator is
// [BIGGER_LIST "in" element] rather than ["element" in BIGGER_LIST]
// yes. slightly disconcerting I know. Sorry.
operation_is_feasible = (left == flex_type_enum::STRING && right == flex_type_enum::STRING) ||
(left == flex_type_enum::VECTOR && right == flex_type_enum::FLOAT) ||
(left == flex_type_enum::VECTOR && right == flex_type_enum::INTEGER) ||
(left == flex_type_enum::DICT) ||
(left == flex_type_enum::LIST);
} else if (op == "left_abs") {
// right part of the operator is ignored in this one
operation_is_feasible = (left == flex_type_enum::FLOAT
|| left == flex_type_enum::INTEGER
|| left == flex_type_enum::VECTOR);
} else {
log_and_throw("Invalid scalar operation");
}
if (!operation_is_feasible) {
throw std::string("Unsupported type operation. cannot perform operation ") +
op + " between " +
flex_type_enum_to_name(left) + " and " +
flex_type_enum_to_name(right);
}
}
flex_type_enum get_output_type(flex_type_enum left,
flex_type_enum right,
std::string op) {
if (op == "+" || op == "-" || op == "*") {
if (left == flex_type_enum::INTEGER && right == flex_type_enum::FLOAT) {
// operations against float always returns float
return flex_type_enum::FLOAT;
} else if (left == flex_type_enum::DATETIME && right == flex_type_enum::DATETIME && op == "-") {
return flex_type_enum::FLOAT;
} else if (left == flex_type_enum::VECTOR || right == flex_type_enum::VECTOR) {
// vector operations always return vector
return flex_type_enum::VECTOR;
} else {
// otherwise we take the type on the left hand side
return left;
}
} else if (op == "**") {
if (left == flex_type_enum::VECTOR || right == flex_type_enum::VECTOR) {
// vector operations always return vector
return flex_type_enum::VECTOR;
} else {
return flex_type_enum::FLOAT;
}
} else if (op == "//") {
if (left == flex_type_enum::VECTOR || right == flex_type_enum::VECTOR) {
// vector operations always return vector
return flex_type_enum::VECTOR;
} else if (left == flex_type_enum::FLOAT || right == flex_type_enum::FLOAT) {
return flex_type_enum::FLOAT;
} else {
return flex_type_enum::INTEGER;
}
} else if (op == "%") {
return flex_type_enum::INTEGER;
} else if (op == "/") {
if (left == flex_type_enum::VECTOR || right == flex_type_enum::VECTOR) {
// vector operations always return vector
return flex_type_enum::VECTOR;
} else {
return flex_type_enum::FLOAT;
}
} else if (op == "<" || op == ">" || op == "<=" ||
op == ">=" || op == "==" || op == "!=") {
// comparison always returns integer
return flex_type_enum::INTEGER;
} else if (op == "&" || op == "|") {
// boolean operations always returns integer
return flex_type_enum::INTEGER;
} else if (op == "in") {
return flex_type_enum::INTEGER;
} else if (op == "left_abs") {
return left;
} else {
throw std::string("Invalid Operation Type");
}
}
std::function<flexible_type(const flexible_type&, const flexible_type&)>
get_binary_operator(flex_type_enum left, flex_type_enum right, std::string op) {
/**************************************************************************/
/* */
/* Operator + */
/* */
/**************************************************************************/
if (op == "+") {
if (left == flex_type_enum::INTEGER && right == flex_type_enum::FLOAT) {
// integer + float is float
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
return (flex_float)l + (flex_float)r;
};
} else if (left == flex_type_enum::VECTOR && right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
if (l.size() != r.size()) return FLEX_UNDEFINED;
return l + r;
};
} else if (left == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{ return l + r; };
} else if (right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{ return r + l; };
} else {
// everything else, left hand side is good
// int + int -> int
// float + int -> float
// float + float -> float
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return l + r;};
}
/**************************************************************************/
/* */
/* Operator - */
/* */
/**************************************************************************/
} else if (op == "-") {
if (left == flex_type_enum::INTEGER && right == flex_type_enum::FLOAT) {
// integer - float is float
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
return (flex_float)l - (flex_float)r;
};
} else if (left == flex_type_enum::DATETIME && right == flex_type_enum::DATETIME) {
// integer - float is float
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
return l.get<flex_date_time>().microsecond_res_timestamp() -
r.get<flex_date_time>().microsecond_res_timestamp();
};
} else if (left == flex_type_enum::VECTOR && right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
if (l.size() != r.size()) return FLEX_UNDEFINED;
return l - r;
};
} else if (left == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{ return l - r; };
} else if (right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{ return -r + l; };
} else {
// everything else, left hand side is good
// int - int -> int
// float - int -> float
// float - float -> float
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return l - r;};
}
/**************************************************************************/
/* */
/* Operator * */
/* */
/**************************************************************************/
} else if (op == "*") {
if (left == flex_type_enum::INTEGER && right == flex_type_enum::FLOAT) {
// integer * float is float
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
return (flex_float)l * (flex_float)r;
};
} else if (left == flex_type_enum::VECTOR && right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
if (l.size() != r.size()) return FLEX_UNDEFINED;
return l * r;
};
} else if (left == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{ return l * r; };
} else if (right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{ return r * l; };
} else {
// everything else, left hand side is good
// int * int -> int
// float * int -> float
// float * float -> float
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return l * r;};
}
/**************************************************************************/
/* */
/* Operator / */
/* */
/**************************************************************************/
} else if (op == "/") {
if (left == flex_type_enum::VECTOR && right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
if (l.size() != r.size()) return FLEX_UNDEFINED;
return l / r;
};
} else if (left == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{ return l / r; };
} else if (right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
flexible_type ret = r;
for (size_t i = 0;i < ret.size(); ++i) ret[i] = l / ret[i];
return ret;
};
} else {
// divide always returns floats
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
return (flex_float)l / (flex_float)r;
};
}
/**************************************************************************/
/* */
/* Operator ** */
/* */
/**************************************************************************/
} else if (op == "**") {
if (left == flex_type_enum::VECTOR && right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
const flex_vec& lv = l.get<flex_vec>();
const flex_vec& rv = r.get<flex_vec>();
if (lv.size() != rv.size()) return FLEX_UNDEFINED;
flex_vec ret(lv.size());
for(size_t i = 0; i < lv.size(); ++i) {
ret[i] = std::pow(lv[i], rv[i]);
}
return flexible_type(std::move(ret));
};
} else if (left == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
const flex_vec& lv = l.get<flex_vec>();
flex_float rd = r.to<flex_float>();
flex_vec ret(lv.size());
for(size_t i = 0; i < lv.size(); ++i) {
ret[i] = std::pow(lv[i], rd);
}
return flexible_type(std::move(ret));
};
} else if (right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
flex_float ld = l.to<flex_float>();
const flex_vec& rv = r.get<flex_vec>();
flex_vec ret(rv.size());
for(size_t i = 0; i < rv.size(); ++i) {
ret[i] = std::pow(ld, rv[i]);
}
return flexible_type(std::move(ret));
};
} else {
// std::pow always returns floats
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
flex_float rd = (flex_float)r;
if (rd == 0.5) {
return std::sqrt((flex_float)l);
} else {
return std::pow((flex_float)l, (flex_float)r);
}
};
}
} else if (op == "//") {
if (left == flex_type_enum::VECTOR && right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
const flex_vec& lv = l.get<flex_vec>();
const flex_vec& rv = r.get<flex_vec>();
if (lv.size() != rv.size()) return FLEX_UNDEFINED;
flex_vec ret(lv.size());
for(size_t i = 0; i < lv.size(); ++i) {
flex_float res = lv[i] / rv[i];
ret[i] = std::isfinite(res) ? std::floor(res) : res;
}
return flexible_type(std::move(ret));
};
} else if (left == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
const flex_vec& lv = l.get<flex_vec>();
flex_float rd = r.to<flex_float>();
flex_vec ret(lv.size());
for(size_t i = 0; i < lv.size(); ++i) {
flex_float res = lv[i] / rd;
ret[i] = std::isfinite(res) ? std::floor(res) : res;
}
return flexible_type(std::move(ret));
};
} else if (right == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
flex_float ld = l.to<flex_float>();
const flex_vec& rv = r.get<flex_vec>();
flex_vec ret(rv.size());
for(size_t i = 0; i < rv.size(); ++i) {
flex_float res = ld / rv[i];
ret[i] = std::isfinite(res) ? std::floor(res) : res;
}
return flexible_type(std::move(ret));
};
} else if (right == flex_type_enum::FLOAT || left == flex_type_enum::FLOAT) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type {
flex_float ld = l.to<flex_float>();
flex_float rd = r.to<flex_float>();
flex_float res = ld / rd;
return std::isfinite(res) ? std::floor(res) : res;
};
} else {
return [](const flexible_type& l, const flexible_type& r)->flexible_type {
flex_float ld = l.to<flex_float>();
flex_float rd = r.to<flex_float>();
flex_float res = ld / rd;
return (std::isfinite(res)
? flexible_type(flex_int(std::floor(res)))
: FLEX_UNDEFINED);
};
}
/**************************************************************************/
/* */
/* Operator % */
/* */
/**************************************************************************/
} else if (op == "%") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type {
if (l.get_type() == flex_type_enum::INTEGER &&
r.get_type() == flex_type_enum::INTEGER) {
flex_int rightval = r.get<flex_int>();
flex_int leftval = l.get<flex_int>();
/*
* desired result
* 1 % 3 == 1
* -1 % 3 == 2
* 1 % -3 == -2
* -1 % -3 == -1
*/
if (rightval > 0) {
// Result of remainder operator is implementation dependent. It
// could be negative or positive. We lock it to positive.
// That makes more sense.
auto res = leftval % rightval;
if (res < 0) res += rightval;
return res;
} else if (rightval < 0) {
// if the rightval is negative that is also implementation
// dependent. We lock it to negative. This matches Python's
// definition
auto res = leftval % (-rightval);
if (res > 0) res += rightval; // remember rightval is negative here
return res;
} else {
return FLEX_UNDEFINED;
}
} else {
return 0;
}
};
/**************************************************************************/
/* */
/* Operator in */
/* */
/**************************************************************************/
} else if (op == "in") {
// note that while the op is "in", the direction of the operator is
// [BIGGER_LIST "in" element] rather than ["element" in BIGGER_LIST]
// yes. slightly disconcerting I know. Sorry.
if (left == flex_type_enum::STRING && right == flex_type_enum::STRING) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type {
if (l.get_type() == flex_type_enum::STRING &&
r.get_type() == flex_type_enum::STRING ) {
const auto& left_str = l.get<flex_string>();
const auto& right_str = r.get<flex_string>();
return left_str.find(right_str) != std::string::npos;
} else {
return 0;
}
};
} else if (left == flex_type_enum::VECTOR &&
(right == flex_type_enum::FLOAT || right == flex_type_enum::INTEGER)) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type {
if (l.get_type() == flex_type_enum::VECTOR &&
(r.get_type() == flex_type_enum::FLOAT || r.get_type() == flex_type_enum::INTEGER)) {
const auto& vec = l.get<flex_vec>();
const auto val = (flex_float)r;
int ret = (std::find(vec.begin(), vec.end(), val) != vec.end());
return ret;
} else {
return 0;
}
};
} else if (left == flex_type_enum::LIST) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type {
if (l.get_type() == flex_type_enum::LIST) {
const auto& vec = l.get<flex_list>();
int ret = std::find(vec.begin(), vec.end(), r) != vec.end();
return ret;
} else {
return 0;
}
};
} else if (left == flex_type_enum::DICT) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type {
if (l.get_type() == flex_type_enum::DICT) {
const auto& dict = l.get<flex_dict>();
for (const auto& elem: dict) {
if (elem.first == r) return 1;
}
return 0;
} else {
return 0;
}
};
}
/**************************************************************************/
/* */
/* abs of the left value */
/* */
/**************************************************************************/
} else if (op == "left_abs") {
// ** always returns floats
if(left == flex_type_enum::VECTOR) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
const flex_vec& v = l.get<flex_vec>();
flex_vec ret(v.size());
for(size_t i = 0; i < v.size(); ++i) {
ret[i] = std::abs(v[i]);
}
return flexible_type(std::move(ret));
};
} else if(left == flex_type_enum::INTEGER) {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
return std::abs(l.get<flex_int>());
};
} else {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{
return std::abs(l.to<flex_float>());
};
}
/**************************************************************************/
/* */
/* Comparison Operators */
/* */
/**************************************************************************/
} else if (op == "<") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return (int)(l < r);};
} else if (op == ">") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return (int)(l > r);};
} else if (op == "<=") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return (int)(l <= r);};
} else if (op == ">=") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return (int)(l >= r);};
} else if (op == "==") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return (int)(l == r);};
} else if (op == "!=") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return (int)(l != r);};
} else if (op == "&") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return (int)((!l.is_zero()) && (!r.is_zero()));};
} else if (op == "|") {
return [](const flexible_type& l, const flexible_type& r)->flexible_type{return (int)((!l.is_zero()) || (!r.is_zero()));};
} else {
throw std::string("Invalid Operation Type");
}
}
} // namespace unity_sarray_binary_operations
} // namespace turi
| 45.38856 | 127 | 0.484399 | [
"vector"
] |
1753735a06e935050d2ff2170d66d42bb9d21c62 | 790 | cc | C++ | basic/vector/01_find.cc | chanchann/littleMickle | f3a839d8ad55f483bbac4e4224dcd35234c5aa00 | [
"MIT"
] | 1 | 2021-03-16T02:13:12.000Z | 2021-03-16T02:13:12.000Z | basic/vector/01_find.cc | chanchann/littleMickle | f3a839d8ad55f483bbac4e4224dcd35234c5aa00 | [
"MIT"
] | null | null | null | basic/vector/01_find.cc | chanchann/littleMickle | f3a839d8ad55f483bbac4e4224dcd35234c5aa00 | [
"MIT"
] | null | null | null | /*
https://thispointer.com/c-how-to-find-an-element-in-vector-and-get-its-index/
Finding an element in vector using STL Algorithm std::find()
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <cassert>
int main() {
std::vector<int> vecOfNums = { 12, 45, 54, 33, 2, 7, 8, 22, 43, 19 };
// Check if element 22 exists in vector
std::vector<int>::iterator it = std::find(vecOfNums.begin(), vecOfNums.end(), 22);
if (it != vecOfNums.end())
std::cout << "Element Found" << std::endl;
else
std::cout << "Element Not Found" << std::endl;
// Get index of element from iterator
int index = std::distance(vecOfNums.begin(), it);
std::cout << "index is " << index << std::endl;
assert(vecOfNums[index] == 22);
return 0;
}
| 30.384615 | 86 | 0.622785 | [
"vector"
] |
17542b31bba40b46fe0aaefb5c12d3f6c8388e09 | 687 | cpp | C++ | Cogs/src/GLCubemapTexture.cpp | VasilStamatov/cogs2017 | 4efe9af48a6233936192f9db3d893bcb6564debb | [
"MIT"
] | null | null | null | Cogs/src/GLCubemapTexture.cpp | VasilStamatov/cogs2017 | 4efe9af48a6233936192f9db3d893bcb6564debb | [
"MIT"
] | null | null | null | Cogs/src/GLCubemapTexture.cpp | VasilStamatov/cogs2017 | 4efe9af48a6233936192f9db3d893bcb6564debb | [
"MIT"
] | null | null | null | #include "../include/GLCubemapTexture.h"
#include "../include/ResourceLoader.h"
#include <GL\glew.h>
namespace cogs
{
GLCubemapTexture::GLCubemapTexture(const std::vector<std::string>& _fileNames)
{
m_fileNames = _fileNames;
if (!ResourceLoader::loadSOIL2Cubemap(m_fileNames, &m_id))
{
throw std::runtime_error("Texture failed to load");
}
}
GLCubemapTexture::~GLCubemapTexture()
{
if (m_id != 0)
{
glDeleteTextures(1, &m_id);
m_id = 0;
}
}
void GLCubemapTexture::bind() const
{
glBindTexture(GL_TEXTURE_CUBE_MAP, m_id);
}
void GLCubemapTexture::unbind() const
{
glBindTexture(GL_TEXTURE_CUBE_MAP, 0);
}
} | 20.205882 | 80 | 0.660844 | [
"vector"
] |
1757b588d7b872b2b04f65d8002ff732bcc88b25 | 6,174 | hpp | C++ | unparser.hpp | Apache-HB/argo | 88152d81aa07f4df2e6eac38572fcaff34f33d92 | [
"MIT"
] | 2 | 2018-08-30T19:07:18.000Z | 2018-11-05T08:39:40.000Z | unparser.hpp | andrewhaisley/argonaut | 9d34c6716681e1c3fe868b0e7dcbd30610e2bee2 | [
"MIT"
] | null | null | null | unparser.hpp | andrewhaisley/argonaut | 9d34c6716681e1c3fe868b0e7dcbd30610e2bee2 | [
"MIT"
] | 2 | 2018-12-11T02:09:42.000Z | 2019-10-21T04:33:22.000Z | #ifndef _json_unparser_hpp_
#define _json_unparser_hpp_
/*
* Copyright (c) 2017 Andrew Haisley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/// \file unparser.hpp The unparser class.
#include <ostream>
#include "common.hpp"
#include "json.hpp"
#include "writer.hpp"
namespace NAMESPACE
{
/**
* Write the JSON object to a stream. All output will be on one line.
* See below for more options.
*/
std::ostream &operator<<(std::ostream &stream, const json &e);
/**
* Write the JSON object to a string. All output will be on one line.
* See below for more options.
*/
void operator<<(std::string &s, const json &e);
/**
* \brief Class to unparse json instances into JSON messages.
*
* Class to unparse json instances into JSON messages. Various convenience
* methods are supplied for different IO models.
*/
class unparser
{
public:
/**
* Unparse a json instance to an ostream.
* \param o The ostream to write to.
* \param j The json instance to write.
* \param space What to print for the spacing around ":" and after ",".
* \param newline What to print for a newline after name/value pairs and array items.
* \param indent What to print for indents after a newline.
* \param indent_inc How much to increment by when indenting a new object or array.
* 1 == one indent string parameter value.
* \throw json_io_exception Thrown in the case of a IO error whilst writing.
*/
static void unparse(
std::ostream &o,
const json &j,
const char *space = " ",
const char *newline = "",
const char *indent = " ",
int indent_inc = 0);
#ifndef _ARGO_WINDOWS_
/**
* Unparse a json instance to a POSIX file descriptor. See documentation
* for unparse to stream for other parameter details.
* \throw json_io_exception Thrown in the case of a IO error whilst writing.
*/
static void unparse(
int fd,
const json &j,
const char *space = " ",
const char *newline = "",
const char *indent = " ",
int indent_inc = 0);
#endif
/**
* Unparse a json instance to a stdio FILE. See documentation
* for unparse to stream for other parameter details.
* \throw json_io_exception Thrown in the case of a IO error whilst writing.
*/
static void unparse(
FILE *s,
const json &j,
const char *space = " ",
const char *newline = "",
const char *indent = " ",
int indent_inc = 0);
/**
* Convenience method. Create a new file, write a single JSON
* message to it and then close it. See documentation for unparse
* to stream for other parameter details.
* \throw json_io_exception Thrown in the case of a IO error whilst writing.
*/
static void save(
const json &j,
const std::string &file_name,
const char *space = " ",
const char *newline = "",
const char *indent = " ",
int indent_inc = 0);
/**
* Construct a new unparser given a writer instance.
* \param w The writer to use for output.
* \param space What to print for the spacing around ":" and after ",".
* \param newline What to print for a newline after name/value pairs and array items.
* \param indent What to print for indents after a newline.
* \param indent_inc How much to increment by when indenting a new object or array.
* 1 == one indent string parameter value.
* \throw json_io_exception Thrown in the case of a IO error whilst writing.
*/
unparser(writer &w,
const char *space = " ",
const char *newline = "",
const char *indent = " ",
int indent_inc = 0);
/**
* Unparse a single json instance.
* \param j The json instance to output.
* \param indent_level The indent level to start at (usually 0).
* \throw json_io_exception Thrown in the case of a IO error whilst writing.
*/
void unparse(const json &j, int indent_level = 0);
private:
void print_indent(int indent_level);
void unparse_object(const json &j, int indent_level);
void unparse_array(const json &j, int indent_level);
writer &m_writer;
const char *m_space;
const char *m_newline;
const char *m_indent;
int m_indent_inc;
};
}
#endif
| 38.347826 | 99 | 0.578879 | [
"object"
] |
17589c968e06c7fc0f96104f18e500686024fb21 | 623 | hpp | C++ | imp_cu_correspondence/include/imp/cu_correspondence/stereo_solver_enum.hpp | mwerlberger/imp | 2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85 | [
"MIT"
] | 8 | 2015-10-24T18:31:58.000Z | 2019-10-16T03:27:27.000Z | imp_cu_correspondence/include/imp/cu_correspondence/stereo_solver_enum.hpp | henrywen2011/imp | 2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85 | [
"MIT"
] | 7 | 2015-06-22T09:36:32.000Z | 2015-08-20T06:56:10.000Z | imp_cu_correspondence/include/imp/cu_correspondence/stereo_solver_enum.hpp | henrywen2011/imp | 2a2e4d31fa59ca1c32ae7f415306b39e31fc1e85 | [
"MIT"
] | 3 | 2015-05-13T14:46:48.000Z | 2017-01-11T09:20:03.000Z | #ifndef STEREO_SOLVER_ENUM_HPP
#define STEREO_SOLVER_ENUM_HPP
namespace imp {
namespace cu {
enum class StereoPDSolver
{
HuberL1, //!< Huber regularization + pointwise L1 intensity matching costs
PrecondHuberL1, //!< Huber regularization + pointwise L1 intensity matching costs
PrecondHuberL1Weighted, //!< weighted Huber regularization + pointwise L1 intensity matching costs
EpipolarPrecondHuberL1 //!< Huber regularization + pointwise L1 intensity matching costs applied on generic images with known epipolar geometry (not rectified)
};
} // namespace cu
} // namespace imp
#endif // STEREO_SOLVER_ENUM_HPP
| 31.15 | 161 | 0.789727 | [
"geometry"
] |
1759408e6f83e4f5d46e4f4b9c4875190166b171 | 1,081 | cpp | C++ | C++/problems/0154_minimum_falling_path_sum.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 6 | 2019-03-20T22:23:26.000Z | 2020-08-28T03:10:27.000Z | C++/problems/0154_minimum_falling_path_sum.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 15 | 2019-10-13T20:53:53.000Z | 2022-03-31T02:01:35.000Z | C++/problems/0154_minimum_falling_path_sum.cpp | oxone-999/algorithms | 52dc527111e7422923a0e25684d8f4837e81a09b | [
"MIT"
] | 3 | 2019-03-11T10:57:46.000Z | 2020-02-26T21:13:21.000Z | // Problem Statement
// Given a square array of integers A, we want the minimum sum of a falling path through A.
// A falling path starts at any element in the first row, and chooses one element from each row.
// The next row's choice must be in a column that is different from the previous row's column by at most one.
#include "0154_minimum_falling_path_sum.hpp"
#include <bits/stdc++.h>
using namespace std;
int Solution::minFallingPathSum(vector<vector<int>>& A){
vector<vector<int>> dp(A.size(),vector<int>(A[0]));
int result = INT_MAX;
for(int j=0;j<A[0].size();j++){
dp[0][j] = A[0][j];
}
for(int row = 1;row<A.size();row++){
for(int col=0;col<A[0].size();col++){
int curr_best = dp[row-1][col];
if(col>0) curr_best = min(curr_best,dp[row-1][col-1]);
if(col<A[0].size()-1) curr_best = min(curr_best,dp[row-1][col+1]);
dp[row][col] = A[row][col]+curr_best;
}
}
for(auto val : dp.back()){
result = min(result,val);
}
return result;
}
| 31.794118 | 109 | 0.595745 | [
"vector"
] |
175d438f04fb5b9408fba6e33e985f27a24336f7 | 7,619 | cpp | C++ | apps/scn2grd/scn2grd.cpp | kylegenova/trajectories | a7b021a62d699175a4cdfc2ea190c807e78e84f4 | [
"MIT"
] | null | null | null | apps/scn2grd/scn2grd.cpp | kylegenova/trajectories | a7b021a62d699175a4cdfc2ea190c807e78e84f4 | [
"MIT"
] | null | null | null | apps/scn2grd/scn2grd.cpp | kylegenova/trajectories | a7b021a62d699175a4cdfc2ea190c807e78e84f4 | [
"MIT"
] | null | null | null | // Source file for the scene converter program
// Include files
#include "R3Graphics/R3Graphics.h"
// Program arguments
static const char *input_scene_filename = NULL;
static const char *output_grid_filename = NULL;
static const char *selected_node_name = NULL;
static double grid_spacing = 0.01;
static double grid_boundary_radius = 0.05;
static int grid_min_resolution = 8;
static int grid_max_resolution = 512;
static int print_verbose = 0;
////////////////////////////////////////////////////////////////////////
// I/O STUFF
////////////////////////////////////////////////////////////////////////
static R3Scene *
ReadScene(const char *filename)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Allocate scene
R3Scene *scene = new R3Scene();
if (!scene) {
fprintf(stderr, "Unable to allocate scene for %s\n", filename);
return NULL;
}
// Read scene from file
if (!scene->ReadFile(filename)) {
delete scene;
return NULL;
}
// Print statistics
if (print_verbose) {
printf("Read scene from %s ...\n", filename);
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" # Nodes = %d\n", scene->NNodes());
fflush(stdout);
}
// Return scene
return scene;
}
static int
WriteGrid(R3Grid *grid, const char *filename)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Write grid
if (!grid->WriteFile(filename)) return 0;
// Print statistics
if (print_verbose) {
printf("Wrote grid to %s ...\n", filename);
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" Resolution = %d %d %d\n", grid->XResolution(), grid->YResolution(), grid->ZResolution());
printf(" Spacing = %g\n", grid->GridToWorldScaleFactor());
printf(" Cardinality = %d\n", grid->Cardinality());
RNInterval grid_range = grid->Range();
printf(" Minimum = %g\n", grid_range.Min());
printf(" Maximum = %g\n", grid_range.Max());
printf(" L1Norm = %g\n", grid->L1Norm());
printf(" L2Norm = %g\n", grid->L2Norm());
fflush(stdout);
}
// Return success
return 1;
}
////////////////////////////////////////////////////////////////////////
// GRID CREATION FUNCTIONS
////////////////////////////////////////////////////////////////////////
static void
RasterizeTriangles(R3Grid *grid, R3Scene *scene, R3SceneNode *node, const R3Affine& parent_transformation)
{
// Update transformation
R3Affine transformation = R3identity_affine;
transformation.Transform(parent_transformation);
transformation.Transform(node->Transformation());
// Rasterize triangles
for (int i = 0; i < node->NElements(); i++) {
R3SceneElement *element = node->Element(i);
for (int j = 0; j < element->NShapes(); j++) {
R3Shape *shape = element->Shape(j);
if (shape->ClassID() == R3TriangleArray::CLASS_ID()) {
R3TriangleArray *triangles = (R3TriangleArray *) shape;
for (int k = 0; k < triangles->NTriangles(); k++) {
R3Triangle *triangle = triangles->Triangle(k);
R3TriangleVertex *v0 = triangle->V0();
R3TriangleVertex *v1 = triangle->V1();
R3TriangleVertex *v2 = triangle->V2();
R3Point p0 = v0->Position();
R3Point p1 = v1->Position();
R3Point p2 = v2->Position();
p0.Transform(transformation);
p1.Transform(transformation);
p2.Transform(transformation);
grid->RasterizeWorldTriangle(p0, p1, p2, 1.0);
}
}
}
}
// Rasterize references
for (int i = 0; i < node->NReferences(); i++) {
R3SceneReference *reference = node->Reference(i);
R3Scene *referenced_scene = reference->ReferencedScene();
RasterizeTriangles(grid, referenced_scene, referenced_scene->Root(), transformation);
}
// Rasterize children
for (int i = 0; i < node->NChildren(); i++) {
R3SceneNode *child = node->Child(i);
RasterizeTriangles(grid, scene, child, transformation);
}
}
static R3Grid *
CreateGrid(R3Scene *scene, R3SceneNode *node)
{
// Start statistics
RNTime start_time;
start_time.Read();
// Get bounding box
R3Box bbox = node->WorldBBox();
if (grid_boundary_radius > 0) {
bbox[0] -= R3Vector(grid_boundary_radius, grid_boundary_radius, grid_boundary_radius);
bbox[1] += R3Vector(grid_boundary_radius, grid_boundary_radius, grid_boundary_radius);
}
// Allocate grid
R3Grid *grid = new R3Grid(bbox, grid_spacing, grid_min_resolution, grid_max_resolution);
if (!grid) {
fprintf(stderr, "Unable to allocate grid\n");
return NULL;
}
// Rasterize scene into grid
RasterizeTriangles(grid, scene, node, node->CumulativeParentTransformation());
// Threshold grid (to compensate for possible double rasterization)
grid->Threshold(0.5, 0.0, 1.0);
// Print statistics
if (print_verbose) {
printf("Rasterized grid ...\n");
printf(" Time = %.2f seconds\n", start_time.Elapsed());
printf(" Resolution = %d %d %d\n", grid->XResolution(), grid->YResolution(), grid->ZResolution());
printf(" Spacing = %g\n", grid->GridToWorldScaleFactor());
printf(" Cardinality = %d\n", grid->Cardinality());
RNInterval grid_range = grid->Range();
printf(" Minimum = %g\n", grid_range.Min());
printf(" Maximum = %g\n", grid_range.Max());
printf(" L1Norm = %g\n", grid->L1Norm());
printf(" L2Norm = %g\n", grid->L2Norm());
fflush(stdout);
}
// Return grid
return grid;
}
////////////////////////////////////////////////////////////////////////
// PROGRAM ARGUMENT PARSING
////////////////////////////////////////////////////////////////////////
static int
ParseArgs(int argc, char **argv)
{
// Parse arguments
argc--; argv++;
while (argc > 0) {
if ((*argv)[0] == '-') {
if (!strcmp(*argv, "-v")) print_verbose = 1;
else if (!strcmp(*argv, "-node")) { argc--; argv++; selected_node_name = *argv; }
else if (!strcmp(*argv, "-spacing")) { argc--; argv++; grid_spacing = atof(*argv); }
else if (!strcmp(*argv, "-boundary_radius")) { argc--; argv++; grid_boundary_radius = atof(*argv); }
else if (!strcmp(*argv, "-max_resolution")) { argc--; argv++; grid_max_resolution = atoi(*argv); }
else { fprintf(stderr, "Invalid program argument: %s", *argv); exit(1); }
argv++; argc--;
}
else {
if (!input_scene_filename) input_scene_filename = *argv;
else if (!output_grid_filename) output_grid_filename = *argv;
else { fprintf(stderr, "Invalid program argument: %s", *argv); exit(1); }
argv++; argc--;
}
}
// Check input filename
if (!input_scene_filename || !output_grid_filename) {
fprintf(stderr, "Usage: scn2grd inputscenefile outputgridfile [options]\n");
return 0;
}
// Return OK status
return 1;
}
////////////////////////////////////////////////////////////////////////
// MAIN
////////////////////////////////////////////////////////////////////////
int main(int argc, char **argv)
{
// Check number of arguments
if (!ParseArgs(argc, argv)) exit(1);
// Read scene
R3Scene *scene = ReadScene(input_scene_filename);
if (!scene) exit(-1);
// Get root node
R3SceneNode *node = scene->Root();
if (selected_node_name) {
node = scene->Node(selected_node_name);
if (!node) {
fprintf(stderr, "Unable to find selected node %s\n", selected_node_name);
exit(-1);
}
}
// Create grid
R3Grid *grid = CreateGrid(scene, node);
if (!grid) exit(-1);
// Write grid
if (!WriteGrid(grid, output_grid_filename)) exit(-1);
// Return success
return 0;
}
| 28.750943 | 106 | 0.589972 | [
"shape",
"transform"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.