hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
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
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
5816ac5f04c4dae0066ee5aa724582191cca8758
1,809
cc
C++
cpp/src/array/maxNumberOfFamilies.cc
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
1
2019-10-17T08:34:55.000Z
2019-10-17T08:34:55.000Z
cpp/src/array/maxNumberOfFamilies.cc
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
1
2020-05-24T08:32:13.000Z
2020-05-24T08:32:13.000Z
cpp/src/array/maxNumberOfFamilies.cc
dacozai/algorithm-diary
8ed5e119e4450e92e63276047ef19bbf422c2770
[ "MIT" ]
null
null
null
#include "test.h" #include <unordered_map> /** Question no 1386 medium Cinema Seat Allocation * Author : Li-Han, Chen; 陳立瀚 * Date : 22th, March, 2020 * Source : https://leetcode.com/problems/cinema-seat-allocation/ * * A cinema has n rows of seats, numbered from 1 to n and there are ten seats in each row, labelled from 1 to 10 as shown in the figure above. * * Given the array reservedSeats containing the numbers of seats already reserved, * for example, reservedSeats[i]=[3,8] means the seat located in row 3 and labelled with 8 is already reserved. * * Return the maximum number of four-person families you can allocate on the cinema seats. * A four-person family occupies fours seats in one row, that are next to each other. * Seats across an aisle (such as [3,3] and [3,4]) are not considered to be next to each other, however, * It is permissible for the four-person family to be separated by an aisle, but in that case, * exactly two people have to sit on each side of the aisle. * */ /** Solution * Runtime 36 ms MeMory 8 MB; * faster than 65.36%, less than 100.00% * O(n) ; O(n) */ int maxNumberOfFamilies(int n, std::vector<std::vector<int>>& reservedSeats) { std::unordered_map<int, int> mp; int ans=2*n; for (auto seat: reservedSeats) { int row = seat[0], col = seat[1], bny; if (mp.find(row) == mp.end()) mp[row] = 7; int bf = mp[row]; if (col == 4 || col == 5) mp[row]%=2; else if (col == 6 || col == 7) { mp[row]>>=2; mp[row]<<=2; } else if ((col == 2 || col == 3) && mp[row]>3) mp[row]%=4; else if (col == 8 || col == 9) { mp[row]>>=1; mp[row]<<=1; } else continue; if (bf-mp[row] == 0) continue; else if (bf==7) ans--; else if (mp[row]==0) ans--; } return ans; }
34.788462
142
0.625207
dacozai
581bf2d3dbdd0b787a8b7c261d45686e1a88caf5
21,350
cpp
C++
Source/Physics/Joint.cpp
JesseMader/PlasmaEngine
ffda8f76b96e83181cfc1f9ec102c4ad0d7fd131
[ "MIT" ]
null
null
null
Source/Physics/Joint.cpp
JesseMader/PlasmaEngine
ffda8f76b96e83181cfc1f9ec102c4ad0d7fd131
[ "MIT" ]
null
null
null
Source/Physics/Joint.cpp
JesseMader/PlasmaEngine
ffda8f76b96e83181cfc1f9ec102c4ad0d7fd131
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #include "Precompiled.hpp" namespace Plasma { namespace Tags { DefineTag(Joint); } LightningDefineType(Joint, builder, type) { PlasmaBindDocumented(); PlasmaBindDependency(Cog); PlasmaBindDependency(ObjectLink); PlasmaBindSetup(SetupMode::DefaultSerialization); LightningBindGetterSetterProperty(Active); LightningBindGetterSetterProperty(SendsEvents); LightningBindGetterSetterProperty(AutoSnaps); LightningBindGetterSetterProperty(CollideConnected); LightningBindGetterSetterProperty(MaxImpulse); LightningBindMethod(GetOtherObject); LightningBindMethod(GetCog); PlasmaBindEvent(Events::JointExceedImpulseLimit, JointEvent); PlasmaBindTag(Tags::Physics); PlasmaBindTag(Tags::Joint); } Joint::Joint() { mSolver = nullptr; mNode = new JointNode(); mNode->mJoint = this; mFlags.Clear(); } Joint::~Joint() { delete mNode; } void Joint::Serialize(Serializer& stream) { uint mask = JointFlags::OnIsland | JointFlags::Ghost | JointFlags::Valid | JointFlags::Initialized; SerializeBits(stream, mFlags, JointFlags::Names, mask, JointFlags::CollideConnected | JointFlags::Active | JointFlags::SendsEvents); real MaxImpulse; if (stream.GetMode() == SerializerMode::Loading) { SerializeNameDefault(MaxImpulse, Math::PositiveMax()); SetMaxImpulse(MaxImpulse); } else { MaxImpulse = GetMaxImpulse(); SerializeNameDefault(MaxImpulse, Math::PositiveMax()); } } void Joint::Initialize(CogInitializer& initializer) { Space* space = initializer.GetSpace(); mSpace = space->has(PhysicsSpace); ErrorIf(!mSpace, "Joint's space was invalid."); } void Joint::OnAllObjectsCreated(CogInitializer& initializer) { // Only do initialization once (can be called again from pulley or gear joint) if (mFlags.IsSet(JointFlags::Initialized) == true) return; mFlags.SetFlag(JointFlags::Initialized); ConnectThisTo(GetOwner(), Events::ObjectLinkChanged, OnObjectLinkChanged); ConnectThisTo(GetOwner(), Events::ObjectLinkPointChanged, OnObjectLinkPointChanged); // Always add to the space. This makes it easier to deal with partially // invalid joints being destroyed (and the space list is only there for easy // iteration of joints) mSpace->AddComponent(this); // Link up the collider edges to the object link's data. LinkPair(); // Also wake up the objects we're connected to so that newly created joints // will work properly. // @JoshD: Should this only happen when during not object startup so that // saved asleep objects stay asleep? Physics::JointHelpers::ForceAwakeJoint(this); // We were dynamically created so try to compute some logical initial values bool dynamicallyCreated = (initializer.Flags & CreationFlags::DynamicallyAdded) != 0; if (dynamicallyCreated) ComputeInitialConfiguration(); } void Joint::OnDestroy(uint flags) { // Always remove from the space, even if we weren't valid (because we're // always added) mSpace->RemoveComponent(this); // If we were in a partially or completely invalid state then one of our // colliders doesn't exist. If one of them was valid we could wake it up, but // there's not really a point as this joint wasn't doing anything. Since it // wasn't doing anything removing the joint shouldn't cause any change to the // dynamics of a body and therefore waking it up isn't necessary. Same if we // weren't active. if (GetValid() && GetActive()) { mEdges[0].mCollider->ForceAwake(); mEdges[1].mCollider->ForceAwake(); } // Unlink from the colliders we were connected to. This also marks the joint // as not valid just in case any other calls happen that would rely on being // connected. UnLinkPair(); } void Joint::ComponentAdded(BoundType* typeId, Component* component) { if (typeId == LightningTypeId(JointLimit)) { JointLimit* limit = static_cast<JointLimit*>(component); limit->mAtomIds = GetDefaultLimitIds(); Physics::JointHelpers::ForceAwakeJoint(this); } else if (typeId == LightningTypeId(JointMotor)) { JointMotor* motor = static_cast<JointMotor*>(component); motor->mAtomIds = GetDefaultMotorIds(); Physics::JointHelpers::ForceAwakeJoint(this); } else if (typeId == LightningTypeId(JointSpring)) { JointSpring* spring = static_cast<JointSpring*>(component); spring->mAtomIds = GetDefaultSpringIds(); Physics::JointHelpers::ForceAwakeJoint(this); } } void Joint::ComponentRemoved(BoundType* typeId, Component* component) { if (typeId == LightningTypeId(JointLimit)) Physics::JointHelpers::ForceAwakeJoint(this); else if (typeId == LightningTypeId(JointMotor)) Physics::JointHelpers::ForceAwakeJoint(this); else if (typeId == LightningTypeId(JointSpring)) Physics::JointHelpers::ForceAwakeJoint(this); } uint Joint::GetAtomIndexFilterVirtual(uint atomIndex, real& desiredConstraintValue) const { desiredConstraintValue = 0; return 0; } void Joint::SetPair(Physics::ColliderPair& pair) { mEdges[0].mCollider = pair.mObjects[0]; mEdges[0].mOther = pair.mObjects[1]; mEdges[0].mJoint = this; mEdges[1].mCollider = pair.mObjects[1]; mEdges[1].mOther = pair.mObjects[0]; mEdges[1].mJoint = this; // We put not CollideConnected at the front so we can do quick filtering if (GetCollideConnected()) { if (pair.mObjects[0] != nullptr) pair.mObjects[0]->mJointEdges.PushBack(&mEdges[0]); if (pair.mObjects[1] != nullptr) pair.mObjects[1]->mJointEdges.PushBack(&mEdges[1]); } else { if (pair.mObjects[0] != nullptr) pair.mObjects[0]->mJointEdges.PushFront(&mEdges[0]); if (pair.mObjects[1] != nullptr) pair.mObjects[1]->mJointEdges.PushFront(&mEdges[1]); } // If either collider didn't exist, then don't become valid if (pair.mObjects[0] == nullptr || pair.mObjects[1] == nullptr) return; SetValid(true); } void Joint::LinkPair() { ObjectLink* link = GetOwner()->has(ObjectLink); Cog* objectA = link->GetObjectA(); Cog* objectB = link->GetObjectB(); Collider* collider0 = nullptr; Collider* collider1 = nullptr; // Try to find the collider from each object if (objectA != nullptr) collider0 = objectA->has(Collider); if (objectB != nullptr) collider1 = objectB->has(Collider); // If we failed to get either collider then set this joint as not currently // being valid (we can't solve) if (collider0 == nullptr || collider1 == nullptr) SetValid(false); // We do have to set the pair properly so that edges and whatnot can be // properly traversed and unlinked ColliderPair pair; pair.mObjects[0] = collider0; pair.mObjects[1] = collider1; SetPair(pair); } void Joint::UnLinkPair() { typedef InList<Joint, &Joint::SolverLink> JointList; // Only remove from the island and solver if we're on an island. if (GetOnIsland()) { JointList::Unlink(this); } // Unlink from both colliders for (size_t i = 0; i < 2; ++i) { if (mEdges[i].mCollider != nullptr) { Collider::JointEdgeList::Unlink(&mEdges[i]); mEdges[i].mCollider = nullptr; } } // We aren't linked to two valid colliders so mark ourself as !Valid SetValid(false); } void Joint::Relink(uint index, Cog* cog) { // Get the collider from the input cog Collider* collider = nullptr; if (cog != nullptr) collider = cog->has(Collider); // Remove ourself from the island we were on (if we were on one) typedef InList<Joint, &Joint::SolverLink> JointList; if (GetOnIsland()) { SetOnIsland(false); JointList::Unlink(this); } EdgeType& mainEdge = mEdges[index]; EdgeType& otherEdge = mEdges[(index + 1) % 2]; // Unlink the old edge but only if that edge was to a // valid collider (aka the edge hasn't been cleared already). if (mainEdge.mJoint != nullptr && mainEdge.mCollider != nullptr) Collider::JointEdgeList::Unlink(&mainEdge); // Fix the colliders on the edges and add this edge to the new collider mainEdge.mJoint = this; mainEdge.mCollider = collider; otherEdge.mOther = collider; // If we have a collider then link its edge up if (collider != nullptr) collider->mJointEdges.PushBack(&mainEdge); // If we were in a completely invalid state before being setup and now we're // in a valid state we need to update valid (but not active, that should only // ever be changed by the user) bool isValid = (mainEdge.mCollider != nullptr && otherEdge.mCollider != nullptr); SetValid(isValid); // Finally, let joints know that we relinked so any specific joint type // can respond (pulleys and gears need to hook-up some other pointers) if (isValid) SpecificJointRelink(index, collider); } void Joint::OnObjectLinkChanged(ObjectLinkEvent* event) { Relink(event->EdgeId, event->NewCog); } void Joint::OnObjectLinkPointChanged(ObjectLinkPointChangedEvent* e) { ObjectLinkPointUpdated(e->mEdgeId, e->mNewLocalPoint); } uint Joint::GetActiveFilter() const { return mConstraintFilter & FilterFlag; } uint Joint::GetDefaultFilter() const { return (mConstraintFilter >> DefaultOffset) & FilterFlag; } void Joint::ResetFilter() { mConstraintFilter &= ~FilterFlag; mConstraintFilter |= (mConstraintFilter >> DefaultOffset) & FilterFlag; } Collider* Joint::GetCollider(uint index) const { return mEdges[index].mCollider; } Cog* Joint::GetCog(uint index) { Collider* collider = mEdges[index].mCollider; if (collider != nullptr) return collider->GetOwner(); return nullptr; } Cog* Joint::GetOtherObject(Cog* cog) { Cog* cog0 = GetCog(0); Cog* cog1 = GetCog(1); if (cog0 == cog) return cog1; else if (cog1 == cog) return cog0; return nullptr; } Vec3 Joint::GetLocalPointHelper(const Physics::AnchorAtom& anchor, uint index) const { return anchor[index]; } void Joint::SetLocalPointHelper(Physics::AnchorAtom& anchor, uint index, Vec3Param localPoint) { anchor[index] = localPoint; Physics::JointHelpers::ForceAwakeJoint(this); ObjectLink* objectLink = GetOwner()->has(ObjectLink); ErrorIf(objectLink == nullptr, "Joint is missing object link"); objectLink->SetLocalPoint(localPoint, (ObjectLink::ObjectIndex)index); } Vec3 Joint::GetWorldPointHelper(const Physics::AnchorAtom& anchor, uint index) { Collider* collider = GetCollider(index); if (collider == nullptr) return Vec3::cZero; return Physics::JointHelpers::BodyRToWorldPoint(collider, anchor[index]); } void Joint::SetWorldPointAHelper(Physics::AnchorAtom& anchor, Vec3Param worldPoint) { // Register side-effect properties if (OperationQueue::IsListeningForSideEffects()) OperationQueue::RegisterSideEffect(this, "LocalPointA", anchor[0]); SetWorldPointHelper(anchor, worldPoint, 0); } void Joint::SetWorldPointBHelper(Physics::AnchorAtom& anchor, Vec3Param worldPoint) { // Register side-effect properties if (OperationQueue::IsListeningForSideEffects()) OperationQueue::RegisterSideEffect(this, "LocalPointB", anchor[1]); SetWorldPointHelper(anchor, worldPoint, 1); } void Joint::SetWorldPointHelper(Physics::AnchorAtom& anchor, Vec3Param worldPoint, uint index) { Collider* collider = GetCollider(index); if (collider == nullptr) return; anchor[index] = Physics::JointHelpers::WorldPointToBodyR(collider, worldPoint); Physics::JointHelpers::ForceAwakeJoint(this); ObjectLink* objectLink = GetOwner()->has(ObjectLink); ErrorIf(objectLink == nullptr, "Joint is missing object link"); objectLink->SetLocalPoint(anchor[index], (ObjectLink::ObjectIndex)index); } void Joint::SetWorldPointsHelper(Physics::AnchorAtom& anchor, Vec3Param point) { // Register side-effect properties if (OperationQueue::IsListeningForSideEffects()) { OperationQueue::RegisterSideEffect(this, "LocalPointA", anchor[0]); OperationQueue::RegisterSideEffect(this, "LocalPointB", anchor[1]); } Collider* collider0 = GetCollider(0); Collider* collider1 = GetCollider(1); if (collider0 == nullptr || collider1 == nullptr) return; ObjectLink* objectLink = GetOwner()->has(ObjectLink); ErrorIf(objectLink == nullptr, "Joint is missing object link"); anchor[0] = Physics::JointHelpers::WorldPointToBodyR(collider0, point); anchor[1] = Physics::JointHelpers::WorldPointToBodyR(collider1, point); objectLink->SetLocalPointA(anchor[0]); objectLink->SetLocalPointB(anchor[1]); Physics::JointHelpers::ForceAwakeJoint(this); } void Joint::ObjectLinkPointUpdatedHelper(Physics::AnchorAtom& anchor, size_t edgeIndex, Vec3Param localPoint) { anchor[edgeIndex] = localPoint; Physics::JointHelpers::ForceAwakeJoint(this); } Vec3 Joint::GetLocalAxisHelper(const Physics::AxisAtom& axisAtom, uint index) const { return axisAtom[index]; } void Joint::SetLocalAxisHelper(Physics::AxisAtom& axisAtom, uint index, Vec3Param localAxis) { if (localAxis == Vec3::cZero) return; axisAtom[index] = localAxis; Physics::JointHelpers::ForceAwakeJoint(this); } Vec3 Joint::GetWorldAxisHelper(const Physics::AxisAtom& axisAtom) const { // There's no real logical world-space axis if the local space vectors don't // map to the same value. Just use the local axis from object 0. Collider* collider0 = GetCollider(0); if (collider0 == nullptr) return Vec3::cZero; return Physics::JointHelpers::BodyToWorldR(collider0, axisAtom[0]); } void Joint::SetWorldAxisHelper(Physics::AxisAtom& axisAtom, Vec3Param worldAxis) { // Register side-effect properties if (OperationQueue::IsListeningForSideEffects()) { OperationQueue::RegisterSideEffect(this, "LocalAxisA", axisAtom[0]); OperationQueue::RegisterSideEffect(this, "LocalAxisB", axisAtom[1]); } Vec3 fixedAxis = worldAxis; if (fixedAxis == Vec3::cZero) return; Collider* collider0 = GetCollider(0); Collider* collider1 = GetCollider(1); if (collider0 == nullptr || collider1 == nullptr) return; axisAtom[0] = Physics::JointHelpers::WorldToBodyR(collider0, fixedAxis); axisAtom[1] = Physics::JointHelpers::WorldToBodyR(collider1, fixedAxis); Physics::JointHelpers::ForceAwakeJoint(this); } Quat Joint::GetLocalAngleHelper(const Physics::AngleAtom& angleAtom, uint index) const { return angleAtom[index]; } void Joint::SetLocalAngleHelper(Physics::AngleAtom& angleAtom, uint index, QuatParam localReferenceFrame) { angleAtom[index] = localReferenceFrame; Physics::JointHelpers::ForceAwakeJoint(this); } bool Joint::GetShouldBaumgarteBeUsed(uint type) const { PhysicsSolverConfig* config = mSolver->mSolverConfig; ConstraintConfigBlock& block = config->mJointBlocks[type]; JointConfigOverride* configOverride = mNode->mConfigOverride; // Check for the config override component and use its override if it has one. if (configOverride != nullptr) { if (configOverride->mPositionCorrectionType == ConstraintPositionCorrection::PostStabilization) return false; if (configOverride->mPositionCorrectionType == ConstraintPositionCorrection::Baumgarte) return true; } // Check the block type for the given joint. If it specifies one correction // type then use that. if (block.GetPositionCorrectionType() == ConstraintPositionCorrection::PostStabilization) return false; if (block.GetPositionCorrectionType() == ConstraintPositionCorrection::Baumgarte) return true; // Otherwise check the global state. if (config->mPositionCorrectionType == PhysicsSolverPositionCorrection::PostStabilization) return false; return true; } real Joint::GetLinearBaumgarte(uint type) const { // The baumgarte term is always returned even if we aren't using baumgarte. // This is because a joint could have a spring on it, in which case we ignore // the position correction mode and always use baumgarte. Therefore, the code // that calls this should determine whether or not to apply the baumgarte // using GetShouldBaumgarteBeUsed (Same for angular baumgarte) PhysicsSolverConfig* config = mSolver->mSolverConfig; ConstraintConfigBlock& block = config->mJointBlocks[type]; JointConfigOverride* configOverride = mNode->mConfigOverride; if (configOverride != nullptr) return configOverride->mLinearBaumgarte; return block.mLinearBaumgarte; } real Joint::GetAngularBaumgarte(uint type) const { // See the comment at the top of GetLinearBaumgarte for why we always return // the baumgarte value. PhysicsSolverConfig* config = mSolver->mSolverConfig; ConstraintConfigBlock& block = config->mJointBlocks[type]; JointConfigOverride* configOverride = mNode->mConfigOverride; if (configOverride != nullptr) return configOverride->mAngularBaumgarte; return block.mAngularBaumgarte; } real Joint::GetLinearErrorCorrection(uint type) const { PhysicsSolverConfig* config = mSolver->mSolverConfig; ConstraintConfigBlock& block = config->mJointBlocks[type]; JointConfigOverride* configOverride = mNode->mConfigOverride; if (configOverride != nullptr) return configOverride->mLinearErrorCorrection; return block.mLinearErrorCorrection; } real Joint::GetLinearErrorCorrection() const { return GetLinearErrorCorrection(GetJointType()); } real Joint::GetAngularErrorCorrection(uint type) const { PhysicsSolverConfig* config = mSolver->mSolverConfig; ConstraintConfigBlock& block = config->mJointBlocks[type]; JointConfigOverride* configOverride = mNode->mConfigOverride; if (configOverride != nullptr) return configOverride->mAngularErrorCorrection; return block.mAngularErrorCorrection; } real Joint::GetAngularErrorCorrection() const { return GetAngularErrorCorrection(GetJointType()); } real Joint::GetSlop() const { PhysicsSolverConfig* config = mSolver->mSolverConfig; ConstraintConfigBlock& block = config->mJointBlocks[GetJointType()]; JointConfigOverride* configOverride = mNode->mConfigOverride; if (configOverride != nullptr) return configOverride->mSlop; return block.mSlop; } void Joint::UpdateColliderCachedTransforms() { Collider* collider0 = GetCollider(0); if (collider0 != nullptr) collider0->UpdateQueue(); Collider* collider1 = GetCollider(1); if (collider1 != nullptr) collider1->UpdateQueue(); } void Joint::ComputeCurrentAnchors(Physics::AnchorAtom& anchors) { // Just grab the body points from the object link ObjectLink* link = GetOwner()->has(ObjectLink); anchors[0] = link->GetLocalPointA(); anchors[1] = link->GetLocalPointB(); } void Joint::ComputeCurrentReferenceAngle(Physics::AngleAtom& referenceAngle) { ObjectLink* link = GetOwner()->has(ObjectLink); Cog* cogs[2]; cogs[0] = link->GetObjectA(); cogs[1] = link->GetObjectB(); // Compute the relative angles to make the objects maintain their current // rotations. This is done by computing the orientation that will align // the object with the identity (aka the inverse). for (uint i = 0; i < 2; ++i) { Cog* cog = cogs[i]; if (cog != nullptr) { Transform* t = cog->has(Transform); if (t != nullptr) referenceAngle[i] = t->GetWorldRotation().Inverted(); } } } bool Joint::GetOnIsland() const { return mFlags.IsSet(JointFlags::OnIsland); } void Joint::SetOnIsland(bool onIsland) { mFlags.SetState(JointFlags::OnIsland, onIsland); } bool Joint::GetGhost() const { return mFlags.IsSet(JointFlags::Ghost); } void Joint::SetGhost(bool ghost) { mFlags.SetState(JointFlags::Ghost, ghost); } bool Joint::GetValid() const { return mFlags.IsSet(JointFlags::Valid); } void Joint::SetValid(bool valid) { mFlags.SetState(JointFlags::Valid, valid); } bool Joint::GetActive() const { return mFlags.IsSet(JointFlags::Active); } void Joint::SetActive(bool active) { mFlags.SetState(JointFlags::Active, active); Physics::JointHelpers::ForceAwakeJoint(this); } bool Joint::GetSendsEvents() const { return mFlags.IsSet(JointFlags::SendsEvents); } void Joint::SetSendsEvents(bool sendsEvents) { mFlags.SetState(JointFlags::SendsEvents, sendsEvents); } bool Joint::GetAutoSnaps() const { return mFlags.IsSet(JointFlags::AutoSnaps); } void Joint::SetAutoSnaps(bool autoSnaps) { mFlags.SetState(JointFlags::AutoSnaps, autoSnaps); } bool Joint::GetCollideConnected() const { return mFlags.IsSet(JointFlags::CollideConnected); } void Joint::SetCollideConnected(bool collideConnected) { mFlags.SetState(JointFlags::CollideConnected, collideConnected); if (!GetValid()) return; Collider::JointEdgeList::Unlink(&mEdges[0]); Collider::JointEdgeList::Unlink(&mEdges[1]); // By putting not collide connected at the front of each collider's list // we can only check for not CollideConnected objects and stop once we reach a // CollideConnected for quick rejection in ShouldCollide if (collideConnected) { mEdges[0].mCollider->mJointEdges.PushBack(&mEdges[0]); mEdges[1].mCollider->mJointEdges.PushBack(&mEdges[1]); } else { mEdges[0].mCollider->mJointEdges.PushFront(&mEdges[0]); mEdges[1].mCollider->mJointEdges.PushFront(&mEdges[1]); } } real Joint::GetMaxImpulse() const { if (mMaxImpulse == Math::PositiveMax()) return real(0.0); return mMaxImpulse; } void Joint::SetMaxImpulse(real maxImpulse) { if (maxImpulse <= real(0.0)) maxImpulse = Math::PositiveMax(); mMaxImpulse = maxImpulse; } } // namespace Plasma
28.851351
109
0.72993
JesseMader
5820b09759dbd9498493383a041dd42f8a975514
3,055
cpp
C++
modules/boost/simd/base/unit/bitwise/scalar/ctz.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/base/unit/bitwise/scalar/ctz.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/base/unit/bitwise/scalar/ctz.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/simd/bitwise/include/functions/ctz.hpp> #include <boost/dispatch/functor/meta/call.hpp> #include <nt2/sdk/unit/tests/relation.hpp> #include <nt2/sdk/unit/tests/type_expr.hpp> #include <nt2/sdk/unit/tests/exceptions.hpp> #include <nt2/sdk/unit/module.hpp> #include <boost/simd/include/constants/zero.hpp> #include <boost/simd/include/constants/one.hpp> #include <boost/simd/include/constants/signmask.hpp> #include <boost/simd/include/constants/nbmantissabits.hpp> #include <boost/simd/include/constants/nan.hpp> #include <boost/simd/include/constants/inf.hpp> #include <boost/simd/include/constants/minf.hpp> #include <boost/simd/sdk/config.hpp> NT2_TEST_CASE_TPL ( ctz_real, BOOST_SIMD_REAL_TYPES) { using boost::simd::ctz; using boost::simd::tag::ctz_; typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t; typedef typename boost::dispatch::meta::as_integer<T>::type wished_r_t; // return type conformity test NT2_TEST_TYPE_IS(r_t, wished_r_t); // specific values tests #ifndef BOOST_SIMD_NO_INVALIDS NT2_TEST_EQUAL(ctz(boost::simd::Inf<T>()), r_t(boost::simd::Nbmantissabits<T>())); NT2_TEST_EQUAL(ctz(boost::simd::Minf<T>()), r_t(boost::simd::Nbmantissabits<T>())); NT2_TEST_EQUAL(ctz(boost::simd::Nan<T>()), r_t(boost::simd::Zero<r_t>())); #endif NT2_TEST_ASSERT(ctz(boost::simd::Zero<T>())); NT2_TEST_EQUAL(ctz(boost::simd::Signmask<T>()), r_t(sizeof(T)*8-1)); } // end of test for real_ NT2_TEST_CASE_TPL ( ctz_signed_int, BOOST_SIMD_INTEGRAL_SIGNED_TYPES) { using boost::simd::ctz; using boost::simd::tag::ctz_; using boost::simd::Nbmantissabits; using boost::simd::Signmask; typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t; for(std::size_t j=0; j< (sizeof(T)*CHAR_BIT-1); j++) { // Test 01111 ... 10000b T value = ~T(0) & ~((T(1)<<j)-1); NT2_TEST_EQUAL(ctz( value ), r_t(j)); NT2_TEST_EQUAL(ctz( T(-value) ), r_t(j)); } NT2_TEST_EQUAL(ctz(Signmask<T>()) , r_t(sizeof(T)*CHAR_BIT-1) ); } NT2_TEST_CASE_TPL( ctz_unsigned_integer, BOOST_SIMD_UNSIGNED_TYPES ) { using boost::simd::ctz; using boost::simd::tag::ctz_; typedef typename boost::dispatch::meta::call<ctz_(T)>::type r_t; typedef typename boost::dispatch::meta::as_integer<T>::type wished_r_t; // return type conformity test NT2_TEST_TYPE_IS(r_t, wished_r_t); // specific values tests for(std::size_t j=0; j< sizeof(T)*CHAR_BIT; j++) { // Test 1111 ... 10000b T value = ~T(0) & ~((T(1)<<j)-1); NT2_TEST_EQUAL(ctz( value ), r_t(j)); } }
36.807229
85
0.654664
psiha
5821bce6720bed5b84b46e6e158b791fd13d21c7
1,243
cpp
C++
uva/c/10454a.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
uva/c/10454a.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
uva/c/10454a.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
#include<cstdio> int dp[100][100]; int calc(char *,bool); main() { char s[200]; while(scanf("%s",s)!=EOF) printf("%d\n",calc(s,0)); } int calc(char *s,bool star) { int i,j,k,n,num[100]; for(i=n=0;s[i];i++) { if(s[i]=='+' || s[i]=='*')continue; if(s[i]=='(') for(j=i+1;s[j]!=')';j++); else j=i; if(star || s[j+1]!='*') { if(s[i]=='(') { char tmp;tmp=s[j],s[j]=0; num[n++]=calc(s+i+1,0); s[j]=tmp; i=j; } else num[n++]=1; } else { int cnt=0; for(j++;s[j] && (cnt || s[j]!='+');j++) { if(s[j]=='(')cnt++; if(s[j]==')')cnt--; } char tmp=s[j]; s[j]=0; num[n++]=calc(s+i,1); s[j]=tmp; i=j; } } for(i=0;i<n;i++) for(j=0;j<n;j++) dp[i][j]=0; for(i=0;i<n;i++) dp[i][i]=num[i]; for(k=1;k<n;k++) for(i=0;i+k<n;i++) for(j=i;j<i+k;j++) dp[i][i+k]+=dp[i][j]*dp[j+1][i+k]; return dp[0][n-1]; }
21.807018
51
0.295253
dk00
582597bde0f8de7e5184d4ae2a3c7b34dd9aa68d
1,472
cpp
C++
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fuse_subtract_to_fake_quantize_transformation.cpp
oxygenxo/openvino
a984e7e81bcf4a18138b57632914b5a88815282d
[ "Apache-2.0" ]
null
null
null
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fuse_subtract_to_fake_quantize_transformation.cpp
oxygenxo/openvino
a984e7e81bcf4a18138b57632914b5a88815282d
[ "Apache-2.0" ]
29
2020-12-08T07:33:34.000Z
2022-02-21T13:03:37.000Z
inference-engine/tests/functional/plugin/shared/src/low_precision_transformations/fuse_subtract_to_fake_quantize_transformation.cpp
oxygenxo/openvino
a984e7e81bcf4a18138b57632914b5a88815282d
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "low_precision_transformations/fuse_subtract_to_fake_quantize_transformation.hpp" #include <tuple> #include <sstream> #include <string> #include <vector> #include <transformations/init_node_info.hpp> #include "lpt_ngraph_functions/fuse_subtract_to_fake_quantize_function.hpp" namespace LayerTestsDefinitions { std::string FuseSubtractToFakeQuantizeTransformation::getTestCaseName(testing::TestParamInfo<FuseSubtractToFakeQuantizeTransformationParams> obj) { std::string targetDevice; FuseSubtractToFakeQuantizeTransformationTestValues testValues; std::tie(targetDevice, testValues) = obj.param; std::ostringstream result; result << targetDevice << "_" << testValues.actual.dequantization << "_" << testValues.actual.fakeQuantizeOnData; return result.str(); } void FuseSubtractToFakeQuantizeTransformation::SetUp() { FuseSubtractToFakeQuantizeTransformationTestValues testValues; std::tie(targetDevice, testValues) = this->GetParam(); function = ngraph::builder::subgraph::FuseSubtractToFakeQuantizeFunction::get( testValues.inputShape, testValues.actual.fakeQuantizeOnData, testValues.actual.dequantization); ngraph::pass::InitNodeInfo().run_on_function(function); } TEST_P(FuseSubtractToFakeQuantizeTransformation, CompareWithRefImpl) { Run(); }; } // namespace LayerTestsDefinitions
32
147
0.777853
oxygenxo
582647cc35bcc66768b5d2a8e9a6c8bd180f1cd2
84
cc
C++
transport/MessageUtils.cc
ybatrakov/ybtrep
f5142b3f4611957537971f8e105ebb9fc911c726
[ "Apache-2.0" ]
null
null
null
transport/MessageUtils.cc
ybatrakov/ybtrep
f5142b3f4611957537971f8e105ebb9fc911c726
[ "Apache-2.0" ]
null
null
null
transport/MessageUtils.cc
ybatrakov/ybtrep
f5142b3f4611957537971f8e105ebb9fc911c726
[ "Apache-2.0" ]
null
null
null
#include "MessageUtils.h" mamaPayloadBridge MessageUtils::payloadBridge = nullptr;
21
56
0.821429
ybatrakov
5826f170c217ac14e36399a80add561303d113bd
3,407
cpp
C++
sources/sfzformat_db.cpp
sfztools/sfzfoo
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
[ "BSD-2-Clause" ]
3
2019-12-31T10:53:03.000Z
2021-12-16T22:31:42.000Z
sources/sfzformat_db.cpp
sfztools/sfzfoo
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
[ "BSD-2-Clause" ]
1
2020-01-04T01:11:24.000Z
2020-01-04T08:40:50.000Z
sources/sfzformat_db.cpp
sfztools/sfz-opcode-checker
8344c7fd94a4a8b681014aa66cdd0f02d79b8731
[ "BSD-2-Clause" ]
null
null
null
#include "sfzformat_db.h" #include <yaml-cpp/yaml.h> #include <algorithm> #include <iostream> #include <fstream> SfzDb *SfzDb::loadYAML(const ghc::filesystem::path &path) { SfzDb db; db._opcodes.reserve(1024); YAML::Node doc; try { doc = YAML::LoadFile(path); } catch (std::exception &ex) { std::cerr << ex.what() << "\n"; return nullptr; } db.processCategories(doc["categories"]); std::sort(db._opcodes.begin(), db._opcodes.end()); return new SfzDb{std::move(db)}; } std::string SfzDb::createFatOpcodeRegexp() const { std::string re; re.reserve(32 * 1024); re.append("(?:"); bool firstOpcode = true; for (const std::string &opcode : _opcodes) { if (!firstOpcode) re.push_back('|'); for (char c : opcode) { bool isLower = c >= 'a' && c <= 'z'; bool isUpper = c >= 'A' && c <= 'Z'; bool isDigit = c >= '0' && c <= '9'; if (c == 'N' || c == 'X' || c == 'Y' || c == 'Z') re.append("[0-9]+"); else if (c == '*') re.append("[a-zA-Z0-9_]+"); else if (isLower || isUpper || isDigit || c == '_' || c == '#') re.push_back(c); else { std::cerr << "Do not know how to handle character in regexp: " << (int)(unsigned char)c << "\n"; return std::string{}; } } firstOpcode = false; } re.append(")"); return re; } void SfzDb::processCategories(YAML::Node categoryList) { if (!categoryList.IsSequence()) return; size_t numCat = categoryList.size(); for (size_t idxCat = 0; idxCat < numCat; ++idxCat) { YAML::Node category = categoryList[idxCat]; processOpcodes(category["opcodes"]); processTypes(category["types"]); } } void SfzDb::processTypes(YAML::Node typeList) { if (!typeList.IsSequence()) return; size_t numTypes = typeList.size(); for (size_t idxType = 0; idxType < numTypes; ++idxType) { YAML::Node type = typeList[idxType]; processOpcodes(type["opcodes"]); } } void SfzDb::processOpcodes(YAML::Node opcodeList) { if (!opcodeList.IsSequence()) return; size_t numOpcodes = opcodeList.size(); for (size_t idxOpcode = 0; idxOpcode < numOpcodes; ++idxOpcode) { YAML::Node opcode = opcodeList[idxOpcode]; processOpcodeName(opcode["name"].as<std::string>()); processOpcodeAlias(opcode["alias"]); processOpcodeModulation(opcode["modulation"]); } } void SfzDb::processOpcodeAlias(YAML::Node aliasList) { if (!aliasList.IsSequence()) return; size_t numAliases = aliasList.size(); for (size_t idxAlias = 0; idxAlias < numAliases; ++idxAlias) { YAML::Node alias = aliasList[idxAlias]; processOpcodeName(alias["name"].as<std::string>()); } } void SfzDb::processOpcodeModulation(YAML::Node modulationList) { if (!modulationList.IsMap()) return; for (YAML::const_iterator it = modulationList.begin(), end = modulationList.end(); it != end; ++it) { // key: midi_cc, ... (other?) processOpcodes(it->second); } } void SfzDb::processOpcodeName(const std::string &name) { if (_opcodesUnordered.insert(name).second) _opcodes.emplace_back(name); }
25.051471
112
0.563546
sfztools
582749ce944c06ce9ebd21dae64aee0c8b4b40eb
2,804
cpp
C++
src/tzeentch/Vortemis.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
5
2019-02-01T01:41:19.000Z
2021-06-17T02:16:13.000Z
src/tzeentch/Vortemis.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
2
2020-01-14T16:57:42.000Z
2021-04-01T00:53:18.000Z
src/tzeentch/Vortemis.cpp
rweyrauch/AoSSimulator
d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b
[ "MIT" ]
1
2019-03-02T20:03:51.000Z
2019-03-02T20:03:51.000Z
/* * Warhammer Age of Sigmar battle simulator. * * Copyright (C) 2020 by Rick Weyrauch - rpweyrauch@gmail.com * * This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT) */ #include <UnitFactory.h> #include <spells/MysticShield.h> #include "tzeentch/Vortemis.h" #include "TzeentchPrivate.h" #include "TzeentchSpells.h" namespace Tzeentch { static const int g_basesize = 40; static const int g_wounds = 5; static const int g_pointsPerUnit = 215; bool VortemisTheAllSeeing::s_registered = false; Unit *VortemisTheAllSeeing::Create(const ParameterList &parameters) { auto lore = (Lore) GetEnumParam("Lore", parameters, g_loreOfChange[0]); auto general = GetBoolParam("General", parameters, false); return new VortemisTheAllSeeing(lore, general); } void VortemisTheAllSeeing::Init() { if (!s_registered) { static FactoryMethod factoryMethod = { VortemisTheAllSeeing::Create, TzeentchBase::ValueToString, TzeentchBase::EnumStringToInt, VortemisTheAllSeeing::ComputePoints, { EnumParameter("Lore", g_loreOfFate[0], g_loreOfFate), BoolParameter("General") }, CHAOS, {TZEENTCH} }; s_registered = UnitFactory::Register("Vortemis the All-seeing", factoryMethod); } } VortemisTheAllSeeing::VortemisTheAllSeeing(Lore lore, bool isGeneral) : TzeentchBase(ChangeCoven::Cult_Of_The_Transient_Form,"Vortemis the All-seeing", 6, g_wounds, 7, 5, false, g_pointsPerUnit), m_staffMissile(Weapon::Type::Missile, "Tzeenchian Runestaff", 18, 1, 3, 4, 0, RAND_D3), m_staff(Weapon::Type::Melee, "Tzeenchian Runestaff", 1, 1, 4, 4, 0, 1) { m_keywords = {CHAOS, MORTAL, TZEENTCH, ARCANITE, CULT_OF_THE_TRANSIENT_FORM, HERO, WIZARD, MAGISTER, VORTEMIS_THE_ALL_SEEING}; m_weapons = {&m_staffMissile, &m_staff}; m_battleFieldRole = Role::Leader; m_totalSpells = 1; m_totalUnbinds = 1; setGeneral(isGeneral); auto model = new Model(g_basesize, wounds()); model->addMissileWeapon(&m_staffMissile); model->addMeleeWeapon(&m_staff); addModel(model); m_knownSpells.push_back(std::unique_ptr<Spell>(CreateLore(lore, this))); m_knownSpells.push_back(std::unique_ptr<Spell>(CreateArcaneBolt(this))); m_knownSpells.push_back(std::make_unique<MysticShield>(this)); } int VortemisTheAllSeeing::ComputePoints(const ParameterList& /*parameters*/) { return g_pointsPerUnit; } } // Tzeentch
37.891892
135
0.631598
rweyrauch
5827ef3dd8751b2c7cd0a0786c1fec0439b4eabe
3,172
cpp
C++
Source/Core/FontFace.cpp
Unvanquished/libRocket
ba129bb701e6777ac763f279fd8f8cbd8339e38d
[ "Unlicense", "MIT" ]
null
null
null
Source/Core/FontFace.cpp
Unvanquished/libRocket
ba129bb701e6777ac763f279fd8f8cbd8339e38d
[ "Unlicense", "MIT" ]
5
2016-07-13T00:50:00.000Z
2020-02-08T03:49:05.000Z
Source/Core/FontFace.cpp
Unvanquished/libRocket
ba129bb701e6777ac763f279fd8f8cbd8339e38d
[ "Unlicense", "MIT" ]
4
2015-10-24T11:59:32.000Z
2021-12-05T19:15:25.000Z
/* * This source file is part of libRocket, the HTML/CSS Interface Middleware * * For the latest information, see http://www.librocket.com * * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd * * 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 "precompiled.h" #include "FontFace.h" #include <Rocket/Core/FontFaceHandle.h> #include <Rocket/Core/Log.h> namespace Rocket { namespace Core { FontFace::FontFace(FT_Face _face, Font::Style _style, Font::Weight _weight, bool _release_stream) { face = _face; style = _style; weight = _weight; release_stream = _release_stream; } FontFace::~FontFace() { for (HandleMap::iterator iterator = handles.begin(); iterator != handles.end(); ++iterator) { iterator->second->RemoveReference(); } ReleaseFace(); } // Returns the style of the font face. Font::Style FontFace::GetStyle() const { return style; } // Returns the weight of the font face. Font::Weight FontFace::GetWeight() const { return weight; } // Returns a handle for positioning and rendering this face at the given size. FontFaceHandle* FontFace::GetHandle(const String& _raw_charset, int size) { UnicodeRangeList charset; HandleMap::iterator iterator = handles.find(size); if (iterator != handles.end()) { iterator->second->AddReference(); return iterator->second; } // See if this face has been released. if (face == NULL) { Log::Message(Log::LT_WARNING, "Font face has been released, unable to generate new handle."); return NULL; } // Construct and initialise the new handle. FontFaceHandle* handle = new FontFaceHandle(); if (!handle->Initialise(face, _raw_charset, size)) { handle->RemoveReference(); return NULL; } // Save the handle, and add a reference for the callee. The initial reference will be removed when the font face // releases it. handles[size] = handle; handle->AddReference(); return handle; } // Releases the face's FreeType face structure. void FontFace::ReleaseFace() { if (face != NULL) { FT_Byte* face_memory = face->stream->base; FT_Done_Face(face); if (release_stream) delete[] face_memory; face = NULL; } } } }
26.214876
113
0.729823
Unvanquished
5829320a442c8eb1dbd064ffecc8acfbdb6fe942
3,300
cpp
C++
src/game/client/c_colorcorrectionvolume.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/client/c_colorcorrectionvolume.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/client/c_colorcorrectionvolume.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: Color correction entity. // // $NoKeywords: $ //===========================================================================// #include "cbase.h" #include "filesystem.h" #include "cdll_client_int.h" #include "materialsystem/MaterialSystemUtil.h" #include "colorcorrectionmgr.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" //------------------------------------------------------------------------------ // FIXME: This really should inherit from something more lightweight //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Purpose : Shadow control entity //------------------------------------------------------------------------------ class C_ColorCorrectionVolume : public C_BaseEntity { public: DECLARE_CLASS(C_ColorCorrectionVolume, C_BaseEntity); DECLARE_CLIENTCLASS(); DECLARE_PREDICTABLE(); C_ColorCorrectionVolume(); virtual ~C_ColorCorrectionVolume(); void OnDataChanged(DataUpdateType_t updateType); bool ShouldDraw(); void ClientThink(); private: float m_Weight; char m_lookupFilename[MAX_PATH]; ClientCCHandle_t m_CCHandle; }; IMPLEMENT_CLIENTCLASS_DT(C_ColorCorrectionVolume, DT_ColorCorrectionVolume, CColorCorrectionVolume) RecvPropFloat(RECVINFO(m_Weight)), RecvPropString(RECVINFO(m_lookupFilename)), END_RECV_TABLE() BEGIN_PREDICTION_DATA(C_ColorCorrectionVolume) DEFINE_PRED_FIELD(m_Weight, FIELD_FLOAT, FTYPEDESC_INSENDTABLE), END_PREDICTION_DATA() //------------------------------------------------------------------------------ // Constructor, destructor //------------------------------------------------------------------------------ C_ColorCorrectionVolume::C_ColorCorrectionVolume() { m_CCHandle = INVALID_CLIENT_CCHANDLE; } C_ColorCorrectionVolume::~C_ColorCorrectionVolume() { g_pColorCorrectionMgr->RemoveColorCorrection(m_CCHandle); } //------------------------------------------------------------------------------ // Purpose : // Input : // Output : //------------------------------------------------------------------------------ void C_ColorCorrectionVolume::OnDataChanged(DataUpdateType_t updateType) { BaseClass::OnDataChanged(updateType); if (updateType == DATA_UPDATE_CREATED) { if (m_CCHandle == INVALID_CLIENT_CCHANDLE) { char filename[MAX_PATH]; Q_strncpy(filename, m_lookupFilename, MAX_PATH); m_CCHandle = g_pColorCorrectionMgr->AddColorCorrection(filename); SetNextClientThink((m_CCHandle != INVALID_CLIENT_CCHANDLE) ? CLIENT_THINK_ALWAYS : CLIENT_THINK_NEVER); } } } //------------------------------------------------------------------------------ // We don't draw... //------------------------------------------------------------------------------ bool C_ColorCorrectionVolume::ShouldDraw() { return false; } void C_ColorCorrectionVolume::ClientThink() { Vector entityPosition = GetAbsOrigin(); g_pColorCorrectionMgr->SetColorCorrectionWeight(m_CCHandle, m_Weight); }
28.947368
115
0.531212
cstom4994
582d76a97d660cd80c90c2781b8d143006860485
1,667
cpp
C++
src/Platform/android/Application_Android.cpp
AmazingCow/MonsterFramework
e2cc94012ff3074c20aec2e095ea4242f91aa99e
[ "BSD-3-Clause" ]
null
null
null
src/Platform/android/Application_Android.cpp
AmazingCow/MonsterFramework
e2cc94012ff3074c20aec2e095ea4242f91aa99e
[ "BSD-3-Clause" ]
2
2016-09-27T00:13:22.000Z
2016-09-27T00:21:30.000Z
src/Platform/android/Application_Android.cpp
AmazingCow-Game-Framework/MonsterFramework
e2cc94012ff3074c20aec2e095ea4242f91aa99e
[ "BSD-3-Clause" ]
null
null
null
#include "MonsterFramework/include/Platform/Application.h" //Prevent the file to be compiled in NON Android builds. #if( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID ) //Jni #include "platform/android/jni/JniHelper.h" //Usings USING_NS_MF; USING_NS_CC; //////////////////////////////////////////////////////////////////////////////// // CTOR / DTOR // //////////////////////////////////////////////////////////////////////////////// mf::Application::Application() : cc::Application() { constexpr auto kClassPath = "org/cocos2dx/cpp/AppActivity"; constexpr auto kMethodName = "getApplicationName"; constexpr auto kMethodSig = "()Ljava/lang/String;"; JNIEnv* pEnv; JavaVM* j_jvm = cc::JniHelper::getJavaVM(); jint j_ret = j_jvm->GetEnv((void**)&pEnv, JNI_VERSION_1_4); jclass j_class = pEnv->FindClass(kClassPath); jmethodID j_methodId = pEnv->GetStaticMethodID(j_class, kMethodName, kMethodSig); jstring j_str = (jstring)pEnv->CallStaticObjectMethod(j_class, j_methodId); const char* cstr = pEnv->GetStringUTFChars(j_str, JNI_FALSE); m_appName = cstr; pEnv->ReleaseStringUTFChars(j_str, cstr); //Release the Java stuff. } //////////////////////////////////////////////////////////////////////////////// // Public Methods // //////////////////////////////////////////////////////////////////////////////// const std::string& mf::Application::getApplicationName() const { return m_appName; } #endif // ( CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID ) //
34.729167
86
0.513497
AmazingCow
583172a2b7d53d2cf52f28108b0434e11a3251ef
13,487
cpp
C++
src/esp/bindings/PhysicsBindings.cpp
narekvslife/habitat-sim
69ae4848503d5dcc74d6b5920957c1a641ef0a9b
[ "MIT" ]
1,457
2019-02-21T21:42:41.000Z
2022-03-29T13:34:28.000Z
src/esp/bindings/PhysicsBindings.cpp
narekvslife/habitat-sim
69ae4848503d5dcc74d6b5920957c1a641ef0a9b
[ "MIT" ]
1,131
2019-02-27T16:14:06.000Z
2022-03-31T15:41:24.000Z
src/esp/bindings/PhysicsBindings.cpp
narekvslife/habitat-sim
69ae4848503d5dcc74d6b5920957c1a641ef0a9b
[ "MIT" ]
316
2019-02-26T22:45:38.000Z
2022-03-26T04:55:32.000Z
#include "esp/bindings/Bindings.h" #include "esp/physics/PhysicsManager.h" #include "python/corrade/EnumOperators.h" namespace py = pybind11; using py::literals::operator""_a; namespace esp { namespace physics { void initPhysicsBindings(py::module& m) { // ==== enum object PhysicsSimulationLibrary ==== py::enum_<PhysicsManager::PhysicsSimulationLibrary>( m, "PhysicsSimulationLibrary") .value("NoPhysics", PhysicsManager::PhysicsSimulationLibrary::NoPhysics) .value("Bullet", PhysicsManager::PhysicsSimulationLibrary::Bullet); // ==== enum object MotionType ==== py::enum_<MotionType>(m, "MotionType") .value("UNDEFINED", MotionType::UNDEFINED) .value("STATIC", MotionType::STATIC) .value("KINEMATIC", MotionType::KINEMATIC) .value("DYNAMIC", MotionType::DYNAMIC); // ==== struct object VelocityControl ==== py::class_<VelocityControl, VelocityControl::ptr>(m, "VelocityControl") .def(py::init(&VelocityControl::create<>)) .def_readwrite("linear_velocity", &VelocityControl::linVel, R"(The linear velocity in meters/second.)") .def_readwrite( "angular_velocity", &VelocityControl::angVel, R"(The angular velocity (Omega) in units of radians per second.)") .def_readwrite("controlling_lin_vel", &VelocityControl::controllingLinVel, R"(Whether or not linear velocity is integrated.)") .def_readwrite( "lin_vel_is_local", &VelocityControl::linVelIsLocal, R"(Whether the linear velocity is considered to be in object local space or global space.)") .def_readwrite("controlling_ang_vel", &VelocityControl::controllingAngVel, R"(Whether or not angular velocity is integrated.)") .def_readwrite( "ang_vel_is_local", &VelocityControl::angVelIsLocal, R"(Whether the angular velocity is considered to be in object local space or global space.)") .def( "integrate_transform", &VelocityControl::integrateTransform, "dt"_a, "rigid_state"_a, R"(Integrate the velocity (with explicit Euler) over a discrete timestep (dt) starting at a given state and using configured parameters. Returns the new state after integration.)"); // ==== enum articulated JointType ==== py::enum_<JointType>(m, "JointType") .value("Revolute", JointType::Revolute) .value("Prismatic", JointType::Prismatic) .value("Spherical", JointType::Spherical) .value("Planar", JointType::Planar) .value("Fixed", JointType::Fixed) .value("Invalid", JointType::Invalid); // ==== enum object JointMotorType ==== py::enum_<JointMotorType>(m, "JointMotorType") .value("SingleDof", JointMotorType::SingleDof) .value("Spherical", JointMotorType::Spherical); // ==== struct object JointMotorSettings ==== py::class_<JointMotorSettings, JointMotorSettings::ptr>(m, "JointMotorSettings") .def(py::init(&JointMotorSettings::create<>)) .def(py::init(&JointMotorSettings::create<double, double, double, double, double>), "position_target"_a, "position_gain"_a, "velocity_target"_a, "velocity_gain"_a, "max_impulse"_a) .def(py::init( &JointMotorSettings::create<const Mn::Quaternion&, double, const Mn::Vector3&, double, double>), "spherical_position_target"_a, "position_gain"_a, "spherical_velocity_target"_a, "velocity_gain"_a, "max_impulse"_a) .def_readwrite("position_target", &JointMotorSettings::positionTarget, R"(Single DoF joint position target.)") .def_readwrite("spherical_position_target", &JointMotorSettings::sphericalPositionTarget, R"(Spherical joint position target (Mn::Quaternion).)") .def_readwrite("position_gain", &JointMotorSettings::positionGain, R"(Position (proportional) gain Kp.)") .def_readwrite( "velocity_target", &JointMotorSettings::velocityTarget, R"(Single DoF joint velocity target. Zero acts like joint damping/friction.)") .def_readwrite("spherical_velocity_target", &JointMotorSettings::sphericalVelocityTarget, R"(Spherical joint velocity target.)") .def_readwrite("velocity_gain", &JointMotorSettings::velocityGain, R"(Velocity (derivative) gain Kd.)") .def_readwrite( "max_impulse", &JointMotorSettings::maxImpulse, R"(The maximum impulse applied by this motor. Should be tuned relative to physics timestep.)") .def_readwrite( "motor_type", &JointMotorSettings::motorType, R"(The type of motor parameterized by these settings. Determines which parameters to use.)"); // ==== enum RigidConstraintType ==== py::enum_<RigidConstraintType>(m, "RigidConstraintType") .value("PointToPoint", RigidConstraintType::PointToPoint) .value("Fixed", RigidConstraintType::Fixed); // ==== struct object RigidConstraintSettings ==== py::class_<RigidConstraintSettings, RigidConstraintSettings::ptr>( m, "RigidConstraintSettings") .def(py::init(&RigidConstraintSettings::create<>)) .def_readwrite("constraint_type", &RigidConstraintSettings::constraintType, R"(The type of constraint described by these settings.)") .def_readwrite( "max_impulse", &RigidConstraintSettings::maxImpulse, R"(The maximum impulse applied by this constraint. Should be tuned relative to physics timestep.)") .def_readwrite( "object_id_a", &RigidConstraintSettings::objectIdA, R"(The id of the first object. Must be >=0. For mixed type constraints, objectA must be the ArticulatedObject.)") .def_readwrite("object_id_b", &RigidConstraintSettings::objectIdB, R"(The id of the second object. -1 for world/global.)") .def_readwrite( "link_id_a", &RigidConstraintSettings::linkIdA, R"(The id of the link for objectA if articulated, otherwise ignored. -1 for base link.)") .def_readwrite( "link_id_b", &RigidConstraintSettings::linkIdB, R"(The id of the link for objectB if articulated, otherwise ignored. -1 for base link.)") .def_readwrite("pivot_a", &RigidConstraintSettings::pivotA, R"(Constraint point in local space of objectA.)") .def_readwrite("pivot_b", &RigidConstraintSettings::pivotB, R"(Constraint point in local space of objectB.)") .def_readwrite( "frame_a", &RigidConstraintSettings::frameA, R"(Constraint orientation frame in local space of objectA as 3x3 rotation matrix for RigidConstraintType::Fixed.)") .def_readwrite( "frame_b", &RigidConstraintSettings::frameB, R"(Constraint orientation frame in local space of objectB as 3x3 rotation matrix for RigidConstraintType::Fixed.)"); // ==== struct object RayHitInfo ==== py::class_<RayHitInfo, RayHitInfo::ptr>(m, "RayHitInfo") .def(py::init(&RayHitInfo::create<>)) .def_readonly("object_id", &RayHitInfo::objectId) .def_readonly("point", &RayHitInfo::point) .def_readonly("normal", &RayHitInfo::normal) .def_readonly("ray_distance", &RayHitInfo::rayDistance); // ==== struct object RaycastResults ==== py::class_<RaycastResults, RaycastResults::ptr>(m, "RaycastResults") .def(py::init(&RaycastResults::create<>)) .def_readonly("hits", &RaycastResults::hits) .def_readonly("ray", &RaycastResults::ray) .def("has_hits", &RaycastResults::hasHits); // ==== struct object ContactPointData ==== py::class_<ContactPointData, ContactPointData::ptr>(m, "ContactPointData") .def(py::init(&ContactPointData::create<>)) .def_readwrite( "object_id_a", &ContactPointData::objectIdA, R"(The Habitat object id of the first object in this collision pair.)") .def_readwrite( "object_id_b", &ContactPointData::objectIdB, R"(The Habitat object id of the second object in this collision pair.)") .def_readwrite( "link_id_a", &ContactPointData::linkIndexA, R"(The Habitat link id of the first object in this collision pair if an articulated link. -1 can indicate base link.)") .def_readwrite( "link_id_b", &ContactPointData::linkIndexB, R"(The Habitat link id of the second object in this collision pair if an articulated link. -1 can indicate base link.)") .def_readwrite( "position_on_a_in_ws", &ContactPointData::positionOnAInWS, R"(The global position of the contact point on the first object.)") .def_readwrite( "position_on_b_in_ws", &ContactPointData::positionOnBInWS, R"(The global position of the contact point on the second object.)") .def_readwrite( "contact_normal_on_b_in_ws", &ContactPointData::contactNormalOnBInWS, R"(The contact normal relative to the second object in world space.)") .def_readwrite("contact_distance", &ContactPointData::contactDistance, R"(The penetration depth of the contact point.)") .def_readwrite("normal_force", &ContactPointData::normalForce, R"(The normal force produced by the contact point.)") .def_readwrite("linear_friction_force1", &ContactPointData::linearFrictionForce1) .def_readwrite("linear_friction_force2", &ContactPointData::linearFrictionForce2) .def_readwrite("linear_friction_direction1", &ContactPointData::linearFrictionDirection1) .def_readwrite("linear_friction_direction2", &ContactPointData::linearFrictionDirection2) .def_readwrite( "is_active", &ContactPointData::isActive, R"(Whether or not the contact is between active objects. Deactivated objects may produce contact points but no reaction.)"); // ==== enum object CollisionGroup ==== py::enum_<CollisionGroup> collisionGroups{m, "CollisionGroups", "CollisionGroups"}; collisionGroups.value("Default", CollisionGroup::Default) .value("Static", CollisionGroup::Static) .value("Kinematic", CollisionGroup::Kinematic) .value("Dynamic", CollisionGroup::Dynamic) .value("Robot", CollisionGroup::Robot) .value("Noncollidable", CollisionGroup::Noncollidable) .value("UserGroup0", CollisionGroup::UserGroup0) .value("UserGroup1", CollisionGroup::UserGroup1) .value("UserGroup2", CollisionGroup::UserGroup2) .value("UserGroup3", CollisionGroup::UserGroup3) .value("UserGroup4", CollisionGroup::UserGroup4) .value("UserGroup5", CollisionGroup::UserGroup5) .value("UserGroup6", CollisionGroup::UserGroup6) .value("UserGroup7", CollisionGroup::UserGroup7) .value("UserGroup8", CollisionGroup::UserGroup8) .value("UserGroup9", CollisionGroup::UserGroup9) .value("None", CollisionGroup{}); corrade::enumOperators(collisionGroups); // ==== class object CollisionGroupHelper ==== py::class_<CollisionGroupHelper, std::shared_ptr<CollisionGroupHelper>>( m, "CollisionGroupHelper") .def_static("get_group", &CollisionGroupHelper::getGroup, "name"_a, R"(Get a group by assigned name.)") .def_static("get_group_name", &CollisionGroupHelper::getGroupName, "group"_a, R"(Get the name assigned to a CollisionGroup.)") .def_static("set_group_name", &CollisionGroupHelper::setGroupName, "group"_a, "name"_a, R"(Assign a name to a CollisionGroup.)") .def_static( "get_mask_for_group", [](CollisionGroup group) { return CollisionGroup( uint32_t(CollisionGroupHelper::getMaskForGroup(group))); }, "group"_a, R"(Get the mask for a collision group describing its interaction with other groups.)") .def_static( "get_mask_for_group", [](const std::string& group_name) { return CollisionGroup( uint32_t(CollisionGroupHelper::getMaskForGroup(group_name))); }, "group"_a, R"(Get the mask for a collision group describing its interaction with other groups.)") .def_static( "set_mask_for_group", [](CollisionGroup group, CollisionGroup mask) { CollisionGroupHelper::setMaskForGroup(group, CollisionGroups(mask)); }, "group"_a, "mask"_a, R"(Set the mask for a collision group describing its interaction with other groups. It is not recommended to modify the mask for default, non-user groups.)") .def_static( "set_group_interacts_with", &CollisionGroupHelper::setGroupInteractsWith, "group_a"_a, "group_b"_a, "interact"_a, R"(Set groupA's collision mask to a specific interaction state with respect to groupB.)") .def_static("get_all_group_names", &CollisionGroupHelper::getAllGroupNames, R"(Get a list of all configured collision group names.)"); } } // namespace physics } // namespace esp
52.683594
191
0.656039
narekvslife
58371ad0697cfe1674f8351eb3ccc3c2bad63277
101
cpp
C++
ACC/acc4p4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
ACC/acc4p4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
ACC/acc4p4.cpp
crackersamdjam/DMOJ-Solutions
97992566595e2c7bf41b5da9217d8ef61bdd1d71
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; string f(int N){ return to_string(1LL*N*N); }
16.833333
31
0.633663
crackersamdjam
5839d0685d548e610c341210d01ab8ac68098520
1,151
hpp
C++
src/include/guinsoodb/storage/table/validity_segment.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-04-22T05:41:54.000Z
2021-04-22T05:41:54.000Z
src/include/guinsoodb/storage/table/validity_segment.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
null
null
null
src/include/guinsoodb/storage/table/validity_segment.hpp
GuinsooLab/guinsoodb
f200538868738ae460f62fb89211deec946cefff
[ "MIT" ]
1
2021-12-12T10:24:57.000Z
2021-12-12T10:24:57.000Z
//===----------------------------------------------------------------------===// // GuinsooDB // // guinsoodb/storage/table/validity_segment.hpp // // //===----------------------------------------------------------------------===// #pragma once #include "guinsoodb/storage/block.hpp" #include "guinsoodb/storage/uncompressed_segment.hpp" #include "guinsoodb/common/types/validity_mask.hpp" namespace guinsoodb { class BlockHandle; class DatabaseInstance; class SegmentStatistics; class Vector; struct VectorData; class ValiditySegment : public UncompressedSegment { public: ValiditySegment(DatabaseInstance &db, idx_t row_start, block_id_t block_id = INVALID_BLOCK); ~ValiditySegment(); public: void InitializeScan(ColumnScanState &state) override; void FetchRow(ColumnFetchState &state, row_t row_id, Vector &result, idx_t result_idx) override; idx_t Append(SegmentStatistics &stats, VectorData &data, idx_t offset, idx_t count) override; void RevertAppend(idx_t start_row) override; protected: void FetchBaseData(ColumnScanState &state, idx_t vector_index, Vector &result) override; }; } // namespace guinsoodb
30.289474
97
0.67159
GuinsooLab
5839ec209599834366af029d48f37d03c2d2a6eb
3,212
cpp
C++
lammps-master/src/compute_pe.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/compute_pe.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
lammps-master/src/compute_pe.cpp
rajkubp020/helloword
4bd22691de24b30a0f5b73821c35a7ac0666b034
[ "MIT" ]
null
null
null
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include <mpi.h> #include <cstring> #include "compute_pe.h" #include "atom.h" #include "update.h" #include "force.h" #include "pair.h" #include "bond.h" #include "angle.h" #include "dihedral.h" #include "improper.h" #include "kspace.h" #include "modify.h" #include "domain.h" #include "error.h" using namespace LAMMPS_NS; /* ---------------------------------------------------------------------- */ ComputePE::ComputePE(LAMMPS *lmp, int narg, char **arg) : Compute(lmp, narg, arg) { if (narg < 3) error->all(FLERR,"Illegal compute pe command"); if (igroup) error->all(FLERR,"Compute pe must use group all"); scalar_flag = 1; extscalar = 1; peflag = 1; timeflag = 1; if (narg == 3) { pairflag = 1; bondflag = angleflag = dihedralflag = improperflag = 1; kspaceflag = 1; fixflag = 1; } else { pairflag = 0; bondflag = angleflag = dihedralflag = improperflag = 0; kspaceflag = 0; fixflag = 0; int iarg = 3; while (iarg < narg) { if (strcmp(arg[iarg],"pair") == 0) pairflag = 1; else if (strcmp(arg[iarg],"bond") == 0) bondflag = 1; else if (strcmp(arg[iarg],"angle") == 0) angleflag = 1; else if (strcmp(arg[iarg],"dihedral") == 0) dihedralflag = 1; else if (strcmp(arg[iarg],"improper") == 0) improperflag = 1; else if (strcmp(arg[iarg],"kspace") == 0) kspaceflag = 1; else if (strcmp(arg[iarg],"fix") == 0) fixflag = 1; else error->all(FLERR,"Illegal compute pe command"); iarg++; } } } /* ---------------------------------------------------------------------- */ double ComputePE::compute_scalar() { invoked_scalar = update->ntimestep; if (update->eflag_global != invoked_scalar) error->all(FLERR,"Energy was not tallied on needed timestep"); double one = 0.0; if (pairflag && force->pair) one += force->pair->eng_vdwl + force->pair->eng_coul; if (atom->molecular) { if (bondflag && force->bond) one += force->bond->energy; if (angleflag && force->angle) one += force->angle->energy; if (dihedralflag && force->dihedral) one += force->dihedral->energy; if (improperflag && force->improper) one += force->improper->energy; } MPI_Allreduce(&one,&scalar,1,MPI_DOUBLE,MPI_SUM,world); if (kspaceflag && force->kspace) scalar += force->kspace->energy; if (pairflag && force->pair && force->pair->tail_flag) { double volume = domain->xprd * domain->yprd * domain->zprd; scalar += force->pair->etail / volume; } if (fixflag && modify->n_thermo_energy) scalar += modify->thermo_energy(); return scalar; }
31.490196
76
0.593088
rajkubp020
5840549749c3d9aea07b804e126b96fb8deb324a
2,851
cpp
C++
applications/ContactStructuralMechanicsApplication/tests/cpp_tests/test_processes.cpp
ma6yu/Kratos
02380412f8a833a2cdda6791e1c7f9c32e088530
[ "BSD-4-Clause" ]
2
2019-10-25T09:28:10.000Z
2019-11-21T12:51:46.000Z
applications/ContactStructuralMechanicsApplication/tests/cpp_tests/test_processes.cpp
ma6yu/Kratos
02380412f8a833a2cdda6791e1c7f9c32e088530
[ "BSD-4-Clause" ]
13
2019-10-07T12:06:51.000Z
2020-02-18T08:48:33.000Z
applications/ContactStructuralMechanicsApplication/tests/cpp_tests/test_processes.cpp
ma6yu/Kratos
02380412f8a833a2cdda6791e1c7f9c32e088530
[ "BSD-4-Clause" ]
1
2020-06-12T08:51:24.000Z
2020-06-12T08:51:24.000Z
// KRATOS ___| | | | // \___ \ __| __| | | __| __| | | __| _` | | // | | | | | ( | | | | ( | | // _____/ \__|_| \__,_|\___|\__|\__,_|_| \__,_|_| MECHANICS // // License: BSD License // license: StructuralMechanicsApplication/license.txt // // Main authors: Vicente Mataix Ferrandiz // // System includes // External includes // Project includes #include "testing/testing.h" #include "containers/model.h" #include "contact_structural_mechanics_application_variables.h" /* Processes */ #include "custom_processes/aalm_adapt_penalty_value_process.h" namespace Kratos { namespace Testing { typedef Point PointType; typedef Node<3> NodeType; typedef Geometry<NodeType> GeometryNodeType; typedef Geometry<PointType> GeometryPointType; /** * Checks the correct work of the AALM dynamic penalty process */ KRATOS_TEST_CASE_IN_SUITE(AALMProcess1, KratosContactStructuralMechanicsFastSuite) { Model this_model; ModelPart& r_model_part = this_model.CreateModelPart("Main", 3); r_model_part.AddNodalSolutionStepVariable(DISPLACEMENT); r_model_part.AddNodalSolutionStepVariable(WEIGHTED_GAP); r_model_part.AddNodalSolutionStepVariable(NODAL_H); r_model_part.AddNodalSolutionStepVariable(LAGRANGE_MULTIPLIER_CONTACT_PRESSURE); auto& process_info = r_model_part.GetProcessInfo(); process_info[STEP] = 1; process_info[NL_ITERATION_NUMBER] = 1; double& penalty_parameter = process_info[INITIAL_PENALTY]; penalty_parameter = 1.0e7; double& max_gap_factor = process_info[MAX_GAP_FACTOR]; max_gap_factor = 1.0; // First we create the nodes NodeType::Pointer p_node_1 = r_model_part.CreateNewNode(0,0.0,0.0,0.0); p_node_1->SetValue(NODAL_AREA, 1.0); p_node_1->FastGetSolutionStepValue(NODAL_H) = 0.1; p_node_1->FastGetSolutionStepValue(WEIGHTED_GAP) = 0.05; p_node_1->FastGetSolutionStepValue(WEIGHTED_GAP, 1) = -0.1; AALMAdaptPenaltyValueProcess process = AALMAdaptPenaltyValueProcess(r_model_part); process.Execute(); // // DEBUG // KRATOS_WATCH(p_node_1->GetValue(INITIAL_PENALTY)) const double tolerance = 1.0e-6; KRATOS_CHECK_NEAR(p_node_1->GetValue(INITIAL_PENALTY), 0.2 * penalty_parameter, tolerance); } } // namespace Testing } // namespace Kratos.
39.054795
103
0.585759
ma6yu
58413fa8896e29eb1ca31e5dfdc513105e8947fa
22,166
cpp
C++
drm/DrmSetDisplayPageFlipHandler.cpp
intel/hwc-
3617c208959bd7c865021dd0d0bc69a94c804f99
[ "Apache-2.0" ]
null
null
null
drm/DrmSetDisplayPageFlipHandler.cpp
intel/hwc-
3617c208959bd7c865021dd0d0bc69a94c804f99
[ "Apache-2.0" ]
null
null
null
drm/DrmSetDisplayPageFlipHandler.cpp
intel/hwc-
3617c208959bd7c865021dd0d0bc69a94c804f99
[ "Apache-2.0" ]
null
null
null
/* // Copyright (c) 2017 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #include "Common.h" #include "DrmSetDisplayPageFlipHandler.h" #include "Drm.h" #include "DrmDisplay.h" #include "DisplayCaps.h" #include "Utils.h" #include "Log.h" #if VPG_DRM_HAVE_ATOMIC_SETDISPLAY #define DRM_PFH_NAME "DrmSetDisplayPageFlip" namespace intel { namespace ufo { namespace hwc { // ***************************************************************************** // DrmSetDisplayPageFlipHandler // ***************************************************************************** // Start SetDisplay option as eSetDisplayUnknown. // When this is eSetDisplayUnknown a first-use test of the API will be made to determine the // availability of the SetDisplay API - following which the option will be self-updated to // eSetDisplayEnabled or eSetDisplayDisabled. // Set this to eSetDisplayDisabled or eSetDisplayEnabled to force behaviour and skip the test. Option DrmSetDisplayPageFlipHandler::sOptionSetDisplay("setdisplay", eSetDisplayUnknown, false); DrmSetDisplayPageFlipHandler::DrmSetDisplayPageFlipHandler( DrmDisplay& display ) : mDisplay( display ), mDrm( Drm::get() ) { doInit(); } DrmSetDisplayPageFlipHandler::~DrmSetDisplayPageFlipHandler( ) { doUninit(); } bool DrmSetDisplayPageFlipHandler::test( DrmDisplay& display ) { // Check if result of test is already known. if ( sOptionSetDisplay.get() == eSetDisplayDisabled ) { ALOGI( "Drm atomic API is disabled" ); return false; } else if ( sOptionSetDisplay.get() == eSetDisplayEnabled ) { ALOGI( "Drm atomic API is enabled" ); return true; } // Test atomic API by making a NOP call. const uint32_t setDisplayBytes = sizeof( drm_mode_set_display ); drm_mode_set_display setDisplay; memset( &setDisplay, 0, setDisplayBytes ); setDisplay.version = DRM_MODE_SET_DISPLAY_VERSION; setDisplay.size = setDisplayBytes; setDisplay.crtc_id = display.getDrmCrtcID( ); ALOGD( "Testing Drm atomic API" ); int err = Drm::get().drmSetDisplay( setDisplay ); if ( err == Drm::SUCCESS ) { ALOGD( "Drm atomic API is available" ); sOptionSetDisplay.set(eSetDisplayEnabled); return true; } else { Log::alogd( true, "DrmDisplay atomic API errored:0x%x [err:%s]", setDisplay.errored, strerror( -err ) ); } ALOGD( "Drm atomic API is not available" ); sOptionSetDisplay.set(eSetDisplayDisabled); return false; } void DrmSetDisplayPageFlipHandler::doInit() { // One-shot set up of planes. const DisplayCaps& genCaps = mDisplay.getDisplayCaps( ); const DrmDisplayCaps& drmCaps = mDisplay.getDrmDisplayCaps( ); mNumPlanes = genCaps.getNumPlanes( ); mMainPlaneIndex = -1; mbHaveMainPlaneDisable = drmCaps.isMainPlaneDisableSupported( ); const uint32_t setDisplayBytes = sizeof( drm_mode_set_display ); memset( &mSetDisplay, 0, setDisplayBytes ); mSetDisplay.version = DRM_MODE_SET_DISPLAY_VERSION; mSetDisplay.size = setDisplayBytes; mSetDisplay.crtc_id = mDisplay.getDrmCrtcID( ); mSetDisplay.num_planes = genCaps.getNumPlanes( ); // Force ZOrder set (Z:0). mSetDisplay.update_flag |= DRM_MODE_SET_DISPLAY_UPDATE_ZORDER; #if VPG_DRM_HAVE_PANEL_FITTER // Force panel fitter update (PFIT:OFF). const uint32_t w = mDisplay.getAppliedWidth( ); const uint32_t h = mDisplay.getAppliedHeight( ); mSetDisplay.update_flag |= DRM_MODE_SET_DISPLAY_UPDATE_PANEL_FITTER; mSetDisplay.panel_fitter.mode = DRM_PFIT_OFF; mSetDisplay.panel_fitter.src_w = w; mSetDisplay.panel_fitter.src_h = h; mSetDisplay.panel_fitter.dst_w = w; mSetDisplay.panel_fitter.dst_h = h; #endif for ( uint32_t p = 0; p < mNumPlanes; ++p ) { const DrmDisplayCaps::PlaneCaps& planeCaps = drmCaps.getPlaneCaps( p ); drm_mode_set_display_plane& plane = mSetDisplay.plane[ p ]; // Set plane object type and id. plane.obj_id = drmCaps.getPlaneCaps( p ).getDrmID(); if ( planeCaps.getDrmPlaneType( ) == DrmDisplayCaps::PLANE_TYPE_SPRITE ) { plane.obj_type = DRM_MODE_OBJECT_PLANE; } else { plane.obj_type = DRM_MODE_OBJECT_CRTC; // NOTE: // flip() implementation assumes main planes will always be at slot 0. ALOG_ASSERT( p == 0 ); mMainPlaneIndex = p; } // Force Plane update (to disabled). mSetDisplay.update_flag |= DRM_MODE_SET_DISPLAY_UPDATE_PLANE( p ); plane.update_flag |= DRM_MODE_SET_DISPLAY_PLANE_UPDATE_PRESENT; } } void DrmSetDisplayPageFlipHandler::doUninit( void ) { } bool DrmSetDisplayPageFlipHandler::doFlip( DisplayQueue::Frame* pNewFrame, bool bMainBlanked, uint32_t flipEvData ) { // ************************************************************************* // Panel fitter processing. // ************************************************************************* mDisplay.issueGlobalScalingConfig( mSetDisplay, pNewFrame->getConfig().getGlobalScaling() ); // ************************************************************************* // ZOrder processing. // ************************************************************************* const uint32_t zorder = pNewFrame->getZOrder(); if ( mSetDisplay.zorder != zorder ) { mSetDisplay.zorder = zorder; mSetDisplay.update_flag |= DRM_MODE_SET_DISPLAY_UPDATE_ZORDER; Log::alogd( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " Crtc:%d Pipe:%u ZOrder:%u,%s", mDisplay.getDrmCrtcID(), mDisplay.getDrmPipeIndex(), zorder, mDrm.zOrderToString( zorder ) ); } // ************************************************************************* // Plane processing. // ************************************************************************* // NOTES: // MCG builds only support flip request on SpriteA. // GMIN builds support flip request from any Sprite. // In either case, we can assert: // SpriteA will always be used if any sprite is used. const bool bHaveMainPlane = ( mMainPlaneIndex != -1 ); // Can we use sprites for the flip event request? // Only if // 1/ We don't have any main planes. //OR 2/ We have main plane but it is blanked (using the sprite for flip event will fully disable main). const bool bUseSpriteEv = !bHaveMainPlane || ( mbHaveMainPlaneDisable && bMainBlanked ); bool bRequestedFlip = false; // The flip sprite index is 0 or 1 depending on whether we have a main plane. const uint32_t flipSpritePlane = bHaveMainPlane ? 1 : 0; // Plane processing is reversed so main is processed last. for( uint32_t p = mNumPlanes; p > 0; ) { --p; // Get layer. const Layer* pLayer = NULL; if ( p < pNewFrame->getLayerCount( ) ) { pLayer = &pNewFrame->getLayer( p )->getLayer( ); } else { pLayer = NULL; } // Is this plane the main plane? const bool bMainPlane = bHaveMainPlane && ( p == (uint32_t)mMainPlaneIndex ); // If this plane is the main plane and the main layer was blanked then swap in blanking layer. bool bIsBlanking; if ( bMainPlane && bMainBlanked ) { pLayer = &mDisplay.getBlankingLayer( ); bIsBlanking = true; } else { bIsBlanking = false; } uint32_t flipEventData; if ( !bRequestedFlip && ( bMainPlane || ( bUseSpriteEv && ( p == flipSpritePlane ) ) ) ) { flipEventData = flipEvData; } else { flipEventData = 0; } ALOGD_IF( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " updatePlane %u flipEventData 0x%x, bRequestedFlip %d", p, flipEventData, bRequestedFlip ); if ( updatePlane( &mSetDisplay.plane[ p ], pLayer, flipEventData, &bRequestedFlip, bIsBlanking ) ) { mSetDisplay.update_flag |= DRM_MODE_SET_DISPLAY_UPDATE_PLANE( p ); } } // Must always request flip. ALOGE_IF( !bRequestedFlip, "Failed to issue flip event request for frame %s", pNewFrame->getFrameId().dump().string() ); // Issue display update. mSetDisplay.errored = 0; mSetDisplay.presented = 0; if ( mMainPlaneIndex != -1 ) { // NOTE: // The atomic API will fail if we try to modify the RRB2 state for a main plane, even if // just to ensure it's disabled. So clear the RRB2 update flag for the main plane. ALOG_ASSERT( !mSetDisplay.plane[ mMainPlaneIndex ].rrb2_enable ); mSetDisplay.plane[ mMainPlaneIndex ].update_flag &= ~DRM_MODE_SET_DISPLAY_PLANE_UPDATE_RRB2; } ALOGD_IF( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " %s", Drm::drmDisplayPipeToString( mSetDisplay ).string( ) ); for ( uint32_t p = 0; p < mSetDisplay.num_planes; ++p ) { ALOGD_IF( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " %s", Drm::drmDisplayPlaneToString( mSetDisplay, p ).string( ) ); } #if INTEL_HWC_INTERNAL_BUILD validateSetDisplay( ); #endif // Issue the atomic display update. bool bAtomicDisplayUpdateOK = false; bAtomicDisplayUpdateOK = ( mDrm.drmSetDisplay( mSetDisplay ) == Drm::SUCCESS ); // Process succesfully issued update. if ( bAtomicDisplayUpdateOK ) { // Finalise panel fitter update. if ( mSetDisplay.update_flag & DRM_MODE_SET_DISPLAY_UPDATE_PANEL_FITTER ) { mDisplay.finalizeGlobalScalingConfig(pNewFrame->getConfig().getGlobalScaling() ); } // Reset update flags. mSetDisplay.update_flag = 0; for ( uint32_t p = 0; p < mNumPlanes; ++p ) { mSetDisplay.plane[p].update_flag &= ~DRM_MODE_SET_DISPLAY_PLANE_UPDATE_PRESENT; // Only reset remaining flags if the plane is actually enabled. if ( mSetDisplay.plane[p].fb_id ) mSetDisplay.plane[p].update_flag = 0; } } return bAtomicDisplayUpdateOK; } bool DrmSetDisplayPageFlipHandler::updatePlane( drm_mode_set_display_plane* pPlane, const Layer* pLayer, uint32_t flipEventData, bool* pbRequestedFlip, bool bIsBlanking ) { ALOG_ASSERT( pPlane ); ALOGD_IF( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " Crtc %u Update %s %u", mDisplay.getDrmCrtcID(), Drm::getObjectTypeString( pPlane->obj_type ), pPlane->obj_id ); bool bDisable = false; const uint64_t fb = pLayer ? pLayer->getBufferDeviceId() : 0; // Set/reset flags/event callback. // We can only request flip event if we have an fb. if ( flipEventData && fb ) { pPlane->user_data = flipEventData; pPlane->flags = DRM_MODE_PAGE_FLIP_EVENT; } else { pPlane->user_data = 0ULL; pPlane->flags = 0; } if ( pLayer ) { // Update plane state from layer state. // Get buffer ID - skip update if no buffer change. const hwc_frect_t& src = pLayer->getSrc(); const hwc_rect_t& dst = pLayer->getDst(); // Property: Alpha const bool bAlpha = pLayer->isBlend(); // Property: RRB2 const bool bRrb2 = pLayer->isEncrypted(); // NOTE: // The layer's HWC/HAL transform must be converted to a Drm API transform. // Current Drm APIs only support ROT180. const ETransform hwcTransform = pLayer->getTransform(); ALOG_ASSERT( ( hwcTransform == ETransform::NONE ) || ( hwcTransform == ETransform::ROT_180 ) ); // Property: Transform const uint32_t drmTransform = ( hwcTransform == ETransform::ROT_180 ) ? DRM_MODE_SET_DISPLAY_PLANE_TRANSFORM_ROT180 : DRM_MODE_SET_DISPLAY_PLANE_TRANSFORM_NONE; bool bChange = ( pPlane->update_flag != 0 ) || ( pPlane->fb_id != fb ) || ( pPlane->alpha != bAlpha ) || ( pPlane->rrb2_enable != bRrb2 ) || ( pPlane->transform != drmTransform ) || ( pPlane->crtc_x != pLayer->getDstX() ) || ( pPlane->crtc_y != pLayer->getDstY() ) || ( pPlane->crtc_w != pLayer->getDstWidth() ) || ( pPlane->crtc_h != pLayer->getDstHeight() ) || ( pPlane->src_x != (uint32_t)floatToFixed16(pLayer->getSrcX()) ) || ( pPlane->src_y != (uint32_t)floatToFixed16(pLayer->getSrcY()) ) || ( pPlane->src_w != (uint32_t)floatToFixed16(pLayer->getSrcWidth()) ) || ( pPlane->src_h != (uint32_t)floatToFixed16(pLayer->getSrcHeight()) ); if ( !bChange && !flipEventData ) { Log::alogd( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " %5s %u H:%p%s%s TX:%d S:%.1f,%.1f,%.1fx%.1f F:%d,%d,%dx%d Skipped (No Change)", Drm::getObjectTypeString( pPlane->obj_type ), pPlane->obj_id, pLayer->getHandle(), pLayer->isDisabled() ? ":DISABLE" : "", pLayer->isEncrypted() ? ":DECRYPT" : "", pLayer->getTransform(), src.left, src.top, src.right - src.left, src.bottom - src.top, dst.left, dst.top, dst.right - dst.left, dst.bottom - dst.top ); return false; } if ( fb ) { // We have a buffer to present. // Update presentation (flip). pPlane->update_flag |= DRM_MODE_SET_DISPLAY_PLANE_UPDATE_PRESENT; if ( !pPlane->fb_id ) { // Force an update all properties when a plane transitions from disabled->enabled. pPlane->update_flag |= ( DRM_MODE_SET_DISPLAY_PLANE_UPDATE_ALPHA | DRM_MODE_SET_DISPLAY_PLANE_UPDATE_RRB2 | DRM_MODE_SET_DISPLAY_PLANE_UPDATE_TRANSFORM ); } // Update plane state for this flip. uint32_t drmFlags = flipEventData ? DRM_MODE_PAGE_FLIP_EVENT : 0; pPlane->fb_id = fb; pPlane->crtc_x = pLayer->getDstX(); pPlane->crtc_y = pLayer->getDstY(); pPlane->crtc_w = pLayer->getDstWidth(); pPlane->crtc_h = pLayer->getDstHeight(); pPlane->src_x = floatToFixed16(pLayer->getSrcX()); pPlane->src_y = floatToFixed16(pLayer->getSrcY()); pPlane->src_w = floatToFixed16(pLayer->getSrcWidth()); pPlane->src_h = floatToFixed16(pLayer->getSrcHeight()); pPlane->user_data = flipEventData; pPlane->flags = drmFlags; ALOGD_IF( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " Crtc %u fb -> %d src:%.2f,%.2f %.2fx%.2f -> dst:%d,%d %dx%d ud:0x%llx", mDisplay.getDrmCrtcID(), pPlane->fb_id, fixed16ToFloat(pPlane->src_x), fixed16ToFloat(pPlane->src_y), fixed16ToFloat(pPlane->src_w), fixed16ToFloat(pPlane->src_h), pPlane->crtc_x, pPlane->crtc_y, pPlane->crtc_w, pPlane->crtc_h, pPlane->user_data ); if ( pPlane->flags & DRM_MODE_PAGE_FLIP_EVENT ) { *pbRequestedFlip = true; } // Update properties. if ( pPlane->alpha != bAlpha ) { // Update alpha. pPlane->update_flag |= DRM_MODE_SET_DISPLAY_PLANE_UPDATE_ALPHA; pPlane->alpha = bAlpha; ALOGD_IF( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " Crtc %u alpha -> %d", mDisplay.getDrmCrtcID(), bAlpha ); } if ( pPlane->rrb2_enable != bRrb2 ) { // Update RRB2. pPlane->update_flag |= DRM_MODE_SET_DISPLAY_PLANE_UPDATE_RRB2; pPlane->rrb2_enable = bRrb2; ALOGD_IF( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " Crtc %u rrb2 -> %d", mDisplay.getDrmCrtcID(), bRrb2 ); } if ( pPlane->transform != drmTransform ) { // Update transform. pPlane->update_flag |= DRM_MODE_SET_DISPLAY_PLANE_UPDATE_TRANSFORM; pPlane->transform = drmTransform; ALOGD_IF( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " Crtc %u transform -> %d", mDisplay.getDrmCrtcID(), drmTransform ); } Log::alogd( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " %5s %u H:%p%s%s TX:%d S:%.1f,%.1f,%.1fx%.1f F:%d,%d,%dx%d %s%s", Drm::getObjectTypeString( pPlane->obj_type ), pPlane->obj_id, pLayer->getHandle(), pLayer->isDisabled() ? ":DISABLE" : "", pLayer->isEncrypted() ? ":DECRYPT" : "", pLayer->getTransform(), src.left, src.top, src.right - src.left, src.bottom - src.top, dst.left, dst.top, dst.right - dst.left, dst.bottom - dst.top, drmFlags & DRM_MODE_PAGE_FLIP_EVENT ? ":FLIPEVENT" : "", bIsBlanking ? ":BLANKING" : "" ); return true; } else { // We have set a NULL buffer => disable. bDisable = true; } } else { // We have no layer => disable. bDisable = ( pPlane->fb_id != 0 ); } if ( bDisable ) { // Clear state. pPlane->fb_id = 0; pPlane->crtc_x = 0; pPlane->crtc_y = 0; pPlane->crtc_w = 0; pPlane->crtc_h = 0; pPlane->src_x = 0; pPlane->src_y = 0; pPlane->src_w = 0; pPlane->src_h = 0; pPlane->user_data = 0; pPlane->flags = 0; pPlane->alpha = 0; pPlane->rrb2_enable = 0; pPlane->transform = 0; // Update presentation (disable). pPlane->update_flag |= DRM_MODE_SET_DISPLAY_PLANE_UPDATE_PRESENT; Log::alogd( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " Plane %u Disabled", pPlane->obj_id ); return true; } Log::alogd( DRM_PAGEFLIP_DEBUG, DRM_PFH_NAME " Plane %u Disabled (No Change)", pPlane->obj_id ); return false; } #if INTEL_HWC_INTERNAL_BUILD void DrmSetDisplayPageFlipHandler::validateSetDisplay( void ) { // Run some sanity checks. bool bHaveFlip = false; for( uint32_t p = 0; p < mNumPlanes; ++p ) { if ( mSetDisplay.update_flag & DRM_MODE_SET_DISPLAY_UPDATE_PLANE( p ) ) { // If plane is marked for update then we must have some plane-specific state flagged. if ( !mSetDisplay.plane[p].update_flag ) { ALOGE( "Plane %u has plane update flag set but no plane-specific dirty bits set", p ); ALOG_ASSERT( false ); } // If plane flags include flip event then we must have user data and also presentation flag. if ( mSetDisplay.plane[p].flags & DRM_MODE_PAGE_FLIP_EVENT ) { if ( mSetDisplay.plane[p].user_data == 0ULL ) { ALOGE( "Plane %u has DRM_MODE_PAGE_FLIP_EVENT set but user data is not set", p ); ALOG_ASSERT( false ); } if ( !(mSetDisplay.plane[p].update_flag & DRM_MODE_SET_DISPLAY_PLANE_UPDATE_PRESENT ) ) { ALOGE( "Plane %u has DRM_MODE_PAGE_FLIP_EVENT set but presentation flag is not set", p ); ALOG_ASSERT( false ); } bHaveFlip = true; } } else { // If plane is not marked for update then we must not have any plane-specific update flag. if ( mSetDisplay.plane[p].update_flag & DRM_MODE_SET_DISPLAY_PLANE_UPDATE_PRESENT ) { ALOGE( "Plane %u is not flagged for update but has plane-specific update flag set", p ); ALOG_ASSERT( false ); } // If plane is not marked for update then if it is enabled then we must not have any plane-specific state flaggged. if ( mSetDisplay.plane[p].fb_id && ( mSetDisplay.plane[p].update_flag & ~DRM_MODE_SET_DISPLAY_PLANE_UPDATE_PRESENT ) ) { ALOGE( "Plane %u is enabled but is not flagged for update and has plane-specific dirty bits set", p ); ALOG_ASSERT( false ); } if ( mSetDisplay.plane[p].flags & DRM_MODE_PAGE_FLIP_EVENT ) { ALOGE( "Plane %u is not flagged for update but has DRM_MODE_PAGE_FLIP_EVENT set", p ); ALOG_ASSERT( false ); } if ( mSetDisplay.plane[p].user_data != 0ULL ) { ALOGE( "Plane %u is not flagged for update but has user_data set", p ); ALOG_ASSERT( false ); } } } if ( !bHaveFlip ) { // This can occur if we have no fbs. ALOGE( "Did not set DRM_MODE_PAGE_FLIP_EVENT for any active presented plane" ); } } #endif }; // namespace hwc }; // namespace ufo }; // namespace intel #endif
37.955479
130
0.572995
intel
5843439eade84033f422e6f86c98ec44d44fd90a
4,781
cpp
C++
src/shapes/sphere.cpp
guerarda/rt1w
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
[ "MIT" ]
null
null
null
src/shapes/sphere.cpp
guerarda/rt1w
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
[ "MIT" ]
null
null
null
src/shapes/sphere.cpp
guerarda/rt1w
2fa13326e0a745214fb1a9fdc49a345c1407b6f3
[ "MIT" ]
null
null
null
#include "shapes/sphere.hpp" #include "rt1w/efloat.hpp" #include "rt1w/error.h" #include "rt1w/interaction.hpp" #include "rt1w/params.hpp" #include "rt1w/ray.hpp" #include "rt1w/sampling.hpp" #include "rt1w/transform.hpp" #include "rt1w/utils.hpp" #include "rt1w/value.hpp" static inline bool SphereQuadratic(const Ray &r, const v3f &oError, const v3f &dError, float radius, EFloat &t0, EFloat &t1) { EFloat ox = { r.org().x, oError.x }; EFloat oy = { r.org().y, oError.y }; EFloat oz = { r.org().z, oError.z }; EFloat dx = { r.dir().x, dError.x }; EFloat dy = { r.dir().y, dError.y }; EFloat dz = { r.dir().z, dError.z }; EFloat a = dx * dx + dy * dy + dz * dz; EFloat b = 2.f * (dx * ox + dy * oy + dz * oz); EFloat c = ox * ox + oy * oy + oz * oz - radius * radius; return Quadratic(a, b, c, t0, t1); } struct _Sphere : Sphere { _Sphere(const Transform &t, float r) : m_worldToObj(t), m_box(Inverse(t)(bounds3f{ -v3f{ r, r, r }, v3f{ r, r, r } })), m_radius(r) {} bool intersect(const Ray &r, Interaction &isect) const override; bool qIntersect(const Ray &r) const override; float area() const override { return (float)(4. * Pi * m_radius * m_radius); } bounds3f bounds() const override { return m_box; } Transform worldToObj() const override { return m_worldToObj; } Interaction sample(const v2f &u) const override; float pdf() const override { return 1.f / area(); } Interaction sample(const Interaction &ref, const v2f &u) const override; float pdf(const Interaction &ref, const v3f &wi) const override; float radius() const override { return m_radius; } Transform m_worldToObj; bounds3f m_box; float m_radius; }; bool _Sphere::intersect(const Ray &ray, Interaction &isect) const { v3f oError, dError; Ray r = m_worldToObj(ray, oError, dError); EFloat t0, t1; if (!SphereQuadratic(r, oError, dError, m_radius, t0, t1)) { return false; } EFloat t = t0.lo() > .0f && t0.hi() < r.max() ? t0 : t1; if (t.lo() <= .0f || t.hi() >= r.max()) { return false; } isect.t = (float)t; isect.p = r(isect.t); isect.n = Normalize(isect.p); isect.wo = -r.dir(); /* Reproject p onto the sphere */ isect.p *= m_radius / isect.p.length(); isect.error = gamma(5) * Abs(isect.p); /* Compute sphere uv */ v3f p = isect.n; double theta = std::acos(Clamp(p.y, -1.0, 1.0)); double phi = std::atan2(p.x, p.z); phi = phi < .0 ? phi + 2 * Pi : phi; isect.uv.x = (float)(phi / (2.0 * Pi)); isect.uv.y = (float)(theta / Pi); /* Compute dp/du & dp/dv */ double d = std::sqrt(p.x * p.x + p.z * p.z); double sinPhi = p.x / d; double cosPhi = p.z / d; isect.dpdu = { (float)(2.0 * Pi * p.z), 0.0, (float)(-2.0 * Pi * p.x) }; isect.dpdv = v3f{ (float)(Pi * p.y * sinPhi), (float)(Pi * -d), (float)(Pi * p.y * cosPhi) }; /* Shading Geometry */ isect.shading.n = isect.n; isect.shading.dpdu = isect.dpdu; isect.shading.dpdv = isect.dpdv; isect = Inverse(m_worldToObj)(isect); return true; } bool _Sphere::qIntersect(const Ray &ray) const { v3f oError, dError; Ray r = m_worldToObj(ray, oError, dError); EFloat t0, t1; if (SphereQuadratic(r, oError, dError, m_radius, t0, t1)) { EFloat t = t0.lo() > .0f && t0.hi() < r.max() ? t0 : t1; if (t.lo() > .0f && t.hi() < r.max()) { return true; } } return false; } Interaction _Sphere::sample(const v2f &u) const { Interaction it; it.p = m_radius * UniformSampleSphere(u); it.n = Normalize(it.p); it.p = Mulp(Inverse(m_worldToObj), it.p); it.n = Muln(Inverse(m_worldToObj), it.n); return it; } Interaction _Sphere::sample(const Interaction &, const v2f &u) const { return sample(u); } float _Sphere::pdf(const Interaction &ref, const v3f &wi) const { Ray r = SpawnRay(ref, wi); Interaction isect; if (!intersect(r, isect)) { return .0f; } return DistanceSquared(ref.p, isect.p) / (AbsDot(isect.n, -wi) * area()); } #pragma mark - Static constructors sptr<Sphere> Sphere::create(const Transform &worldToObj, float radius) { return std::make_shared<_Sphere>(worldToObj, radius); } sptr<Sphere> Sphere::create(const sptr<Params> &p) { float radius = Params::f32(p, "radius", 1.f); m44f mat = Params::matrix44f(p, "transform", m44f_identity()); Transform t = Transform(mat); return Sphere::create(t, radius); }
28.289941
82
0.568919
guerarda
5844f58f7f9da3d7690c64d5e7f42f06d081b46e
4,647
cpp
C++
src/annlib/training_buffer.cpp
mirkoruether/ann-cpp
7b7aae3f59b0ab82b4a83c4705f7025077b8bfd5
[ "MIT" ]
null
null
null
src/annlib/training_buffer.cpp
mirkoruether/ann-cpp
7b7aae3f59b0ab82b4a83c4705f7025077b8bfd5
[ "MIT" ]
null
null
null
src/annlib/training_buffer.cpp
mirkoruether/ann-cpp
7b7aae3f59b0ab82b4a83c4705f7025077b8bfd5
[ "MIT" ]
null
null
null
#include "training_buffer.h" #include "mat_arr_math.h" using namespace annlib; training_buffer::training_buffer(training_buffer* buf, unsigned start, unsigned count) : mini_batch_size(count) { for (auto& act : buf->activations) { activations.emplace_back(act.get_mats(start, count)); } for (auto& err : buf->errors) { errors.emplace_back(err.get_mats(start, count)); } for (auto& lb : buf->lbufs) { lbufs.emplace_back(lb.get_part(start, count)); } } unsigned training_buffer::layer_count() const { return static_cast<unsigned>(lbufs.size()); } mat_arr* training_buffer::in(unsigned layer_no) { return &activations[layer_no]; } mat_arr* training_buffer::out(unsigned layer_no) { return &activations[layer_no + 1]; } mat_arr* training_buffer::error(unsigned layer_no) { return &errors[layer_no]; } mat_arr* training_buffer::sol() { return &errors.back(); } layer_buffer* training_buffer::lbuf(unsigned layer_no) { return &lbufs[layer_no]; } std::vector<training_buffer> training_buffer::do_split(unsigned part_count) { std::vector<training_buffer> partial_buffers; const unsigned part_size = mini_batch_size / part_count; const unsigned remainder = mini_batch_size % part_count; unsigned current_start = 0; for (unsigned i = 0; i < part_count; i++) { const unsigned current_part_size = i < remainder ? part_size + 1 : part_size; partial_buffers.emplace_back(this, current_start, current_part_size); current_start += current_part_size; } return partial_buffers; } training_buffer::training_buffer(unsigned mini_batch_size, std::vector<unsigned> sizes) : mini_batch_size(mini_batch_size) { const auto layer_count = static_cast<unsigned>(sizes.size() - 1); activations.emplace_back(mini_batch_size, 1, sizes[0]); for (unsigned i = 1; i < layer_count + 1; i++) { activations.emplace_back(mini_batch_size, 1, sizes[i]); errors.emplace_back(mini_batch_size, 1, sizes[i]); } for (unsigned i = 0; i < layer_count; i++) { lbufs.emplace_back(mini_batch_size, activations[i], activations[i + 1], errors[i]); } } void layer_buffer::add_mini_batch_size(const std::string& key, unsigned rows, unsigned cols) { add(key, mini_batch_size, rows, cols, true); } void layer_buffer::add_single(const std::string& key, unsigned rows, unsigned cols) { add_custom_count(key, 1, rows, cols); } layer_buffer::layer_buffer(unsigned mini_batch_size, mat_arr in, mat_arr out, mat_arr error) : mini_batch_size(mini_batch_size), in(std::move(in)), out(std::move(out)), error(std::move(error)) { } void layer_buffer::add_custom_count(const std::string& key, std::array<unsigned, 3> dim) { add_custom_count(key, dim[0], dim[1], dim[2]); } void layer_buffer::add_custom_count(const std::string& key, unsigned count, unsigned rows, unsigned cols) { add(key, count, rows, cols, false); } buf::buf(bool split, unsigned count, unsigned rows, unsigned cols) : split(split), mat(count, rows, cols) { } buf::buf(bool split, mat_arr mat) : split(split), mat(std::move(mat)) { } opt_target::opt_target(mat_arr* target) : target(target), grad(target->count, target->rows, target->cols) { } void opt_target::init_opt_buffer(unsigned buffer_count) { for (unsigned i = 0; i < buffer_count; i++) { opt_buf.emplace_back(target->count, target->rows, target->cols); } } void layer_buffer::add(const std::string& key, unsigned count, unsigned rows, unsigned cols, bool split) { m[key] = std::make_shared<buf>(split, count, rows, cols); } void layer_buffer::add(const std::string& key, mat_arr mat, bool split) { m[key] = std::make_shared<buf>(split, std::move(mat)); } void layer_buffer::remove(const std::string& key) { m.erase(key); } mat_arr layer_buffer::get_val(const std::string& key) { return m[key]->mat; } mat_arr* layer_buffer::get_ptr(const std::string& key) { return &m[key]->mat; } void layer_buffer::add_opt_target(mat_arr* target) { opt_targets.emplace_back(target); } void layer_buffer::init_opt_target_buffers(unsigned opt_buffer_count) { for (auto& e : opt_targets) { e.init_opt_buffer(opt_buffer_count); } } mat_arr* layer_buffer::get_grad_ptr(unsigned index) { return &opt_targets[index].grad; } layer_buffer layer_buffer::get_part(unsigned start, unsigned count) { layer_buffer res(count, in.get_mats(start, count), out.get_mats(start, count), error.get_mats(start, count)); for (const auto& e : m) { if (e.second->split) { res.add(e.first, e.second->mat.get_mats(start, count), true); } else { res.add(e.first, e.second->mat, false); } } return res; }
22.558252
105
0.711427
mirkoruether
5848d8168c31b51e78b0c8ea0422f46dc16cd2a8
265
cc
C++
aria/examples/bar.cc
gunhoon2/aria
5bb0ac5c14c88c14b3078ee4af800aa8ec1aaadf
[ "MIT" ]
null
null
null
aria/examples/bar.cc
gunhoon2/aria
5bb0ac5c14c88c14b3078ee4af800aa8ec1aaadf
[ "MIT" ]
null
null
null
aria/examples/bar.cc
gunhoon2/aria
5bb0ac5c14c88c14b3078ee4af800aa8ec1aaadf
[ "MIT" ]
null
null
null
// Copyright (c) 2017, Gunhoon Lee (gunhoon@gmail.com) #include "aria/examples/bar.h" #include <iostream> namespace aria { Bar::Bar() { std::cout << "Bar ctor.." << std::endl; } Bar::~Bar() { std::cout << "Bar dtor.." << std::endl; } } // namespace aria
14.722222
54
0.592453
gunhoon2
584abe4a2122eb6e93668529e399634992c7214e
1,245
hpp
C++
include/cppurses/widget/widgets/checkbox.hpp
jktjkt/CPPurses
652d702258db8fab55ae945f7bb38e0b7c29521b
[ "MIT" ]
null
null
null
include/cppurses/widget/widgets/checkbox.hpp
jktjkt/CPPurses
652d702258db8fab55ae945f7bb38e0b7c29521b
[ "MIT" ]
null
null
null
include/cppurses/widget/widgets/checkbox.hpp
jktjkt/CPPurses
652d702258db8fab55ae945f7bb38e0b7c29521b
[ "MIT" ]
null
null
null
#ifndef CPPURSES_WIDGET_WIDGETS_CHECKBOX_HPP #define CPPURSES_WIDGET_WIDGETS_CHECKBOX_HPP #include <cstddef> #include <cstdint> #include <signals/signals.hpp> #include <cppurses/painter/glyph.hpp> #include <cppurses/painter/glyph_string.hpp> #include <cppurses/system/mouse_data.hpp> #include <cppurses/widget/widget.hpp> namespace cppurses { /// On/Off state checkbox, using mouse input. class Checkbox : public Widget { public: explicit Checkbox(Glyph_string title = "", int padding = 3); void toggle(); bool is_checked() const; Glyph_string title() const; // Signals sig::Signal<void()> checked; sig::Signal<void()> unchecked; sig::Signal<void()> toggled; protected: bool paint_event() override; bool mouse_press_event(const Mouse_data& mouse) override; private: Glyph empty_box_{L'☐'}; Glyph checked_box_{L'☒'}; bool is_checked_{false}; Glyph_string title_; int padding_; }; void check(Checkbox& cb); void uncheck(Checkbox& cb); namespace slot { sig::Slot<void()> toggle(Checkbox& cb); sig::Slot<void()> check(Checkbox& cb); sig::Slot<void()> uncheck(Checkbox& cb); } // namespace slot } // namespace cppurses #endif // CPPURSES_WIDGET_WIDGETS_CHECKBOX_HPP
23.490566
64
0.713253
jktjkt
584e170ebe14efc0400153eaa30cdc1b49e1a7d8
2,666
cpp
C++
cpp/tests/openpaltests/src/ManagedPointerTestSuite.cpp
SensusDA/opendnp3
c9aab97279fa7461155fd583d3955853b3ad99a0
[ "Apache-2.0" ]
null
null
null
cpp/tests/openpaltests/src/ManagedPointerTestSuite.cpp
SensusDA/opendnp3
c9aab97279fa7461155fd583d3955853b3ad99a0
[ "Apache-2.0" ]
null
null
null
cpp/tests/openpaltests/src/ManagedPointerTestSuite.cpp
SensusDA/opendnp3
c9aab97279fa7461155fd583d3955853b3ad99a0
[ "Apache-2.0" ]
null
null
null
/** * Licensed to Green Energy Corp (www.greenenergycorp.com) under one or * more contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright ownership. * Green Energy Corp licenses this file to you 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. * * This project was forked on 01/01/2013 by Automatak, LLC and modifications * may have been made to this file. Automatak, LLC licenses these modifications * to you under the terms of the License. */ #include <catch.hpp> #include <openpal/container/ManagedPtr.h> using namespace openpal; #include <vector> #define SUITE(name) "ManagedPointerTestSuite - " name struct Flags { Flags(int x_, int y_) : x(x_), y(y_) {} int x; int y; }; TEST_CASE(SUITE("ManagedPointersCanCreatedViaPoinerToStack")) { Flags stack = { 4, 3 }; auto pFlags = ManagedPtr<Flags>::WrapperOnly(&stack); REQUIRE(pFlags->x == 4); REQUIRE(pFlags->y == 3); pFlags->x = 10; pFlags->y = 20; REQUIRE(pFlags->x == 10); REQUIRE(pFlags->y == 20); } TEST_CASE(SUITE("ContainerTypesLikeVectorCanHoldAMixtureOfManagedAndUnmanaged")) { std::vector<ManagedPtr<Flags>> container; Flags stack = { 4, 3 }; container.push_back(ManagedPtr<Flags>::WrapperOnly(&stack)); container.push_back(ManagedPtr<Flags>::WrapperOnly(&stack)); container.push_back(ManagedPtr<Flags>::Deleted(new Flags{ 10, 20 })); container.push_back(ManagedPtr<Flags>::Deleted(new Flags{ 30, 40 })); } TEST_CASE(SUITE("ManagedPointersCanBeDereferenced")) { auto pFlags = ManagedPtr<Flags>::Deleted(new Flags{ 4, 3 }); REQUIRE(pFlags->x == 4); REQUIRE(pFlags->y == 3); pFlags->x = 10; pFlags->y = 20; REQUIRE(pFlags->x == 10); REQUIRE(pFlags->y == 20); } TEST_CASE(SUITE("ManagedPointersCanBeMovementConstructed")) { auto pInt = ManagedPtr<int>::Deleted(new int); ManagedPtr<int> copy(std::move(pInt)); REQUIRE_FALSE(pInt.IsDefined()); REQUIRE(copy.IsDefined()); } TEST_CASE(SUITE("ManagedPointersCanBeMovementAssigned")) { auto pInt = ManagedPtr<int>::Deleted(new int); auto pInt2 = std::move(pInt); REQUIRE_FALSE(pInt.IsDefined()); REQUIRE(pInt2.IsDefined()); }
26.137255
80
0.723556
SensusDA
584f96c0ba024b5ad58956d1a91f0191a6e1b2c8
3,004
hpp
C++
include/continuable/detail/traversal/container-category.hpp
sTabishAzam/continuable
809f82673ad3458fe12b11fa6dee46d3cbcaf749
[ "MIT" ]
745
2017-02-27T22:17:27.000Z
2022-03-21T20:15:14.000Z
include/continuable/detail/traversal/container-category.hpp
sTabishAzam/continuable
809f82673ad3458fe12b11fa6dee46d3cbcaf749
[ "MIT" ]
45
2018-02-14T22:32:13.000Z
2022-02-09T14:56:09.000Z
include/continuable/detail/traversal/container-category.hpp
sTabishAzam/continuable
809f82673ad3458fe12b11fa6dee46d3cbcaf749
[ "MIT" ]
47
2017-03-07T17:24:13.000Z
2022-02-03T07:06:21.000Z
/* /~` _ _ _|_. _ _ |_ | _ \_,(_)| | | || ||_|(_||_)|(/_ https://github.com/Naios/continuable v4.1.0 Copyright(c) 2015 - 2020 Denis Blank <denis.blank at outlook dot com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **/ #ifndef CONTINUABLE_DETAIL_CONTAINER_CATEGORY_HPP_INCLUDED #define CONTINUABLE_DETAIL_CONTAINER_CATEGORY_HPP_INCLUDED #include <tuple> #include <type_traits> #include <continuable/detail/utility/traits.hpp> namespace cti { namespace detail { namespace traversal { /// Deduces to a true type if the given parameter T /// has a begin() and end() method. // TODO Find out whether we should use std::begin and std::end instead, which // could cause issues with plain arrays. template <typename T, typename = void> struct is_range : std::false_type {}; template <typename T> struct is_range<T, traits::void_t<decltype(std::declval<T>().begin() == std::declval<T>().end())>> : std::true_type {}; /// Deduces to a true type if the given parameter T /// is accessible through std::tuple_size. template <typename T, typename = void> struct is_tuple_like : std::false_type {}; template <typename T> struct is_tuple_like<T, traits::void_t<decltype(std::tuple_size<T>::value)>> : std::true_type {}; /// A tag for dispatching based on the tuple like /// or container properties of a type. /// /// This type deduces to a true_type if it has any category. template <bool IsContainer, bool IsTupleLike> struct container_category_tag : std::integral_constant<bool, IsContainer || IsTupleLike> {}; /// Deduces to the container_category_tag of the given type T. template <typename T> using container_category_of_t = container_category_tag<is_range<T>::value, is_tuple_like<T>::value>; } // namespace traversal } // namespace detail } // namespace cti #endif // CONTINUABLE_DETAIL_CONTAINER_CATEGORY_HPP_INCLUDED
39.012987
79
0.713049
sTabishAzam
585a8db0da616575e381bdefb6bb7a4707690ade
1,502
cpp
C++
hw4/src/medium.cpp
jrabasco/acg2015
419fd0fdf5293dda95ea0231cf6c6f4af5331120
[ "MIT" ]
null
null
null
hw4/src/medium.cpp
jrabasco/acg2015
419fd0fdf5293dda95ea0231cf6c6f4af5331120
[ "MIT" ]
null
null
null
hw4/src/medium.cpp
jrabasco/acg2015
419fd0fdf5293dda95ea0231cf6c6f4af5331120
[ "MIT" ]
null
null
null
/* This file is part of Nori, a simple educational ray tracer Copyright (c) 2012 by Wenzel Jakob and Steve Marschner. Nori is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License Version 3 as published by the Free Software Foundation. Nori is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <nori/medium.h> #include <nori/phase.h> NORI_NAMESPACE_BEGIN Medium::Medium() : m_phaseFunction(NULL) { } Medium::~Medium() { if (m_phaseFunction) delete m_phaseFunction; } void Medium::addChild(NoriObject *child) { switch (child->getClassType()) { case EPhaseFunction: if (m_phaseFunction) throw NoriException("Medium: tried to register multiple phase function instances!"); m_phaseFunction = static_cast<PhaseFunction *>(child); break; default: throw NoriException(QString("Medium::addChild(<%1>) is not supported!").arg( classTypeName(child->getClassType()))); } } void Medium::activate() { if (!m_phaseFunction) m_phaseFunction = static_cast<PhaseFunction *>( NoriObjectFactory::createInstance("isotropic", PropertyList())); } NORI_NAMESPACE_END
28.884615
88
0.731691
jrabasco
585aec9599f2b44a9fc6e914ba7a38d72528d475
10,982
cpp
C++
examples/src/jsonpointer_examples.cpp
bergmansj/jsoncons
11db194bd3f0e3e89f29b3447e28d131db242501
[ "BSL-1.0" ]
null
null
null
examples/src/jsonpointer_examples.cpp
bergmansj/jsoncons
11db194bd3f0e3e89f29b3447e28d131db242501
[ "BSL-1.0" ]
null
null
null
examples/src/jsonpointer_examples.cpp
bergmansj/jsoncons
11db194bd3f0e3e89f29b3447e28d131db242501
[ "BSL-1.0" ]
null
null
null
// Copyright 2017 Daniel Parker // Distributed under Boost license #include <jsoncons/json.hpp> #include <jsoncons_ext/jsonpointer/jsonpointer.hpp> namespace jp = jsoncons::jsonpointer; void jsonpointer_select_RFC6901() { // Example from RFC 6901 auto j = jsoncons::json::parse(R"( { "foo": ["bar", "baz"], "": 0, "a/b": 1, "c%d": 2, "e^f": 3, "g|h": 4, "i\\j": 5, "k\"l": 6, " ": 7, "m~n": 8 } )"); try { const jsoncons::json& result1 = jp::get(j, ""); std::cout << "(1) " << result1 << std::endl; const jsoncons::json& result2 = jp::get(j, "/foo"); std::cout << "(2) " << result2 << std::endl; const jsoncons::json& result3 = jp::get(j, "/foo/0"); std::cout << "(3) " << result3 << std::endl; const jsoncons::json& result4 = jp::get(j, "/"); std::cout << "(4) " << result4 << std::endl; const jsoncons::json& result5 = jp::get(j, "/a~1b"); std::cout << "(5) " << result5 << std::endl; const jsoncons::json& result6 = jp::get(j, "/c%d"); std::cout << "(6) " << result6 << std::endl; const jsoncons::json& result7 = jp::get(j, "/e^f"); std::cout << "(7) " << result7 << std::endl; const jsoncons::json& result8 = jp::get(j, "/g|h"); std::cout << "(8) " << result8 << std::endl; const jsoncons::json& result9 = jp::get(j, "/i\\j"); std::cout << "(9) " << result9 << std::endl; const jsoncons::json& result10 = jp::get(j, "/k\"l"); std::cout << "(10) " << result10 << std::endl; const jsoncons::json& result11 = jp::get(j, "/ "); std::cout << "(11) " << result11 << std::endl; const jsoncons::json& result12 = jp::get(j, "/m~0n"); std::cout << "(12) " << result12 << std::endl; } catch (const jp::jsonpointer_error& e) { std::cerr << e.what() << std::endl; } } void jsonpointer_contains() { // Example from RFC 6901 auto j = jsoncons::json::parse(R"( { "foo": ["bar", "baz"], "": 0, "a/b": 1, "c%d": 2, "e^f": 3, "g|h": 4, "i\\j": 5, "k\"l": 6, " ": 7, "m~n": 8 } )"); std::cout << "(1) " << jp::contains(j, "/foo/0") << std::endl; std::cout << "(2) " << jp::contains(j, "e^g") << std::endl; } void jsonpointer_select_author() { auto j = jsoncons::json::parse(R"( [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 } ] )"); // Using exceptions to report errors try { jsoncons::json result = jp::get(j, "/1/author"); std::cout << "(1) " << result << std::endl; } catch (const jp::jsonpointer_error& e) { std::cout << e.what() << std::endl; } // Using error codes to report errors std::error_code ec; const jsoncons::json& result = jp::get(j, "/0/title", ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << "(2) " << result << std::endl; } } void jsonpointer_add_member_to_object() { auto target = jsoncons::json::parse(R"( { "foo": "bar"} )"); std::error_code ec; jp::insert(target, "/baz", jsoncons::json("qux"), ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_add_element_to_array() { auto target = jsoncons::json::parse(R"( { "foo": [ "bar", "baz" ] } )"); std::error_code ec; jp::insert(target, "/foo/1", jsoncons::json("qux"), ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_add_element_to_end_array() { auto target = jsoncons::json::parse(R"( { "foo": [ "bar", "baz" ] } )"); std::error_code ec; jp::insert(target, "/foo/-", jsoncons::json("qux"), ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_insert_name_exists() { auto target = jsoncons::json::parse(R"( { "foo": "bar", "baz" : "abc"} )"); std::error_code ec; jp::insert(target, "/baz", jsoncons::json("qux"), ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_add_element_outside_range() { auto target = jsoncons::json::parse(R"( { "foo": [ "bar", "baz" ] } )"); std::error_code ec; jp::insert_or_assign(target, "/foo/3", jsoncons::json("qux"), ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_insert_or_assign_name_exists() { auto target = jsoncons::json::parse(R"( { "foo": "bar", "baz" : "abc"} )"); std::error_code ec; jp::insert_or_assign(target, "/baz", jsoncons::json("qux"), ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_remove_object_member() { auto target = jsoncons::json::parse(R"( { "foo": "bar", "baz" : "qux"} )"); std::error_code ec; jp::remove(target, "/baz", ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_remove_array_element() { auto target = jsoncons::json::parse(R"( { "foo": [ "bar", "qux", "baz" ] } )"); std::error_code ec; jp::remove(target, "/foo/1", ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_replace_object_value() { auto target = jsoncons::json::parse(R"( { "baz": "qux", "foo": "bar" } )"); std::error_code ec; jp::replace(target, "/baz", jsoncons::json("boo"), ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << target << std::endl; } } void jsonpointer_replace_array_value() { auto target = jsoncons::json::parse(R"( { "foo": [ "bar", "baz" ] } )"); std::error_code ec; jp::replace(target, "/foo/1", jsoncons::json("qux"), ec); if (ec) { std::cout << ec.message() << std::endl; } else { std::cout << pretty_print(target) << std::endl; } } void jsonpointer_error_example() { auto j = jsoncons::json::parse(R"( [ { "category": "reference", "author": "Nigel Rees", "title": "Sayings of the Century", "price": 8.95 }, { "category": "fiction", "author": "Evelyn Waugh", "title": "Sword of Honour", "price": 12.99 } ] )"); try { jsoncons::json result = jp::get(j, "/1/isbn"); std::cout << "succeeded?" << std::endl; std::cout << result << std::endl; } catch (const jp::jsonpointer_error& e) { std::cout << "Caught jsonpointer_error with category " << e.code().category().name() << ", code " << e.code().value() << " and message \"" << e.what() << "\"" << std::endl; } } void jsonpointer_get_examples() { { jsoncons::json j = jsoncons::json::array{"baz","foo"}; jsoncons::json& item = jp::get(j,"/0"); std::cout << "(1) " << item << std::endl; //std::vector<uint8_t> u; //cbor::encode_cbor(j,u); //for (auto c : u) //{ // std::cout << "0x" << std::hex << (int)c << ","; //} //std::cout << std::endl; } { const jsoncons::json j = jsoncons::json::array{"baz","foo"}; const jsoncons::json& item = jp::get(j,"/1"); std::cout << "(2) " << item << std::endl; } { jsoncons::json j = jsoncons::json::array{"baz","foo"}; std::error_code ec; jsoncons::json& item = jp::get(j,"/1",ec); std::cout << "(4) " << item << std::endl; } { const jsoncons::json j = jsoncons::json::array{"baz","foo"}; std::error_code ec; const jsoncons::json& item = jp::get(j,"/0",ec); std::cout << "(5) " << item << std::endl; } } void jsonpointer_address_example() { auto j = jsoncons::json::parse(R"( { "a/b": ["bar", "baz"], "m~n": ["foo", "qux"] } )"); jp::address addr; addr /= "m~n"; addr /= "1"; std::cout << "(1) " << addr << "\n\n"; std::cout << "(2)\n"; for (const auto& item : addr) { std::cout << item << "\n"; } std::cout << "\n"; jsoncons::json item = jp::get(j, addr); std::cout << "(3) " << item << "\n"; } void jsonpointer_address_iterator_example() { jp::address addr("/store/book/1/author"); std::cout << "(1) " << addr << "\n\n"; std::cout << "(2)\n"; for (const auto& token : addr) { std::cout << token << "\n"; } std::cout << "\n"; } void jsonpointer_address_append_tokens() { jp::address addr; addr /= "a/b"; addr /= ""; addr /= "m~n"; std::cout << "(1) " << addr << "\n\n"; std::cout << "(2)\n"; for (const auto& token : addr) { std::cout << token << "\n"; } std::cout << "\n"; } void jsonpointer_address_concatentae() { jp::address addr("/a~1b"); addr += jp::address("//m~0n"); std::cout << "(1) " << addr << "\n\n"; std::cout << "(2)\n"; for (const auto& token : addr) { std::cout << token << "\n"; } std::cout << "\n"; } void jsonpointer_examples() { std::cout << "\njsonpointer examples\n\n"; jsonpointer_select_author(); jsonpointer_address_example(); jsonpointer_select_RFC6901(); jsonpointer_add_member_to_object(); jsonpointer_add_element_to_array(); jsonpointer_add_element_to_end_array(); jsonpointer_add_element_outside_range(); jsonpointer_remove_object_member(); jsonpointer_remove_array_element(); jsonpointer_replace_object_value(); jsonpointer_replace_array_value(); jsonpointer_contains(); jsonpointer_error_example(); jsonpointer_insert_name_exists(); jsonpointer_insert_or_assign_name_exists(); jsonpointer_get_examples(); jsonpointer_address_iterator_example(); jsonpointer_address_append_tokens(); jsonpointer_address_concatentae(); }
23.12
93
0.490985
bergmansj
585b9624374e86b71ee3eecae40bcac3b41045de
798
hpp
C++
src/system/mainloop.hpp
ranjak/opengl-tutorial
fff192b9966c9e14d77b4becb9c205ea21a02069
[ "MIT" ]
2
2018-08-24T00:09:03.000Z
2019-08-25T23:03:11.000Z
src/system/mainloop.hpp
ranjak/opengl-tutorial
fff192b9966c9e14d77b4becb9c205ea21a02069
[ "MIT" ]
null
null
null
src/system/mainloop.hpp
ranjak/opengl-tutorial
fff192b9966c9e14d77b4becb9c205ea21a02069
[ "MIT" ]
3
2016-12-02T17:22:14.000Z
2018-05-08T11:34:56.000Z
#ifndef MAINLOOP_HPP #define MAINLOOP_HPP #include "window.hpp" #include "system.hpp" #include "tutorial.hpp" #include <string> #include <memory> class MainLoop { public: static const ogl::time TIMESTEP; static void requestExit(); MainLoop(); MainLoop(const MainLoop &) = delete; MainLoop& operator=(const MainLoop &) = delete; bool init(int width=640, int height=480, const std::string& title="OpenGL Window"); void run(); void setExit(); private: void updateStats(ogl::time frameTime); void logStats(); private: static MainLoop *instance; std::unique_ptr<Window> mMainWindow; std::unique_ptr<Tutorial> mTutorial; bool mExitRequested; bool mDoLogStats; ogl::time mMaxFrameTime; ogl::time mAccuFrameTimes; int mNumFrames; }; #endif // MAINLOOP_HPP
16.978723
85
0.716792
ranjak
5862afb7b1e1ceb3205573978b688bf3ba0fdcf3
110,605
cpp
C++
mysql_install/inc/mysql-connector-c++-1.1.4/driver/mysql_util.cpp
vkardon/dbstream
1e5eb9354a1fb05466a178d2275aecab4b7f8bdd
[ "MIT" ]
null
null
null
mysql_install/inc/mysql-connector-c++-1.1.4/driver/mysql_util.cpp
vkardon/dbstream
1e5eb9354a1fb05466a178d2275aecab4b7f8bdd
[ "MIT" ]
null
null
null
mysql_install/inc/mysql-connector-c++-1.1.4/driver/mysql_util.cpp
vkardon/dbstream
1e5eb9354a1fb05466a178d2275aecab4b7f8bdd
[ "MIT" ]
null
null
null
/* Copyright (c) 2008, 2014, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/C++ is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <string.h> #include <stdlib.h> #include <memory> #include <sstream> #include <cppconn/datatype.h> #include <cppconn/exception.h> #include "mysql_util.h" #include "mysql_debug.h" #include "nativeapi/native_connection_wrapper.h" #include "nativeapi/native_statement_wrapper.h" namespace sql { namespace mysql { namespace util { /* just for cases when we need to return const empty string reference */ const sql::SQLString EMPTYSTR(""); const sql::SQLString LOCALHOST("localhost"); /* {{{ throwSQLException -I- */ void throwSQLException(::sql::mysql::NativeAPI::NativeConnectionWrapper & proxy) { throw sql::SQLException(proxy.error(), proxy.sqlstate(), proxy.errNo()); } /* }}} */ /* {{{ throwSQLException -I- */ void throwSQLException(::sql::mysql::NativeAPI::NativeStatementWrapper & proxy) { throw sql::SQLException(proxy.error(), proxy.sqlstate(), proxy.errNo()); } /* }}} */ #define cppconn_mbcharlen_big5 NULL #define check_mb_big5 NULL #define cppconn_mbcharlen_ujis NULL #define check_mb_ujis NULL #define cppconn_mbcharlen_sjis NULL #define check_mb_sjis NULL #define cppconn_mbcharlen_euckr NULL #define check_mb_euckr NULL #define cppconn_mbcharlen_gb2312 NULL #define check_mb_gb2312 NULL #define cppconn_mbcharlen_gbk NULL #define check_mb_gbk NULL #define cppconn_mbcharlen_utf8 NULL #define check_mb_utf8_valid NULL #define cppconn_mbcharlen_ucs2 NULL #define check_mb_ucs2 NULL #define cppconn_mbcharlen_cp932 NULL #define check_mb_cp932 NULL #define cppconn_mbcharlen_eucjpms NULL #define check_mb_eucjpms NULL #define cppconn_mbcharlen_utf8 NULL #define check_mb_utf8_valid NULL #define cppconn_mbcharlen_utf8mb4 cppconn_mbcharlen_utf8 #define check_mb_utf8mb4_valid check_mb_utf8_valid #define cppconn_mbcharlen_utf16 NULL #define check_mb_utf16_valid NULL #define cppconn_mbcharlen_utf32 NULL #define check_mb_utf32_valid NULL /* {{{ our_charsets60 */ const OUR_CHARSET our_charsets60[] = { { 1, "big5","big5_chinese_ci", 1, 2, "", cppconn_mbcharlen_big5, check_mb_big5}, { 3, "dec8", "dec8_swedisch_ci", 1, 1, "", NULL, NULL}, { 4, "cp850", "cp850_general_ci", 1, 1, "", NULL, NULL}, { 6, "hp8", "hp8_english_ci", 1, 1, "", NULL, NULL}, { 7, "koi8r", "koi8r_general_ci", 1, 1, "", NULL, NULL}, { 8, "latin1", "latin1_swedish_ci", 1, 1, "", NULL, NULL}, { 9, "latin2", "latin2_general_ci", 1, 1, "", NULL, NULL}, { 10, "swe7", "swe7_swedish_ci", 1, 1, "", NULL, NULL}, { 11, "ascii", "ascii_general_ci", 1, 1, "", NULL, NULL}, { 12, "ujis", "ujis_japanese_ci", 1, 3, "", cppconn_mbcharlen_ujis, check_mb_ujis}, { 13, "sjis", "sjis_japanese_ci", 1, 2, "", cppconn_mbcharlen_sjis, check_mb_sjis}, { 16, "hebrew", "hebrew_general_ci", 1, 1, "", NULL, NULL}, { 18, "tis620", "tis620_thai_ci", 1, 1, "", NULL, NULL}, { 19, "euckr", "euckr_korean_ci", 1, 2, "", cppconn_mbcharlen_euckr, check_mb_euckr}, { 22, "koi8u", "koi8u_general_ci", 1, 1, "", NULL, NULL}, { 24, "gb2312", "gb2312_chinese_ci", 1, 2, "", cppconn_mbcharlen_gb2312, check_mb_gb2312}, { 25, "greek", "greek_general_ci", 1, 1, "", NULL, NULL}, { 26, "cp1250", "cp1250_general_ci", 1, 1, "", NULL, NULL}, { 28, "gbk", "gbk_chinese_ci", 1, 2, "", cppconn_mbcharlen_gbk, check_mb_gbk}, { 30, "latin5", "latin5_turkish_ci", 1, 1, "", NULL, NULL}, { 32, "armscii8", "armscii8_general_ci", 1, 1, "", NULL, NULL}, { 33, "utf8", "utf8_general_ci", 1, 3, "UTF-8 Unicode", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 35, "ucs2", "ucs2_general_ci", 2, 2, "UCS-2 Unicode", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 36, "cp866", "cp866_general_ci", 1, 1, "", NULL, NULL}, { 37, "keybcs2", "keybcs2_general_ci", 1, 1, "", NULL, NULL}, { 38, "macce", "macce_general_ci", 1, 1, "", NULL, NULL}, { 39, "macroman", "macroman_general_ci", 1, 1, "", NULL, NULL}, { 40, "cp852", "cp852_general_ci", 1, 1, "", NULL, NULL}, { 41, "latin7", "latin7_general_ci", 1, 1, "", NULL, NULL}, { 51, "cp1251", "cp1251_general_ci", 1, 1, "", NULL, NULL}, { 57, "cp1256", "cp1256_general_ci", 1, 1, "", NULL, NULL}, { 59, "cp1257", "cp1257_general_ci", 1, 1, "", NULL, NULL}, { 63, "binary", "binary", 1, 1, "", NULL, NULL}, { 92, "geostd8", "geostd8_general_ci", 1, 1, "", NULL, NULL}, { 95, "cp932", "cp932_japanese_ci", 1, 2, "", cppconn_mbcharlen_cp932, check_mb_cp932}, { 97, "eucjpms", "eucjpms_japanese_ci", 1, 3, "", cppconn_mbcharlen_eucjpms, check_mb_eucjpms}, { 2, "latin2", "latin2_czech_cs", 1, 1, "", NULL, NULL}, { 5, "latin1", "latin1_german_ci", 1, 1, "", NULL, NULL}, { 14, "cp1251", "cp1251_bulgarian_ci", 1, 1, "", NULL, NULL}, { 15, "latin1", "latin1_danish_ci", 1, 1, "", NULL, NULL}, { 17, "filename", "filename", 1, 5, "", NULL, NULL}, { 20, "latin7", "latin7_estonian_cs", 1, 1, "", NULL, NULL}, { 21, "latin2", "latin2_hungarian_ci", 1, 1, "", NULL, NULL}, { 23, "cp1251", "cp1251_ukrainian_ci", 1, 1, "", NULL, NULL}, { 27, "latin2", "latin2_croatian_ci", 1, 1, "", NULL, NULL}, { 29, "cp1257", "cp1257_lithunian_ci", 1, 1, "", NULL, NULL}, { 31, "latin1", "latin1_german2_ci", 1, 1, "", NULL, NULL}, { 34, "cp1250", "cp1250_czech_cs", 1, 1, "", NULL, NULL}, { 42, "latin7", "latin7_general_cs", 1, 1, "", NULL, NULL}, { 43, "macce", "macce_bin", 1, 1, "", NULL, NULL}, { 44, "cp1250", "cp1250_croatian_ci", 1, 1, "", NULL, NULL}, { 47, "latin1", "latin1_bin", 1, 1, "", NULL, NULL}, { 48, "latin1", "latin1_general_ci", 1, 1, "", NULL, NULL}, { 49, "latin1", "latin1_general_cs", 1, 1, "", NULL, NULL}, { 50, "cp1251", "cp1251_bin", 1, 1, "", NULL, NULL}, { 52, "cp1251", "cp1251_general_cs", 1, 1, "", NULL, NULL}, { 53, "macroman", "macroman_bin", 1, 1, "", NULL, NULL}, { 58, "cp1257", "cp1257_bin", 1, 1, "", NULL, NULL}, { 60, "armascii8", "armascii8_bin", 1, 1, "", NULL, NULL}, { 65, "ascii", "ascii_bin", 1, 1, "", NULL, NULL}, { 66, "cp1250", "cp1250_bin", 1, 1, "", NULL, NULL}, { 67, "cp1256", "cp1256_bin", 1, 1, "", NULL, NULL}, { 68, "cp866", "cp866_bin", 1, 1, "", NULL, NULL}, { 69, "dec8", "dec8_bin", 1, 1, "", NULL, NULL}, { 70, "greek", "greek_bin", 1, 1, "", NULL, NULL}, { 71, "hebrew", "hebrew_bin", 1, 1, "", NULL, NULL}, { 72, "hp8", "hp8_bin", 1, 1, "", NULL, NULL}, { 73, "keybcs2", "keybcs2_bin", 1, 1, "", NULL, NULL}, { 74, "koi8r", "koi8r_bin", 1, 1, "", NULL, NULL}, { 75, "koi8u", "koi8u_bin", 1, 1, "", NULL, NULL}, { 77, "latin2", "latin2_bin", 1, 1, "", NULL, NULL}, { 78, "latin5", "latin5_bin", 1, 1, "", NULL, NULL}, { 79, "latin7", "latin7_bin", 1, 1, "", NULL, NULL}, { 80, "cp850", "cp850_bin", 1, 1, "", NULL, NULL}, { 81, "cp852", "cp852_bin", 1, 1, "", NULL, NULL}, { 82, "swe7", "swe7_bin", 1, 1, "", NULL, NULL}, { 93, "geostd8", "geostd8_bin", 1, 1, "", NULL, NULL}, { 83, "utf8", "utf8_bin", 1, 3, "UTF-8 Unicode", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 84, "big5", "big5_bin", 1, 2, "", cppconn_mbcharlen_big5, check_mb_big5}, { 85, "euckr", "euckr_bin", 1, 2, "", cppconn_mbcharlen_euckr, check_mb_euckr}, { 86, "gb2312", "gb2312_bin", 1, 2, "", cppconn_mbcharlen_gb2312, check_mb_gb2312}, { 87, "gbk", "gbk_bin", 1, 2, "", cppconn_mbcharlen_gbk, check_mb_gbk}, { 88, "sjis", "sjis_bin", 1, 2, "", cppconn_mbcharlen_sjis, check_mb_sjis}, { 89, "tis620", "tis620_bin", 1, 1, "", NULL, NULL}, { 90, "ucs2", "ucs2_bin", 2, 2, "UCS-2 Unicode", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 91, "ujis", "ujis_bin", 1, 3, "", cppconn_mbcharlen_ujis, check_mb_ujis}, { 94, "latin1", "latin1_spanish_ci", 1, 1, "", NULL, NULL}, { 96, "cp932", "cp932_bin", 1, 2, "", cppconn_mbcharlen_cp932, check_mb_cp932}, { 99, "cp1250", "cp1250_polish_ci", 1, 1, "", NULL, NULL}, { 98, "eucjpms", "eucjpms_bin", 1, 3, "", cppconn_mbcharlen_eucjpms, check_mb_eucjpms}, { 128, "ucs2", "ucs2_unicode_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 129, "ucs2", "ucs2_icelandic_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 130, "ucs2", "ucs2_latvian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 131, "ucs2", "ucs2_romanian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 132, "ucs2", "ucs2_slovenian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 133, "ucs2", "ucs2_polish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 134, "ucs2", "ucs2_estonian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 135, "ucs2", "ucs2_spanish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 136, "ucs2", "ucs2_swedish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 137, "ucs2", "ucs2_turkish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 138, "ucs2", "ucs2_czech_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 139, "ucs2", "ucs2_danish_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 140, "ucs2", "ucs2_lithunian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 141, "ucs2", "ucs2_slovak_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 142, "ucs2", "ucs2_spanish2_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 143, "ucs2", "ucs2_roman_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 144, "ucs2", "ucs2_persian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 145, "ucs2", "ucs2_esperanto_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 146, "ucs2", "ucs2_hungarian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 147, "ucs2", "ucs2_sinhala_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 148, "ucs2", "ucs2_german2_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 149, "ucs2", "ucs2_croatian_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 150, "ucs2", "ucs2_unicode_520_ci", 2, 2, "", cppconn_mbcharlen_ucs2, check_mb_ucs2}, { 192, "utf8", "utf8_unicode_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 193, "utf8", "utf8_icelandic_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 194, "utf8", "utf8_latvian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 195, "utf8", "utf8_romanian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 196, "utf8", "utf8_slovenian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 197, "utf8", "utf8_polish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 198, "utf8", "utf8_estonian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 199, "utf8", "utf8_spanish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 200, "utf8", "utf8_swedish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 201, "utf8", "utf8_turkish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 202, "utf8", "utf8_czech_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 203, "utf8", "utf8_danish_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid }, { 204, "utf8", "utf8_lithunian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid }, { 205, "utf8", "utf8_slovak_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 206, "utf8", "utf8_spanish2_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 207, "utf8", "utf8_roman_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 208, "utf8", "utf8_persian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 209, "utf8", "utf8_esperanto_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 210, "utf8", "utf8_hungarian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 211, "utf8", "utf8_sinhala_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 212, "utf8", "utf8_german2_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 213, "utf8", "utf8_croatian_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 214, "utf8", "utf8_unicode_520_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 215, "utf8", "utf8_vietnamese_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 223, "utf8", "utf8_general_mysql500_ci", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 45, "utf8mb4", "utf8mb4_general_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 46, "utf8mb4", "utf8mb4_bin", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 224, "utf8mb4", "utf8mb4_unicode_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 225, "utf8mb4", "utf8mb4_icelandic_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 226, "utf8mb4", "utf8mb4_latvian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 227, "utf8mb4", "utf8mb4_romanian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 228, "utf8mb4", "utf8mb4_slovenian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 229, "utf8mb4", "utf8mb4_polish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 230, "utf8mb4", "utf8mb4_estonian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 231, "utf8mb4", "utf8mb4_spanish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 232, "utf8mb4", "utf8mb4_swedish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 233, "utf8mb4", "utf8mb4_turkish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 234, "utf8mb4", "utf8mb4_czech_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 235, "utf8mb4", "utf8mb4_danish_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 236, "utf8mb4", "utf8mb4_lithuanian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 237, "utf8mb4", "utf8mb4_slovak_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 238, "utf8mb4", "utf8mb4_spanish2_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 239, "utf8mb4", "utf8mb4_roman_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 240, "utf8mb4", "utf8mb4_persian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 241, "utf8mb4", "utf8mb4_esperanto_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 242, "utf8mb4", "utf8mb4_hungarian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 243, "utf8mb4", "utf8mb4_sinhala_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 244, "utf8mb4", "utf8mb4_german2_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 245, "utf8mb4", "utf8mb4_croatian_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 246, "utf8mb4", "utf8mb4_unicode_520_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, { 247, "utf8mb4", "utf8mb4_vietnamese_ci", 1, 4, "", cppconn_mbcharlen_utf8mb4, check_mb_utf8mb4_valid}, /*Should not really happen, but adding them */ { 254, "utf8", "utf8_general_cs", 1, 3, "", cppconn_mbcharlen_utf8, check_mb_utf8_valid}, { 101, "utf16", "utf16_unicode_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 102, "utf16", "utf16_icelandic_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 103, "utf16", "utf16_latvian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 104, "utf16", "utf16_romanian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 105, "utf16", "utf16_slovenian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 106, "utf16", "utf16_polish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 107, "utf16", "utf16_estonian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 108, "utf16", "utf16_spanish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 109, "utf16", "utf16_swedish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 110, "utf16", "utf16_turkish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 111, "utf16", "utf16_czech_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 112, "utf16", "utf16_danish_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 113, "utf16", "utf16_lithuanian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 114, "utf16", "utf16_slovak_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 115, "utf16", "utf16_spanish2_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 116, "utf16", "utf16_roman_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 117, "utf16", "utf16_persian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 118, "utf16", "utf16_esperanto_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 119, "utf16", "utf16_hungarian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 120, "utf16", "utf16_sinhala_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 121, "utf16", "utf16_german2_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 122, "utf16", "utf16_croatian_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 123, "utf16", "utf16_unicode_520_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 124, "utf16", "utf16_vietnamese_ci", 2, 4, "", cppconn_mbcharlen_utf16, check_mb_utf16_valid}, { 160, "utf32", "utf32_unicode_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 161, "utf32", "utf32_icelandic_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 162, "utf32", "utf32_latvian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 163, "utf32", "utf32_romanian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 164, "utf32", "utf32_slovenian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 165, "utf32", "utf32_polish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 166, "utf32", "utf32_estonian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 167, "utf32", "utf32_spanish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 168, "utf32", "utf32_swedish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 169, "utf32", "utf32_turkish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 170, "utf32", "utf32_czech_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 171, "utf32", "utf32_danish_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 172, "utf32", "utf32_lithuanian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 173, "utf32", "utf32_slovak_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 174, "utf32", "utf32_spanish2_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 175, "utf32", "utf32_roman_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 176, "utf32", "utf32_persian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 177, "utf32", "utf32_esperanto_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 178, "utf32", "utf32_hungarian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 179, "utf32", "utf32_sinhala_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 180, "utf32", "utf32_german2_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 181, "utf32", "utf32_croatian_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 182, "utf32", "utf32_unicode_520_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 183, "utf32", "utf32_vietnamese_ci", 4, 4, "", cppconn_mbcharlen_utf32, check_mb_utf32_valid}, { 0, NULL, NULL, 0, 0, NULL, NULL, NULL} }; /* }}} */ /* {{{ find_charset */ const OUR_CHARSET * find_charset(unsigned int charsetnr) { const OUR_CHARSET * c = our_charsets60; do { if (c->nr == charsetnr) { return c; } ++c; } while (c[0].nr != 0); return NULL; } /* }}} */ #define MAGIC_BINARY_CHARSET_NR 63 /* {{{ mysql_to_datatype() -I- */ int mysql_type_to_datatype(const MYSQL_FIELD * const field) { switch (field->type) { case MYSQL_TYPE_BIT: return sql::DataType::BIT; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: return sql::DataType::DECIMAL; case MYSQL_TYPE_TINY: return sql::DataType::TINYINT; case MYSQL_TYPE_SHORT: return sql::DataType::SMALLINT; case MYSQL_TYPE_INT24: return sql::DataType::MEDIUMINT; case MYSQL_TYPE_LONG: return sql::DataType::INTEGER; case MYSQL_TYPE_LONGLONG: return sql::DataType::BIGINT; case MYSQL_TYPE_FLOAT: return sql::DataType::REAL; case MYSQL_TYPE_DOUBLE: return sql::DataType::DOUBLE; case MYSQL_TYPE_NULL: return sql::DataType::SQLNULL; case MYSQL_TYPE_TIMESTAMP: return sql::DataType::TIMESTAMP; case MYSQL_TYPE_DATE: return sql::DataType::DATE; case MYSQL_TYPE_TIME: return sql::DataType::TIME; case MYSQL_TYPE_YEAR: return sql::DataType::YEAR; case MYSQL_TYPE_DATETIME: return sql::DataType::TIMESTAMP; case MYSQL_TYPE_TINY_BLOB:// should no appear over the wire { bool isBinary = (field->flags & BINARY_FLAG) && field->charsetnr == MAGIC_BINARY_CHARSET_NR; const sql::mysql::util::OUR_CHARSET * const cs = sql::mysql::util::find_charset(field->charsetnr); if (!cs) { std::ostringstream msg("Server sent unknown charsetnr ("); msg << field->charsetnr << ") . Please report"; throw SQLException(msg.str()); } return isBinary ? sql::DataType::VARBINARY : sql::DataType::VARCHAR; } case MYSQL_TYPE_MEDIUM_BLOB:// should no appear over the wire case MYSQL_TYPE_LONG_BLOB:// should no appear over the wire case MYSQL_TYPE_BLOB: { bool isBinary = (field->flags & BINARY_FLAG) && field->charsetnr == MAGIC_BINARY_CHARSET_NR; const sql::mysql::util::OUR_CHARSET * const cs = sql::mysql::util::find_charset(field->charsetnr); if (!cs) { std::ostringstream msg("Server sent unknown charsetnr ("); msg << field->charsetnr << ") . Please report"; throw SQLException(msg.str()); } return isBinary ? sql::DataType::LONGVARBINARY : sql::DataType::LONGVARCHAR; } case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_VAR_STRING: if (field->flags & SET_FLAG) { return sql::DataType::SET; } if (field->flags & ENUM_FLAG) { return sql::DataType::ENUM; } if ((field->flags & BINARY_FLAG) && field->charsetnr == MAGIC_BINARY_CHARSET_NR) { return sql::DataType::VARBINARY; } return sql::DataType::VARCHAR; case MYSQL_TYPE_STRING: if (field->flags & SET_FLAG) { return sql::DataType::SET; } if (field->flags & ENUM_FLAG) { return sql::DataType::ENUM; } if ((field->flags & BINARY_FLAG) && field->charsetnr == MAGIC_BINARY_CHARSET_NR) { return sql::DataType::BINARY; } return sql::DataType::CHAR; case MYSQL_TYPE_ENUM: /* This hould never happen - MYSQL_TYPE_ENUM is not sent over the wire, just used in the server */ return sql::DataType::ENUM; case MYSQL_TYPE_SET: /* This hould never happen - MYSQL_TYPE_SET is not sent over the wire, just used in the server */ return sql::DataType::SET; case MYSQL_TYPE_GEOMETRY: return sql::DataType::GEOMETRY; default: return sql::DataType::UNKNOWN; } } /* }}} */ /* {{{ mysql_to_datatype() -I- */ int mysql_string_type_to_datatype(const sql::SQLString & name) { /* I_S.COLUMNS is buggy, because it deflivers (float|double) unsigned but not (tinyint|smallint|mediumint|int|bigint) unsigned */ if (!name.compare("bit")) { return sql::DataType::BIT; } else if (!name.compare("decimal") || !name.compare("decimal unsigned")) { return sql::DataType::DECIMAL; } else if (!name.compare("tinyint") || !name.compare("tinyint unsigned")) { return sql::DataType::TINYINT; } else if (!name.compare("smallint") || !name.compare("smallint unsigned")) { return sql::DataType::SMALLINT; } else if (!name.compare("mediumint") || !name.compare("mediumint unsigned")) { return sql::DataType::MEDIUMINT; } else if (!name.compare("int") || !name.compare("int unsigned")) { return sql::DataType::INTEGER; } else if (!name.compare("bigint") || !name.compare("bigint unsigned")) { return sql::DataType::BIGINT; } else if (!name.compare("float") || !name.compare("float unsigned")) { return sql::DataType::REAL; } else if (!name.compare("double") || !name.compare("double unsigned")) { return sql::DataType::DOUBLE; } else if (!name.compare("timestamp")) { return sql::DataType::TIMESTAMP; } else if (!name.compare("date")) { return sql::DataType::DATE; } else if (!name.compare("time")) { return sql::DataType::TIME; } else if (!name.compare("year")) { return sql::DataType::YEAR; } else if (!name.compare("datetime")) { return sql::DataType::TIMESTAMP; } else if (!name.compare("tinytext")) { return sql::DataType::VARCHAR; } else if (!name.compare("mediumtext") || !name.compare("text") || !name.compare("longtext")) { return sql::DataType::LONGVARCHAR; } else if (!name.compare("tinyblob")) { return sql::DataType::VARBINARY; } else if (!name.compare("mediumblob") || !name.compare("blob") || !name.compare("longblob")) { return sql::DataType::LONGVARBINARY; } else if (!name.compare("char")) { return sql::DataType::CHAR; } else if (!name.compare("binary")) { return sql::DataType::BINARY; } else if (!name.compare("varchar")) { return sql::DataType::VARCHAR; } else if (!name.compare("varbinary")) { return sql::DataType::VARBINARY; } else if (!name.compare("enum")) { return sql::DataType::ENUM; } else if (!name.compare("set")) { return sql::DataType::SET; } else if (!name.compare("geometry")) { return sql::DataType::GEOMETRY; } else { return sql::DataType::UNKNOWN; } } /* }}} */ /* {{{ mysql_to_datatype() -I- */ const char * mysql_type_to_string(const MYSQL_FIELD * const field, boost::shared_ptr< sql::mysql::MySQL_DebugLogger > & l) { CPP_ENTER_WL(l, "mysql_type_to_string"); bool isUnsigned = (field->flags & UNSIGNED_FLAG) != 0; bool isZerofill = (field->flags & ZEROFILL_FLAG) != 0; switch (field->type) { case MYSQL_TYPE_BIT: return "BIT"; case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: return isUnsigned ? (isZerofill? "DECIMAL UNSIGNED ZEROFILL" : "DECIMAL UNSIGNED"): "DECIMAL"; case MYSQL_TYPE_TINY: return isUnsigned ? (isZerofill? "TINYINT UNSIGNED ZEROFILL" : "TINYINT UNSIGNED"): "TINYINT"; case MYSQL_TYPE_SHORT: return isUnsigned ? (isZerofill? "SMALLINT UNSIGNED ZEROFILL" : "SMALLINT UNSIGNED"): "SMALLINT"; case MYSQL_TYPE_LONG: return isUnsigned ? (isZerofill? "INT UNSIGNED ZEROFILL" : "INT UNSIGNED"): "INT"; case MYSQL_TYPE_FLOAT: return isUnsigned ? (isZerofill? "FLOAT UNSIGNED ZEROFILL" : "FLOAT UNSIGNED"): "FLOAT"; case MYSQL_TYPE_DOUBLE: return isUnsigned ? (isZerofill? "DOUBLE UNSIGNED ZEROFILL" : "DOUBLE UNSIGNED"): "DOUBLE"; case MYSQL_TYPE_NULL: return "NULL"; case MYSQL_TYPE_TIMESTAMP: return "TIMESTAMP"; case MYSQL_TYPE_LONGLONG: return isUnsigned ? (isZerofill? "BIGINT UNSIGNED ZEROFILL" : "BIGINT UNSIGNED") : "BIGINT"; case MYSQL_TYPE_INT24: return isUnsigned ? (isZerofill? "MEDIUMINT UNSIGNED ZEROFILL" : "MEDIUMINT UNSIGNED") : "MEDIUMINT"; case MYSQL_TYPE_DATE: return "DATE"; case MYSQL_TYPE_TIME: return "TIME"; case MYSQL_TYPE_DATETIME: return "DATETIME"; case MYSQL_TYPE_TINY_BLOB:// should no appear over the wire { bool isBinary = field->charsetnr == MAGIC_BINARY_CHARSET_NR; unsigned int char_maxlen = 1; if (!isBinary) { const sql::mysql::util::OUR_CHARSET * cset = find_charset(field->charsetnr); if (!cset) { std::ostringstream msg("Server sent unknown charsetnr ("); msg << field->charsetnr << ") . Please report"; throw SQLException(msg.str()); } char_maxlen = cset->char_maxlen; } CPP_INFO_FMT("char_maxlen=%u field->length=%lu", char_maxlen, field->length); return isBinary? "TINYBLOB":"TINYTEXT"; } case MYSQL_TYPE_MEDIUM_BLOB:// should no appear over the wire { bool isBinary = field->charsetnr == MAGIC_BINARY_CHARSET_NR; unsigned int char_maxlen = 1; if (!isBinary) { const sql::mysql::util::OUR_CHARSET * cset = find_charset(field->charsetnr); if (!cset) { std::ostringstream msg("Server sent unknown charsetnr ("); msg << field->charsetnr << ") . Please report"; throw SQLException(msg.str()); } char_maxlen = cset->char_maxlen; } CPP_INFO_FMT("char_maxlen=%u field->length=%lu", char_maxlen, field->length); return isBinary? "MEDIUMBLOB":"MEDIUMTEXT"; } case MYSQL_TYPE_LONG_BLOB:// should no appear over the wire { bool isBinary = field->charsetnr == MAGIC_BINARY_CHARSET_NR; unsigned int char_maxlen = 1; if (!isBinary) { const sql::mysql::util::OUR_CHARSET * cset = find_charset(field->charsetnr); if (!cset) { std::ostringstream msg("Server sent unknown charsetnr ("); msg << field->charsetnr << ") . Please report"; throw SQLException(msg.str()); } char_maxlen = cset->char_maxlen; } CPP_INFO_FMT("char_maxlen=%u field->length=%lu", char_maxlen, field->length); return isBinary? "LONGBLOB":"LONGTEXT"; } case MYSQL_TYPE_BLOB: { bool isBinary= field->charsetnr == MAGIC_BINARY_CHARSET_NR; unsigned int char_maxlen = 1; if (!isBinary) { const sql::mysql::util::OUR_CHARSET * cset = find_charset(field->charsetnr); if (!cset) { std::ostringstream msg("Server sent unknown charsetnr ("); msg << field->charsetnr << ") . Please report"; throw SQLException(msg.str()); } char_maxlen = cset->char_maxlen; } CPP_INFO_FMT("char_maxlen=%u field->length=%lu", char_maxlen, field->length); return isBinary? "BLOB":"TEXT"; } case MYSQL_TYPE_VARCHAR: case MYSQL_TYPE_VAR_STRING: if (field->flags & ENUM_FLAG) { return "ENUM"; } if (field->flags & SET_FLAG) { return "SET"; } if (field->charsetnr == MAGIC_BINARY_CHARSET_NR) { return "VARBINARY"; } return "VARCHAR"; case MYSQL_TYPE_STRING: if (field->flags & ENUM_FLAG) { return "ENUM"; } if (field->flags & SET_FLAG) { return "SET"; } if ((field->flags & BINARY_FLAG) && field->charsetnr == MAGIC_BINARY_CHARSET_NR) { return "BINARY"; } return "CHAR"; case MYSQL_TYPE_ENUM: /* This should never happen */ return "ENUM"; case MYSQL_TYPE_YEAR: return "YEAR"; case MYSQL_TYPE_SET: /* This should never happen */ return "SET"; case MYSQL_TYPE_GEOMETRY: return "GEOMETRY"; default: return "UNKNOWN"; } } /* }}} */ /* The following code is from libmysql and is under the following license */ /* Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. The MySQL Connector/C++ is licensed under the terms of the GPLv2 <http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>, like most MySQL Connectors. There are special exceptions to the terms and conditions of the GPLv2 as it is applied to this software, see the FLOSS License Exception <http://www.mysql.com/about/legal/licensing/foss-exception.html>. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ /* UTF8 according RFC 2279 */ /* Written by Alexander Barkov <bar@udm.net> */ typedef struct unicase_info_st { uint16_t toupper; uint16_t tolower; uint16_t sort; } MY_UNICASE_INFO; static MY_UNICASE_INFO plane00[]={ {0x0000,0x0000,0x0000}, {0x0001,0x0001,0x0001}, {0x0002,0x0002,0x0002}, {0x0003,0x0003,0x0003}, {0x0004,0x0004,0x0004}, {0x0005,0x0005,0x0005}, {0x0006,0x0006,0x0006}, {0x0007,0x0007,0x0007}, {0x0008,0x0008,0x0008}, {0x0009,0x0009,0x0009}, {0x000A,0x000A,0x000A}, {0x000B,0x000B,0x000B}, {0x000C,0x000C,0x000C}, {0x000D,0x000D,0x000D}, {0x000E,0x000E,0x000E}, {0x000F,0x000F,0x000F}, {0x0010,0x0010,0x0010}, {0x0011,0x0011,0x0011}, {0x0012,0x0012,0x0012}, {0x0013,0x0013,0x0013}, {0x0014,0x0014,0x0014}, {0x0015,0x0015,0x0015}, {0x0016,0x0016,0x0016}, {0x0017,0x0017,0x0017}, {0x0018,0x0018,0x0018}, {0x0019,0x0019,0x0019}, {0x001A,0x001A,0x001A}, {0x001B,0x001B,0x001B}, {0x001C,0x001C,0x001C}, {0x001D,0x001D,0x001D}, {0x001E,0x001E,0x001E}, {0x001F,0x001F,0x001F}, {0x0020,0x0020,0x0020}, {0x0021,0x0021,0x0021}, {0x0022,0x0022,0x0022}, {0x0023,0x0023,0x0023}, {0x0024,0x0024,0x0024}, {0x0025,0x0025,0x0025}, {0x0026,0x0026,0x0026}, {0x0027,0x0027,0x0027}, {0x0028,0x0028,0x0028}, {0x0029,0x0029,0x0029}, {0x002A,0x002A,0x002A}, {0x002B,0x002B,0x002B}, {0x002C,0x002C,0x002C}, {0x002D,0x002D,0x002D}, {0x002E,0x002E,0x002E}, {0x002F,0x002F,0x002F}, {0x0030,0x0030,0x0030}, {0x0031,0x0031,0x0031}, {0x0032,0x0032,0x0032}, {0x0033,0x0033,0x0033}, {0x0034,0x0034,0x0034}, {0x0035,0x0035,0x0035}, {0x0036,0x0036,0x0036}, {0x0037,0x0037,0x0037}, {0x0038,0x0038,0x0038}, {0x0039,0x0039,0x0039}, {0x003A,0x003A,0x003A}, {0x003B,0x003B,0x003B}, {0x003C,0x003C,0x003C}, {0x003D,0x003D,0x003D}, {0x003E,0x003E,0x003E}, {0x003F,0x003F,0x003F}, {0x0040,0x0040,0x0040}, {0x0041,0x0061,0x0041}, {0x0042,0x0062,0x0042}, {0x0043,0x0063,0x0043}, {0x0044,0x0064,0x0044}, {0x0045,0x0065,0x0045}, {0x0046,0x0066,0x0046}, {0x0047,0x0067,0x0047}, {0x0048,0x0068,0x0048}, {0x0049,0x0069,0x0049}, {0x004A,0x006A,0x004A}, {0x004B,0x006B,0x004B}, {0x004C,0x006C,0x004C}, {0x004D,0x006D,0x004D}, {0x004E,0x006E,0x004E}, {0x004F,0x006F,0x004F}, {0x0050,0x0070,0x0050}, {0x0051,0x0071,0x0051}, {0x0052,0x0072,0x0052}, {0x0053,0x0073,0x0053}, {0x0054,0x0074,0x0054}, {0x0055,0x0075,0x0055}, {0x0056,0x0076,0x0056}, {0x0057,0x0077,0x0057}, {0x0058,0x0078,0x0058}, {0x0059,0x0079,0x0059}, {0x005A,0x007A,0x005A}, {0x005B,0x005B,0x005B}, {0x005C,0x005C,0x005C}, {0x005D,0x005D,0x005D}, {0x005E,0x005E,0x005E}, {0x005F,0x005F,0x005F}, {0x0060,0x0060,0x0060}, {0x0041,0x0061,0x0041}, {0x0042,0x0062,0x0042}, {0x0043,0x0063,0x0043}, {0x0044,0x0064,0x0044}, {0x0045,0x0065,0x0045}, {0x0046,0x0066,0x0046}, {0x0047,0x0067,0x0047}, {0x0048,0x0068,0x0048}, {0x0049,0x0069,0x0049}, {0x004A,0x006A,0x004A}, {0x004B,0x006B,0x004B}, {0x004C,0x006C,0x004C}, {0x004D,0x006D,0x004D}, {0x004E,0x006E,0x004E}, {0x004F,0x006F,0x004F}, {0x0050,0x0070,0x0050}, {0x0051,0x0071,0x0051}, {0x0052,0x0072,0x0052}, {0x0053,0x0073,0x0053}, {0x0054,0x0074,0x0054}, {0x0055,0x0075,0x0055}, {0x0056,0x0076,0x0056}, {0x0057,0x0077,0x0057}, {0x0058,0x0078,0x0058}, {0x0059,0x0079,0x0059}, {0x005A,0x007A,0x005A}, {0x007B,0x007B,0x007B}, {0x007C,0x007C,0x007C}, {0x007D,0x007D,0x007D}, {0x007E,0x007E,0x007E}, {0x007F,0x007F,0x007F}, {0x0080,0x0080,0x0080}, {0x0081,0x0081,0x0081}, {0x0082,0x0082,0x0082}, {0x0083,0x0083,0x0083}, {0x0084,0x0084,0x0084}, {0x0085,0x0085,0x0085}, {0x0086,0x0086,0x0086}, {0x0087,0x0087,0x0087}, {0x0088,0x0088,0x0088}, {0x0089,0x0089,0x0089}, {0x008A,0x008A,0x008A}, {0x008B,0x008B,0x008B}, {0x008C,0x008C,0x008C}, {0x008D,0x008D,0x008D}, {0x008E,0x008E,0x008E}, {0x008F,0x008F,0x008F}, {0x0090,0x0090,0x0090}, {0x0091,0x0091,0x0091}, {0x0092,0x0092,0x0092}, {0x0093,0x0093,0x0093}, {0x0094,0x0094,0x0094}, {0x0095,0x0095,0x0095}, {0x0096,0x0096,0x0096}, {0x0097,0x0097,0x0097}, {0x0098,0x0098,0x0098}, {0x0099,0x0099,0x0099}, {0x009A,0x009A,0x009A}, {0x009B,0x009B,0x009B}, {0x009C,0x009C,0x009C}, {0x009D,0x009D,0x009D}, {0x009E,0x009E,0x009E}, {0x009F,0x009F,0x009F}, {0x00A0,0x00A0,0x00A0}, {0x00A1,0x00A1,0x00A1}, {0x00A2,0x00A2,0x00A2}, {0x00A3,0x00A3,0x00A3}, {0x00A4,0x00A4,0x00A4}, {0x00A5,0x00A5,0x00A5}, {0x00A6,0x00A6,0x00A6}, {0x00A7,0x00A7,0x00A7}, {0x00A8,0x00A8,0x00A8}, {0x00A9,0x00A9,0x00A9}, {0x00AA,0x00AA,0x00AA}, {0x00AB,0x00AB,0x00AB}, {0x00AC,0x00AC,0x00AC}, {0x00AD,0x00AD,0x00AD}, {0x00AE,0x00AE,0x00AE}, {0x00AF,0x00AF,0x00AF}, {0x00B0,0x00B0,0x00B0}, {0x00B1,0x00B1,0x00B1}, {0x00B2,0x00B2,0x00B2}, {0x00B3,0x00B3,0x00B3}, {0x00B4,0x00B4,0x00B4}, {0x039C,0x00B5,0x039C}, {0x00B6,0x00B6,0x00B6}, {0x00B7,0x00B7,0x00B7}, {0x00B8,0x00B8,0x00B8}, {0x00B9,0x00B9,0x00B9}, {0x00BA,0x00BA,0x00BA}, {0x00BB,0x00BB,0x00BB}, {0x00BC,0x00BC,0x00BC}, {0x00BD,0x00BD,0x00BD}, {0x00BE,0x00BE,0x00BE}, {0x00BF,0x00BF,0x00BF}, {0x00C0,0x00E0,0x0041}, {0x00C1,0x00E1,0x0041}, {0x00C2,0x00E2,0x0041}, {0x00C3,0x00E3,0x0041}, {0x00C4,0x00E4,0x0041}, {0x00C5,0x00E5,0x0041}, {0x00C6,0x00E6,0x00C6}, {0x00C7,0x00E7,0x0043}, {0x00C8,0x00E8,0x0045}, {0x00C9,0x00E9,0x0045}, {0x00CA,0x00EA,0x0045}, {0x00CB,0x00EB,0x0045}, {0x00CC,0x00EC,0x0049}, {0x00CD,0x00ED,0x0049}, {0x00CE,0x00EE,0x0049}, {0x00CF,0x00EF,0x0049}, {0x00D0,0x00F0,0x00D0}, {0x00D1,0x00F1,0x004E}, {0x00D2,0x00F2,0x004F}, {0x00D3,0x00F3,0x004F}, {0x00D4,0x00F4,0x004F}, {0x00D5,0x00F5,0x004F}, {0x00D6,0x00F6,0x004F}, {0x00D7,0x00D7,0x00D7}, {0x00D8,0x00F8,0x00D8}, {0x00D9,0x00F9,0x0055}, {0x00DA,0x00FA,0x0055}, {0x00DB,0x00FB,0x0055}, {0x00DC,0x00FC,0x0055}, {0x00DD,0x00FD,0x0059}, {0x00DE,0x00FE,0x00DE}, {0x00DF,0x00DF,0x00DF}, {0x00C0,0x00E0,0x0041}, {0x00C1,0x00E1,0x0041}, {0x00C2,0x00E2,0x0041}, {0x00C3,0x00E3,0x0041}, {0x00C4,0x00E4,0x0041}, {0x00C5,0x00E5,0x0041}, {0x00C6,0x00E6,0x00C6}, {0x00C7,0x00E7,0x0043}, {0x00C8,0x00E8,0x0045}, {0x00C9,0x00E9,0x0045}, {0x00CA,0x00EA,0x0045}, {0x00CB,0x00EB,0x0045}, {0x00CC,0x00EC,0x0049}, {0x00CD,0x00ED,0x0049}, {0x00CE,0x00EE,0x0049}, {0x00CF,0x00EF,0x0049}, {0x00D0,0x00F0,0x00D0}, {0x00D1,0x00F1,0x004E}, {0x00D2,0x00F2,0x004F}, {0x00D3,0x00F3,0x004F}, {0x00D4,0x00F4,0x004F}, {0x00D5,0x00F5,0x004F}, {0x00D6,0x00F6,0x004F}, {0x00F7,0x00F7,0x00F7}, {0x00D8,0x00F8,0x00D8}, {0x00D9,0x00F9,0x0055}, {0x00DA,0x00FA,0x0055}, {0x00DB,0x00FB,0x0055}, {0x00DC,0x00FC,0x0055}, {0x00DD,0x00FD,0x0059}, {0x00DE,0x00FE,0x00DE}, {0x0178,0x00FF,0x0059} }; static MY_UNICASE_INFO plane01[]={ {0x0100,0x0101,0x0041}, {0x0100,0x0101,0x0041}, {0x0102,0x0103,0x0041}, {0x0102,0x0103,0x0041}, {0x0104,0x0105,0x0041}, {0x0104,0x0105,0x0041}, {0x0106,0x0107,0x0043}, {0x0106,0x0107,0x0043}, {0x0108,0x0109,0x0043}, {0x0108,0x0109,0x0043}, {0x010A,0x010B,0x0043}, {0x010A,0x010B,0x0043}, {0x010C,0x010D,0x0043}, {0x010C,0x010D,0x0043}, {0x010E,0x010F,0x0044}, {0x010E,0x010F,0x0044}, {0x0110,0x0111,0x0110}, {0x0110,0x0111,0x0110}, {0x0112,0x0113,0x0045}, {0x0112,0x0113,0x0045}, {0x0114,0x0115,0x0045}, {0x0114,0x0115,0x0045}, {0x0116,0x0117,0x0045}, {0x0116,0x0117,0x0045}, {0x0118,0x0119,0x0045}, {0x0118,0x0119,0x0045}, {0x011A,0x011B,0x0045}, {0x011A,0x011B,0x0045}, {0x011C,0x011D,0x0047}, {0x011C,0x011D,0x0047}, {0x011E,0x011F,0x0047}, {0x011E,0x011F,0x0047}, {0x0120,0x0121,0x0047}, {0x0120,0x0121,0x0047}, {0x0122,0x0123,0x0047}, {0x0122,0x0123,0x0047}, {0x0124,0x0125,0x0048}, {0x0124,0x0125,0x0048}, {0x0126,0x0127,0x0126}, {0x0126,0x0127,0x0126}, {0x0128,0x0129,0x0049}, {0x0128,0x0129,0x0049}, {0x012A,0x012B,0x0049}, {0x012A,0x012B,0x0049}, {0x012C,0x012D,0x0049}, {0x012C,0x012D,0x0049}, {0x012E,0x012F,0x0049}, {0x012E,0x012F,0x0049}, {0x0130,0x0069,0x0049}, {0x0049,0x0131,0x0049}, {0x0132,0x0133,0x0132}, {0x0132,0x0133,0x0132}, {0x0134,0x0135,0x004A}, {0x0134,0x0135,0x004A}, {0x0136,0x0137,0x004B}, {0x0136,0x0137,0x004B}, {0x0138,0x0138,0x0138}, {0x0139,0x013A,0x004C}, {0x0139,0x013A,0x004C}, {0x013B,0x013C,0x004C}, {0x013B,0x013C,0x004C}, {0x013D,0x013E,0x004C}, {0x013D,0x013E,0x004C}, {0x013F,0x0140,0x013F}, {0x013F,0x0140,0x013F}, {0x0141,0x0142,0x0141}, {0x0141,0x0142,0x0141}, {0x0143,0x0144,0x004E}, {0x0143,0x0144,0x004E}, {0x0145,0x0146,0x004E}, {0x0145,0x0146,0x004E}, {0x0147,0x0148,0x004E}, {0x0147,0x0148,0x004E}, {0x0149,0x0149,0x0149}, {0x014A,0x014B,0x014A}, {0x014A,0x014B,0x014A}, {0x014C,0x014D,0x004F}, {0x014C,0x014D,0x004F}, {0x014E,0x014F,0x004F}, {0x014E,0x014F,0x004F}, {0x0150,0x0151,0x004F}, {0x0150,0x0151,0x004F}, {0x0152,0x0153,0x0152}, {0x0152,0x0153,0x0152}, {0x0154,0x0155,0x0052}, {0x0154,0x0155,0x0052}, {0x0156,0x0157,0x0052}, {0x0156,0x0157,0x0052}, {0x0158,0x0159,0x0052}, {0x0158,0x0159,0x0052}, {0x015A,0x015B,0x0053}, {0x015A,0x015B,0x0053}, {0x015C,0x015D,0x0053}, {0x015C,0x015D,0x0053}, {0x015E,0x015F,0x0053}, {0x015E,0x015F,0x0053}, {0x0160,0x0161,0x0053}, {0x0160,0x0161,0x0053}, {0x0162,0x0163,0x0054}, {0x0162,0x0163,0x0054}, {0x0164,0x0165,0x0054}, {0x0164,0x0165,0x0054}, {0x0166,0x0167,0x0166}, {0x0166,0x0167,0x0166}, {0x0168,0x0169,0x0055}, {0x0168,0x0169,0x0055}, {0x016A,0x016B,0x0055}, {0x016A,0x016B,0x0055}, {0x016C,0x016D,0x0055}, {0x016C,0x016D,0x0055}, {0x016E,0x016F,0x0055}, {0x016E,0x016F,0x0055}, {0x0170,0x0171,0x0055}, {0x0170,0x0171,0x0055}, {0x0172,0x0173,0x0055}, {0x0172,0x0173,0x0055}, {0x0174,0x0175,0x0057}, {0x0174,0x0175,0x0057}, {0x0176,0x0177,0x0059}, {0x0176,0x0177,0x0059}, {0x0178,0x00FF,0x0059}, {0x0179,0x017A,0x005A}, {0x0179,0x017A,0x005A}, {0x017B,0x017C,0x005A}, {0x017B,0x017C,0x005A}, {0x017D,0x017E,0x005A}, {0x017D,0x017E,0x005A}, {0x0053,0x017F,0x0053}, {0x0180,0x0180,0x0180}, {0x0181,0x0253,0x0181}, {0x0182,0x0183,0x0182}, {0x0182,0x0183,0x0182}, {0x0184,0x0185,0x0184}, {0x0184,0x0185,0x0184}, {0x0186,0x0254,0x0186}, {0x0187,0x0188,0x0187}, {0x0187,0x0188,0x0187}, {0x0189,0x0256,0x0189}, {0x018A,0x0257,0x018A}, {0x018B,0x018C,0x018B}, {0x018B,0x018C,0x018B}, {0x018D,0x018D,0x018D}, {0x018E,0x01DD,0x018E}, {0x018F,0x0259,0x018F}, {0x0190,0x025B,0x0190}, {0x0191,0x0192,0x0191}, {0x0191,0x0192,0x0191}, {0x0193,0x0260,0x0193}, {0x0194,0x0263,0x0194}, {0x01F6,0x0195,0x01F6}, {0x0196,0x0269,0x0196}, {0x0197,0x0268,0x0197}, {0x0198,0x0199,0x0198}, {0x0198,0x0199,0x0198}, {0x019A,0x019A,0x019A}, {0x019B,0x019B,0x019B}, {0x019C,0x026F,0x019C}, {0x019D,0x0272,0x019D}, {0x019E,0x019E,0x019E}, {0x019F,0x0275,0x019F}, {0x01A0,0x01A1,0x004F}, {0x01A0,0x01A1,0x004F}, {0x01A2,0x01A3,0x01A2}, {0x01A2,0x01A3,0x01A2}, {0x01A4,0x01A5,0x01A4}, {0x01A4,0x01A5,0x01A4}, {0x01A6,0x0280,0x01A6}, {0x01A7,0x01A8,0x01A7}, {0x01A7,0x01A8,0x01A7}, {0x01A9,0x0283,0x01A9}, {0x01AA,0x01AA,0x01AA}, {0x01AB,0x01AB,0x01AB}, {0x01AC,0x01AD,0x01AC}, {0x01AC,0x01AD,0x01AC}, {0x01AE,0x0288,0x01AE}, {0x01AF,0x01B0,0x0055}, {0x01AF,0x01B0,0x0055}, {0x01B1,0x028A,0x01B1}, {0x01B2,0x028B,0x01B2}, {0x01B3,0x01B4,0x01B3}, {0x01B3,0x01B4,0x01B3}, {0x01B5,0x01B6,0x01B5}, {0x01B5,0x01B6,0x01B5}, {0x01B7,0x0292,0x01B7}, {0x01B8,0x01B9,0x01B8}, {0x01B8,0x01B9,0x01B8}, {0x01BA,0x01BA,0x01BA}, {0x01BB,0x01BB,0x01BB}, {0x01BC,0x01BD,0x01BC}, {0x01BC,0x01BD,0x01BC}, {0x01BE,0x01BE,0x01BE}, {0x01F7,0x01BF,0x01F7}, {0x01C0,0x01C0,0x01C0}, {0x01C1,0x01C1,0x01C1}, {0x01C2,0x01C2,0x01C2}, {0x01C3,0x01C3,0x01C3}, {0x01C4,0x01C6,0x01C4}, {0x01C4,0x01C6,0x01C4}, {0x01C4,0x01C6,0x01C4}, {0x01C7,0x01C9,0x01C7}, {0x01C7,0x01C9,0x01C7}, {0x01C7,0x01C9,0x01C7}, {0x01CA,0x01CC,0x01CA}, {0x01CA,0x01CC,0x01CA}, {0x01CA,0x01CC,0x01CA}, {0x01CD,0x01CE,0x0041}, {0x01CD,0x01CE,0x0041}, {0x01CF,0x01D0,0x0049}, {0x01CF,0x01D0,0x0049}, {0x01D1,0x01D2,0x004F}, {0x01D1,0x01D2,0x004F}, {0x01D3,0x01D4,0x0055}, {0x01D3,0x01D4,0x0055}, {0x01D5,0x01D6,0x0055}, {0x01D5,0x01D6,0x0055}, {0x01D7,0x01D8,0x0055}, {0x01D7,0x01D8,0x0055}, {0x01D9,0x01DA,0x0055}, {0x01D9,0x01DA,0x0055}, {0x01DB,0x01DC,0x0055}, {0x01DB,0x01DC,0x0055}, {0x018E,0x01DD,0x018E}, {0x01DE,0x01DF,0x0041}, {0x01DE,0x01DF,0x0041}, {0x01E0,0x01E1,0x0041}, {0x01E0,0x01E1,0x0041}, {0x01E2,0x01E3,0x00C6}, {0x01E2,0x01E3,0x00C6}, {0x01E4,0x01E5,0x01E4}, {0x01E4,0x01E5,0x01E4}, {0x01E6,0x01E7,0x0047}, {0x01E6,0x01E7,0x0047}, {0x01E8,0x01E9,0x004B}, {0x01E8,0x01E9,0x004B}, {0x01EA,0x01EB,0x004F}, {0x01EA,0x01EB,0x004F}, {0x01EC,0x01ED,0x004F}, {0x01EC,0x01ED,0x004F}, {0x01EE,0x01EF,0x01B7}, {0x01EE,0x01EF,0x01B7}, {0x01F0,0x01F0,0x004A}, {0x01F1,0x01F3,0x01F1}, {0x01F1,0x01F3,0x01F1}, {0x01F1,0x01F3,0x01F1}, {0x01F4,0x01F5,0x0047}, {0x01F4,0x01F5,0x0047}, {0x01F6,0x0195,0x01F6}, {0x01F7,0x01BF,0x01F7}, {0x01F8,0x01F9,0x004E}, {0x01F8,0x01F9,0x004E}, {0x01FA,0x01FB,0x0041}, {0x01FA,0x01FB,0x0041}, {0x01FC,0x01FD,0x00C6}, {0x01FC,0x01FD,0x00C6}, {0x01FE,0x01FF,0x00D8}, {0x01FE,0x01FF,0x00D8} }; static MY_UNICASE_INFO plane02[]={ {0x0200,0x0201,0x0041}, {0x0200,0x0201,0x0041}, {0x0202,0x0203,0x0041}, {0x0202,0x0203,0x0041}, {0x0204,0x0205,0x0045}, {0x0204,0x0205,0x0045}, {0x0206,0x0207,0x0045}, {0x0206,0x0207,0x0045}, {0x0208,0x0209,0x0049}, {0x0208,0x0209,0x0049}, {0x020A,0x020B,0x0049}, {0x020A,0x020B,0x0049}, {0x020C,0x020D,0x004F}, {0x020C,0x020D,0x004F}, {0x020E,0x020F,0x004F}, {0x020E,0x020F,0x004F}, {0x0210,0x0211,0x0052}, {0x0210,0x0211,0x0052}, {0x0212,0x0213,0x0052}, {0x0212,0x0213,0x0052}, {0x0214,0x0215,0x0055}, {0x0214,0x0215,0x0055}, {0x0216,0x0217,0x0055}, {0x0216,0x0217,0x0055}, {0x0218,0x0219,0x0053}, {0x0218,0x0219,0x0053}, {0x021A,0x021B,0x0054}, {0x021A,0x021B,0x0054}, {0x021C,0x021D,0x021C}, {0x021C,0x021D,0x021C}, {0x021E,0x021F,0x0048}, {0x021E,0x021F,0x0048}, {0x0220,0x0220,0x0220}, {0x0221,0x0221,0x0221}, {0x0222,0x0223,0x0222}, {0x0222,0x0223,0x0222}, {0x0224,0x0225,0x0224}, {0x0224,0x0225,0x0224}, {0x0226,0x0227,0x0041}, {0x0226,0x0227,0x0041}, {0x0228,0x0229,0x0045}, {0x0228,0x0229,0x0045}, {0x022A,0x022B,0x004F}, {0x022A,0x022B,0x004F}, {0x022C,0x022D,0x004F}, {0x022C,0x022D,0x004F}, {0x022E,0x022F,0x004F}, {0x022E,0x022F,0x004F}, {0x0230,0x0231,0x004F}, {0x0230,0x0231,0x004F}, {0x0232,0x0233,0x0059}, {0x0232,0x0233,0x0059}, {0x0234,0x0234,0x0234}, {0x0235,0x0235,0x0235}, {0x0236,0x0236,0x0236}, {0x0237,0x0237,0x0237}, {0x0238,0x0238,0x0238}, {0x0239,0x0239,0x0239}, {0x023A,0x023A,0x023A}, {0x023B,0x023B,0x023B}, {0x023C,0x023C,0x023C}, {0x023D,0x023D,0x023D}, {0x023E,0x023E,0x023E}, {0x023F,0x023F,0x023F}, {0x0240,0x0240,0x0240}, {0x0241,0x0241,0x0241}, {0x0242,0x0242,0x0242}, {0x0243,0x0243,0x0243}, {0x0244,0x0244,0x0244}, {0x0245,0x0245,0x0245}, {0x0246,0x0246,0x0246}, {0x0247,0x0247,0x0247}, {0x0248,0x0248,0x0248}, {0x0249,0x0249,0x0249}, {0x024A,0x024A,0x024A}, {0x024B,0x024B,0x024B}, {0x024C,0x024C,0x024C}, {0x024D,0x024D,0x024D}, {0x024E,0x024E,0x024E}, {0x024F,0x024F,0x024F}, {0x0250,0x0250,0x0250}, {0x0251,0x0251,0x0251}, {0x0252,0x0252,0x0252}, {0x0181,0x0253,0x0181}, {0x0186,0x0254,0x0186}, {0x0255,0x0255,0x0255}, {0x0189,0x0256,0x0189}, {0x018A,0x0257,0x018A}, {0x0258,0x0258,0x0258}, {0x018F,0x0259,0x018F}, {0x025A,0x025A,0x025A}, {0x0190,0x025B,0x0190}, {0x025C,0x025C,0x025C}, {0x025D,0x025D,0x025D}, {0x025E,0x025E,0x025E}, {0x025F,0x025F,0x025F}, {0x0193,0x0260,0x0193}, {0x0261,0x0261,0x0261}, {0x0262,0x0262,0x0262}, {0x0194,0x0263,0x0194}, {0x0264,0x0264,0x0264}, {0x0265,0x0265,0x0265}, {0x0266,0x0266,0x0266}, {0x0267,0x0267,0x0267}, {0x0197,0x0268,0x0197}, {0x0196,0x0269,0x0196}, {0x026A,0x026A,0x026A}, {0x026B,0x026B,0x026B}, {0x026C,0x026C,0x026C}, {0x026D,0x026D,0x026D}, {0x026E,0x026E,0x026E}, {0x019C,0x026F,0x019C}, {0x0270,0x0270,0x0270}, {0x0271,0x0271,0x0271}, {0x019D,0x0272,0x019D}, {0x0273,0x0273,0x0273}, {0x0274,0x0274,0x0274}, {0x019F,0x0275,0x019F}, {0x0276,0x0276,0x0276}, {0x0277,0x0277,0x0277}, {0x0278,0x0278,0x0278}, {0x0279,0x0279,0x0279}, {0x027A,0x027A,0x027A}, {0x027B,0x027B,0x027B}, {0x027C,0x027C,0x027C}, {0x027D,0x027D,0x027D}, {0x027E,0x027E,0x027E}, {0x027F,0x027F,0x027F}, {0x01A6,0x0280,0x01A6}, {0x0281,0x0281,0x0281}, {0x0282,0x0282,0x0282}, {0x01A9,0x0283,0x01A9}, {0x0284,0x0284,0x0284}, {0x0285,0x0285,0x0285}, {0x0286,0x0286,0x0286}, {0x0287,0x0287,0x0287}, {0x01AE,0x0288,0x01AE}, {0x0289,0x0289,0x0289}, {0x01B1,0x028A,0x01B1}, {0x01B2,0x028B,0x01B2}, {0x028C,0x028C,0x028C}, {0x028D,0x028D,0x028D}, {0x028E,0x028E,0x028E}, {0x028F,0x028F,0x028F}, {0x0290,0x0290,0x0290}, {0x0291,0x0291,0x0291}, {0x01B7,0x0292,0x01B7}, {0x0293,0x0293,0x0293}, {0x0294,0x0294,0x0294}, {0x0295,0x0295,0x0295}, {0x0296,0x0296,0x0296}, {0x0297,0x0297,0x0297}, {0x0298,0x0298,0x0298}, {0x0299,0x0299,0x0299}, {0x029A,0x029A,0x029A}, {0x029B,0x029B,0x029B}, {0x029C,0x029C,0x029C}, {0x029D,0x029D,0x029D}, {0x029E,0x029E,0x029E}, {0x029F,0x029F,0x029F}, {0x02A0,0x02A0,0x02A0}, {0x02A1,0x02A1,0x02A1}, {0x02A2,0x02A2,0x02A2}, {0x02A3,0x02A3,0x02A3}, {0x02A4,0x02A4,0x02A4}, {0x02A5,0x02A5,0x02A5}, {0x02A6,0x02A6,0x02A6}, {0x02A7,0x02A7,0x02A7}, {0x02A8,0x02A8,0x02A8}, {0x02A9,0x02A9,0x02A9}, {0x02AA,0x02AA,0x02AA}, {0x02AB,0x02AB,0x02AB}, {0x02AC,0x02AC,0x02AC}, {0x02AD,0x02AD,0x02AD}, {0x02AE,0x02AE,0x02AE}, {0x02AF,0x02AF,0x02AF}, {0x02B0,0x02B0,0x02B0}, {0x02B1,0x02B1,0x02B1}, {0x02B2,0x02B2,0x02B2}, {0x02B3,0x02B3,0x02B3}, {0x02B4,0x02B4,0x02B4}, {0x02B5,0x02B5,0x02B5}, {0x02B6,0x02B6,0x02B6}, {0x02B7,0x02B7,0x02B7}, {0x02B8,0x02B8,0x02B8}, {0x02B9,0x02B9,0x02B9}, {0x02BA,0x02BA,0x02BA}, {0x02BB,0x02BB,0x02BB}, {0x02BC,0x02BC,0x02BC}, {0x02BD,0x02BD,0x02BD}, {0x02BE,0x02BE,0x02BE}, {0x02BF,0x02BF,0x02BF}, {0x02C0,0x02C0,0x02C0}, {0x02C1,0x02C1,0x02C1}, {0x02C2,0x02C2,0x02C2}, {0x02C3,0x02C3,0x02C3}, {0x02C4,0x02C4,0x02C4}, {0x02C5,0x02C5,0x02C5}, {0x02C6,0x02C6,0x02C6}, {0x02C7,0x02C7,0x02C7}, {0x02C8,0x02C8,0x02C8}, {0x02C9,0x02C9,0x02C9}, {0x02CA,0x02CA,0x02CA}, {0x02CB,0x02CB,0x02CB}, {0x02CC,0x02CC,0x02CC}, {0x02CD,0x02CD,0x02CD}, {0x02CE,0x02CE,0x02CE}, {0x02CF,0x02CF,0x02CF}, {0x02D0,0x02D0,0x02D0}, {0x02D1,0x02D1,0x02D1}, {0x02D2,0x02D2,0x02D2}, {0x02D3,0x02D3,0x02D3}, {0x02D4,0x02D4,0x02D4}, {0x02D5,0x02D5,0x02D5}, {0x02D6,0x02D6,0x02D6}, {0x02D7,0x02D7,0x02D7}, {0x02D8,0x02D8,0x02D8}, {0x02D9,0x02D9,0x02D9}, {0x02DA,0x02DA,0x02DA}, {0x02DB,0x02DB,0x02DB}, {0x02DC,0x02DC,0x02DC}, {0x02DD,0x02DD,0x02DD}, {0x02DE,0x02DE,0x02DE}, {0x02DF,0x02DF,0x02DF}, {0x02E0,0x02E0,0x02E0}, {0x02E1,0x02E1,0x02E1}, {0x02E2,0x02E2,0x02E2}, {0x02E3,0x02E3,0x02E3}, {0x02E4,0x02E4,0x02E4}, {0x02E5,0x02E5,0x02E5}, {0x02E6,0x02E6,0x02E6}, {0x02E7,0x02E7,0x02E7}, {0x02E8,0x02E8,0x02E8}, {0x02E9,0x02E9,0x02E9}, {0x02EA,0x02EA,0x02EA}, {0x02EB,0x02EB,0x02EB}, {0x02EC,0x02EC,0x02EC}, {0x02ED,0x02ED,0x02ED}, {0x02EE,0x02EE,0x02EE}, {0x02EF,0x02EF,0x02EF}, {0x02F0,0x02F0,0x02F0}, {0x02F1,0x02F1,0x02F1}, {0x02F2,0x02F2,0x02F2}, {0x02F3,0x02F3,0x02F3}, {0x02F4,0x02F4,0x02F4}, {0x02F5,0x02F5,0x02F5}, {0x02F6,0x02F6,0x02F6}, {0x02F7,0x02F7,0x02F7}, {0x02F8,0x02F8,0x02F8}, {0x02F9,0x02F9,0x02F9}, {0x02FA,0x02FA,0x02FA}, {0x02FB,0x02FB,0x02FB}, {0x02FC,0x02FC,0x02FC}, {0x02FD,0x02FD,0x02FD}, {0x02FE,0x02FE,0x02FE}, {0x02FF,0x02FF,0x02FF} }; static MY_UNICASE_INFO plane03[]={ {0x0300,0x0300,0x0300}, {0x0301,0x0301,0x0301}, {0x0302,0x0302,0x0302}, {0x0303,0x0303,0x0303}, {0x0304,0x0304,0x0304}, {0x0305,0x0305,0x0305}, {0x0306,0x0306,0x0306}, {0x0307,0x0307,0x0307}, {0x0308,0x0308,0x0308}, {0x0309,0x0309,0x0309}, {0x030A,0x030A,0x030A}, {0x030B,0x030B,0x030B}, {0x030C,0x030C,0x030C}, {0x030D,0x030D,0x030D}, {0x030E,0x030E,0x030E}, {0x030F,0x030F,0x030F}, {0x0310,0x0310,0x0310}, {0x0311,0x0311,0x0311}, {0x0312,0x0312,0x0312}, {0x0313,0x0313,0x0313}, {0x0314,0x0314,0x0314}, {0x0315,0x0315,0x0315}, {0x0316,0x0316,0x0316}, {0x0317,0x0317,0x0317}, {0x0318,0x0318,0x0318}, {0x0319,0x0319,0x0319}, {0x031A,0x031A,0x031A}, {0x031B,0x031B,0x031B}, {0x031C,0x031C,0x031C}, {0x031D,0x031D,0x031D}, {0x031E,0x031E,0x031E}, {0x031F,0x031F,0x031F}, {0x0320,0x0320,0x0320}, {0x0321,0x0321,0x0321}, {0x0322,0x0322,0x0322}, {0x0323,0x0323,0x0323}, {0x0324,0x0324,0x0324}, {0x0325,0x0325,0x0325}, {0x0326,0x0326,0x0326}, {0x0327,0x0327,0x0327}, {0x0328,0x0328,0x0328}, {0x0329,0x0329,0x0329}, {0x032A,0x032A,0x032A}, {0x032B,0x032B,0x032B}, {0x032C,0x032C,0x032C}, {0x032D,0x032D,0x032D}, {0x032E,0x032E,0x032E}, {0x032F,0x032F,0x032F}, {0x0330,0x0330,0x0330}, {0x0331,0x0331,0x0331}, {0x0332,0x0332,0x0332}, {0x0333,0x0333,0x0333}, {0x0334,0x0334,0x0334}, {0x0335,0x0335,0x0335}, {0x0336,0x0336,0x0336}, {0x0337,0x0337,0x0337}, {0x0338,0x0338,0x0338}, {0x0339,0x0339,0x0339}, {0x033A,0x033A,0x033A}, {0x033B,0x033B,0x033B}, {0x033C,0x033C,0x033C}, {0x033D,0x033D,0x033D}, {0x033E,0x033E,0x033E}, {0x033F,0x033F,0x033F}, {0x0340,0x0340,0x0340}, {0x0341,0x0341,0x0341}, {0x0342,0x0342,0x0342}, {0x0343,0x0343,0x0343}, {0x0344,0x0344,0x0344}, {0x0399,0x0345,0x0399}, {0x0346,0x0346,0x0346}, {0x0347,0x0347,0x0347}, {0x0348,0x0348,0x0348}, {0x0349,0x0349,0x0349}, {0x034A,0x034A,0x034A}, {0x034B,0x034B,0x034B}, {0x034C,0x034C,0x034C}, {0x034D,0x034D,0x034D}, {0x034E,0x034E,0x034E}, {0x034F,0x034F,0x034F}, {0x0350,0x0350,0x0350}, {0x0351,0x0351,0x0351}, {0x0352,0x0352,0x0352}, {0x0353,0x0353,0x0353}, {0x0354,0x0354,0x0354}, {0x0355,0x0355,0x0355}, {0x0356,0x0356,0x0356}, {0x0357,0x0357,0x0357}, {0x0358,0x0358,0x0358}, {0x0359,0x0359,0x0359}, {0x035A,0x035A,0x035A}, {0x035B,0x035B,0x035B}, {0x035C,0x035C,0x035C}, {0x035D,0x035D,0x035D}, {0x035E,0x035E,0x035E}, {0x035F,0x035F,0x035F}, {0x0360,0x0360,0x0360}, {0x0361,0x0361,0x0361}, {0x0362,0x0362,0x0362}, {0x0363,0x0363,0x0363}, {0x0364,0x0364,0x0364}, {0x0365,0x0365,0x0365}, {0x0366,0x0366,0x0366}, {0x0367,0x0367,0x0367}, {0x0368,0x0368,0x0368}, {0x0369,0x0369,0x0369}, {0x036A,0x036A,0x036A}, {0x036B,0x036B,0x036B}, {0x036C,0x036C,0x036C}, {0x036D,0x036D,0x036D}, {0x036E,0x036E,0x036E}, {0x036F,0x036F,0x036F}, {0x0370,0x0370,0x0370}, {0x0371,0x0371,0x0371}, {0x0372,0x0372,0x0372}, {0x0373,0x0373,0x0373}, {0x0374,0x0374,0x0374}, {0x0375,0x0375,0x0375}, {0x0376,0x0376,0x0376}, {0x0377,0x0377,0x0377}, {0x0378,0x0378,0x0378}, {0x0379,0x0379,0x0379}, {0x037A,0x037A,0x037A}, {0x037B,0x037B,0x037B}, {0x037C,0x037C,0x037C}, {0x037D,0x037D,0x037D}, {0x037E,0x037E,0x037E}, {0x037F,0x037F,0x037F}, {0x0380,0x0380,0x0380}, {0x0381,0x0381,0x0381}, {0x0382,0x0382,0x0382}, {0x0383,0x0383,0x0383}, {0x0384,0x0384,0x0384}, {0x0385,0x0385,0x0385}, {0x0386,0x03AC,0x0391}, {0x0387,0x0387,0x0387}, {0x0388,0x03AD,0x0395}, {0x0389,0x03AE,0x0397}, {0x038A,0x03AF,0x0399}, {0x038B,0x038B,0x038B}, {0x038C,0x03CC,0x039F}, {0x038D,0x038D,0x038D}, {0x038E,0x03CD,0x03A5}, {0x038F,0x03CE,0x03A9}, {0x0390,0x0390,0x0399}, {0x0391,0x03B1,0x0391}, {0x0392,0x03B2,0x0392}, {0x0393,0x03B3,0x0393}, {0x0394,0x03B4,0x0394}, {0x0395,0x03B5,0x0395}, {0x0396,0x03B6,0x0396}, {0x0397,0x03B7,0x0397}, {0x0398,0x03B8,0x0398}, {0x0399,0x03B9,0x0399}, {0x039A,0x03BA,0x039A}, {0x039B,0x03BB,0x039B}, {0x039C,0x03BC,0x039C}, {0x039D,0x03BD,0x039D}, {0x039E,0x03BE,0x039E}, {0x039F,0x03BF,0x039F}, {0x03A0,0x03C0,0x03A0}, {0x03A1,0x03C1,0x03A1}, {0x03A2,0x03A2,0x03A2}, {0x03A3,0x03C3,0x03A3}, {0x03A4,0x03C4,0x03A4}, {0x03A5,0x03C5,0x03A5}, {0x03A6,0x03C6,0x03A6}, {0x03A7,0x03C7,0x03A7}, {0x03A8,0x03C8,0x03A8}, {0x03A9,0x03C9,0x03A9}, {0x03AA,0x03CA,0x0399}, {0x03AB,0x03CB,0x03A5}, {0x0386,0x03AC,0x0391}, {0x0388,0x03AD,0x0395}, {0x0389,0x03AE,0x0397}, {0x038A,0x03AF,0x0399}, {0x03B0,0x03B0,0x03A5}, {0x0391,0x03B1,0x0391}, {0x0392,0x03B2,0x0392}, {0x0393,0x03B3,0x0393}, {0x0394,0x03B4,0x0394}, {0x0395,0x03B5,0x0395}, {0x0396,0x03B6,0x0396}, {0x0397,0x03B7,0x0397}, {0x0398,0x03B8,0x0398}, {0x0399,0x03B9,0x0399}, {0x039A,0x03BA,0x039A}, {0x039B,0x03BB,0x039B}, {0x039C,0x03BC,0x039C}, {0x039D,0x03BD,0x039D}, {0x039E,0x03BE,0x039E}, {0x039F,0x03BF,0x039F}, {0x03A0,0x03C0,0x03A0}, {0x03A1,0x03C1,0x03A1}, {0x03A3,0x03C2,0x03A3}, {0x03A3,0x03C3,0x03A3}, {0x03A4,0x03C4,0x03A4}, {0x03A5,0x03C5,0x03A5}, {0x03A6,0x03C6,0x03A6}, {0x03A7,0x03C7,0x03A7}, {0x03A8,0x03C8,0x03A8}, {0x03A9,0x03C9,0x03A9}, {0x03AA,0x03CA,0x0399}, {0x03AB,0x03CB,0x03A5}, {0x038C,0x03CC,0x039F}, {0x038E,0x03CD,0x03A5}, {0x038F,0x03CE,0x03A9}, {0x03CF,0x03CF,0x03CF}, {0x0392,0x03D0,0x0392}, {0x0398,0x03D1,0x0398}, {0x03D2,0x03D2,0x03D2}, {0x03D3,0x03D3,0x03D2}, {0x03D4,0x03D4,0x03D2}, {0x03A6,0x03D5,0x03A6}, {0x03A0,0x03D6,0x03A0}, {0x03D7,0x03D7,0x03D7}, {0x03D8,0x03D8,0x03D8}, {0x03D9,0x03D9,0x03D9}, {0x03DA,0x03DB,0x03DA}, {0x03DA,0x03DB,0x03DA}, {0x03DC,0x03DD,0x03DC}, {0x03DC,0x03DD,0x03DC}, {0x03DE,0x03DF,0x03DE}, {0x03DE,0x03DF,0x03DE}, {0x03E0,0x03E1,0x03E0}, {0x03E0,0x03E1,0x03E0}, {0x03E2,0x03E3,0x03E2}, {0x03E2,0x03E3,0x03E2}, {0x03E4,0x03E5,0x03E4}, {0x03E4,0x03E5,0x03E4}, {0x03E6,0x03E7,0x03E6}, {0x03E6,0x03E7,0x03E6}, {0x03E8,0x03E9,0x03E8}, {0x03E8,0x03E9,0x03E8}, {0x03EA,0x03EB,0x03EA}, {0x03EA,0x03EB,0x03EA}, {0x03EC,0x03ED,0x03EC}, {0x03EC,0x03ED,0x03EC}, {0x03EE,0x03EF,0x03EE}, {0x03EE,0x03EF,0x03EE}, {0x039A,0x03F0,0x039A}, {0x03A1,0x03F1,0x03A1}, {0x03A3,0x03F2,0x03A3}, {0x03F3,0x03F3,0x03F3}, {0x03F4,0x03F4,0x03F4}, {0x03F5,0x03F5,0x03F5}, {0x03F6,0x03F6,0x03F6}, {0x03F7,0x03F7,0x03F7}, {0x03F8,0x03F8,0x03F8}, {0x03F9,0x03F9,0x03F9}, {0x03FA,0x03FA,0x03FA}, {0x03FB,0x03FB,0x03FB}, {0x03FC,0x03FC,0x03FC}, {0x03FD,0x03FD,0x03FD}, {0x03FE,0x03FE,0x03FE}, {0x03FF,0x03FF,0x03FF} }; static MY_UNICASE_INFO plane04[]={ {0x0400,0x0450,0x0415}, {0x0401,0x0451,0x0415}, {0x0402,0x0452,0x0402}, {0x0403,0x0453,0x0413}, {0x0404,0x0454,0x0404}, {0x0405,0x0455,0x0405}, {0x0406,0x0456,0x0406}, {0x0407,0x0457,0x0406}, {0x0408,0x0458,0x0408}, {0x0409,0x0459,0x0409}, {0x040A,0x045A,0x040A}, {0x040B,0x045B,0x040B}, {0x040C,0x045C,0x041A}, {0x040D,0x045D,0x0418}, {0x040E,0x045E,0x0423}, {0x040F,0x045F,0x040F}, {0x0410,0x0430,0x0410}, {0x0411,0x0431,0x0411}, {0x0412,0x0432,0x0412}, {0x0413,0x0433,0x0413}, {0x0414,0x0434,0x0414}, {0x0415,0x0435,0x0415}, {0x0416,0x0436,0x0416}, {0x0417,0x0437,0x0417}, {0x0418,0x0438,0x0418}, {0x0419,0x0439,0x0419}, {0x041A,0x043A,0x041A}, {0x041B,0x043B,0x041B}, {0x041C,0x043C,0x041C}, {0x041D,0x043D,0x041D}, {0x041E,0x043E,0x041E}, {0x041F,0x043F,0x041F}, {0x0420,0x0440,0x0420}, {0x0421,0x0441,0x0421}, {0x0422,0x0442,0x0422}, {0x0423,0x0443,0x0423}, {0x0424,0x0444,0x0424}, {0x0425,0x0445,0x0425}, {0x0426,0x0446,0x0426}, {0x0427,0x0447,0x0427}, {0x0428,0x0448,0x0428}, {0x0429,0x0449,0x0429}, {0x042A,0x044A,0x042A}, {0x042B,0x044B,0x042B}, {0x042C,0x044C,0x042C}, {0x042D,0x044D,0x042D}, {0x042E,0x044E,0x042E}, {0x042F,0x044F,0x042F}, {0x0410,0x0430,0x0410}, {0x0411,0x0431,0x0411}, {0x0412,0x0432,0x0412}, {0x0413,0x0433,0x0413}, {0x0414,0x0434,0x0414}, {0x0415,0x0435,0x0415}, {0x0416,0x0436,0x0416}, {0x0417,0x0437,0x0417}, {0x0418,0x0438,0x0418}, {0x0419,0x0439,0x0419}, {0x041A,0x043A,0x041A}, {0x041B,0x043B,0x041B}, {0x041C,0x043C,0x041C}, {0x041D,0x043D,0x041D}, {0x041E,0x043E,0x041E}, {0x041F,0x043F,0x041F}, {0x0420,0x0440,0x0420}, {0x0421,0x0441,0x0421}, {0x0422,0x0442,0x0422}, {0x0423,0x0443,0x0423}, {0x0424,0x0444,0x0424}, {0x0425,0x0445,0x0425}, {0x0426,0x0446,0x0426}, {0x0427,0x0447,0x0427}, {0x0428,0x0448,0x0428}, {0x0429,0x0449,0x0429}, {0x042A,0x044A,0x042A}, {0x042B,0x044B,0x042B}, {0x042C,0x044C,0x042C}, {0x042D,0x044D,0x042D}, {0x042E,0x044E,0x042E}, {0x042F,0x044F,0x042F}, {0x0400,0x0450,0x0415}, {0x0401,0x0451,0x0415}, {0x0402,0x0452,0x0402}, {0x0403,0x0453,0x0413}, {0x0404,0x0454,0x0404}, {0x0405,0x0455,0x0405}, {0x0406,0x0456,0x0406}, {0x0407,0x0457,0x0406}, {0x0408,0x0458,0x0408}, {0x0409,0x0459,0x0409}, {0x040A,0x045A,0x040A}, {0x040B,0x045B,0x040B}, {0x040C,0x045C,0x041A}, {0x040D,0x045D,0x0418}, {0x040E,0x045E,0x0423}, {0x040F,0x045F,0x040F}, {0x0460,0x0461,0x0460}, {0x0460,0x0461,0x0460}, {0x0462,0x0463,0x0462}, {0x0462,0x0463,0x0462}, {0x0464,0x0465,0x0464}, {0x0464,0x0465,0x0464}, {0x0466,0x0467,0x0466}, {0x0466,0x0467,0x0466}, {0x0468,0x0469,0x0468}, {0x0468,0x0469,0x0468}, {0x046A,0x046B,0x046A}, {0x046A,0x046B,0x046A}, {0x046C,0x046D,0x046C}, {0x046C,0x046D,0x046C}, {0x046E,0x046F,0x046E}, {0x046E,0x046F,0x046E}, {0x0470,0x0471,0x0470}, {0x0470,0x0471,0x0470}, {0x0472,0x0473,0x0472}, {0x0472,0x0473,0x0472}, {0x0474,0x0475,0x0474}, {0x0474,0x0475,0x0474}, {0x0476,0x0477,0x0474}, {0x0476,0x0477,0x0474}, {0x0478,0x0479,0x0478}, {0x0478,0x0479,0x0478}, {0x047A,0x047B,0x047A}, {0x047A,0x047B,0x047A}, {0x047C,0x047D,0x047C}, {0x047C,0x047D,0x047C}, {0x047E,0x047F,0x047E}, {0x047E,0x047F,0x047E}, {0x0480,0x0481,0x0480}, {0x0480,0x0481,0x0480}, {0x0482,0x0482,0x0482}, {0x0483,0x0483,0x0483}, {0x0484,0x0484,0x0484}, {0x0485,0x0485,0x0485}, {0x0486,0x0486,0x0486}, {0x0487,0x0487,0x0487}, {0x0488,0x0488,0x0488}, {0x0489,0x0489,0x0489}, {0x048A,0x048A,0x048A}, {0x048B,0x048B,0x048B}, {0x048C,0x048D,0x048C}, {0x048C,0x048D,0x048C}, {0x048E,0x048F,0x048E}, {0x048E,0x048F,0x048E}, {0x0490,0x0491,0x0490}, {0x0490,0x0491,0x0490}, {0x0492,0x0493,0x0492}, {0x0492,0x0493,0x0492}, {0x0494,0x0495,0x0494}, {0x0494,0x0495,0x0494}, {0x0496,0x0497,0x0496}, {0x0496,0x0497,0x0496}, {0x0498,0x0499,0x0498}, {0x0498,0x0499,0x0498}, {0x049A,0x049B,0x049A}, {0x049A,0x049B,0x049A}, {0x049C,0x049D,0x049C}, {0x049C,0x049D,0x049C}, {0x049E,0x049F,0x049E}, {0x049E,0x049F,0x049E}, {0x04A0,0x04A1,0x04A0}, {0x04A0,0x04A1,0x04A0}, {0x04A2,0x04A3,0x04A2}, {0x04A2,0x04A3,0x04A2}, {0x04A4,0x04A5,0x04A4}, {0x04A4,0x04A5,0x04A4}, {0x04A6,0x04A7,0x04A6}, {0x04A6,0x04A7,0x04A6}, {0x04A8,0x04A9,0x04A8}, {0x04A8,0x04A9,0x04A8}, {0x04AA,0x04AB,0x04AA}, {0x04AA,0x04AB,0x04AA}, {0x04AC,0x04AD,0x04AC}, {0x04AC,0x04AD,0x04AC}, {0x04AE,0x04AF,0x04AE}, {0x04AE,0x04AF,0x04AE}, {0x04B0,0x04B1,0x04B0}, {0x04B0,0x04B1,0x04B0}, {0x04B2,0x04B3,0x04B2}, {0x04B2,0x04B3,0x04B2}, {0x04B4,0x04B5,0x04B4}, {0x04B4,0x04B5,0x04B4}, {0x04B6,0x04B7,0x04B6}, {0x04B6,0x04B7,0x04B6}, {0x04B8,0x04B9,0x04B8}, {0x04B8,0x04B9,0x04B8}, {0x04BA,0x04BB,0x04BA}, {0x04BA,0x04BB,0x04BA}, {0x04BC,0x04BD,0x04BC}, {0x04BC,0x04BD,0x04BC}, {0x04BE,0x04BF,0x04BE}, {0x04BE,0x04BF,0x04BE}, {0x04C0,0x04C0,0x04C0}, {0x04C1,0x04C2,0x0416}, {0x04C1,0x04C2,0x0416}, {0x04C3,0x04C4,0x04C3}, {0x04C3,0x04C4,0x04C3}, {0x04C5,0x04C5,0x04C5}, {0x04C6,0x04C6,0x04C6}, {0x04C7,0x04C8,0x04C7}, {0x04C7,0x04C8,0x04C7}, {0x04C9,0x04C9,0x04C9}, {0x04CA,0x04CA,0x04CA}, {0x04CB,0x04CC,0x04CB}, {0x04CB,0x04CC,0x04CB}, {0x04CD,0x04CD,0x04CD}, {0x04CE,0x04CE,0x04CE}, {0x04CF,0x04CF,0x04CF}, {0x04D0,0x04D1,0x0410}, {0x04D0,0x04D1,0x0410}, {0x04D2,0x04D3,0x0410}, {0x04D2,0x04D3,0x0410}, {0x04D4,0x04D5,0x04D4}, {0x04D4,0x04D5,0x04D4}, {0x04D6,0x04D7,0x0415}, {0x04D6,0x04D7,0x0415}, {0x04D8,0x04D9,0x04D8}, {0x04D8,0x04D9,0x04D8}, {0x04DA,0x04DB,0x04D8}, {0x04DA,0x04DB,0x04D8}, {0x04DC,0x04DD,0x0416}, {0x04DC,0x04DD,0x0416}, {0x04DE,0x04DF,0x0417}, {0x04DE,0x04DF,0x0417}, {0x04E0,0x04E1,0x04E0}, {0x04E0,0x04E1,0x04E0}, {0x04E2,0x04E3,0x0418}, {0x04E2,0x04E3,0x0418}, {0x04E4,0x04E5,0x0418}, {0x04E4,0x04E5,0x0418}, {0x04E6,0x04E7,0x041E}, {0x04E6,0x04E7,0x041E}, {0x04E8,0x04E9,0x04E8}, {0x04E8,0x04E9,0x04E8}, {0x04EA,0x04EB,0x04E8}, {0x04EA,0x04EB,0x04E8}, {0x04EC,0x04ED,0x042D}, {0x04EC,0x04ED,0x042D}, {0x04EE,0x04EF,0x0423}, {0x04EE,0x04EF,0x0423}, {0x04F0,0x04F1,0x0423}, {0x04F0,0x04F1,0x0423}, {0x04F2,0x04F3,0x0423}, {0x04F2,0x04F3,0x0423}, {0x04F4,0x04F5,0x0427}, {0x04F4,0x04F5,0x0427}, {0x04F6,0x04F6,0x04F6}, {0x04F7,0x04F7,0x04F7}, {0x04F8,0x04F9,0x042B}, {0x04F8,0x04F9,0x042B}, {0x04FA,0x04FA,0x04FA}, {0x04FB,0x04FB,0x04FB}, {0x04FC,0x04FC,0x04FC}, {0x04FD,0x04FD,0x04FD}, {0x04FE,0x04FE,0x04FE}, {0x04FF,0x04FF,0x04FF} }; static MY_UNICASE_INFO plane05[]={ {0x0500,0x0500,0x0500}, {0x0501,0x0501,0x0501}, {0x0502,0x0502,0x0502}, {0x0503,0x0503,0x0503}, {0x0504,0x0504,0x0504}, {0x0505,0x0505,0x0505}, {0x0506,0x0506,0x0506}, {0x0507,0x0507,0x0507}, {0x0508,0x0508,0x0508}, {0x0509,0x0509,0x0509}, {0x050A,0x050A,0x050A}, {0x050B,0x050B,0x050B}, {0x050C,0x050C,0x050C}, {0x050D,0x050D,0x050D}, {0x050E,0x050E,0x050E}, {0x050F,0x050F,0x050F}, {0x0510,0x0510,0x0510}, {0x0511,0x0511,0x0511}, {0x0512,0x0512,0x0512}, {0x0513,0x0513,0x0513}, {0x0514,0x0514,0x0514}, {0x0515,0x0515,0x0515}, {0x0516,0x0516,0x0516}, {0x0517,0x0517,0x0517}, {0x0518,0x0518,0x0518}, {0x0519,0x0519,0x0519}, {0x051A,0x051A,0x051A}, {0x051B,0x051B,0x051B}, {0x051C,0x051C,0x051C}, {0x051D,0x051D,0x051D}, {0x051E,0x051E,0x051E}, {0x051F,0x051F,0x051F}, {0x0520,0x0520,0x0520}, {0x0521,0x0521,0x0521}, {0x0522,0x0522,0x0522}, {0x0523,0x0523,0x0523}, {0x0524,0x0524,0x0524}, {0x0525,0x0525,0x0525}, {0x0526,0x0526,0x0526}, {0x0527,0x0527,0x0527}, {0x0528,0x0528,0x0528}, {0x0529,0x0529,0x0529}, {0x052A,0x052A,0x052A}, {0x052B,0x052B,0x052B}, {0x052C,0x052C,0x052C}, {0x052D,0x052D,0x052D}, {0x052E,0x052E,0x052E}, {0x052F,0x052F,0x052F}, {0x0530,0x0530,0x0530}, {0x0531,0x0561,0x0531}, {0x0532,0x0562,0x0532}, {0x0533,0x0563,0x0533}, {0x0534,0x0564,0x0534}, {0x0535,0x0565,0x0535}, {0x0536,0x0566,0x0536}, {0x0537,0x0567,0x0537}, {0x0538,0x0568,0x0538}, {0x0539,0x0569,0x0539}, {0x053A,0x056A,0x053A}, {0x053B,0x056B,0x053B}, {0x053C,0x056C,0x053C}, {0x053D,0x056D,0x053D}, {0x053E,0x056E,0x053E}, {0x053F,0x056F,0x053F}, {0x0540,0x0570,0x0540}, {0x0541,0x0571,0x0541}, {0x0542,0x0572,0x0542}, {0x0543,0x0573,0x0543}, {0x0544,0x0574,0x0544}, {0x0545,0x0575,0x0545}, {0x0546,0x0576,0x0546}, {0x0547,0x0577,0x0547}, {0x0548,0x0578,0x0548}, {0x0549,0x0579,0x0549}, {0x054A,0x057A,0x054A}, {0x054B,0x057B,0x054B}, {0x054C,0x057C,0x054C}, {0x054D,0x057D,0x054D}, {0x054E,0x057E,0x054E}, {0x054F,0x057F,0x054F}, {0x0550,0x0580,0x0550}, {0x0551,0x0581,0x0551}, {0x0552,0x0582,0x0552}, {0x0553,0x0583,0x0553}, {0x0554,0x0584,0x0554}, {0x0555,0x0585,0x0555}, {0x0556,0x0586,0x0556}, {0x0557,0x0557,0x0557}, {0x0558,0x0558,0x0558}, {0x0559,0x0559,0x0559}, {0x055A,0x055A,0x055A}, {0x055B,0x055B,0x055B}, {0x055C,0x055C,0x055C}, {0x055D,0x055D,0x055D}, {0x055E,0x055E,0x055E}, {0x055F,0x055F,0x055F}, {0x0560,0x0560,0x0560}, {0x0531,0x0561,0x0531}, {0x0532,0x0562,0x0532}, {0x0533,0x0563,0x0533}, {0x0534,0x0564,0x0534}, {0x0535,0x0565,0x0535}, {0x0536,0x0566,0x0536}, {0x0537,0x0567,0x0537}, {0x0538,0x0568,0x0538}, {0x0539,0x0569,0x0539}, {0x053A,0x056A,0x053A}, {0x053B,0x056B,0x053B}, {0x053C,0x056C,0x053C}, {0x053D,0x056D,0x053D}, {0x053E,0x056E,0x053E}, {0x053F,0x056F,0x053F}, {0x0540,0x0570,0x0540}, {0x0541,0x0571,0x0541}, {0x0542,0x0572,0x0542}, {0x0543,0x0573,0x0543}, {0x0544,0x0574,0x0544}, {0x0545,0x0575,0x0545}, {0x0546,0x0576,0x0546}, {0x0547,0x0577,0x0547}, {0x0548,0x0578,0x0548}, {0x0549,0x0579,0x0549}, {0x054A,0x057A,0x054A}, {0x054B,0x057B,0x054B}, {0x054C,0x057C,0x054C}, {0x054D,0x057D,0x054D}, {0x054E,0x057E,0x054E}, {0x054F,0x057F,0x054F}, {0x0550,0x0580,0x0550}, {0x0551,0x0581,0x0551}, {0x0552,0x0582,0x0552}, {0x0553,0x0583,0x0553}, {0x0554,0x0584,0x0554}, {0x0555,0x0585,0x0555}, {0x0556,0x0586,0x0556}, {0x0587,0x0587,0x0587}, {0x0588,0x0588,0x0588}, {0x0589,0x0589,0x0589}, {0x058A,0x058A,0x058A}, {0x058B,0x058B,0x058B}, {0x058C,0x058C,0x058C}, {0x058D,0x058D,0x058D}, {0x058E,0x058E,0x058E}, {0x058F,0x058F,0x058F}, {0x0590,0x0590,0x0590}, {0x0591,0x0591,0x0591}, {0x0592,0x0592,0x0592}, {0x0593,0x0593,0x0593}, {0x0594,0x0594,0x0594}, {0x0595,0x0595,0x0595}, {0x0596,0x0596,0x0596}, {0x0597,0x0597,0x0597}, {0x0598,0x0598,0x0598}, {0x0599,0x0599,0x0599}, {0x059A,0x059A,0x059A}, {0x059B,0x059B,0x059B}, {0x059C,0x059C,0x059C}, {0x059D,0x059D,0x059D}, {0x059E,0x059E,0x059E}, {0x059F,0x059F,0x059F}, {0x05A0,0x05A0,0x05A0}, {0x05A1,0x05A1,0x05A1}, {0x05A2,0x05A2,0x05A2}, {0x05A3,0x05A3,0x05A3}, {0x05A4,0x05A4,0x05A4}, {0x05A5,0x05A5,0x05A5}, {0x05A6,0x05A6,0x05A6}, {0x05A7,0x05A7,0x05A7}, {0x05A8,0x05A8,0x05A8}, {0x05A9,0x05A9,0x05A9}, {0x05AA,0x05AA,0x05AA}, {0x05AB,0x05AB,0x05AB}, {0x05AC,0x05AC,0x05AC}, {0x05AD,0x05AD,0x05AD}, {0x05AE,0x05AE,0x05AE}, {0x05AF,0x05AF,0x05AF}, {0x05B0,0x05B0,0x05B0}, {0x05B1,0x05B1,0x05B1}, {0x05B2,0x05B2,0x05B2}, {0x05B3,0x05B3,0x05B3}, {0x05B4,0x05B4,0x05B4}, {0x05B5,0x05B5,0x05B5}, {0x05B6,0x05B6,0x05B6}, {0x05B7,0x05B7,0x05B7}, {0x05B8,0x05B8,0x05B8}, {0x05B9,0x05B9,0x05B9}, {0x05BA,0x05BA,0x05BA}, {0x05BB,0x05BB,0x05BB}, {0x05BC,0x05BC,0x05BC}, {0x05BD,0x05BD,0x05BD}, {0x05BE,0x05BE,0x05BE}, {0x05BF,0x05BF,0x05BF}, {0x05C0,0x05C0,0x05C0}, {0x05C1,0x05C1,0x05C1}, {0x05C2,0x05C2,0x05C2}, {0x05C3,0x05C3,0x05C3}, {0x05C4,0x05C4,0x05C4}, {0x05C5,0x05C5,0x05C5}, {0x05C6,0x05C6,0x05C6}, {0x05C7,0x05C7,0x05C7}, {0x05C8,0x05C8,0x05C8}, {0x05C9,0x05C9,0x05C9}, {0x05CA,0x05CA,0x05CA}, {0x05CB,0x05CB,0x05CB}, {0x05CC,0x05CC,0x05CC}, {0x05CD,0x05CD,0x05CD}, {0x05CE,0x05CE,0x05CE}, {0x05CF,0x05CF,0x05CF}, {0x05D0,0x05D0,0x05D0}, {0x05D1,0x05D1,0x05D1}, {0x05D2,0x05D2,0x05D2}, {0x05D3,0x05D3,0x05D3}, {0x05D4,0x05D4,0x05D4}, {0x05D5,0x05D5,0x05D5}, {0x05D6,0x05D6,0x05D6}, {0x05D7,0x05D7,0x05D7}, {0x05D8,0x05D8,0x05D8}, {0x05D9,0x05D9,0x05D9}, {0x05DA,0x05DA,0x05DA}, {0x05DB,0x05DB,0x05DB}, {0x05DC,0x05DC,0x05DC}, {0x05DD,0x05DD,0x05DD}, {0x05DE,0x05DE,0x05DE}, {0x05DF,0x05DF,0x05DF}, {0x05E0,0x05E0,0x05E0}, {0x05E1,0x05E1,0x05E1}, {0x05E2,0x05E2,0x05E2}, {0x05E3,0x05E3,0x05E3}, {0x05E4,0x05E4,0x05E4}, {0x05E5,0x05E5,0x05E5}, {0x05E6,0x05E6,0x05E6}, {0x05E7,0x05E7,0x05E7}, {0x05E8,0x05E8,0x05E8}, {0x05E9,0x05E9,0x05E9}, {0x05EA,0x05EA,0x05EA}, {0x05EB,0x05EB,0x05EB}, {0x05EC,0x05EC,0x05EC}, {0x05ED,0x05ED,0x05ED}, {0x05EE,0x05EE,0x05EE}, {0x05EF,0x05EF,0x05EF}, {0x05F0,0x05F0,0x05F0}, {0x05F1,0x05F1,0x05F1}, {0x05F2,0x05F2,0x05F2}, {0x05F3,0x05F3,0x05F3}, {0x05F4,0x05F4,0x05F4}, {0x05F5,0x05F5,0x05F5}, {0x05F6,0x05F6,0x05F6}, {0x05F7,0x05F7,0x05F7}, {0x05F8,0x05F8,0x05F8}, {0x05F9,0x05F9,0x05F9}, {0x05FA,0x05FA,0x05FA}, {0x05FB,0x05FB,0x05FB}, {0x05FC,0x05FC,0x05FC}, {0x05FD,0x05FD,0x05FD}, {0x05FE,0x05FE,0x05FE}, {0x05FF,0x05FF,0x05FF} }; static MY_UNICASE_INFO plane1E[]={ {0x1E00,0x1E01,0x0041}, {0x1E00,0x1E01,0x0041}, {0x1E02,0x1E03,0x0042}, {0x1E02,0x1E03,0x0042}, {0x1E04,0x1E05,0x0042}, {0x1E04,0x1E05,0x0042}, {0x1E06,0x1E07,0x0042}, {0x1E06,0x1E07,0x0042}, {0x1E08,0x1E09,0x0043}, {0x1E08,0x1E09,0x0043}, {0x1E0A,0x1E0B,0x0044}, {0x1E0A,0x1E0B,0x0044}, {0x1E0C,0x1E0D,0x0044}, {0x1E0C,0x1E0D,0x0044}, {0x1E0E,0x1E0F,0x0044}, {0x1E0E,0x1E0F,0x0044}, {0x1E10,0x1E11,0x0044}, {0x1E10,0x1E11,0x0044}, {0x1E12,0x1E13,0x0044}, {0x1E12,0x1E13,0x0044}, {0x1E14,0x1E15,0x0045}, {0x1E14,0x1E15,0x0045}, {0x1E16,0x1E17,0x0045}, {0x1E16,0x1E17,0x0045}, {0x1E18,0x1E19,0x0045}, {0x1E18,0x1E19,0x0045}, {0x1E1A,0x1E1B,0x0045}, {0x1E1A,0x1E1B,0x0045}, {0x1E1C,0x1E1D,0x0045}, {0x1E1C,0x1E1D,0x0045}, {0x1E1E,0x1E1F,0x0046}, {0x1E1E,0x1E1F,0x0046}, {0x1E20,0x1E21,0x0047}, {0x1E20,0x1E21,0x0047}, {0x1E22,0x1E23,0x0048}, {0x1E22,0x1E23,0x0048}, {0x1E24,0x1E25,0x0048}, {0x1E24,0x1E25,0x0048}, {0x1E26,0x1E27,0x0048}, {0x1E26,0x1E27,0x0048}, {0x1E28,0x1E29,0x0048}, {0x1E28,0x1E29,0x0048}, {0x1E2A,0x1E2B,0x0048}, {0x1E2A,0x1E2B,0x0048}, {0x1E2C,0x1E2D,0x0049}, {0x1E2C,0x1E2D,0x0049}, {0x1E2E,0x1E2F,0x0049}, {0x1E2E,0x1E2F,0x0049}, {0x1E30,0x1E31,0x004B}, {0x1E30,0x1E31,0x004B}, {0x1E32,0x1E33,0x004B}, {0x1E32,0x1E33,0x004B}, {0x1E34,0x1E35,0x004B}, {0x1E34,0x1E35,0x004B}, {0x1E36,0x1E37,0x004C}, {0x1E36,0x1E37,0x004C}, {0x1E38,0x1E39,0x004C}, {0x1E38,0x1E39,0x004C}, {0x1E3A,0x1E3B,0x004C}, {0x1E3A,0x1E3B,0x004C}, {0x1E3C,0x1E3D,0x004C}, {0x1E3C,0x1E3D,0x004C}, {0x1E3E,0x1E3F,0x004D}, {0x1E3E,0x1E3F,0x004D}, {0x1E40,0x1E41,0x004D}, {0x1E40,0x1E41,0x004D}, {0x1E42,0x1E43,0x004D}, {0x1E42,0x1E43,0x004D}, {0x1E44,0x1E45,0x004E}, {0x1E44,0x1E45,0x004E}, {0x1E46,0x1E47,0x004E}, {0x1E46,0x1E47,0x004E}, {0x1E48,0x1E49,0x004E}, {0x1E48,0x1E49,0x004E}, {0x1E4A,0x1E4B,0x004E}, {0x1E4A,0x1E4B,0x004E}, {0x1E4C,0x1E4D,0x004F}, {0x1E4C,0x1E4D,0x004F}, {0x1E4E,0x1E4F,0x004F}, {0x1E4E,0x1E4F,0x004F}, {0x1E50,0x1E51,0x004F}, {0x1E50,0x1E51,0x004F}, {0x1E52,0x1E53,0x004F}, {0x1E52,0x1E53,0x004F}, {0x1E54,0x1E55,0x0050}, {0x1E54,0x1E55,0x0050}, {0x1E56,0x1E57,0x0050}, {0x1E56,0x1E57,0x0050}, {0x1E58,0x1E59,0x0052}, {0x1E58,0x1E59,0x0052}, {0x1E5A,0x1E5B,0x0052}, {0x1E5A,0x1E5B,0x0052}, {0x1E5C,0x1E5D,0x0052}, {0x1E5C,0x1E5D,0x0052}, {0x1E5E,0x1E5F,0x0052}, {0x1E5E,0x1E5F,0x0052}, {0x1E60,0x1E61,0x0053}, {0x1E60,0x1E61,0x0053}, {0x1E62,0x1E63,0x0053}, {0x1E62,0x1E63,0x0053}, {0x1E64,0x1E65,0x0053}, {0x1E64,0x1E65,0x0053}, {0x1E66,0x1E67,0x0053}, {0x1E66,0x1E67,0x0053}, {0x1E68,0x1E69,0x0053}, {0x1E68,0x1E69,0x0053}, {0x1E6A,0x1E6B,0x0054}, {0x1E6A,0x1E6B,0x0054}, {0x1E6C,0x1E6D,0x0054}, {0x1E6C,0x1E6D,0x0054}, {0x1E6E,0x1E6F,0x0054}, {0x1E6E,0x1E6F,0x0054}, {0x1E70,0x1E71,0x0054}, {0x1E70,0x1E71,0x0054}, {0x1E72,0x1E73,0x0055}, {0x1E72,0x1E73,0x0055}, {0x1E74,0x1E75,0x0055}, {0x1E74,0x1E75,0x0055}, {0x1E76,0x1E77,0x0055}, {0x1E76,0x1E77,0x0055}, {0x1E78,0x1E79,0x0055}, {0x1E78,0x1E79,0x0055}, {0x1E7A,0x1E7B,0x0055}, {0x1E7A,0x1E7B,0x0055}, {0x1E7C,0x1E7D,0x0056}, {0x1E7C,0x1E7D,0x0056}, {0x1E7E,0x1E7F,0x0056}, {0x1E7E,0x1E7F,0x0056}, {0x1E80,0x1E81,0x0057}, {0x1E80,0x1E81,0x0057}, {0x1E82,0x1E83,0x0057}, {0x1E82,0x1E83,0x0057}, {0x1E84,0x1E85,0x0057}, {0x1E84,0x1E85,0x0057}, {0x1E86,0x1E87,0x0057}, {0x1E86,0x1E87,0x0057}, {0x1E88,0x1E89,0x0057}, {0x1E88,0x1E89,0x0057}, {0x1E8A,0x1E8B,0x0058}, {0x1E8A,0x1E8B,0x0058}, {0x1E8C,0x1E8D,0x0058}, {0x1E8C,0x1E8D,0x0058}, {0x1E8E,0x1E8F,0x0059}, {0x1E8E,0x1E8F,0x0059}, {0x1E90,0x1E91,0x005A}, {0x1E90,0x1E91,0x005A}, {0x1E92,0x1E93,0x005A}, {0x1E92,0x1E93,0x005A}, {0x1E94,0x1E95,0x005A}, {0x1E94,0x1E95,0x005A}, {0x1E96,0x1E96,0x0048}, {0x1E97,0x1E97,0x0054}, {0x1E98,0x1E98,0x0057}, {0x1E99,0x1E99,0x0059}, {0x1E9A,0x1E9A,0x1E9A}, {0x1E60,0x1E9B,0x0053}, {0x1E9C,0x1E9C,0x1E9C}, {0x1E9D,0x1E9D,0x1E9D}, {0x1E9E,0x1E9E,0x1E9E}, {0x1E9F,0x1E9F,0x1E9F}, {0x1EA0,0x1EA1,0x0041}, {0x1EA0,0x1EA1,0x0041}, {0x1EA2,0x1EA3,0x0041}, {0x1EA2,0x1EA3,0x0041}, {0x1EA4,0x1EA5,0x0041}, {0x1EA4,0x1EA5,0x0041}, {0x1EA6,0x1EA7,0x0041}, {0x1EA6,0x1EA7,0x0041}, {0x1EA8,0x1EA9,0x0041}, {0x1EA8,0x1EA9,0x0041}, {0x1EAA,0x1EAB,0x0041}, {0x1EAA,0x1EAB,0x0041}, {0x1EAC,0x1EAD,0x0041}, {0x1EAC,0x1EAD,0x0041}, {0x1EAE,0x1EAF,0x0041}, {0x1EAE,0x1EAF,0x0041}, {0x1EB0,0x1EB1,0x0041}, {0x1EB0,0x1EB1,0x0041}, {0x1EB2,0x1EB3,0x0041}, {0x1EB2,0x1EB3,0x0041}, {0x1EB4,0x1EB5,0x0041}, {0x1EB4,0x1EB5,0x0041}, {0x1EB6,0x1EB7,0x0041}, {0x1EB6,0x1EB7,0x0041}, {0x1EB8,0x1EB9,0x0045}, {0x1EB8,0x1EB9,0x0045}, {0x1EBA,0x1EBB,0x0045}, {0x1EBA,0x1EBB,0x0045}, {0x1EBC,0x1EBD,0x0045}, {0x1EBC,0x1EBD,0x0045}, {0x1EBE,0x1EBF,0x0045}, {0x1EBE,0x1EBF,0x0045}, {0x1EC0,0x1EC1,0x0045}, {0x1EC0,0x1EC1,0x0045}, {0x1EC2,0x1EC3,0x0045}, {0x1EC2,0x1EC3,0x0045}, {0x1EC4,0x1EC5,0x0045}, {0x1EC4,0x1EC5,0x0045}, {0x1EC6,0x1EC7,0x0045}, {0x1EC6,0x1EC7,0x0045}, {0x1EC8,0x1EC9,0x0049}, {0x1EC8,0x1EC9,0x0049}, {0x1ECA,0x1ECB,0x0049}, {0x1ECA,0x1ECB,0x0049}, {0x1ECC,0x1ECD,0x004F}, {0x1ECC,0x1ECD,0x004F}, {0x1ECE,0x1ECF,0x004F}, {0x1ECE,0x1ECF,0x004F}, {0x1ED0,0x1ED1,0x004F}, {0x1ED0,0x1ED1,0x004F}, {0x1ED2,0x1ED3,0x004F}, {0x1ED2,0x1ED3,0x004F}, {0x1ED4,0x1ED5,0x004F}, {0x1ED4,0x1ED5,0x004F}, {0x1ED6,0x1ED7,0x004F}, {0x1ED6,0x1ED7,0x004F}, {0x1ED8,0x1ED9,0x004F}, {0x1ED8,0x1ED9,0x004F}, {0x1EDA,0x1EDB,0x004F}, {0x1EDA,0x1EDB,0x004F}, {0x1EDC,0x1EDD,0x004F}, {0x1EDC,0x1EDD,0x004F}, {0x1EDE,0x1EDF,0x004F}, {0x1EDE,0x1EDF,0x004F}, {0x1EE0,0x1EE1,0x004F}, {0x1EE0,0x1EE1,0x004F}, {0x1EE2,0x1EE3,0x004F}, {0x1EE2,0x1EE3,0x004F}, {0x1EE4,0x1EE5,0x0055}, {0x1EE4,0x1EE5,0x0055}, {0x1EE6,0x1EE7,0x0055}, {0x1EE6,0x1EE7,0x0055}, {0x1EE8,0x1EE9,0x0055}, {0x1EE8,0x1EE9,0x0055}, {0x1EEA,0x1EEB,0x0055}, {0x1EEA,0x1EEB,0x0055}, {0x1EEC,0x1EED,0x0055}, {0x1EEC,0x1EED,0x0055}, {0x1EEE,0x1EEF,0x0055}, {0x1EEE,0x1EEF,0x0055}, {0x1EF0,0x1EF1,0x0055}, {0x1EF0,0x1EF1,0x0055}, {0x1EF2,0x1EF3,0x0059}, {0x1EF2,0x1EF3,0x0059}, {0x1EF4,0x1EF5,0x0059}, {0x1EF4,0x1EF5,0x0059}, {0x1EF6,0x1EF7,0x0059}, {0x1EF6,0x1EF7,0x0059}, {0x1EF8,0x1EF9,0x0059}, {0x1EF8,0x1EF9,0x0059}, {0x1EFA,0x1EFA,0x1EFA}, {0x1EFB,0x1EFB,0x1EFB}, {0x1EFC,0x1EFC,0x1EFC}, {0x1EFD,0x1EFD,0x1EFD}, {0x1EFE,0x1EFE,0x1EFE}, {0x1EFF,0x1EFF,0x1EFF} }; static MY_UNICASE_INFO plane1F[]={ {0x1F08,0x1F00,0x0391}, {0x1F09,0x1F01,0x0391}, {0x1F0A,0x1F02,0x0391}, {0x1F0B,0x1F03,0x0391}, {0x1F0C,0x1F04,0x0391}, {0x1F0D,0x1F05,0x0391}, {0x1F0E,0x1F06,0x0391}, {0x1F0F,0x1F07,0x0391}, {0x1F08,0x1F00,0x0391}, {0x1F09,0x1F01,0x0391}, {0x1F0A,0x1F02,0x0391}, {0x1F0B,0x1F03,0x0391}, {0x1F0C,0x1F04,0x0391}, {0x1F0D,0x1F05,0x0391}, {0x1F0E,0x1F06,0x0391}, {0x1F0F,0x1F07,0x0391}, {0x1F18,0x1F10,0x0395}, {0x1F19,0x1F11,0x0395}, {0x1F1A,0x1F12,0x0395}, {0x1F1B,0x1F13,0x0395}, {0x1F1C,0x1F14,0x0395}, {0x1F1D,0x1F15,0x0395}, {0x1F16,0x1F16,0x1F16}, {0x1F17,0x1F17,0x1F17}, {0x1F18,0x1F10,0x0395}, {0x1F19,0x1F11,0x0395}, {0x1F1A,0x1F12,0x0395}, {0x1F1B,0x1F13,0x0395}, {0x1F1C,0x1F14,0x0395}, {0x1F1D,0x1F15,0x0395}, {0x1F1E,0x1F1E,0x1F1E}, {0x1F1F,0x1F1F,0x1F1F}, {0x1F28,0x1F20,0x0397}, {0x1F29,0x1F21,0x0397}, {0x1F2A,0x1F22,0x0397}, {0x1F2B,0x1F23,0x0397}, {0x1F2C,0x1F24,0x0397}, {0x1F2D,0x1F25,0x0397}, {0x1F2E,0x1F26,0x0397}, {0x1F2F,0x1F27,0x0397}, {0x1F28,0x1F20,0x0397}, {0x1F29,0x1F21,0x0397}, {0x1F2A,0x1F22,0x0397}, {0x1F2B,0x1F23,0x0397}, {0x1F2C,0x1F24,0x0397}, {0x1F2D,0x1F25,0x0397}, {0x1F2E,0x1F26,0x0397}, {0x1F2F,0x1F27,0x0397}, {0x1F38,0x1F30,0x0399}, {0x1F39,0x1F31,0x0399}, {0x1F3A,0x1F32,0x0399}, {0x1F3B,0x1F33,0x0399}, {0x1F3C,0x1F34,0x0399}, {0x1F3D,0x1F35,0x0399}, {0x1F3E,0x1F36,0x0399}, {0x1F3F,0x1F37,0x0399}, {0x1F38,0x1F30,0x0399}, {0x1F39,0x1F31,0x0399}, {0x1F3A,0x1F32,0x0399}, {0x1F3B,0x1F33,0x0399}, {0x1F3C,0x1F34,0x0399}, {0x1F3D,0x1F35,0x0399}, {0x1F3E,0x1F36,0x0399}, {0x1F3F,0x1F37,0x0399}, {0x1F48,0x1F40,0x039F}, {0x1F49,0x1F41,0x039F}, {0x1F4A,0x1F42,0x039F}, {0x1F4B,0x1F43,0x039F}, {0x1F4C,0x1F44,0x039F}, {0x1F4D,0x1F45,0x039F}, {0x1F46,0x1F46,0x1F46}, {0x1F47,0x1F47,0x1F47}, {0x1F48,0x1F40,0x039F}, {0x1F49,0x1F41,0x039F}, {0x1F4A,0x1F42,0x039F}, {0x1F4B,0x1F43,0x039F}, {0x1F4C,0x1F44,0x039F}, {0x1F4D,0x1F45,0x039F}, {0x1F4E,0x1F4E,0x1F4E}, {0x1F4F,0x1F4F,0x1F4F}, {0x1F50,0x1F50,0x03A5}, {0x1F59,0x1F51,0x03A5}, {0x1F52,0x1F52,0x03A5}, {0x1F5B,0x1F53,0x03A5}, {0x1F54,0x1F54,0x03A5}, {0x1F5D,0x1F55,0x03A5}, {0x1F56,0x1F56,0x03A5}, {0x1F5F,0x1F57,0x03A5}, {0x1F58,0x1F58,0x1F58}, {0x1F59,0x1F51,0x03A5}, {0x1F5A,0x1F5A,0x1F5A}, {0x1F5B,0x1F53,0x03A5}, {0x1F5C,0x1F5C,0x1F5C}, {0x1F5D,0x1F55,0x03A5}, {0x1F5E,0x1F5E,0x1F5E}, {0x1F5F,0x1F57,0x03A5}, {0x1F68,0x1F60,0x03A9}, {0x1F69,0x1F61,0x03A9}, {0x1F6A,0x1F62,0x03A9}, {0x1F6B,0x1F63,0x03A9}, {0x1F6C,0x1F64,0x03A9}, {0x1F6D,0x1F65,0x03A9}, {0x1F6E,0x1F66,0x03A9}, {0x1F6F,0x1F67,0x03A9}, {0x1F68,0x1F60,0x03A9}, {0x1F69,0x1F61,0x03A9}, {0x1F6A,0x1F62,0x03A9}, {0x1F6B,0x1F63,0x03A9}, {0x1F6C,0x1F64,0x03A9}, {0x1F6D,0x1F65,0x03A9}, {0x1F6E,0x1F66,0x03A9}, {0x1F6F,0x1F67,0x03A9}, {0x1FBA,0x1F70,0x0391}, {0x1FBB,0x1F71,0x1FBB}, {0x1FC8,0x1F72,0x0395}, {0x1FC9,0x1F73,0x1FC9}, {0x1FCA,0x1F74,0x0397}, {0x1FCB,0x1F75,0x1FCB}, {0x1FDA,0x1F76,0x0399}, {0x1FDB,0x1F77,0x1FDB}, {0x1FF8,0x1F78,0x039F}, {0x1FF9,0x1F79,0x1FF9}, {0x1FEA,0x1F7A,0x03A5}, {0x1FEB,0x1F7B,0x1FEB}, {0x1FFA,0x1F7C,0x03A9}, {0x1FFB,0x1F7D,0x1FFB}, {0x1F7E,0x1F7E,0x1F7E}, {0x1F7F,0x1F7F,0x1F7F}, {0x1F88,0x1F80,0x0391}, {0x1F89,0x1F81,0x0391}, {0x1F8A,0x1F82,0x0391}, {0x1F8B,0x1F83,0x0391}, {0x1F8C,0x1F84,0x0391}, {0x1F8D,0x1F85,0x0391}, {0x1F8E,0x1F86,0x0391}, {0x1F8F,0x1F87,0x0391}, {0x1F88,0x1F80,0x0391}, {0x1F89,0x1F81,0x0391}, {0x1F8A,0x1F82,0x0391}, {0x1F8B,0x1F83,0x0391}, {0x1F8C,0x1F84,0x0391}, {0x1F8D,0x1F85,0x0391}, {0x1F8E,0x1F86,0x0391}, {0x1F8F,0x1F87,0x0391}, {0x1F98,0x1F90,0x0397}, {0x1F99,0x1F91,0x0397}, {0x1F9A,0x1F92,0x0397}, {0x1F9B,0x1F93,0x0397}, {0x1F9C,0x1F94,0x0397}, {0x1F9D,0x1F95,0x0397}, {0x1F9E,0x1F96,0x0397}, {0x1F9F,0x1F97,0x0397}, {0x1F98,0x1F90,0x0397}, {0x1F99,0x1F91,0x0397}, {0x1F9A,0x1F92,0x0397}, {0x1F9B,0x1F93,0x0397}, {0x1F9C,0x1F94,0x0397}, {0x1F9D,0x1F95,0x0397}, {0x1F9E,0x1F96,0x0397}, {0x1F9F,0x1F97,0x0397}, {0x1FA8,0x1FA0,0x03A9}, {0x1FA9,0x1FA1,0x03A9}, {0x1FAA,0x1FA2,0x03A9}, {0x1FAB,0x1FA3,0x03A9}, {0x1FAC,0x1FA4,0x03A9}, {0x1FAD,0x1FA5,0x03A9}, {0x1FAE,0x1FA6,0x03A9}, {0x1FAF,0x1FA7,0x03A9}, {0x1FA8,0x1FA0,0x03A9}, {0x1FA9,0x1FA1,0x03A9}, {0x1FAA,0x1FA2,0x03A9}, {0x1FAB,0x1FA3,0x03A9}, {0x1FAC,0x1FA4,0x03A9}, {0x1FAD,0x1FA5,0x03A9}, {0x1FAE,0x1FA6,0x03A9}, {0x1FAF,0x1FA7,0x03A9}, {0x1FB8,0x1FB0,0x0391}, {0x1FB9,0x1FB1,0x0391}, {0x1FB2,0x1FB2,0x0391}, {0x1FBC,0x1FB3,0x0391}, {0x1FB4,0x1FB4,0x0391}, {0x1FB5,0x1FB5,0x1FB5}, {0x1FB6,0x1FB6,0x0391}, {0x1FB7,0x1FB7,0x0391}, {0x1FB8,0x1FB0,0x0391}, {0x1FB9,0x1FB1,0x0391}, {0x1FBA,0x1F70,0x0391}, {0x1FBB,0x1F71,0x1FBB}, {0x1FBC,0x1FB3,0x0391}, {0x1FBD,0x1FBD,0x1FBD}, {0x0399,0x1FBE,0x0399}, {0x1FBF,0x1FBF,0x1FBF}, {0x1FC0,0x1FC0,0x1FC0}, {0x1FC1,0x1FC1,0x1FC1}, {0x1FC2,0x1FC2,0x0397}, {0x1FCC,0x1FC3,0x0397}, {0x1FC4,0x1FC4,0x0397}, {0x1FC5,0x1FC5,0x1FC5}, {0x1FC6,0x1FC6,0x0397}, {0x1FC7,0x1FC7,0x0397}, {0x1FC8,0x1F72,0x0395}, {0x1FC9,0x1F73,0x1FC9}, {0x1FCA,0x1F74,0x0397}, {0x1FCB,0x1F75,0x1FCB}, {0x1FCC,0x1FC3,0x0397}, {0x1FCD,0x1FCD,0x1FCD}, {0x1FCE,0x1FCE,0x1FCE}, {0x1FCF,0x1FCF,0x1FCF}, {0x1FD8,0x1FD0,0x0399}, {0x1FD9,0x1FD1,0x0399}, {0x1FD2,0x1FD2,0x0399}, {0x1FD3,0x1FD3,0x1FD3}, {0x1FD4,0x1FD4,0x1FD4}, {0x1FD5,0x1FD5,0x1FD5}, {0x1FD6,0x1FD6,0x0399}, {0x1FD7,0x1FD7,0x0399}, {0x1FD8,0x1FD0,0x0399}, {0x1FD9,0x1FD1,0x0399}, {0x1FDA,0x1F76,0x0399}, {0x1FDB,0x1F77,0x1FDB}, {0x1FDC,0x1FDC,0x1FDC}, {0x1FDD,0x1FDD,0x1FDD}, {0x1FDE,0x1FDE,0x1FDE}, {0x1FDF,0x1FDF,0x1FDF}, {0x1FE8,0x1FE0,0x03A5}, {0x1FE9,0x1FE1,0x03A5}, {0x1FE2,0x1FE2,0x03A5}, {0x1FE3,0x1FE3,0x1FE3}, {0x1FE4,0x1FE4,0x03A1}, {0x1FEC,0x1FE5,0x03A1}, {0x1FE6,0x1FE6,0x03A5}, {0x1FE7,0x1FE7,0x03A5}, {0x1FE8,0x1FE0,0x03A5}, {0x1FE9,0x1FE1,0x03A5}, {0x1FEA,0x1F7A,0x03A5}, {0x1FEB,0x1F7B,0x1FEB}, {0x1FEC,0x1FE5,0x03A1}, {0x1FED,0x1FED,0x1FED}, {0x1FEE,0x1FEE,0x1FEE}, {0x1FEF,0x1FEF,0x1FEF}, {0x1FF0,0x1FF0,0x1FF0}, {0x1FF1,0x1FF1,0x1FF1}, {0x1FF2,0x1FF2,0x03A9}, {0x1FFC,0x1FF3,0x03A9}, {0x1FF4,0x1FF4,0x03A9}, {0x1FF5,0x1FF5,0x1FF5}, {0x1FF6,0x1FF6,0x03A9}, {0x1FF7,0x1FF7,0x03A9}, {0x1FF8,0x1F78,0x039F}, {0x1FF9,0x1F79,0x1FF9}, {0x1FFA,0x1F7C,0x03A9}, {0x1FFB,0x1F7D,0x1FFB}, {0x1FFC,0x1FF3,0x03A9}, {0x1FFD,0x1FFD,0x1FFD}, {0x1FFE,0x1FFE,0x1FFE}, {0x1FFF,0x1FFF,0x1FFF} }; static MY_UNICASE_INFO plane21[]={ {0x2100,0x2100,0x2100}, {0x2101,0x2101,0x2101}, {0x2102,0x2102,0x2102}, {0x2103,0x2103,0x2103}, {0x2104,0x2104,0x2104}, {0x2105,0x2105,0x2105}, {0x2106,0x2106,0x2106}, {0x2107,0x2107,0x2107}, {0x2108,0x2108,0x2108}, {0x2109,0x2109,0x2109}, {0x210A,0x210A,0x210A}, {0x210B,0x210B,0x210B}, {0x210C,0x210C,0x210C}, {0x210D,0x210D,0x210D}, {0x210E,0x210E,0x210E}, {0x210F,0x210F,0x210F}, {0x2110,0x2110,0x2110}, {0x2111,0x2111,0x2111}, {0x2112,0x2112,0x2112}, {0x2113,0x2113,0x2113}, {0x2114,0x2114,0x2114}, {0x2115,0x2115,0x2115}, {0x2116,0x2116,0x2116}, {0x2117,0x2117,0x2117}, {0x2118,0x2118,0x2118}, {0x2119,0x2119,0x2119}, {0x211A,0x211A,0x211A}, {0x211B,0x211B,0x211B}, {0x211C,0x211C,0x211C}, {0x211D,0x211D,0x211D}, {0x211E,0x211E,0x211E}, {0x211F,0x211F,0x211F}, {0x2120,0x2120,0x2120}, {0x2121,0x2121,0x2121}, {0x2122,0x2122,0x2122}, {0x2123,0x2123,0x2123}, {0x2124,0x2124,0x2124}, {0x2125,0x2125,0x2125}, {0x2126,0x03C9,0x2126}, {0x2127,0x2127,0x2127}, {0x2128,0x2128,0x2128}, {0x2129,0x2129,0x2129}, {0x212A,0x006B,0x212A}, {0x212B,0x00E5,0x212B}, {0x212C,0x212C,0x212C}, {0x212D,0x212D,0x212D}, {0x212E,0x212E,0x212E}, {0x212F,0x212F,0x212F}, {0x2130,0x2130,0x2130}, {0x2131,0x2131,0x2131}, {0x2132,0x2132,0x2132}, {0x2133,0x2133,0x2133}, {0x2134,0x2134,0x2134}, {0x2135,0x2135,0x2135}, {0x2136,0x2136,0x2136}, {0x2137,0x2137,0x2137}, {0x2138,0x2138,0x2138}, {0x2139,0x2139,0x2139}, {0x213A,0x213A,0x213A}, {0x213B,0x213B,0x213B}, {0x213C,0x213C,0x213C}, {0x213D,0x213D,0x213D}, {0x213E,0x213E,0x213E}, {0x213F,0x213F,0x213F}, {0x2140,0x2140,0x2140}, {0x2141,0x2141,0x2141}, {0x2142,0x2142,0x2142}, {0x2143,0x2143,0x2143}, {0x2144,0x2144,0x2144}, {0x2145,0x2145,0x2145}, {0x2146,0x2146,0x2146}, {0x2147,0x2147,0x2147}, {0x2148,0x2148,0x2148}, {0x2149,0x2149,0x2149}, {0x214A,0x214A,0x214A}, {0x214B,0x214B,0x214B}, {0x214C,0x214C,0x214C}, {0x214D,0x214D,0x214D}, {0x214E,0x214E,0x214E}, {0x214F,0x214F,0x214F}, {0x2150,0x2150,0x2150}, {0x2151,0x2151,0x2151}, {0x2152,0x2152,0x2152}, {0x2153,0x2153,0x2153}, {0x2154,0x2154,0x2154}, {0x2155,0x2155,0x2155}, {0x2156,0x2156,0x2156}, {0x2157,0x2157,0x2157}, {0x2158,0x2158,0x2158}, {0x2159,0x2159,0x2159}, {0x215A,0x215A,0x215A}, {0x215B,0x215B,0x215B}, {0x215C,0x215C,0x215C}, {0x215D,0x215D,0x215D}, {0x215E,0x215E,0x215E}, {0x215F,0x215F,0x215F}, {0x2160,0x2170,0x2160}, {0x2161,0x2171,0x2161}, {0x2162,0x2172,0x2162}, {0x2163,0x2173,0x2163}, {0x2164,0x2174,0x2164}, {0x2165,0x2175,0x2165}, {0x2166,0x2176,0x2166}, {0x2167,0x2177,0x2167}, {0x2168,0x2178,0x2168}, {0x2169,0x2179,0x2169}, {0x216A,0x217A,0x216A}, {0x216B,0x217B,0x216B}, {0x216C,0x217C,0x216C}, {0x216D,0x217D,0x216D}, {0x216E,0x217E,0x216E}, {0x216F,0x217F,0x216F}, {0x2160,0x2170,0x2160}, {0x2161,0x2171,0x2161}, {0x2162,0x2172,0x2162}, {0x2163,0x2173,0x2163}, {0x2164,0x2174,0x2164}, {0x2165,0x2175,0x2165}, {0x2166,0x2176,0x2166}, {0x2167,0x2177,0x2167}, {0x2168,0x2178,0x2168}, {0x2169,0x2179,0x2169}, {0x216A,0x217A,0x216A}, {0x216B,0x217B,0x216B}, {0x216C,0x217C,0x216C}, {0x216D,0x217D,0x216D}, {0x216E,0x217E,0x216E}, {0x216F,0x217F,0x216F}, {0x2180,0x2180,0x2180}, {0x2181,0x2181,0x2181}, {0x2182,0x2182,0x2182}, {0x2183,0x2183,0x2183}, {0x2184,0x2184,0x2184}, {0x2185,0x2185,0x2185}, {0x2186,0x2186,0x2186}, {0x2187,0x2187,0x2187}, {0x2188,0x2188,0x2188}, {0x2189,0x2189,0x2189}, {0x218A,0x218A,0x218A}, {0x218B,0x218B,0x218B}, {0x218C,0x218C,0x218C}, {0x218D,0x218D,0x218D}, {0x218E,0x218E,0x218E}, {0x218F,0x218F,0x218F}, {0x2190,0x2190,0x2190}, {0x2191,0x2191,0x2191}, {0x2192,0x2192,0x2192}, {0x2193,0x2193,0x2193}, {0x2194,0x2194,0x2194}, {0x2195,0x2195,0x2195}, {0x2196,0x2196,0x2196}, {0x2197,0x2197,0x2197}, {0x2198,0x2198,0x2198}, {0x2199,0x2199,0x2199}, {0x219A,0x219A,0x219A}, {0x219B,0x219B,0x219B}, {0x219C,0x219C,0x219C}, {0x219D,0x219D,0x219D}, {0x219E,0x219E,0x219E}, {0x219F,0x219F,0x219F}, {0x21A0,0x21A0,0x21A0}, {0x21A1,0x21A1,0x21A1}, {0x21A2,0x21A2,0x21A2}, {0x21A3,0x21A3,0x21A3}, {0x21A4,0x21A4,0x21A4}, {0x21A5,0x21A5,0x21A5}, {0x21A6,0x21A6,0x21A6}, {0x21A7,0x21A7,0x21A7}, {0x21A8,0x21A8,0x21A8}, {0x21A9,0x21A9,0x21A9}, {0x21AA,0x21AA,0x21AA}, {0x21AB,0x21AB,0x21AB}, {0x21AC,0x21AC,0x21AC}, {0x21AD,0x21AD,0x21AD}, {0x21AE,0x21AE,0x21AE}, {0x21AF,0x21AF,0x21AF}, {0x21B0,0x21B0,0x21B0}, {0x21B1,0x21B1,0x21B1}, {0x21B2,0x21B2,0x21B2}, {0x21B3,0x21B3,0x21B3}, {0x21B4,0x21B4,0x21B4}, {0x21B5,0x21B5,0x21B5}, {0x21B6,0x21B6,0x21B6}, {0x21B7,0x21B7,0x21B7}, {0x21B8,0x21B8,0x21B8}, {0x21B9,0x21B9,0x21B9}, {0x21BA,0x21BA,0x21BA}, {0x21BB,0x21BB,0x21BB}, {0x21BC,0x21BC,0x21BC}, {0x21BD,0x21BD,0x21BD}, {0x21BE,0x21BE,0x21BE}, {0x21BF,0x21BF,0x21BF}, {0x21C0,0x21C0,0x21C0}, {0x21C1,0x21C1,0x21C1}, {0x21C2,0x21C2,0x21C2}, {0x21C3,0x21C3,0x21C3}, {0x21C4,0x21C4,0x21C4}, {0x21C5,0x21C5,0x21C5}, {0x21C6,0x21C6,0x21C6}, {0x21C7,0x21C7,0x21C7}, {0x21C8,0x21C8,0x21C8}, {0x21C9,0x21C9,0x21C9}, {0x21CA,0x21CA,0x21CA}, {0x21CB,0x21CB,0x21CB}, {0x21CC,0x21CC,0x21CC}, {0x21CD,0x21CD,0x21CD}, {0x21CE,0x21CE,0x21CE}, {0x21CF,0x21CF,0x21CF}, {0x21D0,0x21D0,0x21D0}, {0x21D1,0x21D1,0x21D1}, {0x21D2,0x21D2,0x21D2}, {0x21D3,0x21D3,0x21D3}, {0x21D4,0x21D4,0x21D4}, {0x21D5,0x21D5,0x21D5}, {0x21D6,0x21D6,0x21D6}, {0x21D7,0x21D7,0x21D7}, {0x21D8,0x21D8,0x21D8}, {0x21D9,0x21D9,0x21D9}, {0x21DA,0x21DA,0x21DA}, {0x21DB,0x21DB,0x21DB}, {0x21DC,0x21DC,0x21DC}, {0x21DD,0x21DD,0x21DD}, {0x21DE,0x21DE,0x21DE}, {0x21DF,0x21DF,0x21DF}, {0x21E0,0x21E0,0x21E0}, {0x21E1,0x21E1,0x21E1}, {0x21E2,0x21E2,0x21E2}, {0x21E3,0x21E3,0x21E3}, {0x21E4,0x21E4,0x21E4}, {0x21E5,0x21E5,0x21E5}, {0x21E6,0x21E6,0x21E6}, {0x21E7,0x21E7,0x21E7}, {0x21E8,0x21E8,0x21E8}, {0x21E9,0x21E9,0x21E9}, {0x21EA,0x21EA,0x21EA}, {0x21EB,0x21EB,0x21EB}, {0x21EC,0x21EC,0x21EC}, {0x21ED,0x21ED,0x21ED}, {0x21EE,0x21EE,0x21EE}, {0x21EF,0x21EF,0x21EF}, {0x21F0,0x21F0,0x21F0}, {0x21F1,0x21F1,0x21F1}, {0x21F2,0x21F2,0x21F2}, {0x21F3,0x21F3,0x21F3}, {0x21F4,0x21F4,0x21F4}, {0x21F5,0x21F5,0x21F5}, {0x21F6,0x21F6,0x21F6}, {0x21F7,0x21F7,0x21F7}, {0x21F8,0x21F8,0x21F8}, {0x21F9,0x21F9,0x21F9}, {0x21FA,0x21FA,0x21FA}, {0x21FB,0x21FB,0x21FB}, {0x21FC,0x21FC,0x21FC}, {0x21FD,0x21FD,0x21FD}, {0x21FE,0x21FE,0x21FE}, {0x21FF,0x21FF,0x21FF} }; static MY_UNICASE_INFO plane24[]={ {0x2400,0x2400,0x2400}, {0x2401,0x2401,0x2401}, {0x2402,0x2402,0x2402}, {0x2403,0x2403,0x2403}, {0x2404,0x2404,0x2404}, {0x2405,0x2405,0x2405}, {0x2406,0x2406,0x2406}, {0x2407,0x2407,0x2407}, {0x2408,0x2408,0x2408}, {0x2409,0x2409,0x2409}, {0x240A,0x240A,0x240A}, {0x240B,0x240B,0x240B}, {0x240C,0x240C,0x240C}, {0x240D,0x240D,0x240D}, {0x240E,0x240E,0x240E}, {0x240F,0x240F,0x240F}, {0x2410,0x2410,0x2410}, {0x2411,0x2411,0x2411}, {0x2412,0x2412,0x2412}, {0x2413,0x2413,0x2413}, {0x2414,0x2414,0x2414}, {0x2415,0x2415,0x2415}, {0x2416,0x2416,0x2416}, {0x2417,0x2417,0x2417}, {0x2418,0x2418,0x2418}, {0x2419,0x2419,0x2419}, {0x241A,0x241A,0x241A}, {0x241B,0x241B,0x241B}, {0x241C,0x241C,0x241C}, {0x241D,0x241D,0x241D}, {0x241E,0x241E,0x241E}, {0x241F,0x241F,0x241F}, {0x2420,0x2420,0x2420}, {0x2421,0x2421,0x2421}, {0x2422,0x2422,0x2422}, {0x2423,0x2423,0x2423}, {0x2424,0x2424,0x2424}, {0x2425,0x2425,0x2425}, {0x2426,0x2426,0x2426}, {0x2427,0x2427,0x2427}, {0x2428,0x2428,0x2428}, {0x2429,0x2429,0x2429}, {0x242A,0x242A,0x242A}, {0x242B,0x242B,0x242B}, {0x242C,0x242C,0x242C}, {0x242D,0x242D,0x242D}, {0x242E,0x242E,0x242E}, {0x242F,0x242F,0x242F}, {0x2430,0x2430,0x2430}, {0x2431,0x2431,0x2431}, {0x2432,0x2432,0x2432}, {0x2433,0x2433,0x2433}, {0x2434,0x2434,0x2434}, {0x2435,0x2435,0x2435}, {0x2436,0x2436,0x2436}, {0x2437,0x2437,0x2437}, {0x2438,0x2438,0x2438}, {0x2439,0x2439,0x2439}, {0x243A,0x243A,0x243A}, {0x243B,0x243B,0x243B}, {0x243C,0x243C,0x243C}, {0x243D,0x243D,0x243D}, {0x243E,0x243E,0x243E}, {0x243F,0x243F,0x243F}, {0x2440,0x2440,0x2440}, {0x2441,0x2441,0x2441}, {0x2442,0x2442,0x2442}, {0x2443,0x2443,0x2443}, {0x2444,0x2444,0x2444}, {0x2445,0x2445,0x2445}, {0x2446,0x2446,0x2446}, {0x2447,0x2447,0x2447}, {0x2448,0x2448,0x2448}, {0x2449,0x2449,0x2449}, {0x244A,0x244A,0x244A}, {0x244B,0x244B,0x244B}, {0x244C,0x244C,0x244C}, {0x244D,0x244D,0x244D}, {0x244E,0x244E,0x244E}, {0x244F,0x244F,0x244F}, {0x2450,0x2450,0x2450}, {0x2451,0x2451,0x2451}, {0x2452,0x2452,0x2452}, {0x2453,0x2453,0x2453}, {0x2454,0x2454,0x2454}, {0x2455,0x2455,0x2455}, {0x2456,0x2456,0x2456}, {0x2457,0x2457,0x2457}, {0x2458,0x2458,0x2458}, {0x2459,0x2459,0x2459}, {0x245A,0x245A,0x245A}, {0x245B,0x245B,0x245B}, {0x245C,0x245C,0x245C}, {0x245D,0x245D,0x245D}, {0x245E,0x245E,0x245E}, {0x245F,0x245F,0x245F}, {0x2460,0x2460,0x2460}, {0x2461,0x2461,0x2461}, {0x2462,0x2462,0x2462}, {0x2463,0x2463,0x2463}, {0x2464,0x2464,0x2464}, {0x2465,0x2465,0x2465}, {0x2466,0x2466,0x2466}, {0x2467,0x2467,0x2467}, {0x2468,0x2468,0x2468}, {0x2469,0x2469,0x2469}, {0x246A,0x246A,0x246A}, {0x246B,0x246B,0x246B}, {0x246C,0x246C,0x246C}, {0x246D,0x246D,0x246D}, {0x246E,0x246E,0x246E}, {0x246F,0x246F,0x246F}, {0x2470,0x2470,0x2470}, {0x2471,0x2471,0x2471}, {0x2472,0x2472,0x2472}, {0x2473,0x2473,0x2473}, {0x2474,0x2474,0x2474}, {0x2475,0x2475,0x2475}, {0x2476,0x2476,0x2476}, {0x2477,0x2477,0x2477}, {0x2478,0x2478,0x2478}, {0x2479,0x2479,0x2479}, {0x247A,0x247A,0x247A}, {0x247B,0x247B,0x247B}, {0x247C,0x247C,0x247C}, {0x247D,0x247D,0x247D}, {0x247E,0x247E,0x247E}, {0x247F,0x247F,0x247F}, {0x2480,0x2480,0x2480}, {0x2481,0x2481,0x2481}, {0x2482,0x2482,0x2482}, {0x2483,0x2483,0x2483}, {0x2484,0x2484,0x2484}, {0x2485,0x2485,0x2485}, {0x2486,0x2486,0x2486}, {0x2487,0x2487,0x2487}, {0x2488,0x2488,0x2488}, {0x2489,0x2489,0x2489}, {0x248A,0x248A,0x248A}, {0x248B,0x248B,0x248B}, {0x248C,0x248C,0x248C}, {0x248D,0x248D,0x248D}, {0x248E,0x248E,0x248E}, {0x248F,0x248F,0x248F}, {0x2490,0x2490,0x2490}, {0x2491,0x2491,0x2491}, {0x2492,0x2492,0x2492}, {0x2493,0x2493,0x2493}, {0x2494,0x2494,0x2494}, {0x2495,0x2495,0x2495}, {0x2496,0x2496,0x2496}, {0x2497,0x2497,0x2497}, {0x2498,0x2498,0x2498}, {0x2499,0x2499,0x2499}, {0x249A,0x249A,0x249A}, {0x249B,0x249B,0x249B}, {0x249C,0x249C,0x249C}, {0x249D,0x249D,0x249D}, {0x249E,0x249E,0x249E}, {0x249F,0x249F,0x249F}, {0x24A0,0x24A0,0x24A0}, {0x24A1,0x24A1,0x24A1}, {0x24A2,0x24A2,0x24A2}, {0x24A3,0x24A3,0x24A3}, {0x24A4,0x24A4,0x24A4}, {0x24A5,0x24A5,0x24A5}, {0x24A6,0x24A6,0x24A6}, {0x24A7,0x24A7,0x24A7}, {0x24A8,0x24A8,0x24A8}, {0x24A9,0x24A9,0x24A9}, {0x24AA,0x24AA,0x24AA}, {0x24AB,0x24AB,0x24AB}, {0x24AC,0x24AC,0x24AC}, {0x24AD,0x24AD,0x24AD}, {0x24AE,0x24AE,0x24AE}, {0x24AF,0x24AF,0x24AF}, {0x24B0,0x24B0,0x24B0}, {0x24B1,0x24B1,0x24B1}, {0x24B2,0x24B2,0x24B2}, {0x24B3,0x24B3,0x24B3}, {0x24B4,0x24B4,0x24B4}, {0x24B5,0x24B5,0x24B5}, {0x24B6,0x24D0,0x24B6}, {0x24B7,0x24D1,0x24B7}, {0x24B8,0x24D2,0x24B8}, {0x24B9,0x24D3,0x24B9}, {0x24BA,0x24D4,0x24BA}, {0x24BB,0x24D5,0x24BB}, {0x24BC,0x24D6,0x24BC}, {0x24BD,0x24D7,0x24BD}, {0x24BE,0x24D8,0x24BE}, {0x24BF,0x24D9,0x24BF}, {0x24C0,0x24DA,0x24C0}, {0x24C1,0x24DB,0x24C1}, {0x24C2,0x24DC,0x24C2}, {0x24C3,0x24DD,0x24C3}, {0x24C4,0x24DE,0x24C4}, {0x24C5,0x24DF,0x24C5}, {0x24C6,0x24E0,0x24C6}, {0x24C7,0x24E1,0x24C7}, {0x24C8,0x24E2,0x24C8}, {0x24C9,0x24E3,0x24C9}, {0x24CA,0x24E4,0x24CA}, {0x24CB,0x24E5,0x24CB}, {0x24CC,0x24E6,0x24CC}, {0x24CD,0x24E7,0x24CD}, {0x24CE,0x24E8,0x24CE}, {0x24CF,0x24E9,0x24CF}, {0x24B6,0x24D0,0x24B6}, {0x24B7,0x24D1,0x24B7}, {0x24B8,0x24D2,0x24B8}, {0x24B9,0x24D3,0x24B9}, {0x24BA,0x24D4,0x24BA}, {0x24BB,0x24D5,0x24BB}, {0x24BC,0x24D6,0x24BC}, {0x24BD,0x24D7,0x24BD}, {0x24BE,0x24D8,0x24BE}, {0x24BF,0x24D9,0x24BF}, {0x24C0,0x24DA,0x24C0}, {0x24C1,0x24DB,0x24C1}, {0x24C2,0x24DC,0x24C2}, {0x24C3,0x24DD,0x24C3}, {0x24C4,0x24DE,0x24C4}, {0x24C5,0x24DF,0x24C5}, {0x24C6,0x24E0,0x24C6}, {0x24C7,0x24E1,0x24C7}, {0x24C8,0x24E2,0x24C8}, {0x24C9,0x24E3,0x24C9}, {0x24CA,0x24E4,0x24CA}, {0x24CB,0x24E5,0x24CB}, {0x24CC,0x24E6,0x24CC}, {0x24CD,0x24E7,0x24CD}, {0x24CE,0x24E8,0x24CE}, {0x24CF,0x24E9,0x24CF}, {0x24EA,0x24EA,0x24EA}, {0x24EB,0x24EB,0x24EB}, {0x24EC,0x24EC,0x24EC}, {0x24ED,0x24ED,0x24ED}, {0x24EE,0x24EE,0x24EE}, {0x24EF,0x24EF,0x24EF}, {0x24F0,0x24F0,0x24F0}, {0x24F1,0x24F1,0x24F1}, {0x24F2,0x24F2,0x24F2}, {0x24F3,0x24F3,0x24F3}, {0x24F4,0x24F4,0x24F4}, {0x24F5,0x24F5,0x24F5}, {0x24F6,0x24F6,0x24F6}, {0x24F7,0x24F7,0x24F7}, {0x24F8,0x24F8,0x24F8}, {0x24F9,0x24F9,0x24F9}, {0x24FA,0x24FA,0x24FA}, {0x24FB,0x24FB,0x24FB}, {0x24FC,0x24FC,0x24FC}, {0x24FD,0x24FD,0x24FD}, {0x24FE,0x24FE,0x24FE}, {0x24FF,0x24FF,0x24FF} }; static MY_UNICASE_INFO planeFF[]={ {0xFF00,0xFF00,0xFF00}, {0xFF01,0xFF01,0xFF01}, {0xFF02,0xFF02,0xFF02}, {0xFF03,0xFF03,0xFF03}, {0xFF04,0xFF04,0xFF04}, {0xFF05,0xFF05,0xFF05}, {0xFF06,0xFF06,0xFF06}, {0xFF07,0xFF07,0xFF07}, {0xFF08,0xFF08,0xFF08}, {0xFF09,0xFF09,0xFF09}, {0xFF0A,0xFF0A,0xFF0A}, {0xFF0B,0xFF0B,0xFF0B}, {0xFF0C,0xFF0C,0xFF0C}, {0xFF0D,0xFF0D,0xFF0D}, {0xFF0E,0xFF0E,0xFF0E}, {0xFF0F,0xFF0F,0xFF0F}, {0xFF10,0xFF10,0xFF10}, {0xFF11,0xFF11,0xFF11}, {0xFF12,0xFF12,0xFF12}, {0xFF13,0xFF13,0xFF13}, {0xFF14,0xFF14,0xFF14}, {0xFF15,0xFF15,0xFF15}, {0xFF16,0xFF16,0xFF16}, {0xFF17,0xFF17,0xFF17}, {0xFF18,0xFF18,0xFF18}, {0xFF19,0xFF19,0xFF19}, {0xFF1A,0xFF1A,0xFF1A}, {0xFF1B,0xFF1B,0xFF1B}, {0xFF1C,0xFF1C,0xFF1C}, {0xFF1D,0xFF1D,0xFF1D}, {0xFF1E,0xFF1E,0xFF1E}, {0xFF1F,0xFF1F,0xFF1F}, {0xFF20,0xFF20,0xFF20}, {0xFF21,0xFF41,0xFF21}, {0xFF22,0xFF42,0xFF22}, {0xFF23,0xFF43,0xFF23}, {0xFF24,0xFF44,0xFF24}, {0xFF25,0xFF45,0xFF25}, {0xFF26,0xFF46,0xFF26}, {0xFF27,0xFF47,0xFF27}, {0xFF28,0xFF48,0xFF28}, {0xFF29,0xFF49,0xFF29}, {0xFF2A,0xFF4A,0xFF2A}, {0xFF2B,0xFF4B,0xFF2B}, {0xFF2C,0xFF4C,0xFF2C}, {0xFF2D,0xFF4D,0xFF2D}, {0xFF2E,0xFF4E,0xFF2E}, {0xFF2F,0xFF4F,0xFF2F}, {0xFF30,0xFF50,0xFF30}, {0xFF31,0xFF51,0xFF31}, {0xFF32,0xFF52,0xFF32}, {0xFF33,0xFF53,0xFF33}, {0xFF34,0xFF54,0xFF34}, {0xFF35,0xFF55,0xFF35}, {0xFF36,0xFF56,0xFF36}, {0xFF37,0xFF57,0xFF37}, {0xFF38,0xFF58,0xFF38}, {0xFF39,0xFF59,0xFF39}, {0xFF3A,0xFF5A,0xFF3A}, {0xFF3B,0xFF3B,0xFF3B}, {0xFF3C,0xFF3C,0xFF3C}, {0xFF3D,0xFF3D,0xFF3D}, {0xFF3E,0xFF3E,0xFF3E}, {0xFF3F,0xFF3F,0xFF3F}, {0xFF40,0xFF40,0xFF40}, {0xFF21,0xFF41,0xFF21}, {0xFF22,0xFF42,0xFF22}, {0xFF23,0xFF43,0xFF23}, {0xFF24,0xFF44,0xFF24}, {0xFF25,0xFF45,0xFF25}, {0xFF26,0xFF46,0xFF26}, {0xFF27,0xFF47,0xFF27}, {0xFF28,0xFF48,0xFF28}, {0xFF29,0xFF49,0xFF29}, {0xFF2A,0xFF4A,0xFF2A}, {0xFF2B,0xFF4B,0xFF2B}, {0xFF2C,0xFF4C,0xFF2C}, {0xFF2D,0xFF4D,0xFF2D}, {0xFF2E,0xFF4E,0xFF2E}, {0xFF2F,0xFF4F,0xFF2F}, {0xFF30,0xFF50,0xFF30}, {0xFF31,0xFF51,0xFF31}, {0xFF32,0xFF52,0xFF32}, {0xFF33,0xFF53,0xFF33}, {0xFF34,0xFF54,0xFF34}, {0xFF35,0xFF55,0xFF35}, {0xFF36,0xFF56,0xFF36}, {0xFF37,0xFF57,0xFF37}, {0xFF38,0xFF58,0xFF38}, {0xFF39,0xFF59,0xFF39}, {0xFF3A,0xFF5A,0xFF3A}, {0xFF5B,0xFF5B,0xFF5B}, {0xFF5C,0xFF5C,0xFF5C}, {0xFF5D,0xFF5D,0xFF5D}, {0xFF5E,0xFF5E,0xFF5E}, {0xFF5F,0xFF5F,0xFF5F}, {0xFF60,0xFF60,0xFF60}, {0xFF61,0xFF61,0xFF61}, {0xFF62,0xFF62,0xFF62}, {0xFF63,0xFF63,0xFF63}, {0xFF64,0xFF64,0xFF64}, {0xFF65,0xFF65,0xFF65}, {0xFF66,0xFF66,0xFF66}, {0xFF67,0xFF67,0xFF67}, {0xFF68,0xFF68,0xFF68}, {0xFF69,0xFF69,0xFF69}, {0xFF6A,0xFF6A,0xFF6A}, {0xFF6B,0xFF6B,0xFF6B}, {0xFF6C,0xFF6C,0xFF6C}, {0xFF6D,0xFF6D,0xFF6D}, {0xFF6E,0xFF6E,0xFF6E}, {0xFF6F,0xFF6F,0xFF6F}, {0xFF70,0xFF70,0xFF70}, {0xFF71,0xFF71,0xFF71}, {0xFF72,0xFF72,0xFF72}, {0xFF73,0xFF73,0xFF73}, {0xFF74,0xFF74,0xFF74}, {0xFF75,0xFF75,0xFF75}, {0xFF76,0xFF76,0xFF76}, {0xFF77,0xFF77,0xFF77}, {0xFF78,0xFF78,0xFF78}, {0xFF79,0xFF79,0xFF79}, {0xFF7A,0xFF7A,0xFF7A}, {0xFF7B,0xFF7B,0xFF7B}, {0xFF7C,0xFF7C,0xFF7C}, {0xFF7D,0xFF7D,0xFF7D}, {0xFF7E,0xFF7E,0xFF7E}, {0xFF7F,0xFF7F,0xFF7F}, {0xFF80,0xFF80,0xFF80}, {0xFF81,0xFF81,0xFF81}, {0xFF82,0xFF82,0xFF82}, {0xFF83,0xFF83,0xFF83}, {0xFF84,0xFF84,0xFF84}, {0xFF85,0xFF85,0xFF85}, {0xFF86,0xFF86,0xFF86}, {0xFF87,0xFF87,0xFF87}, {0xFF88,0xFF88,0xFF88}, {0xFF89,0xFF89,0xFF89}, {0xFF8A,0xFF8A,0xFF8A}, {0xFF8B,0xFF8B,0xFF8B}, {0xFF8C,0xFF8C,0xFF8C}, {0xFF8D,0xFF8D,0xFF8D}, {0xFF8E,0xFF8E,0xFF8E}, {0xFF8F,0xFF8F,0xFF8F}, {0xFF90,0xFF90,0xFF90}, {0xFF91,0xFF91,0xFF91}, {0xFF92,0xFF92,0xFF92}, {0xFF93,0xFF93,0xFF93}, {0xFF94,0xFF94,0xFF94}, {0xFF95,0xFF95,0xFF95}, {0xFF96,0xFF96,0xFF96}, {0xFF97,0xFF97,0xFF97}, {0xFF98,0xFF98,0xFF98}, {0xFF99,0xFF99,0xFF99}, {0xFF9A,0xFF9A,0xFF9A}, {0xFF9B,0xFF9B,0xFF9B}, {0xFF9C,0xFF9C,0xFF9C}, {0xFF9D,0xFF9D,0xFF9D}, {0xFF9E,0xFF9E,0xFF9E}, {0xFF9F,0xFF9F,0xFF9F}, {0xFFA0,0xFFA0,0xFFA0}, {0xFFA1,0xFFA1,0xFFA1}, {0xFFA2,0xFFA2,0xFFA2}, {0xFFA3,0xFFA3,0xFFA3}, {0xFFA4,0xFFA4,0xFFA4}, {0xFFA5,0xFFA5,0xFFA5}, {0xFFA6,0xFFA6,0xFFA6}, {0xFFA7,0xFFA7,0xFFA7}, {0xFFA8,0xFFA8,0xFFA8}, {0xFFA9,0xFFA9,0xFFA9}, {0xFFAA,0xFFAA,0xFFAA}, {0xFFAB,0xFFAB,0xFFAB}, {0xFFAC,0xFFAC,0xFFAC}, {0xFFAD,0xFFAD,0xFFAD}, {0xFFAE,0xFFAE,0xFFAE}, {0xFFAF,0xFFAF,0xFFAF}, {0xFFB0,0xFFB0,0xFFB0}, {0xFFB1,0xFFB1,0xFFB1}, {0xFFB2,0xFFB2,0xFFB2}, {0xFFB3,0xFFB3,0xFFB3}, {0xFFB4,0xFFB4,0xFFB4}, {0xFFB5,0xFFB5,0xFFB5}, {0xFFB6,0xFFB6,0xFFB6}, {0xFFB7,0xFFB7,0xFFB7}, {0xFFB8,0xFFB8,0xFFB8}, {0xFFB9,0xFFB9,0xFFB9}, {0xFFBA,0xFFBA,0xFFBA}, {0xFFBB,0xFFBB,0xFFBB}, {0xFFBC,0xFFBC,0xFFBC}, {0xFFBD,0xFFBD,0xFFBD}, {0xFFBE,0xFFBE,0xFFBE}, {0xFFBF,0xFFBF,0xFFBF}, {0xFFC0,0xFFC0,0xFFC0}, {0xFFC1,0xFFC1,0xFFC1}, {0xFFC2,0xFFC2,0xFFC2}, {0xFFC3,0xFFC3,0xFFC3}, {0xFFC4,0xFFC4,0xFFC4}, {0xFFC5,0xFFC5,0xFFC5}, {0xFFC6,0xFFC6,0xFFC6}, {0xFFC7,0xFFC7,0xFFC7}, {0xFFC8,0xFFC8,0xFFC8}, {0xFFC9,0xFFC9,0xFFC9}, {0xFFCA,0xFFCA,0xFFCA}, {0xFFCB,0xFFCB,0xFFCB}, {0xFFCC,0xFFCC,0xFFCC}, {0xFFCD,0xFFCD,0xFFCD}, {0xFFCE,0xFFCE,0xFFCE}, {0xFFCF,0xFFCF,0xFFCF}, {0xFFD0,0xFFD0,0xFFD0}, {0xFFD1,0xFFD1,0xFFD1}, {0xFFD2,0xFFD2,0xFFD2}, {0xFFD3,0xFFD3,0xFFD3}, {0xFFD4,0xFFD4,0xFFD4}, {0xFFD5,0xFFD5,0xFFD5}, {0xFFD6,0xFFD6,0xFFD6}, {0xFFD7,0xFFD7,0xFFD7}, {0xFFD8,0xFFD8,0xFFD8}, {0xFFD9,0xFFD9,0xFFD9}, {0xFFDA,0xFFDA,0xFFDA}, {0xFFDB,0xFFDB,0xFFDB}, {0xFFDC,0xFFDC,0xFFDC}, {0xFFDD,0xFFDD,0xFFDD}, {0xFFDE,0xFFDE,0xFFDE}, {0xFFDF,0xFFDF,0xFFDF}, {0xFFE0,0xFFE0,0xFFE0}, {0xFFE1,0xFFE1,0xFFE1}, {0xFFE2,0xFFE2,0xFFE2}, {0xFFE3,0xFFE3,0xFFE3}, {0xFFE4,0xFFE4,0xFFE4}, {0xFFE5,0xFFE5,0xFFE5}, {0xFFE6,0xFFE6,0xFFE6}, {0xFFE7,0xFFE7,0xFFE7}, {0xFFE8,0xFFE8,0xFFE8}, {0xFFE9,0xFFE9,0xFFE9}, {0xFFEA,0xFFEA,0xFFEA}, {0xFFEB,0xFFEB,0xFFEB}, {0xFFEC,0xFFEC,0xFFEC}, {0xFFED,0xFFED,0xFFED}, {0xFFEE,0xFFEE,0xFFEE}, {0xFFEF,0xFFEF,0xFFEF}, {0xFFF0,0xFFF0,0xFFF0}, {0xFFF1,0xFFF1,0xFFF1}, {0xFFF2,0xFFF2,0xFFF2}, {0xFFF3,0xFFF3,0xFFF3}, {0xFFF4,0xFFF4,0xFFF4}, {0xFFF5,0xFFF5,0xFFF5}, {0xFFF6,0xFFF6,0xFFF6}, {0xFFF7,0xFFF7,0xFFF7}, {0xFFF8,0xFFF8,0xFFF8}, {0xFFF9,0xFFF9,0xFFF9}, {0xFFFA,0xFFFA,0xFFFA}, {0xFFFB,0xFFFB,0xFFFB}, {0xFFFC,0xFFFC,0xFFFC}, {0xFFFD,0xFFFD,0xFFFD}, {0xFFFE,0xFFFE,0xFFFE}, {0xFFFF,0xFFFF,0xFFFF} }; MY_UNICASE_INFO *my_unicase_default[256]={ plane00, plane01, plane02, plane03, plane04, plane05, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, plane1E, plane1F, NULL, plane21, NULL, NULL, plane24, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, planeFF }; #define MY_CS_ILSEQ 0 /* Wrong by sequence: wb_wc */ #define MY_CS_TOOSMALL -101 /* Need at least one byte: wc_mb and mb_wc */ #define MY_CS_TOOSMALL2 -102 /* Need at least two bytes: wc_mb and mb_wc */ #define MY_CS_TOOSMALL3 -103 /* Need at least three bytes: wc_mb and mb_wc */ #define MY_CS_TOOSMALL4 -104 /* Need at least 4 bytes: wc_mb and mb_wc */ #define MY_CS_TOOSMALL5 -105 /* Need at least 5 bytes: wc_mb and mb_wc */ #define MY_CS_TOOSMALL6 -106 /* Need at least 6 bytes: wc_mb and mb_wc */ static int my_utf8_uni(unsigned long * pwc, const unsigned char *s, const unsigned char *e) { unsigned char c; if (s >= e) return MY_CS_TOOSMALL; c= s[0]; if (c < 0x80) { *pwc = c; return 1; } else if (c < 0xc2) return MY_CS_ILSEQ; else if (c < 0xe0) { if (s+2 > e) /* We need 2 characters */ return MY_CS_TOOSMALL2; if (!((s[1] ^ 0x80) < 0x40)) return MY_CS_ILSEQ; *pwc = ((unsigned long) (c & 0x1f) << 6) | (unsigned long) (s[1] ^ 0x80); return 2; } else if (c < 0xf0) { if (s+3 > e) /* We need 3 characters */ return MY_CS_TOOSMALL3; if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 && (c >= 0xe1 || s[1] >= 0xa0))) return MY_CS_ILSEQ; *pwc = ((unsigned long) (c & 0x0f) << 12) | ((unsigned long) (s[1] ^ 0x80) << 6) | (unsigned long) (s[2] ^ 0x80); return 3; } #ifdef UNICODE_32BIT else if (c < 0xf8 && sizeof(my_wc_t)*8 >= 32) { if (s+4 > e) /* We need 4 characters */ return MY_CS_TOOSMALL4; if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 && (s[3] ^ 0x80) < 0x40 && (c >= 0xf1 || s[1] >= 0x90))) return MY_CS_ILSEQ; *pwc = ((unsigned long) (c & 0x07) << 18) | ((unsigned long) (s[1] ^ 0x80) << 12) | ((unsigned long) (s[2] ^ 0x80) << 6) | (unsigned long) (s[3] ^ 0x80); return 4; } else if (c < 0xfc && sizeof(my_wc_t)*8 >= 32) { if (s+5 >e) /* We need 5 characters */ return MY_CS_TOOSMALL5; if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 && (s[3] ^ 0x80) < 0x40 && (s[4] ^ 0x80) < 0x40 && (c >= 0xf9 || s[1] >= 0x88))) return MY_CS_ILSEQ; *pwc = ((unsigned long) (c & 0x03) << 24) | ((unsigned long) (s[1] ^ 0x80) << 18) | ((unsigned long) (s[2] ^ 0x80) << 12) | ((unsigned long) (s[3] ^ 0x80) << 6) | (unsigned long) (s[4] ^ 0x80); return 5; } else if (c < 0xfe && sizeof(my_wc_t)*8 >= 32) { if ( s+6 >e ) /* We need 6 characters */ return MY_CS_TOOSMALL6; if (!((s[1] ^ 0x80) < 0x40 && (s[2] ^ 0x80) < 0x40 && (s[3] ^ 0x80) < 0x40 && (s[4] ^ 0x80) < 0x40 && (s[5] ^ 0x80) < 0x40 && (c >= 0xfd || s[1] >= 0x84))) return MY_CS_ILSEQ; *pwc = ((unsigned long) (c & 0x01) << 30) | ((unsigned long) (s[1] ^ 0x80) << 24) | ((unsigned long) (s[2] ^ 0x80) << 18) | ((unsigned long) (s[3] ^ 0x80) << 12) | ((unsigned long) (s[4] ^ 0x80) << 6) | (unsigned long) (s[5] ^ 0x80); return 6; } #endif return MY_CS_ILSEQ; } #define MY_CS_ILUNI 0 /* Cannot encode Unicode to charset: wc_mb */ #define MY_CS_TOOSMALLN(n) (-100-(n)) static int my_uni_utf8(unsigned long wc, unsigned char *r, unsigned char *e) { int count; if (r >= e) return MY_CS_TOOSMALL; if (wc < 0x80) count = 1; else if (wc < 0x800) count = 2; else if (wc < 0x10000) count = 3; #ifdef UNICODE_32BIT else if (wc < 0x200000) count = 4; else if (wc < 0x4000000) count = 5; else if (wc <= 0x7fffffff) count = 6; #endif else return MY_CS_ILUNI; /* e is a character after the string r, not the last character of it. Because of it (r+count > e), not (r+count-1 >e ) */ if ( r+count > e ) return MY_CS_TOOSMALLN(count); switch (count) { /* Fall through all cases!!! */ #ifdef UNICODE_32BIT case 6: r[5] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x4000000; case 5: r[4] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x200000; case 4: r[3] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x10000; #endif case 3: r[2] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0x800; case 2: r[1] = (unsigned char) (0x80 | (wc & 0x3f)); wc = wc >> 6; wc |= 0xc0; case 1: r[0] = (unsigned char) wc; } return count; } static int cppmysql_caseup_utf8(const char * src, size_t srclen, char *dst, size_t dstlen) { unsigned long wc; int srcres, dstres; const char *srcend = src + srclen; char *dstend = dst + dstlen, *dst0 = dst; MY_UNICASE_INFO **uni_plane= my_unicase_default; while ((src < srcend) && (srcres= my_utf8_uni(&wc, (unsigned char *) src, (unsigned char*) srcend)) > 0) { int plane = (wc>>8) & 0xFF; wc = uni_plane[plane] ? uni_plane[plane][wc & 0xFF].toupper : wc; if ((dstres = my_uni_utf8(wc, (unsigned char*) dst, (unsigned char*) dstend)) <= 0) { break; } src += srcres; dst += dstres; } return static_cast<int>((dst - dst0)); } char * utf8_strup(const char * const src, size_t srclen) { size_t dstlen; char * dst; if (srclen == 0) { srclen = strlen(src); } dst = new char[(dstlen = srclen * 4) + 1]; if (!dst) { return NULL; } dst[cppmysql_caseup_utf8(src, srclen, dst, dstlen)] = '\0'; return dst; } /* HPUX has some problems with long double : http://docs.hp.com/en/B3782-90716/ch02s02.html strtold() has implementations that return struct long_double, 128bit one, which contains four 32bit words. Fix described : -------- union { long_double l_d; long double ld; } u; // convert str to a long_double; store return val in union //(Putting value into union enables converted value to be // accessed as an ANSI C long double) u.l_d = strtold( (const char *)str, (char **)NULL); -------- reinterpret_cast doesn't work :( */ long double strtold(const char *nptr, char **endptr) { /* * Experienced odd compilation errors on one of windows build hosts - * cmake reported there is strold function. Since double and long double on windows * are of the same size - we are using strtod on those platforms regardless * to the HAVE_FUNCTION_STRTOLD value */ #ifdef _WIN32 return ::strtod(nptr, endptr); #else # ifndef HAVE_FUNCTION_STRTOLD return ::strtod(nptr, endptr); # else # if defined(__hpux) && defined(_LONG_DOUBLE) union { long_double l_d; long double ld; } u; u.l_d = ::strtold( nptr, endptr); return u.ld; # else return ::strtold(nptr, endptr); # endif # endif #endif } } /* namespace util */ } /* namespace mysql */ } /* namespace sql */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
45.591509
109
0.71174
vkardon
58637e2a66280026e181478605dca564d3859560
12,121
cpp
C++
src_lib/internal_glyph_for_gen.cpp
ShoYamanishi/SDFont
07dfa7c08ed9074ea87f98d2a3cc882405b09f1b
[ "MIT" ]
15
2019-08-30T15:47:28.000Z
2022-03-18T23:06:37.000Z
src_lib/internal_glyph_for_gen.cpp
0x4D3342/SDFont
07dfa7c08ed9074ea87f98d2a3cc882405b09f1b
[ "MIT" ]
null
null
null
src_lib/internal_glyph_for_gen.cpp
0x4D3342/SDFont
07dfa7c08ed9074ea87f98d2a3cc882405b09f1b
[ "MIT" ]
6
2019-03-31T17:15:45.000Z
2022-01-12T14:58:48.000Z
#include <iostream> #include <fstream> #include <sstream> #include <math.h> #include "generator_config.hpp" #include "internal_glyph_for_gen.hpp" using namespace std; namespace SDFont { const long InternalGlyphForGen::FREE_TYPE_FIXED_POINT_SCALING = 64 ; InternalGlyphForGen::InternalGlyphForGen ( GeneratorConfig& conf, long codePoint, FT_Glyph_Metrics& m ): mConf ( conf ), mCodePoint ( codePoint ), mTextureCoordX ( 0.0 ), mTextureCoordY ( 0.0 ), mTextureWidth ( 0.0 ), mTextureHeight ( 0.0 ), mWidth ( m.width / FREE_TYPE_FIXED_POINT_SCALING ), mHeight ( m.height / FREE_TYPE_FIXED_POINT_SCALING ), mHorizontalBearingX ( m.horiBearingX / FREE_TYPE_FIXED_POINT_SCALING ), mHorizontalBearingY ( m.horiBearingY / FREE_TYPE_FIXED_POINT_SCALING ), mHorizontalAdvance ( m.horiAdvance / FREE_TYPE_FIXED_POINT_SCALING ), mVerticalBearingX ( m.vertBearingX / FREE_TYPE_FIXED_POINT_SCALING ), mVerticalBearingY ( m.vertBearingY / FREE_TYPE_FIXED_POINT_SCALING ), mVerticalAdvance ( m.vertAdvance / FREE_TYPE_FIXED_POINT_SCALING ), mSignedDist ( nullptr ), mSignedDistWidth ( 0 ), mSignedDistHeight ( 0 ), mSignedDistBaseX ( 0 ), mSignedDistBaseY ( 0 ) { mSignedDistWidth = mWidth / mConf.scale() + 2 * mConf.signedDistExtent(); mSignedDistHeight = mHeight/ mConf.scale() + 2 * mConf.signedDistExtent(); } InternalGlyphForGen::~InternalGlyphForGen () { if ( mSignedDist != nullptr ) { free ( mSignedDist ); } } void InternalGlyphForGen::setBaseXY( long x, long y ) { mSignedDistBaseX = x; mSignedDistBaseY = y; auto fDim = (float) mConf.textureSize() ; mTextureCoordX = (float) ( x + mConf.signedDistExtent() ) / fDim ; mTextureCoordY = (float) ( y + mConf.signedDistExtent() ) / fDim ; mTextureWidth = (float) mWidth / ( (float)mConf.scale() * fDim ) ; mTextureHeight = (float) mHeight / ( (float)mConf.scale() * fDim ) ; } void InternalGlyphForGen::addKerning( long followingCodePoint, FT_Pos v ) { mKernings[ followingCodePoint ] = v / FREE_TYPE_FIXED_POINT_SCALING ; } bool InternalGlyphForGen::testOrthogonalPoints( FT_Bitmap& bm, bool testBase, long xBase, long yBase, long offset ) { bool test01 = isPixelSet( bm, xBase, yBase + offset ); bool test02 = isPixelSet( bm, xBase, yBase - offset ); bool test03 = isPixelSet( bm, xBase + offset, yBase ); bool test04 = isPixelSet( bm, xBase - offset, yBase ); if ( test01 && test02 && test03 && test04 ) { if ( !testBase ) { // All the four points are set and the center point is not set. return true; } else { return false; } } else if ( !( test01 || test02 || test03 || test04 ) ) { if ( testBase ) { // All the four points are not set and the center point is set. return true; } else { return false; } } else { // The four points are mixed. return true; } } bool InternalGlyphForGen::testSymmetricPoints( FT_Bitmap& bm, bool testBase, long xBase, long yBase, long offset1, long offset2 ) { bool test01 = isPixelSet( bm, xBase + offset1, yBase + offset2 ); bool test02 = isPixelSet( bm, xBase + offset1, yBase - offset2 ); bool test03 = isPixelSet( bm, xBase - offset1, yBase + offset2 ); bool test04 = isPixelSet( bm, xBase - offset1, yBase - offset2 ); bool test05 = isPixelSet( bm, xBase + offset2, yBase + offset1 ); bool test06 = isPixelSet( bm, xBase + offset2, yBase - offset1 ); bool test07 = isPixelSet( bm, xBase - offset2, yBase + offset1 ); bool test08 = isPixelSet( bm, xBase - offset2, yBase - offset1 ); if ( test01 && test02 && test03 && test04 && test05 && test06 && test07 && test08 ) { if ( !testBase ) { // All the four points are set and the center point is not set. return true; } else { return false; } } else if ( !( test01 || test02 || test03 || test04 || test05 || test06 || test07 || test08 ) ) { if ( testBase ) { // All the four points are not set and the center point is set. return true; } else { return false; } } else { // The four points are mixed. return true; } } bool InternalGlyphForGen::testDiagonalPoints( FT_Bitmap& bm, bool testBase, long xBase, long yBase, long offset ) { bool test01 = isPixelSet( bm, xBase + offset, yBase + offset ); bool test02 = isPixelSet( bm, xBase + offset, yBase - offset ); bool test03 = isPixelSet( bm, xBase - offset, yBase + offset ); bool test04 = isPixelSet( bm, xBase - offset, yBase - offset ); if ( test01 && test02 && test03 && test04 ) { if ( !testBase ) { // All the four points are set and the center point is not set. return true; } else { return false; } } else if ( !( test01 || test02 || test03 || test04 ) ) { if ( testBase ) { // All the four points are not set and the center point is set. return true; } else { return false; } } else { // The four points are mixed. return true; } } float InternalGlyphForGen::getSignedDistance( FT_Bitmap& bm, long scale, long spread, long xSD, long ySD ) { auto hScale = scale / 2; auto xPix = xSD * scale + hScale; auto yPix = ySD * scale + hScale; bool curP = isPixelSet( bm, xPix, yPix ); float fSpread = (float) spread ; float minSqDist = fSpread * fSpread ; long nextStartI = spread + 1; for (auto i = 1 ; i <= spread; i++ ) { float fi = (float)i; if ( testOrthogonalPoints( bm, curP, xPix, yPix, i ) ) { minSqDist = min( minSqDist, fi * fi ); nextStartI = i + 1; break; } bool breaking = false; for ( auto j = 1 ; j < i; j++ ) { if ( testSymmetricPoints( bm, curP, xPix, yPix, i, j ) ) { float fj = (float) j; minSqDist = min( minSqDist, fi * fi + fj * fj ); nextStartI = i + 1; breaking = true; break; } } if (breaking) { break; } if ( testDiagonalPoints( bm, curP, xPix, yPix, i ) ) { minSqDist = min( minSqDist, 2 * fi * fi ); nextStartI = i + 1; break; } } long maxI = min( (long)(sqrt(minSqDist)) + 1, spread ); for (auto i = nextStartI ; i <= maxI; i++ ) { float fi = (float)i; if ( testOrthogonalPoints( bm, curP, xPix, yPix, i ) ) { minSqDist = min( minSqDist, fi * fi ); break; } bool breaking = false; for ( auto j = 1 ; j < nextStartI; j++ ) { if ( testSymmetricPoints( bm, curP, xPix, yPix, i, j ) ) { float fj = (float) j; minSqDist = min( minSqDist, fi * fi + fj * fj ); breaking = true; break; } } if (breaking) { break; } } auto normalizedMinDist = ( (float)sqrt(minSqDist) - 1.0 ) / fSpread ; if (curP) { return 0.5 + ( normalizedMinDist / 2.0 ); } else { return 0.5 - ( normalizedMinDist / 2.0 ); } } void InternalGlyphForGen::setSignedDist( FT_Bitmap& bm ) { mSignedDistWidth = mWidth / mConf.scale() + 2 * mConf.signedDistExtent(); mSignedDistHeight = mHeight/ mConf.scale() + 2 * mConf.signedDistExtent(); size_t arraySizeInBytes = mSignedDistWidth * mSignedDistHeight * sizeof(float) ; mSignedDist = (float*) malloc( arraySizeInBytes ); if ( mSignedDist != nullptr ) { long offset = mConf.signedDistExtent(); for ( long i = 0 ; i < mSignedDistHeight; i++ ) { for ( long j = 0 ; j < mSignedDistWidth; j++ ) { auto val = getSignedDistance( bm, mConf.scale(), mConf.defaultSpread(), j - offset, i - offset ); mSignedDist[i * mSignedDistWidth + j] = val; } } } } void InternalGlyphForGen::releaseBitmap() { if ( mSignedDist != nullptr ) { free( mSignedDist ) ; mSignedDist = nullptr; mSignedDistWidth = 0; mSignedDistHeight = 0; } } void InternalGlyphForGen::visualize( ostream& os ) const { if ( mSignedDist != nullptr ) { for ( long i = 0 ; i < mSignedDistHeight; i++ ) { for ( long j = 0 ; j < mSignedDistWidth; j++ ) { auto val = mSignedDist[ i * mSignedDistWidth + j ]; if ( val >= 0.5 ) { cerr << "*"; } else { cerr << "."; } } cerr << "\n"; } } } void InternalGlyphForGen::emitMetrics( ostream& os ) const { float factor = (float) ( mConf.scale() * mConf.textureSize() ) ; os << mCodePoint ; os << "\t"; os << ( (float)mWidth / factor ); os << "\t"; os << ( (float)mHeight / factor ); os << "\t"; os << ( (float)mHorizontalBearingX / factor ); os << "\t"; os << ( (float)mHorizontalBearingY / factor ); os << "\t"; os << ( (float)mHorizontalAdvance / factor ); os << "\t"; os << ( (float)mVerticalBearingX / factor ); os << "\t"; os << ( (float)mVerticalBearingY / factor ); os << "\t"; os << ( (float)mVerticalAdvance / factor ); os << "\t"; os << mTextureCoordX ; os << "\t"; os << mTextureCoordY ; os << "\t"; os << mTextureWidth ; os << "\t"; os << mTextureHeight ; } void InternalGlyphForGen::emitKernings( ostream& os ) const { if ( mKernings.size() > 0 ) { float factor = (float) ( mConf.scale() * mConf.textureSize() ) ; os << mCodePoint ; for ( auto it = mKernings.begin(); it != mKernings.end(); it++ ) { os << "\t" << it->first ; os << "\t" << (float)( (it->second ) / factor ) ; } os << "\n"; } } Glyph InternalGlyphForGen::generateSDGlyph() const { float factor = (float) ( mConf.scale() * mConf.textureSize() ) ; Glyph g; g.mCodePoint = mCodePoint; g.mWidth = (float)mWidth / factor ; g.mHeight = (float)mHeight / factor ; g.mHorizontalBearingX = (float)mHorizontalBearingX / factor ; g.mHorizontalBearingY = (float)mHorizontalBearingY / factor ; g.mHorizontalAdvance = (float)mHorizontalAdvance / factor ; g.mVerticalBearingX = (float)mVerticalBearingX / factor ; g.mVerticalBearingY = (float)mVerticalBearingY / factor ; g.mVerticalAdvance = (float)mVerticalAdvance / factor ; g.mTextureCoordX = mTextureCoordX ; g.mTextureCoordY = mTextureCoordY ; g.mTextureWidth = mTextureWidth ; g.mTextureHeight = mTextureHeight ; for ( auto it = mKernings.begin(); it != mKernings.end(); it++ ) { g.mKernings[ it->first ] = (float)( (it->second ) / factor ) ; } return g; } } // namespace SDFont
25.57173
78
0.521822
ShoYamanishi
5865579641bcaa78604060f2531c001750bf1e03
4,298
cpp
C++
src/frameworks/native/services/surfaceflinger/tests/unittests/SchedulerUtilsTest.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/services/surfaceflinger/tests/unittests/SchedulerUtilsTest.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
src/frameworks/native/services/surfaceflinger/tests/unittests/SchedulerUtilsTest.cpp
dAck2cC2/m3e
475b89b59d5022a94e00b636438b25e27e4eaab2
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2018 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. */ #undef LOG_TAG #define LOG_TAG "SchedulerUnittests" #include <gmock/gmock.h> #include <gtest/gtest.h> #include <array> #include "Scheduler/SchedulerUtils.h" namespace android { namespace scheduler { class SchedulerUtilsTest : public testing::Test { public: SchedulerUtilsTest() = default; ~SchedulerUtilsTest() override = default; }; namespace { TEST_F(SchedulerUtilsTest, calculate_mean) { std::array<int64_t, 30> testArray{}; // Calling the function on empty array returns 0. EXPECT_EQ(0, calculate_mean(testArray)); testArray[0] = 33; EXPECT_EQ(1, calculate_mean(testArray)); testArray[1] = 33; testArray[2] = 33; EXPECT_EQ(3, calculate_mean(testArray)); testArray[3] = 42; EXPECT_EQ(4, calculate_mean(testArray)); testArray[4] = 33; EXPECT_EQ(5, calculate_mean(testArray)); testArray[5] = 42; EXPECT_EQ(7, calculate_mean(testArray)); for (int i = 6; i < 30; i++) { testArray[i] = 33; } EXPECT_EQ(33, calculate_mean(testArray)); } TEST_F(SchedulerUtilsTest, calculate_median) { std::vector<int64_t> testVector; // Calling the function on empty vector returns 0. EXPECT_EQ(0, calculate_median(&testVector)); testVector.push_back(33); EXPECT_EQ(33, calculate_median(&testVector)); testVector.push_back(33); testVector.push_back(33); EXPECT_EQ(33, calculate_median(&testVector)); testVector.push_back(42); EXPECT_EQ(33, calculate_median(&testVector)); testVector.push_back(33); EXPECT_EQ(33, calculate_median(&testVector)); testVector.push_back(42); EXPECT_EQ(33, calculate_median(&testVector)); testVector.push_back(42); EXPECT_EQ(33, calculate_median(&testVector)); testVector.push_back(42); EXPECT_EQ(42, calculate_median(&testVector)); testVector.push_back(60); EXPECT_EQ(42, calculate_median(&testVector)); testVector.push_back(60); EXPECT_EQ(42, calculate_median(&testVector)); testVector.push_back(33); EXPECT_EQ(42, calculate_median(&testVector)); testVector.push_back(33); EXPECT_EQ(42, calculate_median(&testVector)); testVector.push_back(33); EXPECT_EQ(33, calculate_median(&testVector)); } TEST_F(SchedulerUtilsTest, calculate_mode) { std::vector<int64_t> testVector; // Calling the function on empty vector returns 0. EXPECT_EQ(0, calculate_mode(testVector)); testVector.push_back(33); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(33); testVector.push_back(33); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(42); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(33); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(42); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(42); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(42); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(60); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(60); EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(33); // 5 occurences of 33. EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(42); // 5 occurences of 33, 5 occurences of 42. We choose the first one. EXPECT_EQ(33, calculate_mode(testVector)); testVector.push_back(42); // 5 occurences of 33, 6 occurences of 42. EXPECT_EQ(42, calculate_mode(testVector)); testVector.push_back(42); // 5 occurences of 33, 7 occurences of 42. EXPECT_EQ(42, calculate_mode(testVector)); } } // namespace } // namespace scheduler } // namespace android
32.80916
75
0.713355
dAck2cC2
586594881f6a520469097d6f8f3485a28c805e1f
2,215
cpp
C++
test/lib/core/proxy.test.cpp
tmehnert/complate-cpp
8780cff967e25279584d0e1619666783f7ff6b40
[ "Apache-2.0" ]
5
2021-12-18T09:12:51.000Z
2022-01-28T17:43:13.000Z
test/lib/core/proxy.test.cpp
tmehnert/complate-cpp
8780cff967e25279584d0e1619666783f7ff6b40
[ "Apache-2.0" ]
10
2021-10-18T05:45:18.000Z
2021-12-12T11:09:20.000Z
test/lib/core/proxy.test.cpp
tmehnert/complate-cpp
8780cff967e25279584d0e1619666783f7ff6b40
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Torsten Mehnert * * 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 <complate/core/proxy.h> #include "catch2/catch.hpp" using namespace complate; using namespace std; using Catch::Matchers::Equals; class ProxyTestClass {}; TEST_CASE("Proxy", "[core]") { SECTION("traits") { REQUIRE(is_copy_constructible_v<Proxy>); REQUIRE(is_copy_assignable_v<Proxy>); REQUIRE(is_move_constructible_v<Proxy>); REQUIRE(is_move_assignable_v<Proxy>); } SECTION("constructed without name, take typeid for name") { auto proxy = Proxy(make_shared<ProxyTestClass>()); REQUIRE_THAT(proxy.name(), Equals(typeid(ProxyTestClass).name())); } SECTION("constructed with name, take name") { auto proxy = Proxy("MyProxyTestClass", make_shared<ProxyTestClass>()); REQUIRE_THAT(proxy.name(), Equals("MyProxyTestClass")); } SECTION("ptr return the object") { auto object = make_shared<ProxyTestClass>(); auto proxy = Proxy("ProxyTestClass", object); REQUIRE(proxy.ptr() == object); } SECTION("operator==/!=") { auto object = make_shared<ProxyTestClass>(); auto proxy = Proxy("ProxyTestClass", object); SECTION("this is equal") { REQUIRE(proxy == proxy); } SECTION("with same values is equal") { auto another = Proxy("ProxyTestClass", object); REQUIRE(another == proxy); } SECTION("with different name is not equal") { auto another = Proxy("AnotherName", object); REQUIRE(another != proxy); } SECTION("with different object instance is not equal") { auto another = Proxy("ProxyTestClass", make_shared<ProxyTestClass>()); REQUIRE(another != proxy); } } }
31.197183
76
0.688488
tmehnert
586619c126017122df89c63316c233ea8027efa4
26,060
hpp
C++
Motorola/MCore IDA IDP/5.0/IDA/Inc/area.hpp
erithion/old_junk
b2dcaa23320824f8b2c17571f27826869ccd0d4b
[ "MIT" ]
1
2021-06-26T17:08:24.000Z
2021-06-26T17:08:24.000Z
Motorola/MCore IDA IDP/5.0/IDA/Inc/area.hpp
erithion/old_junk
b2dcaa23320824f8b2c17571f27826869ccd0d4b
[ "MIT" ]
null
null
null
Motorola/MCore IDA IDP/5.0/IDA/Inc/area.hpp
erithion/old_junk
b2dcaa23320824f8b2c17571f27826869ccd0d4b
[ "MIT" ]
null
null
null
/* * Interactive disassembler (IDA). * Copyright (c) 1990-97 by Ilfak Guilfanov. * ALL RIGHTS RESERVED. * E-mail: ig@estar.msk.su * FIDO: 2:5020/209 * */ #ifndef _AREA_HPP #define _AREA_HPP // // This file contains definition of "areacb_t". // "areacb_t" is a base class used by many parts of IDA. // "areacb_t" is a collection of address ranges in the program. // "areacb_t" conceptually consists of separate area_t instances. // An area is a non-empty contiguous range of addresses (specified by // its start and end addresses, the end address is excluded from the // range) with some characteristics. For example, the ensemble of program // segments is represented by an "areacb_t" called "segs". // // Areas are stored in the Btree part of the IDA database. // To learn more about Btrees (Balanced Trees): // http://www.bluerwhite.org/btree/ // #include <help.h> #pragma pack(push, 1) // IDA uses 1 byte alignments! //-------------------------------------------------------------------------- // Base class for an area. This class is used as a base class for // a class with real information - see segment.hpp for example. // The end address points beyond the area. struct area_t { ea_t startEA; ea_t endEA; // endEA excluded area_t(void) {} area_t(ea_t ea1, ea_t ea2) { startEA = ea1; endEA = ea2; } int compare(const area_t &r) const { return startEA > r.startEA ? 1 : startEA < r.startEA ? -1 : 0; } bool operator ==(const area_t &r) const { return compare(r) == 0; } bool operator !=(const area_t &r) const { return compare(r) != 0; } bool operator > (const area_t &r) const { return compare(r) > 0; } bool operator < (const area_t &r) const { return compare(r) < 0; } bool contains(ea_t ea) const { return startEA <= ea && endEA > ea; } bool contains(const area_t &r) const { return r.startEA >= startEA && r.endEA <= endEA; } bool empty(void) const { return startEA >= endEA; } asize_t size(void) const { return endEA - startEA; } void intersect(const area_t &r) { if ( startEA < r.startEA ) startEA = r.startEA; if ( endEA > r.endEA ) endEA = r.endEA; if ( endEA < startEA ) endEA = startEA; } }; // This class is used to store part of information about areacb_t. class sarray; // sorted array - keeps information in Btree. // Size of internal cache of areas. #define AREA_CACHE_SIZE 128 // Convenience shortcut, used internally #define ANODE netnode(areasCode) #define ANODE2 netnode(cb->areasCode) // Special tag used to mark long comments #define AREA_LONG_COMMENT_TAG 0x01020304L // internal //-------------------------------------------------------------------------- // Helper functions. Should not be called directly! #define AREA_HELPER_DEFINITIONS(decl) \ decl void ida_export areacb_t_zero (areacb_t *);\ decl void ida_export areacb_t_terminate (areacb_t *);\ decl void ida_export areacb_t_save (areacb_t *);\ decl bool ida_export areacb_t_link (areacb_t *,const char *file, const char *name, int infosize);\ decl bool ida_export areacb_t_create (areacb_t *,const char *file,const char *name,uint infosize);\ decl void ida_export areacb_t_kill (areacb_t *);\ decl bool ida_export areacb_t_create_area (areacb_t *,area_t *info);\ decl bool ida_export areacb_t_update (areacb_t *,area_t *info);\ decl area_t *ida_export areacb_t_get_area (areacb_t *,ea_t ea);\ decl area_t *ida_export areacb_t_getn_area (areacb_t *,unsigned int n);\ decl int ida_export areacb_t_get_area_num (areacb_t *,ea_t ea);\ decl ea_t ida_export areacb_t_prepare_to_create(areacb_t *,ea_t start,ea_t end);\ decl int ida_export areacb_t_get_next_area (areacb_t *,ea_t ea);\ decl int ida_export areacb_t_get_prev_area (areacb_t *,ea_t ea);\ decl bool ida_export areacb_t_del_area (areacb_t *,ea_t ea, bool delcmt);\ decl bool ida_export areacb_t_may_start_at (areacb_t *,uint n,ea_t newstart);\ decl bool ida_export areacb_t_may_end_at (areacb_t *,uint n,ea_t newend);\ decl bool ida_export areacb_t_set_start (areacb_t *,uint n,ea_t newstart);\ decl bool ida_export areacb_t_set_end (areacb_t *,uint n,ea_t newend);\ decl bool ida_export areacb_t_resize_areas (areacb_t *,uint n,ea_t newstart);\ decl uint ida_export areacb_t_get_area_qty (areacb_t *);\ decl area_t *ida_export areacb_t_choose_area (areacb_t *,int flags, int width, char *(idaapi*getl)(areacb_t *obj,ulong n,char *buf), const char *title, int icon, int x0,int y0,int x1,int y1, const char * const *popup_menus, ea_t defea);\ decl area_t *ida_export areacb_t_choose_area2 (areacb_t *,int flags, int ncol, const int *widths, void (idaapi*getl)(areacb_t *obj,ulong n,char * const *arrptr), const char *title, int icon, int x0,int y0,int x1,int y1, const char * const *popup_menus, ea_t defea);\ decl bool ida_export areacb_t_set_area_cmt (areacb_t *,const area_t *a, const char *cmt, bool repeatable);\ decl char *ida_export areacb_t_get_area_cmt (areacb_t *,const area_t *a, bool repeatable);\ decl int ida_export areacb_t_move_areas (areacb_t *,ea_t from,ea_t to, asize_t size, int (idaapi*area_mover)(area_t *a, adiff_t delta, void *ud), void *ud);\ decl void ida_export areacb_t_make_hole (areacb_t *,ea_t ea1, ea_t ea2, bool create_tail_area);\ decl int ida_export areacb_t_for_all_areas (areacb_t *,ea_t ea1, ea_t ea2, area_visitor_t *av, void *ud); class areacb_t; typedef int idaapi area_visitor_t(area_t *a, void *ud); AREA_HELPER_DEFINITIONS(idaman) //-------------------------------------------------------------------------- // Definition of areas control block. Each type of areas has its own // control block. Access to all areas of one type is made using this // control block. class areacb_t { AREA_HELPER_DEFINITIONS(friend) // private definitions, I won't comment them thoroughly uval_t areasCode; // code in the database ushort infosize; // sizeof info for area area_t *lastInfo; // pointer to the last area long lastNum; // the last area number (-1: no last area) sarray *sa; // sorted array on supvals area_t *cache[AREA_CACHE_SIZE]; void allocate(const char *file, bool del_other); // allocate memory for lastInfo area_t *search(ea_t EA, long *n); // search for area area_t *readArea(ea_t EA); // read area info from base // exit if any error (with a message) int findCache(ea_t ea); area_t *addCache(area_t *a); // returns allocated in cache Area void delCache(ea_t ea); void free_cache(void); ea_t find_nth_start(int n); void build_optimizer(void); void move_area_comment(ea_t oldea, ea_t newea); bool pack_and_write_area(area_t *a); // returns 1-ok, 0-failure bool move_away(int cur, ea_t ea1, ea_t ea2, bool create_tail_area); public: // Read callback: read area from the database. // This function is called when a (possibly packed) area is read from the database. // packed - stream of packed bytes // ebd - ptr to the end of the stream // a - place to put unpacked version of the area // This callback may be NULL. void (idaapi *read_cb)(const uchar *packed, const uchar *end, area_t *a); // Write callback: write area to the database. // This function is called when an area is about to be writed to the database. // It may pack the the area to the stream of bytes. // a - area to be written // packbuf - buffer to hold packed version of the area // packend - ptr to the end of packbuf // Returns: number of bytes in the packed form // This callback may be NULL. size_t (idaapi *write_cb)(const area_t *a,uchar *packbuf, uchar *packend); // Destroy callback: remove an area from the internal cache. // This function is called when an area is freed from the cache. // This callback may be NULL. void (idaapi *delcache_cb)(area_t *a); // The following three callbacks are used in open_areas_window() function. // When the user presses Ctrl-E key the following callback is called // to edit the selected area. // This callback may be NULL. int (idaapi *edit_cb)(area_t *a); // Callback to handle "Del" keystroke in open_areas_window() function // This callback may be NULL. int (idaapi *kill_cb)(area_t *a); // Callback to handle "Ins" keystroke in open_areas_window() function // This callback may be NULL. int (idaapi *new_cb)(void); // Constructor. Initialized area control block. You need to link // area control block to existing area information in Btree (link) or // to create a new area information structure in Btree (create). void zero(void) { areacb_t_zero(this); } areacb_t(void) { zero(); } // Destructor. Flushes all information to Btree, deallocates caches and // unlinks area control block from Btree. void terminate(void) { areacb_t_terminate(this); } ~areacb_t(void) { terminate(); } // Flush area control block to Btree. void save(void) { areacb_t_save(this); } // Link area control block to Btree. Allocate cache, etc. // Btree should contain information about the specified areas. // After calling this function you may work with areas. // file - name of input file being disassembled. // Doesn't matter if useva==0. // This parameter is used to build name of the file // with the virtual array. // name - name of area information in Btree. // The name should start with "$ " (yes, including a space) // You may use any name you like. For example, area control // block keeping information about separation of program regions // to different output files might be: // "$ here is info about output file areas" // infosize- size of a structure with actual area information // (size of class based on class area_t) // This function properly terminates work with the previous area control // block in Btree if the current class was used to access information. // // returns:1-ok,0-failure (no such node in Btree) bool link(const char *file, // Access to existing areas const char *name, int infosize) { return areacb_t_link(this, file, name, infosize); } // Create area information node in Btree. // This function usually is used when a new file is loaded into the database. // See link() for explanations of input parameteres. // This function properly terminates work with the previous area control // block in Btree if the current class was used to access information. // // returns:1-ok // 0-failure (Btree already contains node with the specified name) bool create(const char *file,const char *name,uint infosize) { return areacb_t_create(this, file, name, infosize); } // Delete area information in Btree. // All information about the current type of areas is deleted. // Deallocate cache. void kill(void) { areacb_t_kill(this); } // Create an area. // The new area should not overlap with existing ones. // info - structure containing information about a new area // startEA and endEA specify address range. // startEA should be lower than endEA // returns 1-ok,0-failure, area overlaps with another area or bad address range. bool create_area(area_t *info) // Create new area { return areacb_t_create_area(this, info); } // Update information about area in Btree. // This function can't change startEA and endEA fields. // Its only purpose is to update additional characteristics of the area. bool update(area_t *info) // Update info about area_t. { return areacb_t_update(this, info); } // Get pointer to area structure by address // ea - any address in the area // returns NULL: no area occupies the specified address // otherwise returns pointer to area structure. area_t *get_area(ea_t ea) // Get area by EA { return areacb_t_get_area(this, ea); } // Get pointer to area structure by its number // n - number of area (0..get_area_qty()-1) // returns NULL: the specified area doesn't exist. // otherwise returns pointer to area structure. area_t *getn_area(unsigned int n) // Get n-th area (0..n) { return areacb_t_getn_area(this, n); } // Get number of area by address // ea - any address in the area // returns -1: no area occupies the specified address // otherwise returns number of the specified area (0..get_area_qty()-1) int get_area_num(ea_t ea) // Get area number. -1 - no such area { return areacb_t_get_area_num(this, ea); } // Prepare to create a new area // This function checks whether the new area overlap with an existing one // and trims an existing area to make enough address range for the creation // of the new area. If the trimming of the existing area doesn't make enough // room for the new area, the existing area is simply deleted. // start - start address of the new area // end - end address of the new area // returns: an adjusted end address for the new area. The end address may // require some adjustment if another (next) area exists and occupies // some addresses from (start..end) range. In this case we don't // delete the existing area but adjust end address of the new area. ea_t prepare_to_create(ea_t start,ea_t end)// Prepare to create an area (sEA,eEA) // - trim previous area // - return max allowed end of area { return areacb_t_prepare_to_create(this, start, end); } // Get number of the next area. // This function returns number of the next (higher in the addressing space) // area. // ea - any address in the program // returns -1: no (more) areas // otherwise returns number in the range (0..get_area_qty()-1) int get_next_area(ea_t ea) // Return next area for EA // -1 - no (more) areas { return areacb_t_get_next_area(this, ea); } // Get number of the previous area. // This function returns number of the previous (lower in the addressing space) // area. // ea - any address in the program // returns -1: no (more) areas // otherwise returns number in the range (0..get_area_qty()-1) int get_prev_area(ea_t ea) // Returns prev area for EA // Returns -1 if not found { return areacb_t_get_prev_area(this, ea); } // Delete an area. // ea - any address in the area // delcmt - delete area comments // you may choose not to delete comments if you want to // create a new area with the same start address immediately. // In this case the new area will inherit old area comments. // returns 1-ok,0-failure (no such area) bool del_area(ea_t ea, bool delcmt=true) // Delete area { return areacb_t_del_area(this, ea, delcmt); } // Check if the specified area may start at the specified address. // This function checks whether the specified area can be changed so // that its start address would be 'newstart'. // n - number of area to check // newstart - new start address for the area // returns: 1-yes, it can // 0-no // the specified area doesn't exist // new start address is higher or equal to end address // the area would overlap with another area bool may_start_at(uint n,ea_t newstart) // can the area have 'newstart' { return areacb_t_may_start_at(this, n, newstart); } // Check if the specified area may end at the specified address. // This function checks whether the specified area can be changed so // that its end address would be 'newend'. // n - number of area to check // newend - new end address for the area // returns: 1-yes, it can // 0-no // the specified area doesn't exist // new end address is lower or equal to start address // the area would overlap with another area bool may_end_at(uint n,ea_t newend) // can the area have 'newend' { return areacb_t_may_end_at(this, n, newend); } // Change start address of the area // n - number of area to change // newstart - new start address for the area // This function doesn't modify other areas. // returns: 1-ok, area is changed // 0-failure // the specified area doesn't exist // new start address is higher or equal to end address // the area would overlap with another area bool set_start(uint n, ea_t newstart) { return areacb_t_set_start(this, n, newstart); } // Change end address of the area // n - number of area to change // newend - new end address for the area // This function doesn't modify other areas. // returns: 1-ok, area is changed // 0-failure // the specified area doesn't exist // new end address is lower or equal to start address // the area would overlap with another area bool set_end(uint n, ea_t newend) { return areacb_t_set_end(this, n, newend); } // Make a hole at the specified address by deleting or modifying // existing areas // ea1, ea2 - range to clear // create_tail_area - in the case if there is a big area overlapping // the specified range, should it be divided in two areas? // if 'false', then it will be truncated and the tail // will be left without any covering area void make_hole(ea_t ea1, ea_t ea2, bool create_tail_area) { areacb_t_make_hole(this, ea1, ea2, create_tail_area); } // Resize adjacent areas simultaneously // n - number of area to change // The adjacent (previous) area will be trimmed or expanded // if it exists and two areas are contiguous. // Otherwise this function behaves like set_start() function. // returns: 1-ok,0-failure bool resize_areas(uint n,ea_t newstart) // Resize adjacent areas { return areacb_t_resize_areas(this, n, newstart); } // Get number of areas. // returns: number of areas ( >= 0 ) uint get_area_qty(void) // Get number of areas { return areacb_t_get_area_qty(this); } // Let the user choose an area. (1-column chooser) // This function displays a window with a list of areas // and allows the user to choose an area from the list. // flags - see kernwin.hpp for choose() flags description and callbacks usage // width - width of the window // getl - callback function to get text representation of an area // obj - pointer to area control block // n - (number of area + 1). if n==0 then getl() should // return text of a header line. // buf - buffer for the text representation // getl() should return pointer to text representation string // (not nesessarily the same pointer as 'buf') // title - title of the window. // icon - number of icon to display // defea - address which points to the default area. The cursor will be // position to this area. // (x0,y0,x1,y1) - window position on the screen // -1 values specify default window position // (txt:upper left corner of the screen) // (gui:centered on the foreground window) // popup_menus - default is insert, delete, edit, refresh // returns: NULL - the user pressed Esc. // otherwise - pointer to the selected area. area_t *choose_area(int flags, int width, char *(idaapi*getl)(areacb_t *obj,ulong n,char *buf), const char *title, int icon, int x0=-1,int y0=-1,int x1=-1,int y1=-1, const char * const *popup_menus=NULL, ea_t defea=BADADDR) { return areacb_t_choose_area(this, flags, width, getl, title, icon, x0, y0, x1, y1, popup_menus, defea); } // Let the user choose an area. (n-column chooser) // This function displays a window with a list of areas // and allows the user to choose an area from the list. // flags - see kernwin.hpp for choose() flags description and callbacks usage // ncol - number of columns // widths- widths of each column in characters (may be NULL) // getl - callback function to get text representation of an area // obj - pointer to area control block // n - (number of area + 1). if n==0 then getl() should // return text of a header line. // arrptr - array of buffers for the text representation // title - title of the window. // icon - number of icon to display // defea - address which points to the default area. The cursor will be // position to this area. // (x0,y0,x1,y1) - window position on the screen // -1 values specify default window position // (txt:upper left corner of the screen) // (gui:centered on the foreground window) // popup_menus - default is insert, delete, edit, refresh // returns: NULL - the user cancelled the selection // otherwise - pointer to the selected area. area_t *choose_area2(int flags, int ncol, const int *widths, void (idaapi*getl)(areacb_t *obj,ulong n,char * const *arrptr), const char *title, int icon, int x0=-1,int y0=-1,int x1=-1,int y1=-1, const char * const *popup_menus=NULL, ea_t defea=BADADDR) { return areacb_t_choose_area2(this, flags, ncol, widths, getl, title, icon, x0, y0, x1, y1, popup_menus, defea); } // Find previous gap in areas. // This function finds a gap between areas. Only enabled addresses // (see bytes.hpp for explanations on addressing) are used in the search. // ea - any linear address // returns: BADADDR - no previous gap is found // otherwise returns maximal address in the previous gap ea_t find_prev_gap(ea_t ea); // find prev/next gaps in the enabled addresses // Find next gap in areas. // This function finds a gap between areas. Only enabled addresses // (see bytes.hpp for explanations on addressing) are used in the search. // ea - any linear address // returns: BADADDR - no next gap is found // otherwise returns start address of the next gap ea_t find_next_gap(ea_t ea); // if not found, returns BADADDR // Set area comment. // This function sets area comment. // a - pointer to area structure (may be NULL) // repratable - 0: set regular comment // 1: set repeatable comment bool set_area_cmt(const area_t *a, const char *cmt, bool repeatable) { return areacb_t_set_area_cmt(this, a, cmt, repeatable); } // Delete area comment. // Each area may have its comment (a function may have a comment, for example) // This function deletes such a comment // a - pointer to area structure (may be NULL) // repratable - 0: delete regular comment // 1: delete repeatable comment void del_area_cmt(const area_t *a, bool repeatable) { set_area_cmt(a, "", repeatable); } // Get area comment. // This function gets area comment. // a - pointer to area structure (may be NULL) // repratable - 0: get regular comment // 1: get repeatable comment // The caller must qfree() the result. char *get_area_cmt(const area_t *a, bool repeatable) { return areacb_t_get_area_cmt(this, a, repeatable); } // Move area information to the specified addresses // Returns: 0 if ok, otherwise the code returned by area_mover int move_areas(ea_t from, ea_t to, asize_t size, int (idaapi *area_mover)(area_t *a, adiff_t delta, void *ud)=NULL, void *ud=NULL) { return areacb_t_move_areas(this, from, to, size, area_mover, ud); } // Call a function for all areas in the specified range // Stop the enumeration if the function returns non-zero // Returns: 0 if all areas were visited, otherwise the code returned // by the callback int for_all_areas(ea_t ea1, ea_t ea2, area_visitor_t *av, void *ud) { return areacb_t_for_all_areas(this, ea1, ea2, av, ud); } }; #pragma pack(pop) #endif // _AREA_HPP
43.0033
271
0.622064
erithion
586acdfa15cc8bb76ff4f248d02531c5f6c81d17
3,272
cxx
C++
src/Cxx/Modelling/ExtractLargestIsosurface.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/Modelling/ExtractLargestIsosurface.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/Modelling/ExtractLargestIsosurface.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkActor.h> #include <vtkCamera.h> #include <vtkMarchingCubes.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkPolyDataConnectivityFilter.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkStructuredPointsReader.h> #include <vtkVersion.h> // vtkFlyingEdges3D was introduced in VTK >= 8.2 #if VTK_MAJOR_VERSION >= 9 || (VTK_MAJOR_VERSION >= 8 && VTK_MINOR_VERSION >= 2) #define USE_FLYING_EDGES #else #undef USE_FLYING_EDGES #endif #ifdef USE_FLYING_EDGES #include <vtkFlyingEdges3D.h> #else #include <vtkMarchingCubes.h> #endif #include <array> int main(int argc, char* argv[]) { if (argc < 3) { std::cerr << "Usage: " << argv[0] << " InputFile(.vtk) Threshold e.g. brain.vtk 50 1" << std::endl; return EXIT_FAILURE; } const char* fileName = argv[1]; float threshold = atof(argv[2]); auto extractLargest = true; if (argc == 4) { extractLargest = atoi(argv[3]) == 1; } vtkNew<vtkNamedColors> colors; std::array<unsigned char, 4> skinColor{{240, 184, 160, 255}}; colors->SetColor("SkinColor", skinColor.data()); std::array<unsigned char, 4> backColor{{255, 229, 200, 255}}; colors->SetColor("BackfaceColor", backColor.data()); std::array<unsigned char, 4> bkg{{51, 77, 102, 255}}; // Load data vtkNew<vtkStructuredPointsReader> reader; reader->SetFileName(fileName); // Create a 3D model using flying edges or marching cubes #ifdef USE_FLYING_EDGES vtkNew<vtkFlyingEdges3D> mc; #else vtkNew<vtkMarchingCubes> mc; #endif mc->SetInputConnection(reader->GetOutputPort()); mc->ComputeNormalsOn(); mc->ComputeGradientsOn(); mc->SetValue(0, threshold); // second value acts as threshold // To remain largest region vtkNew<vtkPolyDataConnectivityFilter> confilter; confilter->SetInputConnection(mc->GetOutputPort()); confilter->SetExtractionModeToLargestRegion(); // Create a mapper vtkNew<vtkPolyDataMapper> mapper; if (extractLargest) { mapper->SetInputConnection(confilter->GetOutputPort()); } else { mapper->SetInputConnection(mc->GetOutputPort()); } mapper->ScalarVisibilityOff(); // Visualize vtkNew<vtkActor> actor; actor->GetProperty()->SetColor(colors->GetColor3d("SkinColor").GetData()); vtkNew<vtkProperty> backProp; backProp->SetDiffuseColor(colors->GetColor3d("BackfaceColor").GetData()); actor->SetBackfaceProperty(backProp); actor->SetMapper(mapper); vtkNew<vtkRenderer> renderer; renderer->AddActor(actor); renderer->SetBackground(colors->GetColor3d("SlateGray").GetData()); renderer->GetActiveCamera()->SetViewUp(0.0, 0.0, 1.0); renderer->GetActiveCamera()->SetPosition(0.0, 1.0, 0.0); renderer->GetActiveCamera()->SetFocalPoint(0.0, 0.0, 0.0); renderer->ResetCamera(); renderer->GetActiveCamera()->Azimuth(30.0); renderer->GetActiveCamera()->Elevation(30.0); vtkNew<vtkRenderWindow> renwin; renwin->AddRenderer(renderer); renwin->SetSize(640, 480); renwin->SetWindowName("ExtractLargestIsosurface"); vtkNew<vtkRenderWindowInteractor> iren; iren->SetRenderWindow(renwin); renwin->Render(); iren->Initialize(); iren->Start(); return EXIT_SUCCESS; }
27.965812
80
0.716993
ajpmaclean
586bb863a9de73e152602383fa33a2ad3c592a0f
1,173
hpp
C++
Workspace/src/MediaManager.hpp
Llemmert/UntitledCatGame
4618cef62d329a90a7387a63cdf87b5b9762097b
[ "MIT" ]
null
null
null
Workspace/src/MediaManager.hpp
Llemmert/UntitledCatGame
4618cef62d329a90a7387a63cdf87b5b9762097b
[ "MIT" ]
null
null
null
Workspace/src/MediaManager.hpp
Llemmert/UntitledCatGame
4618cef62d329a90a7387a63cdf87b5b9762097b
[ "MIT" ]
null
null
null
#pragma once using namespace std; class MediaManager { map<string, SDL_Texture *> images; SDL_Renderer *ren; map<string, Mix_Chunk *> samples; public: MediaManager(SDL_Renderer *newRen) { ren = newRen; } Mix_Chunk *readWav(string filename) { if (samples.find(filename) == samples.end()) { Mix_Chunk *sample; sample = Mix_LoadWAV(filename.c_str()); if (!sample) throw Exception(/*"Mix_LoadWav: " +*/ Mix_GetError()); samples[filename] = sample; } return (samples[filename]); } SDL_Texture *read(string filename) { SDL_Texture *bitmapTex; if (images.find(filename) == images.end()) { cout << "Read " << filename << endl; SDL_Surface *ob; ob = SDL_LoadBMP(filename.c_str()); SDL_SetColorKey(ob, SDL_TRUE, SDL_MapRGB(ob->format, 164, 117, 160)); if (ob == NULL) throw Exception("Could not load " + filename); bitmapTex = SDL_CreateTextureFromSurface(ren, ob); if (bitmapTex == NULL) throw Exception("Could not create texture"); SDL_FreeSurface(ob); images[filename] = bitmapTex; } return images[filename]; } ~MediaManager() { for (auto i : images) SDL_DestroyTexture(i.second); } };
22.132075
72
0.666667
Llemmert
586c115efe2b49be30c652d67d7bc4694d5a98bb
478
cpp
C++
source/core/common/PropSharedLockSet.cpp
izenecloud/sf1r-lite
8de9aa83c38c9cd05a80b216579552e89609f136
[ "Apache-2.0" ]
77
2015-02-12T20:59:20.000Z
2022-03-05T18:40:49.000Z
source/core/common/PropSharedLockSet.cpp
fytzzh/sf1r-lite
8de9aa83c38c9cd05a80b216579552e89609f136
[ "Apache-2.0" ]
1
2017-04-28T08:55:47.000Z
2017-07-10T10:10:53.000Z
source/core/common/PropSharedLockSet.cpp
fytzzh/sf1r-lite
8de9aa83c38c9cd05a80b216579552e89609f136
[ "Apache-2.0" ]
33
2015-01-05T03:03:05.000Z
2022-02-06T04:22:46.000Z
#include "PropSharedLockSet.h" #include "PropSharedLock.h" using namespace sf1r; PropSharedLockSet::~PropSharedLockSet() { for (SharedLockSetT::const_iterator it = sharedLockSet_.begin(); it != sharedLockSet_.end(); ++it) { (*it)->unlockShared(); } } void PropSharedLockSet::insertSharedLock(const PropSharedLock* lock) { if (lock == NULL) return; if (sharedLockSet_.insert(lock).second) { lock->lockShared(); } }
19.12
68
0.644351
izenecloud
586c63f7330e0398aa7063848f5ce84fe7f033a4
6,000
cpp
C++
utilities/pandaSetSystemTime.cpp
eswierk/libpanda
6540181edcf7df3e4ec1ee530456fff741176257
[ "MIT" ]
11
2020-12-02T00:12:25.000Z
2022-03-31T07:38:32.000Z
utilities/pandaSetSystemTime.cpp
eswierk/libpanda
6540181edcf7df3e4ec1ee530456fff741176257
[ "MIT" ]
29
2021-07-15T23:03:38.000Z
2021-10-08T22:02:29.000Z
utilities/pandaSetSystemTime.cpp
eswierk/libpanda
6540181edcf7df3e4ec1ee530456fff741176257
[ "MIT" ]
7
2021-07-15T21:09:23.000Z
2022-02-04T04:06:25.000Z
/* Author: Matt Bunting Copyright (c) 2020 Arizona Board of Regents All rights reserved. Permission is hereby granted, without written agreement and without license or royalty fees, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following two paragraphs appear in all copies of this software. IN NO EVENT SHALL THE ARIZONA BOARD OF REGENTS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. THE ARIZONA BOARD OF REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include <iostream> #include <signal.h> #include <unistd.h> // usleep() #include <cmath> // fabs() #include <time.h> #include <iomanip> #include <ctime> #include "panda.h" // A ctrl-c handler for safe panda handler destruction static volatile bool keepRunning = true; void killPanda(int killSignal) { std::cerr << std::endl << "Caught SIGINT: Terminating..." << std::endl; keepRunning = false; } //// For debugging time //std::string timevalToPrettyString(struct timeval& time) { // char timeString[64]; // time_t time_tPrint = time.tv_sec; // struct tm* tmPrint = localtime(&time_tPrint); // int uSecondIndex = strftime(timeString, sizeof(timeString), "%d/%m/%Y %H:%M:%S", tmPrint); // snprintf(timeString+uSecondIndex, sizeof(timeString)-uSecondIndex, ".%06d", (int)time.tv_usec); // return timeString; //} // //class SetSystemTimeObserver : public Panda::GpsListener { //public: // SetSystemTimeObserver(double minimumAcceptableOffsetInSeconds) { // timeHasBeenSet = false; // epsilon = minimumAcceptableOffsetInSeconds; // } // // Check this before using system time // bool hasTimeBeenSet() { // return timeHasBeenSet; // } //private: // bool timeHasBeenSet; // double epsilon; // // void newDataNotification( Panda::GpsData* gpsData ) { // if (timeHasBeenSet || (gpsData->info.status != 'A')) { // return; // } // // // Current system time // struct timeval sysTime; // struct timezone sysZone; // //gettimeofday(&sysTime, &sysZone); // // per web, need NULL or behavior undefined for tz // gettimeofday(&sysTime, NULL); // // // testing different time method // std::time_t t = std::time(nullptr); // std::cout << "UTC: " << std::put_time(std::gmtime(&t), "%c %Z") << '\n'; // std::cout << "local: " << std::put_time(std::localtime(&t), "%c %Z") << '\n'; // std::time_t gmt = mktime(std::gmtime(&t)); // std::time_t localt = mktime(std::localtime(&t)); // // offset in seconds: will use this rather than taking the // // tz value from gettimeofday which may not be consistent or supported // // across different distros or with different packages installed // time_t offset = gmt-localt; // // // Current GPS local time based on GMT offset // time_t gpsTime_t = mktime(&gpsData->time); // struct timeval gpsTime; // // std::cout << " sysTime=" << sysTime.tv_sec << std::endl; // std::cout << " sysZone=" << sysZone.tz_minuteswest << std::endl; // // // fixing CH-61 by removing undefined behavior of tz (timezone) // // the offset value is calculated by the minute subtraction from gmt // gpsTime.tv_sec = gpsTime_t - offset; // //gpsTime.tv_sec = gpsTime_t - sysZone.tz_minuteswest*60; // gpsTime.tv_usec = (gpsData->timeMilliseconds)*1000; // // // This seems convoluted, but I think it will avoid floating point error math // int differenceInSeconds = gpsTime.tv_sec - sysTime.tv_sec; // int differenceInMicroseconds = gpsTime.tv_usec - sysTime.tv_usec; // double totalDifference = (double)differenceInSeconds + ((double)differenceInMicroseconds)/1000000.0; // // std::cout << std::endl << "SetSystemTimeObserver.newDataNotification()" << std::endl; // std::cout << " - GPS Time:" << timevalToPrettyString(gpsTime) << std::endl; // std::cout << " - Sys Time:" << timevalToPrettyString(sysTime) << std::endl; // std::cout << " - Time offset of " << totalDifference << " seconds, epsilon:" << epsilon << std::endl; // // if (fabs(totalDifference) > epsilon) { // if (settimeofday(&gpsTime, NULL)) { // std::cerr << "ERROR: Unable to set system time from GPS!" << std::endl; // } else { // std::cout << " |-- System time set to GPS time!" << std::endl; // } // } else { // std::cout << " |-- No need to change system time" << std::endl; // } // // timeHasBeenSet = true; // } //}; int main(int argc, char **argv) { std::cout << "Starting " << argv[0] << std::endl; //Set up graceful exit signal(SIGINT, killPanda); double epsilon = 0.2; // If system time is off from GPS time by this amount, update time. Panda::SetSystemTimeObserver mSetSystemTimeObserver(epsilon); // Initialize Usb, this requires a conencted Panda Panda::Handler pandaHandler; pandaHandler.addGpsObserver(mSetSystemTimeObserver); //pandaHandler.getGps().saveToFile("nmeaDump.txt"); pandaHandler.initialize(); // starts USB and GPS std::cout << "Waiting to acquire satellites..." << std::endl; std::cout << " - Each \'.\' represents 100 NMEA messages received:" << std::endl; int lastNmeaMessageCount = 0; while (keepRunning == true) { if (pandaHandler.getGps().getData().successfulParseCount-lastNmeaMessageCount > 100) { std::cerr << "."; lastNmeaMessageCount = pandaHandler.getGps().getData().successfulParseCount; } usleep(10000); if (mSetSystemTimeObserver.hasTimeBeenSet()) { // Only run until time has been checked/ keepRunning = false; } } std::cout << std::endl; pandaHandler.stop(); std::cout << "\rDone." << std::endl; return 0; }
36.363636
105
0.692833
eswierk
586f2306c7c0840df4cdd4b2f66351d3924bb447
2,410
cpp
C++
source/dataset.cpp
Santili/cppsqlx
32ba861d737cb16c2e337209c1c54e10fa575d3c
[ "MIT" ]
null
null
null
source/dataset.cpp
Santili/cppsqlx
32ba861d737cb16c2e337209c1c54e10fa575d3c
[ "MIT" ]
null
null
null
source/dataset.cpp
Santili/cppsqlx
32ba861d737cb16c2e337209c1c54e10fa575d3c
[ "MIT" ]
null
null
null
/* * Copyright (c) 2014-2016, Santili Y-HRAH KRONG * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <dataset.hpp> #include <table.hpp> #include <logger.hpp> namespace cppsqlx { Dataset::Dataset(std::string name):name_(name),alias_(name) { LOG_DEBUG("Dataset::Dataset"); } Dataset::~Dataset() { LOG_DEBUG("Dataset::~Dataset"); } std::string Dataset::name() { return name_; } std::string Dataset::alias() { return alias_; } std::string Dataset::schema() { return schema_; } std::string Dataset::catalog() { return catalog_; } DBPROVIDER Dataset::provider() { return provider_; } void Dataset::setSchema(std::string schema) { schema_ = schema; } void Dataset::setProvider(DBPROVIDER provider) { provider_ = provider; } void Dataset::setCatalog(std::string catalog) { catalog_ = catalog; } Dataset& Dataset::as(std::string alias) { alias_ = alias; return *this; } Column Dataset::at(int index) { return columns_.at(index); } int Dataset::rowSize() { return columns_.size(); } std::string Dataset::joinidentifier() { return name_; } };/*namespace cppsqlx*/
21.517857
83
0.726971
Santili
586f36e592acdf9b84d55f1480090bab1221332c
2,186
cc
C++
leetcode/math_pow.cc
prashrock/C-
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
1
2016-12-05T10:42:46.000Z
2016-12-05T10:42:46.000Z
leetcode/math_pow.cc
prashrock/CPP
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
null
null
null
leetcode/math_pow.cc
prashrock/CPP
3ed46815d40b3e42cd9f36d23c8ee2a9de742323
[ "MIT" ]
null
null
null
//g++-5 -Wall --std=c++11 -g -o math_pow math_pow.cc /** * @file Integer Pow(x,n) * @brief Implement Pow(x,n) */ // https://leetcode.com/problems/powx-n/ #include <iostream> /* std::cout */ #include <algorithm> /* std::max */ #include <cmath> /* std::round */ using namespace std; /** Implement int pow(x, n) */ /* If n is -ve and x is an integer, we can avoid floating pt * * ops by using a long to store the ans till the end */ double myPow(double x, int n) { double ans = 1; /* Handle special cases first (x^0 and overflow of -n to n) */ if(n == 0) return ans; if(n == std::numeric_limits<int>::min()) { if(x == 1 || x == -1) return ans; else return 0; } /* If n is negative, make it +ve and instead change x to 1/x */ if(n < 0) { x = 1/x; n = -n; } for(; n > 0; n >>= 1) { if(n & 1) ans *= x; x *= x; } return ans; } struct test_vector { double x; int n; double exp; }; const struct test_vector test[11] = { { 8.88023, 7, 4354812.89022}, { 8.84372, -5, 0.00002}, {34.00515, 3, 39321.86291}, {34.00515, -3, 0.00003}, { 0.00001, 2147483647, 0.00000}, { 1.00000, 2147483647, 1.00000}, { 2.00000, -2147483648, 0.00000}, { 1.00000, -2147483648, 1.00000}, {-1.00000, -2147483648, 1.00000}, { 1.00005, -2147483648, 0.00000}, {12351235, -2147483648, 0.00000}, }; int main() { for(auto tst : test) { auto ans = pow(tst.x, tst.n); ans = ((double)std::round(ans * 10000.0)) / 10000.0; auto exp = ((double)std::round(tst.exp * 10000.0)) / 10000.0; if(ans != exp) { cout << "Error:pow failed. Exp " << exp << " Got " << ans << " for " << tst.x << "^" << tst.n << endl; return -1; } } cout << "Info: All manual testcases passed" << endl; return 0; }
30.788732
69
0.451967
prashrock
586f9c4cc257a6e03952216cace7811fea6b9368
4,939
cpp
C++
ThirdParty/libtorrent-rasterbar-0.15.6/bindings/python/src/torrent_status.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
32
2016-05-22T23:09:19.000Z
2022-03-13T03:32:27.000Z
ThirdParty/libtorrent-rasterbar-0.15.6/bindings/python/src/torrent_status.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
2
2016-05-30T19:45:58.000Z
2018-01-24T22:29:51.000Z
ThirdParty/libtorrent-rasterbar-0.15.6/bindings/python/src/torrent_status.cpp
CarysT/medusa
8e79f7738534d8cf60577ec42ed86621533ac269
[ "MIT" ]
17
2016-05-27T11:01:42.000Z
2022-03-13T03:32:30.000Z
// Copyright Daniel Wallin 2006. Use, modification and distribution is // subject to the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <boost/python.hpp> #include <libtorrent/torrent_handle.hpp> #include <libtorrent/bitfield.hpp> using namespace boost::python; using namespace libtorrent; object pieces(torrent_status const& s) { list result; for (bitfield::const_iterator i(s.pieces.begin()), e(s.pieces.end()); i != e; ++i) result.append(*i); return result; } void bind_torrent_status() { scope status = class_<torrent_status>("torrent_status") .def_readonly("state", &torrent_status::state) .def_readonly("paused", &torrent_status::paused) .def_readonly("progress", &torrent_status::progress) .def_readonly("progress_ppm", &torrent_status::progress_ppm) .add_property( "next_announce" , make_getter( &torrent_status::next_announce, return_value_policy<return_by_value>() ) ) .add_property( "announce_interval" , make_getter( &torrent_status::announce_interval, return_value_policy<return_by_value>() ) ) .def_readonly("current_tracker", &torrent_status::current_tracker) .def_readonly("total_download", &torrent_status::total_download) .def_readonly("total_upload", &torrent_status::total_upload) .def_readonly("total_payload_download", &torrent_status::total_payload_download) .def_readonly("total_payload_upload", &torrent_status::total_payload_upload) .def_readonly("total_failed_bytes", &torrent_status::total_failed_bytes) .def_readonly("total_redundant_bytes", &torrent_status::total_redundant_bytes) .def_readonly("download_rate", &torrent_status::download_rate) .def_readonly("upload_rate", &torrent_status::upload_rate) .def_readonly("download_payload_rate", &torrent_status::download_payload_rate) .def_readonly("upload_payload_rate", &torrent_status::upload_payload_rate) .def_readonly("num_seeds", &torrent_status::num_seeds) .def_readonly("num_peers", &torrent_status::num_peers) .def_readonly("num_complete", &torrent_status::num_complete) .def_readonly("num_incomplete", &torrent_status::num_incomplete) .def_readonly("list_seeds", &torrent_status::list_seeds) .def_readonly("list_peers", &torrent_status::list_peers) .add_property("pieces", pieces) .def_readonly("num_pieces", &torrent_status::num_pieces) .def_readonly("total_done", &torrent_status::total_done) .def_readonly("total_wanted_done", &torrent_status::total_wanted_done) .def_readonly("total_wanted", &torrent_status::total_wanted) .def_readonly("distributed_full_copies", &torrent_status::distributed_full_copies) .def_readonly("distributed_fraction", &torrent_status::distributed_fraction) .def_readonly("distributed_copies", &torrent_status::distributed_copies) .def_readonly("block_size", &torrent_status::block_size) .def_readonly("num_uploads", &torrent_status::num_uploads) .def_readonly("num_connections", &torrent_status::num_connections) .def_readonly("uploads_limit", &torrent_status::uploads_limit) .def_readonly("connections_limit", &torrent_status::connections_limit) .def_readonly("storage_mode", &torrent_status::storage_mode) .def_readonly("up_bandwidth_queue", &torrent_status::up_bandwidth_queue) .def_readonly("down_bandwidth_queue", &torrent_status::down_bandwidth_queue) .def_readonly("all_time_upload", &torrent_status::all_time_upload) .def_readonly("all_time_download", &torrent_status::all_time_download) .def_readonly("active_time", &torrent_status::active_time) .def_readonly("finished_time", &torrent_status::finished_time) .def_readonly("seeding_time", &torrent_status::seeding_time) .def_readonly("seed_rank", &torrent_status::seed_rank) .def_readonly("last_scrape", &torrent_status::last_scrape) .def_readonly("error", &torrent_status::error) .def_readonly("priority", &torrent_status::priority) ; enum_<torrent_status::state_t>("states") .value("queued_for_checking", torrent_status::queued_for_checking) .value("checking_files", torrent_status::checking_files) .value("downloading_metadata", torrent_status::downloading_metadata) .value("downloading", torrent_status::downloading) .value("finished", torrent_status::finished) .value("seeding", torrent_status::seeding) .value("allocating", torrent_status::allocating) .value("checking_resume_data", torrent_status::checking_resume_data) .export_values() ; }
50.397959
90
0.71148
CarysT
587037e5cf7e3e4aabaa681eea335d81562b1fd3
2,225
hpp
C++
src/zipf_distribution.hpp
manuhalo/PLACeS
1574a34a2a98468e72d072cc9d1f2b32fcee38f2
[ "Apache-2.0" ]
null
null
null
src/zipf_distribution.hpp
manuhalo/PLACeS
1574a34a2a98468e72d072cc9d1f2b32fcee38f2
[ "Apache-2.0" ]
1
2015-04-24T10:10:51.000Z
2015-06-18T08:32:16.000Z
src/zipf_distribution.hpp
manuhalo/PLACeS
1574a34a2a98468e72d072cc9d1f2b32fcee38f2
[ "Apache-2.0" ]
null
null
null
/* boost-supplement random/discrete_distribution.hpp header file * * Copyright (C) 2008 Kenta Murata. * 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) * * $Id: discrete_distribution.hpp 5906 2008-01-30 15:09:35Z mrkn $ * */ #ifndef BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP #define BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP 1 #include <boost/random/discrete_distribution.hpp> #include <cmath> namespace boost { namespace random { // Zipf-Mandelbrot distribution // // Let N, q, and s be num, shift, and exp, respectively. The // probability distribution is P(k) = (k + q)^{-s} / H_{N,q,s} where k // = 1, 2, ..., N, and H_{N,q,s} is generalized harmonic number, that // is H_{N,q,s} = \sum_{i=1}^N (i+q)^{-s}. // // http://en.wikipedia.org/wiki/Zipf-Mandelbrot_law. template<class IntType = long, class RealType = double> class zipf_distribution { public: typedef RealType input_type; typedef IntType result_type; #if !defined(BOOST_NO_LIMITS_COMPILE_TIME_CONSTANTS) && !(defined(BOOST_MSVC) && BOOST_MSVC <= 1300) BOOST_STATIC_ASSERT(std::numeric_limits<IntType>::is_integer); BOOST_STATIC_ASSERT(!std::numeric_limits<RealType>::is_integer); #endif private: result_type num_; input_type shift_; input_type exp_; typedef discrete_distribution<IntType, RealType> dist_type; dist_type dist_; dist_type make_dist(result_type num, input_type shift, input_type exp) { std::vector<input_type> buffer(num); for (result_type k = 1; k <= num; ++k) buffer[k-1] = std::pow(k + shift, -exp); return dist_type(buffer.begin(), buffer.end()); } public: zipf_distribution(result_type num, input_type shift, input_type exp) : num_(num), shift_(shift), exp_(exp), dist_(make_dist(num, shift, exp)) {} result_type num() const { return num_; } input_type shift() const { return shift_; } input_type exponent() const { return exp_; } template<class Engine> result_type operator()(Engine& eng) { return dist_(eng); } RealType pmf(IntType i) { return dist_.probabilities().at(i); } }; } } #endif // BOOST_SUPPLEMENT_ZIPF_DISTRIBUTION_HPP
28.525641
100
0.710112
manuhalo
587060467100f53b2f4ee3062af0735d8a2d48d6
3,009
hpp
C++
include/Nazara/Graphics/Sprite.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Graphics/Sprite.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
include/Nazara/Graphics/Sprite.hpp
AntoineJT/NazaraEngine
e0b05a7e7a2779e20a593b4083b4a881cc57ce14
[ "BSD-3-Clause-Clear", "Apache-2.0", "MIT" ]
null
null
null
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Engine - Graphics module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_SPRITE_HPP #define NAZARA_SPRITE_HPP #include <Nazara/Prerequisites.hpp> #include <Nazara/Graphics/InstancedRenderable.hpp> #include <Nazara/Graphics/Material.hpp> #include <array> namespace Nz { class Sprite; using SpriteConstRef = ObjectRef<const Sprite>; using SpriteLibrary = ObjectLibrary<Sprite>; using SpriteRef = ObjectRef<Sprite>; class NAZARA_GRAPHICS_API Sprite : public InstancedRenderable { friend SpriteLibrary; friend class Graphics; public: inline Sprite(); inline Sprite(MaterialRef material); inline Sprite(Texture* texture); Sprite(const Sprite&) = default; Sprite(Sprite&&) = delete; ~Sprite() = default; void AddToRenderQueue(AbstractRenderQueue* renderQueue, const InstanceData& instanceData, const Recti& scissorRect) const override; std::unique_ptr<InstancedRenderable> Clone() const override; inline const Color& GetColor() const; inline const Color& GetCornerColor(RectCorner corner) const; inline const Vector3f& GetOrigin() const; inline const Vector2f& GetSize() const; inline const Rectf& GetTextureCoords() const; inline void SetColor(const Color& color); inline void SetCornerColor(RectCorner corner, const Color& color); inline void SetDefaultMaterial(); inline void SetMaterial(MaterialRef material, bool resizeSprite = true); bool SetMaterial(String materialName, bool resizeSprite = true); inline void SetMaterial(std::size_t skinIndex, MaterialRef material, bool resizeSprite = true); bool SetMaterial(std::size_t skinIndex, String materialName, bool resizeSprite = true); inline void SetOrigin(const Vector3f& origin); inline void SetSize(const Vector2f& size); inline void SetSize(float sizeX, float sizeY); bool SetTexture(String textureName, bool resizeSprite = true); inline void SetTexture(TextureRef texture, bool resizeSprite = true); bool SetTexture(std::size_t skinIndex, String textureName, bool resizeSprite = true); inline void SetTexture(std::size_t skinIndex, TextureRef texture, bool resizeSprite = true); inline void SetTextureCoords(const Rectf& coords); inline void SetTextureRect(const Rectui& rect); inline Sprite& operator=(const Sprite& sprite); Sprite& operator=(Sprite&& sprite) = delete; template<typename... Args> static SpriteRef New(Args&&... args); private: inline void InvalidateVertices(); void MakeBoundingVolume() const override; void UpdateData(InstanceData* instanceData) const override; static bool Initialize(); static void Uninitialize(); std::array<Color, 4> m_cornerColor; Color m_color; Rectf m_textureCoords; Vector2f m_size; Vector3f m_origin; static SpriteLibrary::LibraryMap s_library; }; } #include <Nazara/Graphics/Sprite.inl> #endif // NAZARA_SPRITE_HPP
33.808989
134
0.757062
AntoineJT
5872e1f014689c9510f65ae28c283d928beaf0c8
4,319
cpp
C++
Sources/Engine/Core/Rendering/Sources/Private/Scene/VkSceneElements/FrameBuffers.cpp
PierreEVEN/Engine
34a22cc4694dba0ba50094c1a56e71856f427722
[ "Apache-2.0" ]
3
2020-09-12T23:38:26.000Z
2020-10-21T06:54:13.000Z
Sources/Engine/Core/Rendering/Sources/Private/Scene/VkSceneElements/FrameBuffers.cpp
PierreEVEN/Engine
34a22cc4694dba0ba50094c1a56e71856f427722
[ "Apache-2.0" ]
2
2020-11-25T14:17:13.000Z
2020-11-25T14:36:57.000Z
Sources/Engine/Core/Rendering/Sources/Private/Scene/VkSceneElements/FrameBuffers.cpp
PierreEVEN/Engine
34a22cc4694dba0ba50094c1a56e71856f427722
[ "Apache-2.0" ]
1
2021-09-04T10:17:36.000Z
2021-09-04T10:17:36.000Z
#include "Scene/VkSceneElements/FrameBuffers.h" #include "Scene/VkSceneElements/SwapChain.h" #include "Ressources/TextureRessource.h" #include "Utils.h" Rendering::FramebufferGroup::FramebufferGroup(SwapChain* swapChain) { CreateFrameBufferImages(swapChain); CreateFrameBuffer(swapChain); } Rendering::FramebufferGroup::~FramebufferGroup() { DestroyFrameBuffer(); DestroyFrameBufferImages(); } void Rendering::FramebufferGroup::Rebuild(SwapChain* inSwapChain) { DestroyFrameBuffer(); DestroyFrameBufferImages(); CreateFrameBufferImages(inSwapChain); CreateFrameBuffer(inSwapChain); } void Rendering::FramebufferGroup::CreateFrameBufferImages(SwapChain* swapChain) { /** Color buffer */ VkFormat colorFormat = G_SWAPCHAIN_SURFACE_FORMAT.format; TextureRessource::CreateImage(swapChain->GetSwapChainExtend().width, swapChain->GetSwapChainExtend().height, 1, (VkSampleCountFlagBits)G_MSAA_SAMPLE_COUNT.GetValue(), colorFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, colorImage, colorImageMemory); TextureRessource::CreateImageView(colorImage, colorImageView, colorFormat, VK_IMAGE_ASPECT_COLOR_BIT, 1); /** Depth buffer */ VkFormat depthFormat = FindDepthFormat(); TextureRessource::CreateImage(swapChain->GetSwapChainExtend().width, swapChain->GetSwapChainExtend().height, 1, (VkSampleCountFlagBits)G_MSAA_SAMPLE_COUNT.GetValue(), depthFormat, VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, depthImage, depthImageMemory); TextureRessource::CreateImageView(depthImage, depthImageView, depthFormat, VK_IMAGE_ASPECT_DEPTH_BIT, 1); /** Swap chain buffer */ uint32_t swapChainImageCount = G_SWAP_CHAIN_IMAGE_COUNT; vkGetSwapchainImagesKHR(G_LOGICAL_DEVICE, swapChain->GetSwapChainKhr(), &swapChainImageCount, nullptr); swapChainImages.resize(G_SWAP_CHAIN_IMAGE_COUNT); vkGetSwapchainImagesKHR(G_LOGICAL_DEVICE, swapChain->GetSwapChainKhr(), &swapChainImageCount, swapChainImages.data()); swapChainImageViews.resize(swapChainImages.size()); for (size_t i = 0; i < swapChainImages.size(); i++) TextureRessource::CreateImageView(swapChainImages[i], swapChainImageViews[i], G_SWAPCHAIN_SURFACE_FORMAT.format, VK_IMAGE_ASPECT_COLOR_BIT, 1); } void Rendering::FramebufferGroup::CreateFrameBuffer(SwapChain* swapChain) { frameBuffers.resize(G_SWAP_CHAIN_IMAGE_COUNT); for (size_t i = 0; i < G_SWAP_CHAIN_IMAGE_COUNT; i++) { std::vector<VkImageView> attachments; if (G_MSAA_SAMPLE_COUNT.GetValue() > 1) { attachments.push_back(colorImageView); attachments.push_back(depthImageView); attachments.push_back(swapChainImageViews[i]); } else { attachments.push_back(swapChainImageViews[i]); attachments.push_back(depthImageView); } VkFramebufferCreateInfo framebufferInfo{}; framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO; framebufferInfo.renderPass = G_RENDER_PASS; framebufferInfo.attachmentCount = static_cast<uint32_t>(attachments.size()); framebufferInfo.pAttachments = attachments.data(); framebufferInfo.width = swapChain->GetSwapChainExtend().width; framebufferInfo.height = swapChain->GetSwapChainExtend().height; framebufferInfo.layers = 1; VK_ENSURE(vkCreateFramebuffer(G_LOGICAL_DEVICE, &framebufferInfo, nullptr, &frameBuffers[i]), String("Failed to create framebuffer #") + ToString(i)); } } void Rendering::FramebufferGroup::DestroyFrameBuffer() { for (auto framebuffer : frameBuffers) { vkDestroyFramebuffer(G_LOGICAL_DEVICE, framebuffer, nullptr); } } void Rendering::FramebufferGroup::DestroyFrameBufferImages() { /** Color buffer */ vkDestroyImageView(G_LOGICAL_DEVICE, colorImageView, G_ALLOCATION_CALLBACK); vkDestroyImage(G_LOGICAL_DEVICE, colorImage, G_ALLOCATION_CALLBACK); vkFreeMemory(G_LOGICAL_DEVICE, colorImageMemory, G_ALLOCATION_CALLBACK); /** Depth buffer */ vkDestroyImageView(G_LOGICAL_DEVICE, depthImageView, G_ALLOCATION_CALLBACK); vkDestroyImage(G_LOGICAL_DEVICE, depthImage, G_ALLOCATION_CALLBACK); vkFreeMemory(G_LOGICAL_DEVICE, depthImageMemory, G_ALLOCATION_CALLBACK); /* Swap chain buffers */ for (auto imageView : swapChainImageViews) vkDestroyImageView(G_LOGICAL_DEVICE, imageView, G_ALLOCATION_CALLBACK); }
41.932039
352
0.816624
PierreEVEN
58734ce83a7a5f6a577f18835866dc8f4ec79183
1,816
hpp
C++
Mongoose/Include/Mongoose_QPDelta.hpp
puckbee/suitesparse
306d7f11792aca524571f4ae142bcd8b7e38c362
[ "Apache-2.0" ]
29
2019-11-27T00:43:07.000Z
2020-02-25T14:35:54.000Z
Mongoose/Include/Mongoose_QPDelta.hpp
puckbee/suitesparse
306d7f11792aca524571f4ae142bcd8b7e38c362
[ "Apache-2.0" ]
null
null
null
Mongoose/Include/Mongoose_QPDelta.hpp
puckbee/suitesparse
306d7f11792aca524571f4ae142bcd8b7e38c362
[ "Apache-2.0" ]
4
2019-11-27T05:19:03.000Z
2020-03-23T22:49:53.000Z
/* ========================================================================== */ /* === Include/Mongoose_QPDelta.hpp ========================================= */ /* ========================================================================== */ /* ----------------------------------------------------------------------------- * Mongoose Graph Partitioning Library Copyright (C) 2017-2018, * Scott P. Kolodziej, Nuri S. Yeralan, Timothy A. Davis, William W. Hager * Mongoose is licensed under Version 3 of the GNU General Public License. * Mongoose is also available under other licenses; contact authors for details. * -------------------------------------------------------------------------- */ #pragma once #include "Mongoose_Internal.hpp" namespace Mongoose { class QPDelta { private: static const Int WXSIZE = 3; static const Int WISIZE = 2; public: double *x; /* current estimate of solution */ // FreeSet: Int nFreeSet; /* number of i such that 0 < x_i < 1 */ Int *FreeSet_status; /* ix_i = +1,-1, or 0 if x_i = 1,0, or 0 < x_i < 1 */ Int *FreeSet_list; /* list for free indices */ //--- double *gradient; /* gradient at current x */ double *D; /* max value along the column. */ double lo; // lo <= a'*x <= hi must always hold double hi; // workspace Int *wi[WISIZE]; double *wx[WXSIZE]; Int its; double err; Int ib; // ib = 0 means lo < b < hi // ib = +1 means b == hi // ib = -1 means b == lo double b; // b = a'*x double lambda; static QPDelta *Create(Int numVars); ~QPDelta(); #ifndef NDEBUG double check_cost; #endif }; } // end namespace Mongoose
29.290323
80
0.449339
puckbee
587396b44242fb7813ffea962c03660ef9199317
5,322
cpp
C++
Assignment4/Assignement_4.2/testcar.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
Assignment4/Assignement_4.2/testcar.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
Assignment4/Assignement_4.2/testcar.cpp
JasenRatnam/LearningCplusplus
e2a67decf5233ac9e9f073e3dbcd60bbc4fe4a94
[ "MIT" ]
null
null
null
/* * Author: Jasen Ratnam 40094237 * Date: 11/04/2018 * Due: 11/11/2018 * Assignment 4: Strings/ User-Defined Classes * 4.2: Cars which represents cars of a car rental company. * Prompts the user to enter information about two cars. * Create two objects of the class car with given information. * Test all the member functions of the class. * Contains main function. */ #include <iostream> #include <cmath> #include "car.h" using namespace std; /* * Function that gets information about a car from user. * And creates an car object from the car class constructor. * returns car object. */ car getCar() { // Initialize variables needed to create car object. int id; string brand; string type; // Ask and save the information about the car. cout << "Enter information about car:\n" "1. Enter car id number: "; cin >> id; // Check if input is not an integer. // Print error message if not an integer and get new input until an integer is inserted. // Save correct input in place of wrong input. // While loop until an integer is inserted. while(!cin) { cout << "ERROR: The input was not a number, Please enter a number:\n"; cin.clear(); // Clear the input. cin.ignore(); // Ignore the current input and wait for new input. cin >> id; // Save input. } cout << "2. Enter car brand: "; cin >> brand; cout << "3. Enter car type: "; cin >> type; // Create car object car car(id, brand, type); // Return car return car; } /* * Function that does the menu and choices fro commands. * Goes in a loop until user chooses to quit. */ void menuAction() { // Create 2 car object. car car1 = getCar(); car car2 = getCar(); //boolean: user can choose options until it is false. bool playing = true; // Variable to save the choice chosen. int choice; // Give choices cout << "\nChoose one of the following options: (To test functions of class)\n" "1. Get the first car id number.\n" "2. Get the second car id number.\n" "3. Get the first car brand.\n" "4. Get the second car brand.\n" "5. Get the first car type.\n" "6. Get the second car type.\n" "7. Exit.\n\n"; // Save choice. cin >> choice; cout << "\n"; // Check if input is not an integer. // Print error message if not an integer and get new input until an integer is inserted. // Save correct input in place of wrong input. // While loop until an integer is inserted. while(!cin) { cout << "ERROR: The input was not a number, Please enter a number:\n"; cin.clear(); // Clear the input. cin.ignore(); // Ignore the current input and wait for new input. cin >> choice; // Save input. } // Loop with the current number. while(playing) { switch(choice) { case 1: { cout << "The id number of car 1 is: " << car1.getId(); break; } case 2: { cout << "The id number of car 2 is: " << car2.getId(); break; } case 3: { cout << "The brand of car 1 is: " << car1.getBrand(); break; } case 4: { cout << "The brand of car 2 is: " << car2.getBrand(); break; } case 5: { cout << "The type of car 1 is: " << car1.getType(); break; } case 6: { cout << "The type of car 2 is: " << car2.getType(); break; } case 7: { // Quit program: playing = false; break; } default: // else input is wrong, ask for new input. { cout << "Invalid input. Please enter a correct choice\n"; } } // Ask for new input. if boolean is true if(playing) { cout << "\n\nPlease choose another option from the menu: "; // Save input cin >> choice; cout << "\n"; // Check if input is not an integer. // Print error message if not an integer and get new input until an integer is inserted. // Save correct input in place of wrong input. // While loop until an integer is inserted. while(!cin) { cout << "ERROR: The input was not a number, Please enter a number:\n"; cin.clear(); // Clear the input. cin.ignore(); // Ignore the current input and wait for new input. cin >> choice; // Save input. } } } } int main() { // ask for course info and choices. menuAction(); return 0; }
29.081967
100
0.495866
JasenRatnam
5876c2ebb2b32e30b7c636c1782247e52175ac7b
2,027
cpp
C++
dev/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/PreviewMotionFixture.cpp
brianherrera/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
1,738
2017-09-21T10:59:12.000Z
2022-03-31T21:05:46.000Z
dev/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/PreviewMotionFixture.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
427
2017-09-29T22:54:36.000Z
2022-02-15T19:26:50.000Z
dev/Gems/EMotionFX/Code/Tests/ProvidesUI/AnimGraph/PreviewMotionFixture.cpp
ArchitectureStudios/lumberyard
f85344403c1c2e77ec8c75deb2c116e97b713217
[ "AML" ]
671
2017-09-21T08:04:01.000Z
2022-03-29T14:30:07.000Z
/* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <EMotionStudio/Plugins/StandardPlugins/Source/AnimGraph/AnimGraphPlugin.h> #include <EMotionStudio/Plugins/StandardPlugins/Source/MotionSetsWindow/MotionSetsWindowPlugin.h> #include <Tests/UI/AnimGraphUIFixture.h> #include <Tests/ProvidesUI/AnimGraph/PreviewMotionFixture.h> namespace EMotionFX { void PreviewMotionFixture::SetUp() { AnimGraphUIFixture::SetUp(); //Create one motion set, and import one motion and add to the motion set. ExecuteCommands({ R"str(CreateMotionSet -name MotionSet0)str" }); EMStudio::MotionSetsWindowPlugin* motionSetsWindowPlugin = static_cast<EMStudio::MotionSetsWindowPlugin*>(EMStudio::GetPluginManager()->FindActivePlugin(EMStudio::MotionSetsWindowPlugin::CLASS_ID)); ASSERT_TRUE(motionSetsWindowPlugin) << "Motion Window plugin not loaded"; EMotionFX::MotionSet* motionSet = EMotionFX::GetMotionManager().FindMotionSetByID(0); ASSERT_TRUE(motionSet) << "Motion set with id 0 does not exist"; motionSetsWindowPlugin->SetSelectedSet(motionSet); ExecuteCommands({ R"str(ImportMotion -filename Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin_idle.motion)str", R"str(MotionSetAddMotion -motionSetID 0 -motionFilenamesAndIds Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin_idle.motion;rin_idle)str" }); m_motionFileName = "Gems/EMotionFX/Code/Tests/TestAssets/Rin/rin_idle.motion"; m_motionName = "rin_idle"; } }
46.068182
206
0.742477
brianherrera
5879ad76ce941dd75a2af157749a79d1183d9a36
3,189
cpp
C++
MMOCoreORB/src/server/zone/objects/tangible/terminal/components/UplinkTerminalMenuComponent.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
18
2017-02-09T15:36:05.000Z
2021-12-21T04:22:15.000Z
MMOCoreORB/src/server/zone/objects/tangible/terminal/components/UplinkTerminalMenuComponent.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
61
2016-12-30T21:51:10.000Z
2021-12-10T20:25:56.000Z
MMOCoreORB/src/server/zone/objects/tangible/terminal/components/UplinkTerminalMenuComponent.cpp
V-Fib/FlurryClone
40e0ca7245ec31b3815eb6459329fd9e70f88936
[ "Zlib", "OpenSSL" ]
71
2017-01-01T05:34:38.000Z
2022-03-29T01:04:00.000Z
/* * UplinkTerminalMenuComponent.cpp * * Created on: Oct 31, 2012 * Author: root */ #include "UplinkTerminalMenuComponent.h" #include "server/zone/Zone.h" #include "server/zone/packets/object/ObjectMenuResponse.h" #include "server/zone/objects/scene/SceneObject.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/managers/gcw/GCWManager.h" #include "server/zone/objects/tangible/TangibleObject.h" void UplinkTerminalMenuComponent::fillObjectMenuResponse(SceneObject* sceneObject, ObjectMenuResponse* menuResponse, CreatureObject* player) const { ManagedReference<BuildingObject*> building = sceneObject->getParentRecursively(SceneObjectType::FACTIONBUILDING).castTo<BuildingObject*>(); if (building == nullptr || player->isDead() || player->isIncapacitated()) return; Zone* zone = building->getZone(); if (zone == nullptr) return; GCWManager* gcwMan = zone->getGCWManager(); if (gcwMan == nullptr) return; if (!gcwMan->isBaseVulnerable(building)) return; menuResponse->addRadialMenuItem(20, 3, "@hq:mnu_jam"); } int UplinkTerminalMenuComponent::handleObjectMenuSelect(SceneObject* sceneObject, CreatureObject* player, byte selectedID) const { if (sceneObject == nullptr || !sceneObject->isTangibleObject() || player == nullptr || player->isDead() || player->isIncapacitated() || selectedID != 20) return 0; ManagedReference<BuildingObject*> building = sceneObject->getParentRecursively(SceneObjectType::FACTIONBUILDING).castTo<BuildingObject*>(); ManagedReference<TangibleObject*> uplinkTerminal = cast<TangibleObject*>(sceneObject); if (building == nullptr) return 1; Zone* zone = sceneObject->getZone(); if (zone == nullptr) return 1; ManagedReference<GCWManager*> gcwMan = zone->getGCWManager(); if (gcwMan == nullptr) return 1; if (!gcwMan->isBaseVulnerable(building)) return 1; // Most of the string rows for these errors did not exist in 14.1, pulled string text from a different patch if (!gcwMan->areOpposingFactions(player->getFaction(), building->getFaction())) { player->sendSystemMessage("@faction/faction_hq/faction_hq_response:no_tamper"); // You are not an enemy of this structure. Why would you want to tamper? return 1; } else if (gcwMan->isUplinkJammed(building)) { player->sendSystemMessage("It's no use! The uplink has been jammed."); return 1; } else if (player->isInCombat()) { player->sendSystemMessage("You cannot jam this uplink while you are in combat!"); return 1; } else if (uplinkTerminal->getParentID() != player->getParentID()) { player->sendSystemMessage("You cannot jam the uplink if you are not even in the same room!"); return 1; } else if (uplinkTerminal->getDistanceTo(player) > 15) { player->sendSystemMessage("You are too far away from the uplink to continue jamming!"); return 1; } else if (!player->hasSkill("combat_bountyhunter_investigation_02")) { player->sendSystemMessage("Only a bounty hunter with intermediate surveillance skill could expect to jam this uplink!"); return 1; } gcwMan->sendJamUplinkMenu(player, building, uplinkTerminal); return 0; }
35.433333
154
0.748511
V-Fib
587aa65069ead384a81d3bdbc849434c3d4211d9
4,435
cc
C++
Calibration/LumiAlCaRecoProducers/plugins/AlcaPCCIntegrator.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
null
null
null
Calibration/LumiAlCaRecoProducers/plugins/AlcaPCCIntegrator.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
null
null
null
Calibration/LumiAlCaRecoProducers/plugins/AlcaPCCIntegrator.cc
PKUfudawei/cmssw
8fbb5ce74398269c8a32956d7c7943766770c093
[ "Apache-2.0" ]
null
null
null
/*_________________________________________________________________ class: AlcaPCCIntegrator.cc authors: Sam Higginbotham (shigginb@cern.ch), Chris Palmer (capalmer@cern.ch), Attila Radl (attila.radl@cern.ch) ________________________________________________________________**/ // C++ standard #include <string> // CMS #include "DataFormats/Luminosity/interface/PixelClusterCounts.h" #include "DataFormats/Luminosity/interface/PixelClusterCountsInEvent.h" #include "FWCore/Framework/interface/ConsumesCollector.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/EventSetup.h" #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/LuminosityBlock.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/Framework/interface/one/EDProducer.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/EDGetToken.h" //The class class AlcaPCCIntegrator : public edm::one::EDProducer<edm::EndLuminosityBlockProducer, edm::one::WatchLuminosityBlocks> { public: explicit AlcaPCCIntegrator(const edm::ParameterSet&); ~AlcaPCCIntegrator() override = default; private: void beginLuminosityBlock(edm::LuminosityBlock const& lumiSeg, const edm::EventSetup& iSetup) override; void endLuminosityBlock(edm::LuminosityBlock const& lumiSeg, const edm::EventSetup& iSetup) override; void endLuminosityBlockProduce(edm::LuminosityBlock& lumiSeg, const edm::EventSetup& iSetup) override; void produce(edm::Event& iEvent, const edm::EventSetup& iSetup) override; edm::EDGetTokenT<reco::PixelClusterCountsInEvent> pccToken_; std::string pccSource_; std::string trigstring_; //specifies the input trigger Rand or ZeroBias std::string prodInst_; //file product instance int countEvt_; //counter int countLumi_; //counter std::unique_ptr<reco::PixelClusterCounts> thePCCob; }; //-------------------------------------------------------------------------------------------------- AlcaPCCIntegrator::AlcaPCCIntegrator(const edm::ParameterSet& iConfig) { pccSource_ = iConfig.getParameter<edm::ParameterSet>("AlcaPCCIntegratorParameters").getParameter<std::string>("inputPccLabel"); auto trigstring_ = iConfig.getParameter<edm::ParameterSet>("AlcaPCCIntegratorParameters") .getUntrackedParameter<std::string>("trigstring", "alcaPCC"); prodInst_ = iConfig.getParameter<edm::ParameterSet>("AlcaPCCIntegratorParameters").getParameter<std::string>("ProdInst"); edm::InputTag PCCInputTag_(pccSource_, trigstring_); countLumi_ = 0; produces<reco::PixelClusterCounts, edm::Transition::EndLuminosityBlock>(prodInst_); pccToken_ = consumes<reco::PixelClusterCountsInEvent>(PCCInputTag_); } //-------------------------------------------------------------------------------------------------- void AlcaPCCIntegrator::produce(edm::Event& iEvent, const edm::EventSetup& iSetup) { countEvt_++; unsigned int bx = iEvent.bunchCrossing(); //std::cout<<"The Bunch Crossing Int"<<bx<<std::endl; thePCCob->eventCounter(bx); //Looping over the clusters and adding the counts up edm::Handle<reco::PixelClusterCountsInEvent> pccHandle; iEvent.getByToken(pccToken_, pccHandle); if (!pccHandle.isValid()) { // do not resolve a not existing product! return; } const reco::PixelClusterCountsInEvent inputPcc = *pccHandle; thePCCob->add(inputPcc); } //-------------------------------------------------------------------------------------------------- void AlcaPCCIntegrator::beginLuminosityBlock(edm::LuminosityBlock const& lumiSeg, const edm::EventSetup& iSetup) { //PCC object at the beginning of each lumi section thePCCob = std::make_unique<reco::PixelClusterCounts>(); countLumi_++; } //-------------------------------------------------------------------------------------------------- void AlcaPCCIntegrator::endLuminosityBlock(edm::LuminosityBlock const& lumiSeg, const edm::EventSetup& iSetup) {} //-------------------------------------------------------------------------------------------------- void AlcaPCCIntegrator::endLuminosityBlockProduce(edm::LuminosityBlock& lumiSeg, const edm::EventSetup& iSetup) { //Saving the PCC object lumiSeg.put(std::move(thePCCob), std::string(prodInst_)); } DEFINE_FWK_MODULE(AlcaPCCIntegrator);
42.238095
120
0.686133
PKUfudawei
587b1503d5d3a11080f4df5ea6c7d1b083ae270c
25,018
cpp
C++
src/apps/icon-o-matic/generic/gui/scrollview/ScrollView.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/apps/icon-o-matic/generic/gui/scrollview/ScrollView.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/apps/icon-o-matic/generic/gui/scrollview/ScrollView.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2006-2009, Haiku Inc. All rights reserved. * Distributed under the terms of the MIT License. * * Authors: * Ingo Weinhold <bonefish@cs.tu-berlin.de> * Stephan Aßmus <superstippi@gmx.de> */ #include "ScrollView.h" #include <algorithm> #include <stdio.h> #include <string.h> #include <Bitmap.h> #ifdef __HAIKU__ # include <LayoutUtils.h> #endif #include <Message.h> #include <ScrollBar.h> #include <Window.h> #include "Scrollable.h" #include "ScrollCornerBitmaps.h" using namespace std; // #pragma mark - InternalScrollBar class InternalScrollBar : public BScrollBar { public: InternalScrollBar(ScrollView* scrollView, BRect frame, orientation posture); virtual ~InternalScrollBar(); virtual void ValueChanged(float value); virtual void MouseDown(BPoint where); virtual void MouseUp(BPoint where); private: ScrollView* fScrollView; }; // constructor InternalScrollBar::InternalScrollBar(ScrollView* scrollView, BRect frame, orientation posture) : BScrollBar(frame, NULL, NULL, 0, 0, posture), fScrollView(scrollView) { } // destructor InternalScrollBar::~InternalScrollBar() { } // ValueChanged void InternalScrollBar::ValueChanged(float value) { // Notify our parent scroll view. Note: the value already has changed, // so that we can't check, if it really has changed. if (fScrollView) fScrollView->_ScrollValueChanged(this, value); } // MouseDown void InternalScrollBar::MouseDown(BPoint where) { if (fScrollView) fScrollView->_SetScrolling(true); BScrollBar::MouseDown(where); } // MouseUp void InternalScrollBar::MouseUp(BPoint where) { BScrollBar::MouseUp(where); if (fScrollView) fScrollView->_SetScrolling(false); } // #pragma mark -ScrollCorner class ScrollCorner : public BView { public: ScrollCorner(ScrollView* scrollView); virtual ~ScrollCorner(); virtual void MouseDown(BPoint point); virtual void MouseUp(BPoint point); virtual void MouseMoved(BPoint point, uint32 transit, const BMessage* message); virtual void Draw(BRect updateRect); virtual void WindowActivated(bool active); void SetActive(bool active); inline bool IsActive() const { return fState & STATE_ACTIVE; } private: ScrollView* fScrollView; uint32 fState; BPoint fStartPoint; BPoint fStartScrollOffset; BBitmap* fBitmaps[3]; inline bool IsEnabled() const { return ((fState & STATE_ENABLED) == STATE_ENABLED); } void SetDragging(bool dragging); inline bool IsDragging() const { return (fState & STATE_DRAGGING); } enum { STATE_DRAGGING = 0x01, STATE_WINDOW_ACTIVE = 0x02, STATE_ACTIVE = 0x04, STATE_ENABLED = STATE_WINDOW_ACTIVE | STATE_ACTIVE, }; }; // constructor ScrollCorner::ScrollCorner(ScrollView* scrollView) : BView(BRect(0.0, 0.0, B_V_SCROLL_BAR_WIDTH - 1.0f, B_H_SCROLL_BAR_HEIGHT - 1.0f), NULL, 0, B_WILL_DRAW), fScrollView(scrollView), fState(0), fStartPoint(0, 0), fStartScrollOffset(0, 0) { SetViewColor(B_TRANSPARENT_32_BIT); fBitmaps[0] = new BBitmap(BRect(0.0f, 0.0f, sBitmapWidth - 1, sBitmapHeight - 1), sColorSpace); char* bits = (char*)fBitmaps[0]->Bits(); int32 bpr = fBitmaps[0]->BytesPerRow(); for (int i = 0; i < sBitmapHeight; i++, bits += bpr) { memcpy(bits, &sScrollCornerNormalBits[i * sBitmapHeight * 4], sBitmapWidth * 4); } fBitmaps[1] = new BBitmap(BRect(0.0f, 0.0f, sBitmapWidth - 1, sBitmapHeight - 1), sColorSpace); bits = (char*)fBitmaps[1]->Bits(); bpr = fBitmaps[1]->BytesPerRow(); for (int i = 0; i < sBitmapHeight; i++, bits += bpr) { memcpy(bits, &sScrollCornerPushedBits[i * sBitmapHeight * 4], sBitmapWidth * 4); } fBitmaps[2] = new BBitmap(BRect(0.0f, 0.0f, sBitmapWidth - 1, sBitmapHeight - 1), sColorSpace); bits = (char*)fBitmaps[2]->Bits(); bpr = fBitmaps[2]->BytesPerRow(); for (int i = 0; i < sBitmapHeight; i++, bits += bpr) { memcpy(bits, &sScrollCornerDisabledBits[i * sBitmapHeight * 4], sBitmapWidth * 4); } } // destructor ScrollCorner::~ScrollCorner() { for (int i = 0; i < 3; i++) delete fBitmaps[i]; } // MouseDown void ScrollCorner::MouseDown(BPoint point) { BView::MouseDown(point); uint32 buttons = 0; Window()->CurrentMessage()->FindInt32("buttons", (int32 *)&buttons); if (buttons & B_PRIMARY_MOUSE_BUTTON) { SetMouseEventMask(B_POINTER_EVENTS); if (fScrollView && IsEnabled() && Bounds().Contains(point)) { SetDragging(true); fStartPoint = point; fStartScrollOffset = fScrollView->ScrollOffset(); } } } // MouseUp void ScrollCorner::MouseUp(BPoint point) { BView::MouseUp(point); uint32 buttons = 0; Window()->CurrentMessage()->FindInt32("buttons", (int32 *)&buttons); if (!(buttons & B_PRIMARY_MOUSE_BUTTON)) SetDragging(false); } // MouseMoved void ScrollCorner::MouseMoved(BPoint point, uint32 transit, const BMessage* message) { BView::MouseMoved(point, transit, message); if (IsDragging()) { uint32 buttons = 0; Window()->CurrentMessage()->FindInt32("buttons", (int32 *)&buttons); // This is a work-around for a BeOS bug: We sometimes don't get a // MouseUp(), but fortunately it seems, that within the last // MouseMoved() the button is not longer pressed. if (buttons & B_PRIMARY_MOUSE_BUTTON) { BPoint diff = point - fStartPoint; if (fScrollView) { fScrollView->_ScrollCornerValueChanged(fStartScrollOffset - diff); // + diff); } } else SetDragging(false); } } // Draw void ScrollCorner::Draw(BRect updateRect) { if (IsEnabled()) { if (IsDragging()) DrawBitmap(fBitmaps[1], BPoint(0.0f, 0.0f)); else DrawBitmap(fBitmaps[0], BPoint(0.0f, 0.0f)); } else DrawBitmap(fBitmaps[2], BPoint(0.0f, 0.0f)); } // WindowActivated void ScrollCorner::WindowActivated(bool active) { if (active != (fState & STATE_WINDOW_ACTIVE)) { bool enabled = IsEnabled(); if (active) fState |= STATE_WINDOW_ACTIVE; else fState &= ~STATE_WINDOW_ACTIVE; if (enabled != IsEnabled()) Invalidate(); } } // SetActive void ScrollCorner::SetActive(bool active) { if (active != IsActive()) { bool enabled = IsEnabled(); if (active) fState |= STATE_ACTIVE; else fState &= ~STATE_ACTIVE; if (enabled != IsEnabled()) Invalidate(); } } // SetDragging void ScrollCorner::SetDragging(bool dragging) { if (dragging != IsDragging()) { if (dragging) fState |= STATE_DRAGGING; else fState &= ~STATE_DRAGGING; Invalidate(); } } // #pragma mark - ScrollView // constructor ScrollView::ScrollView(BView* child, uint32 scrollingFlags, BRect frame, const char* name, uint32 resizingMode, uint32 viewFlags, uint32 borderStyle, uint32 borderFlags) : BView(frame, name, resizingMode, viewFlags | B_FRAME_EVENTS | B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE), Scroller() { _Init(child, scrollingFlags, borderStyle, borderFlags); } #ifdef __HAIKU__ // constructor ScrollView::ScrollView(BView* child, uint32 scrollingFlags, const char* name, uint32 viewFlags, uint32 borderStyle, uint32 borderFlags) : BView(name, viewFlags | B_FRAME_EVENTS | B_WILL_DRAW | B_FULL_UPDATE_ON_RESIZE), Scroller() { _Init(child, scrollingFlags, borderStyle, borderFlags); } #endif // __HAIKU__ // destructor ScrollView::~ScrollView() { } // AllAttached void ScrollView::AllAttached() { // do a first layout _Layout(_UpdateScrollBarVisibility()); } // Draw void ScrollView::Draw(BRect updateRect) { if (fBorderStyle == B_NO_BORDER) return; rgb_color keyboardFocus = keyboard_navigation_color(); rgb_color light = tint_color(ui_color(B_PANEL_BACKGROUND_COLOR), B_LIGHTEN_MAX_TINT); rgb_color shadow = tint_color(ui_color(B_PANEL_BACKGROUND_COLOR), B_DARKEN_1_TINT); rgb_color darkShadow = tint_color(ui_color(B_PANEL_BACKGROUND_COLOR), B_DARKEN_2_TINT); BRect r = Bounds(); if (fChildFocused && fWindowActive) { SetHighColor(keyboardFocus); StrokeRect(r); } else { if (fBorderStyle == B_PLAIN_BORDER) { SetHighColor(darkShadow); StrokeRect(r); } else { BeginLineArray(4); AddLine(BPoint(r.left, r.bottom), BPoint(r.left, r.top), shadow); AddLine(BPoint(r.left + 1.0, r.top), BPoint(r.right, r.top), shadow); AddLine(BPoint(r.right, r.top + 1.0), BPoint(r.right, r.bottom), light); AddLine(BPoint(r.right - 1.0, r.bottom), BPoint(r.left + 1.0, r.bottom), light); EndLineArray(); } } if (fBorderStyle == B_PLAIN_BORDER) return; // The right and bottom lines will be hidden if the scroll views are // visible. But that doesn't harm. r.InsetBy(1, 1); SetHighColor(darkShadow); StrokeRect(r); } // FrameResized void ScrollView::FrameResized(float width, float height) { _Layout(0); } // WindowActivated void ScrollView::WindowActivated(bool activated) { fWindowActive = activated; if (fChildFocused) Invalidate(); } #ifdef __HAIKU__ // MinSize BSize ScrollView::MinSize() { BSize size = (fChild ? fChild->MinSize() : BSize(-1, -1)); return _Size(size); } // PreferredSize BSize ScrollView::PreferredSize() { BSize size = (fChild ? fChild->PreferredSize() : BSize(-1, -1)); return _Size(size); } #endif // __HAIKU__ // #pragma mark - // ScrollingFlags uint32 ScrollView::ScrollingFlags() const { return fScrollingFlags; } // SetVisibleRectIsChildBounds void ScrollView::SetVisibleRectIsChildBounds(bool flag) { if (flag != VisibleRectIsChildBounds()) { if (flag) fScrollingFlags |= SCROLL_VISIBLE_RECT_IS_CHILD_BOUNDS; else fScrollingFlags &= ~SCROLL_VISIBLE_RECT_IS_CHILD_BOUNDS; if (fChild && _UpdateScrollBarVisibility()) _Layout(0); } } // VisibleRectIsChildBounds bool ScrollView::VisibleRectIsChildBounds() const { return (fScrollingFlags & SCROLL_VISIBLE_RECT_IS_CHILD_BOUNDS); } // Child BView* ScrollView::Child() const { return fChild; } // ChildFocusChanged // // To be called by the scroll child, when its has got or lost the focus. // We need this to know, when to draw the blue focus frame. void ScrollView::ChildFocusChanged(bool focused) { if (fChildFocused != focused) { fChildFocused = focused; Invalidate(); } } // HScrollBar BScrollBar* ScrollView::HScrollBar() const { return fHScrollBar; } // VScrollBar BScrollBar* ScrollView::VScrollBar() const { return fVScrollBar; } // HVScrollCorner BView* ScrollView::HVScrollCorner() const { return fScrollCorner; } // #pragma mark - // SetHSmallStep void ScrollView::SetHSmallStep(float hStep) { SetSmallSteps(hStep, fVSmallStep); } // SetVSmallStep void ScrollView::SetVSmallStep(float vStep) { SetSmallSteps(fHSmallStep, vStep); } // SetSmallSteps void ScrollView::SetSmallSteps(float hStep, float vStep) { if (fHSmallStep != hStep || fVSmallStep != vStep) { fHSmallStep = hStep; fVSmallStep = vStep; _UpdateScrollBars(); } } // GetSmallSteps void ScrollView::GetSmallSteps(float* hStep, float* vStep) const { *hStep = fHSmallStep; *vStep = fVSmallStep; } // HSmallStep float ScrollView::HSmallStep() const { return fHSmallStep; } // VSmallStep float ScrollView::VSmallStep() const { return fVSmallStep; } // IsScrolling bool ScrollView::IsScrolling() const { return fScrolling; } void ScrollView::SetScrollingEnabled(bool enabled) { Scroller::SetScrollingEnabled(enabled); if (IsScrollingEnabled()) SetScrollOffset(ScrollOffset()); } // #pragma mark - // DataRectChanged void ScrollView::DataRectChanged(BRect /*oldDataRect*/, BRect /*newDataRect*/) { if (ScrollTarget()) { if (_UpdateScrollBarVisibility()) _Layout(0); else _UpdateScrollBars(); } } // ScrollOffsetChanged void ScrollView::ScrollOffsetChanged(BPoint /*oldOffset*/, BPoint newOffset) { if (fHScrollBar && fHScrollBar->Value() != newOffset.x) fHScrollBar->SetValue(newOffset.x); if (fVScrollBar && fVScrollBar->Value() != newOffset.y) fVScrollBar->SetValue(newOffset.y); } // VisibleSizeChanged void ScrollView::VisibleSizeChanged(float /*oldWidth*/, float /*oldHeight*/, float /*newWidth*/, float /*newHeight*/) { if (ScrollTarget()) { if (_UpdateScrollBarVisibility()) _Layout(0); else _UpdateScrollBars(); } } // ScrollTargetChanged void ScrollView::ScrollTargetChanged(Scrollable* /*oldTarget*/, Scrollable* newTarget) { /* // remove the old child if (fChild) RemoveChild(fChild); // add the new child BView* view = dynamic_cast<BView*>(newTarget); fChild = view; if (view) AddChild(view); else if (newTarget) // set the scroll target to NULL, if it isn't a BView SetScrollTarget(NULL); */ } // _Init void ScrollView::_Init(BView* child, uint32 scrollingFlags, uint32 borderStyle, uint32 borderFlags) { fChild = NULL; fScrollingFlags = scrollingFlags; fHScrollBar = NULL; fVScrollBar = NULL; fScrollCorner = NULL; fHVisible = true; fVVisible = true; fCornerVisible = true; fWindowActive = false; fChildFocused = false; fScrolling = false; fHSmallStep = 1; fVSmallStep = 1; fBorderStyle = borderStyle; fBorderFlags = borderFlags; // Set transparent view color -- our area is completely covered by // our children. SetViewColor(B_TRANSPARENT_32_BIT); // create scroll bars if (fScrollingFlags & (SCROLL_HORIZONTAL | SCROLL_HORIZONTAL_MAGIC)) { fHScrollBar = new InternalScrollBar(this, BRect(0.0, 0.0, 100.0, B_H_SCROLL_BAR_HEIGHT), B_HORIZONTAL); AddChild(fHScrollBar); } if (fScrollingFlags & (SCROLL_VERTICAL | SCROLL_VERTICAL_MAGIC)) { fVScrollBar = new InternalScrollBar(this, BRect(0.0, 0.0, B_V_SCROLL_BAR_WIDTH, 100.0), B_VERTICAL); AddChild(fVScrollBar); } // Create a scroll corner, if we can scroll into both direction. if (fHScrollBar && fVScrollBar) { fScrollCorner = new ScrollCorner(this); AddChild(fScrollCorner); } // add child if (child) { fChild = child; AddChild(child); if (Scrollable* scrollable = dynamic_cast<Scrollable*>(child)) SetScrollTarget(scrollable); } } // _ScrollValueChanged void ScrollView::_ScrollValueChanged(InternalScrollBar* scrollBar, float value) { if (!IsScrollingEnabled()) return; switch (scrollBar->Orientation()) { case B_HORIZONTAL: if (fHScrollBar) SetScrollOffset(BPoint(value, ScrollOffset().y)); break; case B_VERTICAL: if (fVScrollBar) SetScrollOffset(BPoint(ScrollOffset().x, value)); break; default: break; } } // _ScrollCornerValueChanged void ScrollView::_ScrollCornerValueChanged(BPoint offset) { // The logic in Scrollable::SetScrollOffset() handles offsets, that // are out of range. SetScrollOffset(offset); } // #pragma mark - // _Layout // // Relayouts all children (fChild, scroll bars). // flags indicates which scrollbars' visibility has changed. // May be overridden to do a custom layout -- the SCROLL_*_MAGIC must // be disabled in this case, or strange things happen. void ScrollView::_Layout(uint32 flags) { bool hbar = (fHScrollBar && fHVisible); bool vbar = (fVScrollBar && fVVisible); bool corner = (fScrollCorner && fCornerVisible); BRect childRect(_ChildRect()); float innerWidth = childRect.Width(); float innerHeight = childRect.Height(); BPoint scrollLT(_InnerRect().LeftTop()); scrollLT.x--; scrollLT.y--; BPoint scrollRB(childRect.RightBottom() + BPoint(1.0f, 1.0f)); // layout scroll bars and scroll corner if (corner) { // In this case the scrollbars overlap one pixel. fHScrollBar->MoveTo(scrollLT.x, scrollRB.y); fHScrollBar->ResizeTo(innerWidth + 2.0, B_H_SCROLL_BAR_HEIGHT); fVScrollBar->MoveTo(scrollRB.x, scrollLT.y); fVScrollBar->ResizeTo(B_V_SCROLL_BAR_WIDTH, innerHeight + 2.0); fScrollCorner->MoveTo(childRect.right + 2.0, childRect.bottom + 2.0); } else if (hbar) { fHScrollBar->MoveTo(scrollLT.x, scrollRB.y); fHScrollBar->ResizeTo(innerWidth + 2.0, B_H_SCROLL_BAR_HEIGHT); } else if (vbar) { fVScrollBar->MoveTo(scrollRB.x, scrollLT.y); fVScrollBar->ResizeTo(B_V_SCROLL_BAR_WIDTH, innerHeight + 2.0); } // layout child if (fChild) { fChild->MoveTo(childRect.LeftTop()); fChild->ResizeTo(innerWidth, innerHeight); if (VisibleRectIsChildBounds()) SetVisibleSize(innerWidth, innerHeight); // Due to a BeOS bug sometimes the area under a recently hidden // scroll bar isn't updated correctly. // We force this manually: The position of hidden scroll bar isn't // updated any longer, so we can't just invalidate it. if (fChild->Window()) { if (flags & SCROLL_HORIZONTAL && !fHVisible) fChild->Invalidate(fHScrollBar->Frame()); if (flags & SCROLL_VERTICAL && !fVVisible) fChild->Invalidate(fVScrollBar->Frame()); } } } // _UpdateScrollBars // // Probably somewhat misnamed. This function updates the scroll bars' // proportion, range attributes and step widths according to the scroll // target's DataRect() and VisibleBounds(). May also be called, if there's // no scroll target -- then the scroll bars are disabled. void ScrollView::_UpdateScrollBars() { BRect dataRect = DataRect(); BRect visibleBounds = VisibleBounds(); if (!fScrollTarget) { dataRect.Set(0.0, 0.0, 0.0, 0.0); visibleBounds.Set(0.0, 0.0, 0.0, 0.0); } float hProportion = min_c(1.0f, (visibleBounds.Width() + 1.0f) / (dataRect.Width() + 1.0f)); float hMaxValue = max_c(dataRect.left, dataRect.right - visibleBounds.Width()); float vProportion = min_c(1.0f, (visibleBounds.Height() + 1.0f) / (dataRect.Height() + 1.0f)); float vMaxValue = max_c(dataRect.top, dataRect.bottom - visibleBounds.Height()); // update horizontal scroll bar if (fHScrollBar) { fHScrollBar->SetProportion(hProportion); fHScrollBar->SetRange(dataRect.left, hMaxValue); // This obviously ineffective line works around a BScrollBar bug: // As documented the scrollbar's value is adjusted, if the range // has been changed and it therefore falls out of the range. But if, // after resetting the range to what it has been before, the user // moves the scrollbar to the original value via one click // it is failed to invoke BScrollBar::ValueChanged(). fHScrollBar->SetValue(fHScrollBar->Value()); fHScrollBar->SetSteps(fHSmallStep, visibleBounds.Width()); } // update vertical scroll bar if (fVScrollBar) { fVScrollBar->SetProportion(vProportion); fVScrollBar->SetRange(dataRect.top, vMaxValue); // This obviously ineffective line works around a BScrollBar bug. fVScrollBar->SetValue(fVScrollBar->Value()); fVScrollBar->SetSteps(fVSmallStep, visibleBounds.Height()); } // update scroll corner if (fScrollCorner) { fScrollCorner->SetActive(hProportion < 1.0f || vProportion < 1.0f); } } // set_visible_state // // Convenience function: Sets a view's visibility state to /visible/. // Returns true, if the state was actually changed, false otherwise. // This function never calls Hide() on a hidden or Show() on a visible // view. /view/ must be valid. static inline bool set_visible_state(BView* view, bool visible, bool* currentlyVisible) { bool changed = false; if (*currentlyVisible != visible) { if (visible) view->Show(); else view->Hide(); *currentlyVisible = visible; changed = true; } return changed; } // _UpdateScrollBarVisibility // // Checks which of scroll bars need to be visible according to // SCROLL_*_MAGIG and shows/hides them, if necessary. // Returns a bitwise combination of SCROLL_HORIZONTAL and SCROLL_VERTICAL // according to which scroll bar's visibility state has changed, 0 if none. // A return value != 0 usually means that the layout isn't valid any longer. uint32 ScrollView::_UpdateScrollBarVisibility() { uint32 changed = 0; BRect childRect(_MaxVisibleRect()); float width = childRect.Width(); float height = childRect.Height(); BRect dataRect = DataRect(); // Invalid if !ScrollTarget(), float dataWidth = dataRect.Width(); // but that doesn't harm. float dataHeight = dataRect.Height(); // bool hbar = (fScrollingFlags & SCROLL_HORIZONTAL_MAGIC); bool vbar = (fScrollingFlags & SCROLL_VERTICAL_MAGIC); if (!ScrollTarget()) { if (hbar) { if (set_visible_state(fHScrollBar, false, &fHVisible)) changed |= SCROLL_HORIZONTAL; } if (vbar) { if (set_visible_state(fVScrollBar, false, &fVVisible)) changed |= SCROLL_VERTICAL; } } else if (hbar && width >= dataWidth && vbar && height >= dataHeight) { // none if (set_visible_state(fHScrollBar, false, &fHVisible)) changed |= SCROLL_HORIZONTAL; if (set_visible_state(fVScrollBar, false, &fVVisible)) changed |= SCROLL_VERTICAL; } else { // The case, that both scroll bars are magic and invisible is catched, // so that while checking one bar we can suppose, that the other one // is visible (if it does exist at all). BRect innerRect(_GuessVisibleRect(fHScrollBar, fVScrollBar)); float innerWidth = innerRect.Width(); float innerHeight = innerRect.Height(); // the horizontal one? if (hbar) { if (innerWidth >= dataWidth) { if (set_visible_state(fHScrollBar, false, &fHVisible)) changed |= SCROLL_HORIZONTAL; } else { if (set_visible_state(fHScrollBar, true, &fHVisible)) changed |= SCROLL_HORIZONTAL; } } // the vertical one? if (vbar) { if (innerHeight >= dataHeight) { if (set_visible_state(fVScrollBar, false, &fVVisible)) changed |= SCROLL_VERTICAL; } else { if (set_visible_state(fVScrollBar, true, &fVVisible)) changed |= SCROLL_VERTICAL; } } } // If anything has changed, update the scroll corner as well. if (changed && fScrollCorner) set_visible_state(fScrollCorner, fHVisible && fVVisible, &fCornerVisible); return changed; } // _InnerRect // // Returns the rectangle that actually can be used for the child and the // scroll bars, i.e. the view's Bounds() subtracted the space for the // decorative frame. BRect ScrollView::_InnerRect() const { BRect r = Bounds(); float borderWidth = 0; switch (fBorderStyle) { case B_NO_BORDER: break; case B_PLAIN_BORDER: borderWidth = 1; break; case B_FANCY_BORDER: default: borderWidth = 2; break; } if (fBorderFlags & BORDER_LEFT) r.left += borderWidth; if (fBorderFlags & BORDER_TOP) r.top += borderWidth; if (fBorderFlags & BORDER_RIGHT) r.right -= borderWidth; if (fBorderFlags & BORDER_BOTTOM) r.bottom -= borderWidth; return r; } // _ChildRect // // Returns the rectangle, that should be the current child frame. // `should' because 1. we might not have a child at all or 2. a // relayout is pending. BRect ScrollView::_ChildRect() const { return _ChildRect(fHScrollBar && fHVisible, fVScrollBar && fVVisible); } // _ChildRect // // The same as _ChildRect() with the exception that not the current // scroll bar visibility, but a fictitious one given by /hbar/ and /vbar/ // is considered. BRect ScrollView::_ChildRect(bool hbar, bool vbar) const { BRect rect(_InnerRect()); if (vbar) rect.right -= B_V_SCROLL_BAR_WIDTH; if (hbar) rect.bottom -= B_H_SCROLL_BAR_HEIGHT; return rect; } // _GuessVisibleRect // // Returns an approximation of the visible rect for the // fictitious scroll bar visibility given by /hbar/ and /vbar/. // In the case !VisibleRectIsChildBounds() it is simply the current // visible rect. BRect ScrollView::_GuessVisibleRect(bool hbar, bool vbar) const { if (VisibleRectIsChildBounds()) return _ChildRect(hbar, vbar).OffsetToCopy(ScrollOffset()); return VisibleRect(); } // _MaxVisibleRect // // Returns the maximal possible visible rect in the current situation, that // is depending on if the visible rect is the child's bounds either the // rectangle the child covers when both scroll bars are hidden (offset to // the scroll offset) or the current visible rect. BRect ScrollView::_MaxVisibleRect() const { return _GuessVisibleRect(true, true); } #ifdef __HAIKU__ BSize ScrollView::_Size(BSize size) { if (fVVisible) size.width += B_V_SCROLL_BAR_WIDTH; if (fHVisible) size.height += B_H_SCROLL_BAR_HEIGHT; switch (fBorderStyle) { case B_NO_BORDER: // one line of pixels from scrollbar possibly hidden if (fBorderFlags & BORDER_RIGHT) size.width += fVVisible ? -1 : 0; if (fBorderFlags & BORDER_BOTTOM) size.height += fHVisible ? -1 : 0; break; case B_PLAIN_BORDER: if (fBorderFlags & BORDER_LEFT) size.width += 1; if (fBorderFlags & BORDER_TOP) size.height += 1; // one line of pixels in frame possibly from scrollbar if (fBorderFlags & BORDER_RIGHT) size.width += fVVisible ? 0 : 1; if (fBorderFlags & BORDER_BOTTOM) size.height += fHVisible ? 0 : 1; break; case B_FANCY_BORDER: default: if (fBorderFlags & BORDER_LEFT) size.width += 2; if (fBorderFlags & BORDER_TOP) size.height += 2; // one line of pixels in frame possibly from scrollbar if (fBorderFlags & BORDER_RIGHT) size.width += fVVisible ? 1 : 2; if (fBorderFlags & BORDER_BOTTOM) size.height += fHVisible ? 1 : 2; break; } return BLayoutUtils::ComposeSize(ExplicitMinSize(), size); } #endif // __HAIKU__ // _SetScrolling void ScrollView::_SetScrolling(bool scrolling) { fScrolling = scrolling; }
24.431641
90
0.709489
Kirishikesan
587b442811398b0ca067d49caf754a9146c31f44
2,465
cpp
C++
inference-engine/src/inference_engine/builders/ie_clamp_layer.cpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
3
2020-02-09T23:25:37.000Z
2021-01-19T09:44:12.000Z
inference-engine/src/inference_engine/builders/ie_clamp_layer.cpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
null
null
null
inference-engine/src/inference_engine/builders/ie_clamp_layer.cpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
2
2020-04-18T16:24:39.000Z
2021-01-19T09:42:19.000Z
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <builders/ie_clamp_layer.hpp> #include <ie_cnn_layer_builder.h> #include <string> using namespace InferenceEngine; Builder::ClampLayer::ClampLayer(const std::string& name): LayerDecorator("Clamp", name) { getLayer()->getOutputPorts().resize(1); getLayer()->getInputPorts().resize(1); setMinValue(0.0f); setMaxValue(1.0f); } Builder::ClampLayer::ClampLayer(const Layer::Ptr& layer): LayerDecorator(layer) { checkType("Clamp"); } Builder::ClampLayer::ClampLayer(const Layer::CPtr& layer): LayerDecorator(layer) { checkType("Clamp"); } Builder::ClampLayer& Builder::ClampLayer::setName(const std::string& name) { getLayer()->setName(name); return *this; } const Port& Builder::ClampLayer::getPort() const { return getLayer()->getOutputPorts()[0]; } Builder::ClampLayer& Builder::ClampLayer::setPort(const Port &port) { getLayer()->getOutputPorts()[0] = port; getLayer()->getInputPorts()[0] = port; return *this; } float Builder::ClampLayer::getMaxValue() const { return getLayer()->getParameters().at("max"); } Builder::ClampLayer& Builder::ClampLayer::setMaxValue(float maxValue) { getLayer()->getParameters()["max"] = maxValue; return *this; } float Builder::ClampLayer::getMinValue() const { return getLayer()->getParameters().at("min"); } Builder::ClampLayer& Builder::ClampLayer::setMinValue(float minValue) { getLayer()->getParameters()["min"] = minValue; return *this; } REG_VALIDATOR_FOR(Clamp, [](const InferenceEngine::Builder::Layer::CPtr& input_layer, bool partial) { Builder::ClampLayer layer(input_layer); if (layer.getMinValue() > layer.getMaxValue()) { THROW_IE_EXCEPTION << "MinValue should be less or equal MaxValue"; } if (!input_layer->getInputPorts().empty() && !input_layer->getOutputPorts().empty() && !input_layer->getInputPorts()[0].shape().empty() && !input_layer->getOutputPorts()[0].shape().empty() && input_layer->getInputPorts()[0].shape() != input_layer->getOutputPorts()[0].shape()) { THROW_IE_EXCEPTION << "Input and output ports should be equal"; } }); REG_CONVERTER_FOR(Clamp, [](const CNNLayerPtr& cnnLayer, Builder::Layer& layer) { layer.getParameters()["max"] = cnnLayer->GetParamAsFloat("max", 0); layer.getParameters()["min"] = cnnLayer->GetParamAsFloat("min", 0); });
31.602564
101
0.685193
zhoub
587f3a3518e699cd57af64cd502cb880151e1ec4
2,884
hpp
C++
Source/Ilum/Graphics/GraphicsContext.hpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
11
2022-01-09T05:32:56.000Z
2022-03-28T06:35:16.000Z
Source/Ilum/Graphics/GraphicsContext.hpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
null
null
null
Source/Ilum/Graphics/GraphicsContext.hpp
Chaf-Libraries/Ilum
83d0b7d4f2ba6cc3ba586f5442a09d55b69aedf8
[ "MIT" ]
1
2021-11-20T15:39:03.000Z
2021-11-20T15:39:03.000Z
#pragma once #include "Engine/Subsystem.hpp" #include "Eventing/Event.hpp" #include "Graphics/Synchronization/QueueSystem.hpp" #include "Graphics/Command/CommandPool.hpp" #include "Timing/Stopwatch.hpp" #include "Utils/PCH.hpp" namespace Ilum { class Instance; class PhysicalDevice; class Surface; class LogicalDevice; class Swapchain; class CommandBuffer; class DescriptorCache; class ShaderCache; class ImGuiContext; class Profiler; class RenderFrame; class GraphicsContext : public TSubsystem<GraphicsContext> { public: GraphicsContext(Context *context); ~GraphicsContext() = default; const Instance &getInstance() const; const PhysicalDevice &getPhysicalDevice() const; const Surface &getSurface() const; const LogicalDevice &getLogicalDevice() const; const Swapchain &getSwapchain() const; DescriptorCache &getDescriptorCache(); ShaderCache &getShaderCache(); QueueSystem &getQueueSystem(); Profiler &getProfiler(); const VkPipelineCache &getPipelineCache() const; CommandPool &getCommandPool(QueueUsage usage = QueueUsage::Graphics, CommandPool::ResetMode reset_mode = CommandPool::ResetMode::ResetPool); uint32_t getFrameIndex() const; const VkSemaphore &getPresentCompleteSemaphore() const; const VkSemaphore &getRenderCompleteSemaphore() const; void submitCommandBuffer(VkCommandBuffer cmd_buffer); RenderFrame &getFrame(); uint64_t getFrameCount() const; bool isVsync() const; void setVsync(bool vsync); public: virtual bool onInitialize() override; virtual void onPreTick() override; virtual void onTick(float delta_time) override; virtual void onPostTick() override; virtual void onShutdown() override; public: void createSwapchain(bool vsync = false); private: void newFrame(); void submitFrame(); private: scope<Instance> m_instance = nullptr; scope<PhysicalDevice> m_physical_device = nullptr; scope<Surface> m_surface = nullptr; scope<LogicalDevice> m_logical_device = nullptr; scope<Swapchain> m_swapchain = nullptr; scope<DescriptorCache> m_descriptor_cache = nullptr; scope<ShaderCache> m_shader_cache = nullptr; scope<Profiler> m_profiler = nullptr; // Command pool per thread std::vector<scope<RenderFrame>> m_render_frames; std::vector<VkCommandBuffer> m_submit_cmd_buffers; // Present resource CommandBuffer * cmd_buffer = nullptr; std::vector<VkSemaphore> m_present_complete; std::vector<VkSemaphore> m_render_complete; uint32_t m_current_frame = 0; bool m_vsync = false; VkPipelineCache m_pipeline_cache = VK_NULL_HANDLE; uint64_t m_frame_count = 0; std::mutex m_command_pool_mutex; std::mutex m_command_buffer_mutex; scope<QueueSystem> m_queue_system = nullptr; public: Event<> Swapchain_Rebuild_Event; }; } // namespace Ilum
22.708661
141
0.748266
Chaf-Libraries
5880350e3a96b3b7863451123c21a0ae18a48323
1,277
cpp
C++
01_Programming_Basics/05_Programming_Basics_Exams/04_CPP_Programming Basics_Online_Exam_3_and_4_November 2018/03_wedding_investment.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
01_Programming_Basics/05_Programming_Basics_Exams/04_CPP_Programming Basics_Online_Exam_3_and_4_November 2018/03_wedding_investment.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
01_Programming_Basics/05_Programming_Basics_Exams/04_CPP_Programming Basics_Online_Exam_3_and_4_November 2018/03_wedding_investment.cpp
Knightwalker/Knowledgebase
00c6dea5e52c0d2b0fe0dc3b7b5c298d445f0161
[ "MIT" ]
null
null
null
#include <iostream> #include <string> //#include <math.h> //#include <stdlib.h> #include <iomanip> using namespace std; int main() { string contractLen = ""; string contractType = ""; string desert = ""; int months = 0; getline(cin, contractLen); getline(cin, contractType); getline(cin, desert); cin >> months; cin.ignore(); double tax = 0.0; if (contractLen == "one") { if (contractType == "Small") { tax = 9.98; } else if (contractType == "Middle") { tax = 18.99; } else if (contractType == "Large") { tax = 25.98; } else if (contractType == "ExtraLarge") { tax = 35.99; } } else if (contractLen == "two") { if (contractType == "Small") { tax = 8.58; } else if (contractType == "Middle") { tax = 17.09; } else if (contractType == "Large") { tax = 23.59; } else if (contractType == "ExtraLarge") { tax = 31.79; } } if (desert == "yes") { if (tax > 0 && tax <= 10) { tax += 5.50; } else if (tax > 10 && tax <= 30) { tax += 4.35; } else if (tax > 30) { tax += 3.85; } } if (contractLen == "two") { tax -= tax * 0.0375; } cout << fixed << setprecision(2) << tax * months << " lv." << endl; return 0; }
20.596774
69
0.511355
Knightwalker
58834bd94e9823c5ce752f747a7a9a76a913d22c
2,918
cpp
C++
Source/MammutQOR/Model/MProperty.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Source/MammutQOR/Model/MProperty.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Source/MammutQOR/Model/MProperty.cpp
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//MProperty.cpp // Copyright Querysoft Limited 2015 // // 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 "MammutQOR.h" #include "MammutQOR/Model/MProperty.h" #include "MammutQOR/Model/MPropertySet.h" //------------------------------------------------------------------------------ namespace nsMammut { //------------------------------------------------------------------------------ CPropertyBase::CPropertyBase( CModel* pContainer, const nsCodeQOR::CString& strName ) : CModelItem( pContainer ), m_Name( strName ) { CPropertySet* pPropertySet = dynamic_cast< CPropertySet* >( pContainer ); if( pPropertySet ) { pPropertySet->insert( Ref() ); } } //------------------------------------------------------------------------------ CPropertyBase::~CPropertyBase() { } //------------------------------------------------------------------------------ CPropertyBase::CPropertyBase( const CPropertyBase& src ) : CModelItem( src ), m_Name( src.m_Name ) { } //------------------------------------------------------------------------------ CPropertyBase& CPropertyBase::operator = ( const CPropertyBase& src ) { CModelItem::operator=( src ); if( &src != this ) { m_Name = src.m_Name; } return *this; } //------------------------------------------------------------------------------ const nsCodeQOR::CString& CPropertyBase::Name( void ) const { return m_Name; } //------------------------------------------------------------------------------ CPropertyBase::refType CPropertyBase::Clone( void ) { return refType( new CPropertyBase( *this ), true ); } }//nsMammut
36.024691
132
0.593215
mfaithfull
5883a7ccd6b8725755a20d88b5404c91fd4f9def
30,503
cpp
C++
UnrealEngine-4.11.2-release/Engine/Source/Runtime/AIModule/Private/AIController.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2016-10-01T21:35:52.000Z
2016-10-01T21:35:52.000Z
UnrealEngine-4.11.2-release/Engine/Source/Runtime/AIModule/Private/AIController.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
null
null
null
UnrealEngine-4.11.2-release/Engine/Source/Runtime/AIModule/Private/AIController.cpp
armroyce/Unreal
ea1cdebe70407d59af4e8366d7111c52ce4606df
[ "MIT" ]
1
2021-04-27T08:48:33.000Z
2021-04-27T08:48:33.000Z
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved. #include "AIModulePrivate.h" #include "Kismet/GameplayStatics.h" #include "DisplayDebugHelpers.h" #include "BrainComponent.h" #include "BehaviorTree/BehaviorTree.h" #include "BehaviorTree/BehaviorTreeManager.h" #include "BehaviorTree/BlackboardComponent.h" #include "Navigation/PathFollowingComponent.h" #include "GameFramework/Pawn.h" #include "GameFramework/PawnMovementComponent.h" #include "Engine/Canvas.h" #include "GameFramework/PhysicsVolume.h" #include "AIController.h" #include "Perception/AIPerceptionComponent.h" #include "GameplayTasksComponent.h" // mz@todo these need to be removed, legacy code #define CLOSEPROXIMITY 500.f #define NEARSIGHTTHRESHOLD 2000.f #define MEDSIGHTTHRESHOLD 3162.f #define FARSIGHTTHRESHOLD 8000.f #define CLOSEPROXIMITYSQUARED (CLOSEPROXIMITY*CLOSEPROXIMITY) #define NEARSIGHTTHRESHOLDSQUARED (NEARSIGHTTHRESHOLD*NEARSIGHTTHRESHOLD) #define MEDSIGHTTHRESHOLDSQUARED (MEDSIGHTTHRESHOLD*MEDSIGHTTHRESHOLD) #define FARSIGHTTHRESHOLDSQUARED (FARSIGHTTHRESHOLD*FARSIGHTTHRESHOLD) //----------------------------------------------------------------------// // AAIController //----------------------------------------------------------------------// bool AAIController::bAIIgnorePlayers = false; DECLARE_CYCLE_STAT(TEXT("MoveTo"), STAT_MoveTo, STATGROUP_AI); DEFINE_LOG_CATEGORY(LogAINavigation); AAIController::AAIController(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PathFollowingComponent = CreateDefaultSubobject<UPathFollowingComponent>(TEXT("PathFollowingComponent")); PathFollowingComponent->OnMoveFinished.AddUObject(this, &AAIController::OnMoveCompleted); ActionsComp = CreateDefaultSubobject<UPawnActionsComponent>("ActionsComp"); bSkipExtraLOSChecks = true; bWantsPlayerState = false; TeamID = FGenericTeamId::NoTeam; bStopAILogicOnUnposses = true; } void AAIController::Tick(float DeltaTime) { Super::Tick(DeltaTime); UpdateControlRotation(DeltaTime); } void AAIController::PostInitializeComponents() { Super::PostInitializeComponents(); if (bWantsPlayerState && !IsPendingKill() && (GetNetMode() != NM_Client)) { InitPlayerState(); } #if ENABLE_VISUAL_LOG TArray<UActorComponent*> ComponentSet; GetComponents(ComponentSet); for (auto Component : ComponentSet) { REDIRECT_OBJECT_TO_VLOG(Component, this); } #endif // ENABLE_VISUAL_LOG } void AAIController::PostRegisterAllComponents() { Super::PostRegisterAllComponents(); // cache PerceptionComponent if not already set // note that it's possible for an AI to not have a perception component at all if (PerceptionComponent == NULL || PerceptionComponent->IsPendingKill() == true) { PerceptionComponent = FindComponentByClass<UAIPerceptionComponent>(); } } void AAIController::Reset() { Super::Reset(); if (PathFollowingComponent) { PathFollowingComponent->AbortMove(TEXT("controller reset")); } } void AAIController::DisplayDebug(UCanvas* Canvas, const FDebugDisplayInfo& DebugDisplay, float& YL, float& YPos) { Super::DisplayDebug(Canvas, DebugDisplay, YL, YPos); static FName NAME_AI = FName(TEXT("AI")); if (DebugDisplay.IsDisplayOn(NAME_AI)) { if (PathFollowingComponent) { PathFollowingComponent->DisplayDebug(Canvas, DebugDisplay, YL, YPos); } AActor* FocusActor = GetFocusActor(); if (FocusActor) { FDisplayDebugManager& DisplayDebugManager = Canvas->DisplayDebugManager; DisplayDebugManager.DrawString(FString::Printf(TEXT(" Focus %s"), *FocusActor->GetName())); } } } #if ENABLE_VISUAL_LOG void AAIController::GrabDebugSnapshot(FVisualLogEntry* Snapshot) const { FVisualLogStatusCategory MyCategory; MyCategory.Category = TEXT("AI Controller"); MyCategory.Add(TEXT("Pawn"), GetNameSafe(GetPawn())); AActor* FocusActor = GetFocusActor(); MyCategory.Add(TEXT("Focus"), GetDebugName(FocusActor)); if (FocusActor == nullptr) { MyCategory.Add(TEXT("Focus Location"), TEXT_AI_LOCATION(GetFocalPoint())); } Snapshot->Status.Add(MyCategory); if (GetPawn()) { Snapshot->Location = GetPawn()->GetActorLocation(); } if (PathFollowingComponent) { PathFollowingComponent->DescribeSelfToVisLog(Snapshot); } if (BrainComponent != nullptr) { BrainComponent->DescribeSelfToVisLog(Snapshot); } if (PerceptionComponent != nullptr) { PerceptionComponent->DescribeSelfToVisLog(Snapshot); } if (CachedGameplayTasksComponent != nullptr) { CachedGameplayTasksComponent->DescribeSelfToVisLog(Snapshot); } } #endif // ENABLE_VISUAL_LOG void AAIController::SetFocalPoint(FVector NewFocus, EAIFocusPriority::Type InPriority) { if (InPriority >= FocusInformation.Priorities.Num()) { FocusInformation.Priorities.SetNum(InPriority + 1); } FFocusKnowledge::FFocusItem& FocusItem = FocusInformation.Priorities[InPriority]; FocusItem.Actor = nullptr; FocusItem.Position = NewFocus; } FVector AAIController::GetFocalPointForPriority(EAIFocusPriority::Type InPriority) const { FVector Result = FAISystem::InvalidLocation; if (InPriority < FocusInformation.Priorities.Num()) { const FFocusKnowledge::FFocusItem& FocusItem = FocusInformation.Priorities[InPriority]; AActor* FocusActor = FocusItem.Actor.Get(); if (FocusActor) { Result = GetFocalPointOnActor(FocusActor); } else { Result = FocusItem.Position; } } return Result; } FVector AAIController::GetFocalPoint() const { FVector Result = FAISystem::InvalidLocation; // find focus with highest priority for (int32 Index = FocusInformation.Priorities.Num() - 1; Index >= 0; --Index) { const FFocusKnowledge::FFocusItem& FocusItem = FocusInformation.Priorities[Index]; AActor* FocusActor = FocusItem.Actor.Get(); if (FocusActor) { Result = GetFocalPointOnActor(FocusActor); break; } else if (FAISystem::IsValidLocation(FocusItem.Position)) { Result = FocusItem.Position; break; } } return Result; } AActor* AAIController::GetFocusActor() const { AActor* FocusActor = nullptr; for (int32 Index = FocusInformation.Priorities.Num() - 1; Index >= 0; --Index) { const FFocusKnowledge::FFocusItem& FocusItem = FocusInformation.Priorities[Index]; FocusActor = FocusItem.Actor.Get(); if (FocusActor) { break; } else if (FAISystem::IsValidLocation(FocusItem.Position)) { break; } } return FocusActor; } FVector AAIController::GetFocalPointOnActor(const AActor *Actor) const { return Actor != nullptr ? Actor->GetActorLocation() : FAISystem::InvalidLocation; } void AAIController::K2_SetFocus(AActor* NewFocus) { SetFocus(NewFocus, EAIFocusPriority::Gameplay); } void AAIController::K2_SetFocalPoint(FVector NewFocus) { SetFocalPoint(NewFocus, EAIFocusPriority::Gameplay); } void AAIController::K2_ClearFocus() { ClearFocus(EAIFocusPriority::Gameplay); } void AAIController::SetFocus(AActor* NewFocus, EAIFocusPriority::Type InPriority) { if (NewFocus) { if (InPriority >= FocusInformation.Priorities.Num()) { FocusInformation.Priorities.SetNum(InPriority + 1); } FocusInformation.Priorities[InPriority].Actor = NewFocus; } else { ClearFocus(InPriority); } } void AAIController::ClearFocus(EAIFocusPriority::Type InPriority) { if (InPriority < FocusInformation.Priorities.Num()) { FocusInformation.Priorities[InPriority].Actor = nullptr; FocusInformation.Priorities[InPriority].Position = FAISystem::InvalidLocation; } } void AAIController::SetPerceptionComponent(UAIPerceptionComponent& InPerceptionComponent) { if (PerceptionComponent != nullptr) { UE_VLOG(this, LogAIPerception, Warning, TEXT("Setting perception component while AIController already has one!")); } PerceptionComponent = &InPerceptionComponent; } bool AAIController::LineOfSightTo(const AActor* Other, FVector ViewPoint, bool bAlternateChecks) const { if (Other == nullptr) { return false; } if (ViewPoint.IsZero()) { FRotator ViewRotation; GetActorEyesViewPoint(ViewPoint, ViewRotation); // if we still don't have a view point we simply fail if (ViewPoint.IsZero()) { return false; } } static FName NAME_LineOfSight = FName(TEXT("LineOfSight")); FVector TargetLocation = Other->GetTargetLocation(GetPawn()); FCollisionQueryParams CollisionParams(NAME_LineOfSight, true, this->GetPawn()); CollisionParams.AddIgnoredActor(Other); bool bHit = GetWorld()->LineTraceTestByChannel(ViewPoint, TargetLocation, ECC_Visibility, CollisionParams); if (!bHit) { return true; } // if other isn't using a cylinder for collision and isn't a Pawn (which already requires an accurate cylinder for AI) // then don't go any further as it likely will not be tracing to the correct location const APawn * OtherPawn = Cast<const APawn>(Other); if (!OtherPawn && Cast<UCapsuleComponent>(Other->GetRootComponent()) == NULL) { return false; } const FVector OtherActorLocation = Other->GetActorLocation(); const float DistSq = (OtherActorLocation - ViewPoint).SizeSquared(); if (DistSq > FARSIGHTTHRESHOLDSQUARED) { return false; } if (!OtherPawn && (DistSq > NEARSIGHTTHRESHOLDSQUARED)) { return false; } float OtherRadius, OtherHeight; Other->GetSimpleCollisionCylinder(OtherRadius, OtherHeight); if (!bAlternateChecks || !bLOSflag) { //try viewpoint to head bHit = GetWorld()->LineTraceTestByChannel(ViewPoint, OtherActorLocation + FVector(0.f, 0.f, OtherHeight), ECC_Visibility, CollisionParams); if (!bHit) { return true; } } if (!bSkipExtraLOSChecks && (!bAlternateChecks || bLOSflag)) { // only check sides if width of other is significant compared to distance if (OtherRadius * OtherRadius / (OtherActorLocation - ViewPoint).SizeSquared() < 0.0001f) { return false; } //try checking sides - look at dist to four side points, and cull furthest and closest FVector Points[4]; Points[0] = OtherActorLocation - FVector(OtherRadius, -1 * OtherRadius, 0); Points[1] = OtherActorLocation + FVector(OtherRadius, OtherRadius, 0); Points[2] = OtherActorLocation - FVector(OtherRadius, OtherRadius, 0); Points[3] = OtherActorLocation + FVector(OtherRadius, -1 * OtherRadius, 0); int32 IndexMin = 0; int32 IndexMax = 0; float CurrentMax = (Points[0] - ViewPoint).SizeSquared(); float CurrentMin = CurrentMax; for (int32 PointIndex = 1; PointIndex<4; PointIndex++) { const float NextSize = (Points[PointIndex] - ViewPoint).SizeSquared(); if (NextSize > CurrentMin) { CurrentMin = NextSize; IndexMax = PointIndex; } else if (NextSize < CurrentMax) { CurrentMax = NextSize; IndexMin = PointIndex; } } for (int32 PointIndex = 0; PointIndex<4; PointIndex++) { if ((PointIndex != IndexMin) && (PointIndex != IndexMax)) { bHit = GetWorld()->LineTraceTestByChannel(ViewPoint, Points[PointIndex], ECC_Visibility, CollisionParams); if (!bHit) { return true; } } } } return false; } void AAIController::ActorsPerceptionUpdated(const TArray<AActor*>& UpdatedActors) { } DEFINE_LOG_CATEGORY_STATIC(LogTestAI, All, All); void AAIController::UpdateControlRotation(float DeltaTime, bool bUpdatePawn) { // Look toward focus FVector FocalPoint = GetFocalPoint(); APawn* const Pawn = GetPawn(); if (Pawn) { FVector Direction = FAISystem::IsValidLocation(FocalPoint) ? (FocalPoint - Pawn->GetPawnViewLocation()) : Pawn->GetActorForwardVector(); FRotator NewControlRotation = Direction.Rotation(); // Don't pitch view unless looking at another pawn if (Cast<APawn>(GetFocusActor()) == nullptr) { NewControlRotation.Pitch = 0.f; } if (GetControlRotation().Equals(NewControlRotation, 1e-3f) == false) { SetControlRotation(NewControlRotation); if (bUpdatePawn) { Pawn->FaceRotation(NewControlRotation, DeltaTime); } } } } void AAIController::Possess(APawn* InPawn) { // don't even try possessing pending-kill pawns if (InPawn != nullptr && InPawn->IsPendingKill()) { return; } Super::Possess(InPawn); if (GetPawn() == nullptr || InPawn == nullptr) { return; } // no point in doing navigation setup if pawn has no movement component const UPawnMovementComponent* MovementComp = InPawn->GetMovementComponent(); if (MovementComp != NULL) { UpdateNavigationComponents(); } if (PathFollowingComponent) { PathFollowingComponent->Initialize(); } if (bWantsPlayerState) { ChangeState(NAME_Playing); } // a Pawn controlled by AI _requires_ a GameplayTasksComponent, so if Pawn // doesn't have one we need to create it if (CachedGameplayTasksComponent == nullptr) { UGameplayTasksComponent* GTComp = InPawn->FindComponentByClass<UGameplayTasksComponent>(); if (GTComp == nullptr) { GTComp = NewObject<UGameplayTasksComponent>(InPawn, TEXT("GameplayTasksComponent")); GTComp->RegisterComponent(); } CachedGameplayTasksComponent = GTComp; } if (CachedGameplayTasksComponent && !CachedGameplayTasksComponent->OnClaimedResourcesChange.Contains(this, GET_FUNCTION_NAME_CHECKED(AAIController, OnGameplayTaskResourcesClaimed))) { CachedGameplayTasksComponent->OnClaimedResourcesChange.AddDynamic(this, &AAIController::OnGameplayTaskResourcesClaimed); REDIRECT_OBJECT_TO_VLOG(CachedGameplayTasksComponent, this); } OnPossess(InPawn); } void AAIController::UnPossess() { APawn* OldPawn = GetPawn(); Super::UnPossess(); if (PathFollowingComponent) { PathFollowingComponent->Cleanup(); } if (bStopAILogicOnUnposses) { if (BrainComponent) { BrainComponent->Cleanup(); } } if (CachedGameplayTasksComponent) { CachedGameplayTasksComponent->OnClaimedResourcesChange.RemoveDynamic(this, &AAIController::OnGameplayTaskResourcesClaimed); CachedGameplayTasksComponent = nullptr; } OnUnpossess(OldPawn); } void AAIController::SetPawn(APawn* InPawn) { Super::SetPawn(InPawn); if (Blackboard) { const UBlackboardData* BBAsset = Blackboard->GetBlackboardAsset(); if (BBAsset) { const FBlackboard::FKey SelfKey = BBAsset->GetKeyID(FBlackboard::KeySelf); if (SelfKey != FBlackboard::InvalidKey) { Blackboard->SetValue<UBlackboardKeyType_Object>(SelfKey, GetPawn()); } } } } void AAIController::InitNavigationControl(UPathFollowingComponent*& PathFollowingComp) { PathFollowingComp = PathFollowingComponent; } EPathFollowingRequestResult::Type AAIController::MoveToActor(AActor* Goal, float AcceptanceRadius, bool bStopOnOverlap, bool bUsePathfinding, bool bCanStrafe, TSubclassOf<UNavigationQueryFilter> FilterClass, bool bAllowPartialPaths) { FAIMoveRequest MoveReq(Goal); MoveReq.SetUsePathfinding(bUsePathfinding); MoveReq.SetAllowPartialPath(bAllowPartialPaths); MoveReq.SetNavigationFilter(FilterClass); MoveReq.SetAcceptanceRadius(AcceptanceRadius); MoveReq.SetStopOnOverlap(bStopOnOverlap); MoveReq.SetCanStrafe(bCanStrafe); return MoveTo(MoveReq); } EPathFollowingRequestResult::Type AAIController::MoveToLocation(const FVector& Dest, float AcceptanceRadius, bool bStopOnOverlap, bool bUsePathfinding, bool bProjectDestinationToNavigation, bool bCanStrafe, TSubclassOf<UNavigationQueryFilter> FilterClass, bool bAllowPartialPaths) { FAIMoveRequest MoveReq(Dest); MoveReq.SetUsePathfinding(bUsePathfinding); MoveReq.SetAllowPartialPath(bAllowPartialPaths); MoveReq.SetProjectGoalLocation(bProjectDestinationToNavigation); MoveReq.SetNavigationFilter(FilterClass); MoveReq.SetAcceptanceRadius(AcceptanceRadius); MoveReq.SetStopOnOverlap(bStopOnOverlap); MoveReq.SetCanStrafe(bCanStrafe); return MoveTo(MoveReq); } EPathFollowingRequestResult::Type AAIController::MoveTo(const FAIMoveRequest& MoveRequest) { SCOPE_CYCLE_COUNTER(STAT_MoveTo); UE_VLOG(this, LogAINavigation, Log, TEXT("MoveTo: %s"), *MoveRequest.ToString()); if (MoveRequest.IsValid() == false) { UE_VLOG(this, LogAINavigation, Error, TEXT("MoveTo request failed due MoveRequest not being valid. Most probably desireg Goal Actor not longer exists"), *MoveRequest.ToString()); return EPathFollowingRequestResult::Failed; } EPathFollowingRequestResult::Type Result = EPathFollowingRequestResult::Failed; bool bCanRequestMove = true; bool bAlreadyAtGoal = false; if (!MoveRequest.IsMoveToActorRequest()) { if (MoveRequest.GetGoalLocation().ContainsNaN() || FAISystem::IsValidLocation(MoveRequest.GetGoalLocation()) == false) { UE_VLOG(this, LogAINavigation, Error, TEXT("AAIController::MoveTo: Destination is not valid! Goal(%s)"), TEXT_AI_LOCATION(MoveRequest.GetGoalLocation())); bCanRequestMove = false; } // fail if projection to navigation is required but it failed if (bCanRequestMove && MoveRequest.IsProjectingGoal()) { UNavigationSystem* NavSys = UNavigationSystem::GetCurrent(GetWorld()); const FNavAgentProperties& AgentProps = GetNavAgentPropertiesRef(); FNavLocation ProjectedLocation; if (NavSys && !NavSys->ProjectPointToNavigation(MoveRequest.GetGoalLocation(), ProjectedLocation, INVALID_NAVEXTENT, &AgentProps)) { UE_VLOG_LOCATION(this, LogAINavigation, Error, MoveRequest.GetGoalLocation(), 30.f, FColor::Red, TEXT("AAIController::MoveTo failed to project destination location to navmesh")); bCanRequestMove = false; } MoveRequest.UpdateGoalLocation(ProjectedLocation.Location); } bAlreadyAtGoal = bCanRequestMove && PathFollowingComponent && PathFollowingComponent->HasReached(MoveRequest.GetGoalLocation(), MoveRequest.GetAcceptanceRadius(), !MoveRequest.CanStopOnOverlap()); } else { bAlreadyAtGoal = bCanRequestMove && PathFollowingComponent && PathFollowingComponent->HasReached(*MoveRequest.GetGoalActor(), MoveRequest.GetAcceptanceRadius(), !MoveRequest.CanStopOnOverlap()); } if (bAlreadyAtGoal) { UE_VLOG(this, LogAINavigation, Log, TEXT("MoveToActor: already at goal!")); if (PathFollowingComponent) { // make sure previous move request gets aborted PathFollowingComponent->AbortMove(TEXT("Aborting move due to new move request finishing with AlreadyAtGoal"), FAIRequestID::AnyRequest); PathFollowingComponent->SetLastMoveAtGoal(true); } OnMoveCompleted(FAIRequestID::CurrentRequest, EPathFollowingResult::Success); Result = EPathFollowingRequestResult::AlreadyAtGoal; } else if (bCanRequestMove) { FPathFindingQuery Query; const bool bValidQuery = PreparePathfinding(MoveRequest, Query); const FAIRequestID RequestID = bValidQuery ? RequestPathAndMove(MoveRequest, Query) : FAIRequestID::InvalidRequest; if (RequestID.IsValid()) { bAllowStrafe = MoveRequest.CanStrafe(); Result = EPathFollowingRequestResult::RequestSuccessful; } } if (Result == EPathFollowingRequestResult::Failed) { if (PathFollowingComponent) { PathFollowingComponent->SetLastMoveAtGoal(false); } OnMoveCompleted(FAIRequestID::InvalidRequest, EPathFollowingResult::Invalid); } return Result; } FAIRequestID AAIController::RequestMove(const FAIMoveRequest& MoveRequest, FNavPathSharedPtr Path) { uint32 RequestID = FAIRequestID::InvalidRequest; if (PathFollowingComponent) { RequestID = PathFollowingComponent->RequestMove(Path, MoveRequest.GetGoalActor(), MoveRequest.GetAcceptanceRadius(), MoveRequest.CanStopOnOverlap(), MoveRequest.GetUserData()); } return RequestID; } // deprecated FAIRequestID AAIController::RequestMove(FNavPathSharedPtr Path, AActor* Goal, float AcceptanceRadius, bool bStopOnOverlap, FCustomMoveSharedPtr CustomData) { FAIMoveRequest MoveReq(Goal); MoveReq.SetAcceptanceRadius(AcceptanceRadius); MoveReq.SetStopOnOverlap(bStopOnOverlap); MoveReq.SetUserData(CustomData); return RequestMove(MoveReq, Path); } bool AAIController::PauseMove(FAIRequestID RequestToPause) { if (PathFollowingComponent != NULL && RequestToPause.IsEquivalent(PathFollowingComponent->GetCurrentRequestId())) { PathFollowingComponent->PauseMove(RequestToPause); return true; } return false; } bool AAIController::ResumeMove(FAIRequestID RequestToResume) { if (PathFollowingComponent != NULL && RequestToResume.IsEquivalent(PathFollowingComponent->GetCurrentRequestId())) { PathFollowingComponent->ResumeMove(RequestToResume); return true; } return false; } void AAIController::StopMovement() { UE_VLOG(this, LogAINavigation, Log, TEXT("AAIController::StopMovement: %s STOP MOVEMENT"), *GetNameSafe(GetPawn())); PathFollowingComponent->AbortMove(TEXT("StopMovement")); } bool AAIController::PreparePathfinding(const FAIMoveRequest& MoveRequest, FPathFindingQuery& Query) { UNavigationSystem* NavSys = UNavigationSystem::GetCurrent(GetWorld()); if (NavSys) { ANavigationData* NavData = MoveRequest.IsUsingPathfinding() ? NavSys->GetNavDataForProps(GetNavAgentPropertiesRef()) : NavSys->GetAbstractNavData(); if (NavData) { FVector GoalLocation = MoveRequest.GetGoalLocation(); if (MoveRequest.IsMoveToActorRequest()) { const INavAgentInterface* NavGoal = Cast<const INavAgentInterface>(MoveRequest.GetGoalActor()); if (NavGoal) { const FVector Offset = NavGoal->GetMoveGoalOffset(this); GoalLocation = FQuatRotationTranslationMatrix(MoveRequest.GetGoalActor()->GetActorQuat(), NavGoal->GetNavAgentLocation()).TransformPosition(Offset); } else { GoalLocation = MoveRequest.GetGoalActor()->GetActorLocation(); } } Query = FPathFindingQuery(*this, *NavData, GetNavAgentLocation(), GoalLocation, UNavigationQueryFilter::GetQueryFilter(*NavData, MoveRequest.GetNavigationFilter())); Query.SetAllowPartialPaths(MoveRequest.IsUsingPartialPaths()); if (PathFollowingComponent) { PathFollowingComponent->OnPathfindingQuery(Query); } return true; } else { UE_VLOG(this, LogAINavigation, Warning, TEXT("Unable to find NavigationData instance while calling AAIController::PreparePathfinding")); } } return false; } // deprecated bool AAIController::PreparePathfinding(FPathFindingQuery& Query, const FVector& Dest, AActor* Goal, bool bUsePathfinding, TSubclassOf<class UNavigationQueryFilter> FilterClass) { if (Goal) { FAIMoveRequest MoveReq(Goal); MoveReq.SetUsePathfinding(bUsePathfinding); MoveReq.SetNavigationFilter(FilterClass); return PreparePathfinding(MoveReq, Query); } FAIMoveRequest MoveReq(Dest); MoveReq.SetUsePathfinding(bUsePathfinding); MoveReq.SetNavigationFilter(FilterClass); return PreparePathfinding(MoveReq, Query); } FAIRequestID AAIController::RequestPathAndMove(const FAIMoveRequest& MoveRequest, FPathFindingQuery& Query) { SCOPE_CYCLE_COUNTER(STAT_AI_Overall); FAIRequestID RequestID; UNavigationSystem* NavSys = UNavigationSystem::GetCurrent(GetWorld()); if (NavSys) { FPathFindingResult PathResult = NavSys->FindPathSync(Query); if (PathResult.Result != ENavigationQueryResult::Error) { if (PathResult.IsSuccessful() && PathResult.Path.IsValid()) { if (MoveRequest.IsMoveToActorRequest()) { PathResult.Path->SetGoalActorObservation(*MoveRequest.GetGoalActor(), 100.0f); } PathResult.Path->EnableRecalculationOnInvalidation(true); RequestID = RequestMove(MoveRequest, PathResult.Path); } } else { UE_VLOG(this, LogAINavigation, Error, TEXT("Trying to find path to %s resulted in Error") , MoveRequest.IsMoveToActorRequest() ? *GetNameSafe(MoveRequest.GetGoalActor()) : *MoveRequest.GetGoalLocation().ToString()); UE_VLOG_SEGMENT(this, LogAINavigation, Error, GetPawn() ? GetPawn()->GetActorLocation() : FAISystem::InvalidLocation , MoveRequest.GetGoalLocation(), FColor::Red, TEXT("Failed move to %s"), *GetNameSafe(MoveRequest.GetGoalActor())); } } return RequestID; } // deprecated FAIRequestID AAIController::RequestPathAndMove(FPathFindingQuery& Query, AActor* Goal, float AcceptanceRadius, bool bStopOnOverlap, FCustomMoveSharedPtr CustomData) { FAIMoveRequest MoveReq(Goal); MoveReq.SetAcceptanceRadius(AcceptanceRadius); MoveReq.SetStopOnOverlap(bStopOnOverlap); MoveReq.SetUserData(CustomData); return RequestPathAndMove(MoveReq, Query); } EPathFollowingStatus::Type AAIController::GetMoveStatus() const { return (PathFollowingComponent) ? PathFollowingComponent->GetStatus() : EPathFollowingStatus::Idle; } bool AAIController::HasPartialPath() const { return (PathFollowingComponent != NULL) && (PathFollowingComponent->HasPartialPath()); } bool AAIController::IsFollowingAPath() const { return (PathFollowingComponent != nullptr) && PathFollowingComponent->HasValidPath(); } FVector AAIController::GetImmediateMoveDestination() const { return (PathFollowingComponent) ? PathFollowingComponent->GetCurrentTargetLocation() : FVector::ZeroVector; } void AAIController::SetMoveBlockDetection(bool bEnable) { if (PathFollowingComponent) { PathFollowingComponent->SetBlockDetectionState(bEnable); } } void AAIController::OnMoveCompleted(FAIRequestID RequestID, EPathFollowingResult::Type Result) { ReceiveMoveCompleted.Broadcast(RequestID, Result); } bool AAIController::RunBehaviorTree(UBehaviorTree* BTAsset) { // @todo: find BrainComponent and see if it's BehaviorTreeComponent // Also check if BTAsset requires BlackBoardComponent, and if so // check if BB type is accepted by BTAsset. // Spawn BehaviorTreeComponent if none present. // Spawn BlackBoardComponent if none present, but fail if one is present but is not of compatible class if (BTAsset == NULL) { UE_VLOG(this, LogBehaviorTree, Warning, TEXT("RunBehaviorTree: Unable to run NULL behavior tree")); return false; } bool bSuccess = true; bool bShouldInitializeBlackboard = false; // see if need a blackboard component at all UBlackboardComponent* BlackboardComp = NULL; if (BTAsset->BlackboardAsset) { bSuccess = UseBlackboard(BTAsset->BlackboardAsset, BlackboardComp); } if (bSuccess) { UBehaviorTreeComponent* BTComp = Cast<UBehaviorTreeComponent>(BrainComponent); if (BTComp == NULL) { UE_VLOG(this, LogBehaviorTree, Log, TEXT("RunBehaviorTree: spawning BehaviorTreeComponent..")); BTComp = NewObject<UBehaviorTreeComponent>(this, TEXT("BTComponent")); BTComp->RegisterComponent(); } // make sure BrainComponent points at the newly created BT component BrainComponent = BTComp; check(BTComp != NULL); BTComp->StartTree(*BTAsset, EBTExecutionMode::Looped); } return bSuccess; } bool AAIController::InitializeBlackboard(UBlackboardComponent& BlackboardComp, UBlackboardData& BlackboardAsset) { check(BlackboardComp.GetOwner() == this); if (BlackboardComp.InitializeBlackboard(BlackboardAsset)) { // find the "self" key and set it to our pawn const FBlackboard::FKey SelfKey = BlackboardAsset.GetKeyID(FBlackboard::KeySelf); if (SelfKey != FBlackboard::InvalidKey) { BlackboardComp.SetValue<UBlackboardKeyType_Object>(SelfKey, GetPawn()); } OnUsingBlackBoard(&BlackboardComp, &BlackboardAsset); return true; } return false; } bool AAIController::UseBlackboard(UBlackboardData* BlackboardAsset, UBlackboardComponent*& BlackboardComponent) { if (BlackboardAsset == nullptr) { UE_VLOG(this, LogBehaviorTree, Log, TEXT("UseBlackboard: trying to use NULL Blackboard asset. Ignoring")); return false; } bool bSuccess = true; Blackboard = FindComponentByClass<UBlackboardComponent>(); if (Blackboard == nullptr) { Blackboard = NewObject<UBlackboardComponent>(this, TEXT("BlackboardComponent")); if (Blackboard != nullptr) { InitializeBlackboard(*Blackboard, *BlackboardAsset); Blackboard->RegisterComponent(); } } else if (Blackboard->GetBlackboardAsset() == nullptr) { InitializeBlackboard(*Blackboard, *BlackboardAsset); } else if (Blackboard->GetBlackboardAsset() != BlackboardAsset) { // @todo this behavior should be opt-out-able. UE_VLOG(this, LogBehaviorTree, Log, TEXT("UseBlackboard: requested blackboard %s while already has %s instantiated. Forcing new BB.") , *GetNameSafe(BlackboardAsset), *GetNameSafe(Blackboard->GetBlackboardAsset())); InitializeBlackboard(*Blackboard, *BlackboardAsset); } BlackboardComponent = Blackboard; return bSuccess; } bool AAIController::SuggestTossVelocity(FVector& OutTossVelocity, FVector Start, FVector End, float TossSpeed, bool bPreferHighArc, float CollisionRadius, bool bOnlyTraceUp) { // pawn's physics volume gets 2nd priority APhysicsVolume const* const PhysicsVolume = GetPawn() ? GetPawn()->GetPawnPhysicsVolume() : NULL; float const GravityOverride = PhysicsVolume ? PhysicsVolume->GetGravityZ() : 0.f; ESuggestProjVelocityTraceOption::Type const TraceOption = bOnlyTraceUp ? ESuggestProjVelocityTraceOption::OnlyTraceWhileAsceding : ESuggestProjVelocityTraceOption::TraceFullPath; return UGameplayStatics::SuggestProjectileVelocity(this, OutTossVelocity, Start, End, TossSpeed, bPreferHighArc, CollisionRadius, GravityOverride, TraceOption); } bool AAIController::PerformAction(UPawnAction& Action, EAIRequestPriority::Type Priority, UObject* const Instigator /*= NULL*/) { return ActionsComp != NULL && ActionsComp->PushAction(Action, Priority, Instigator); } FString AAIController::GetDebugIcon() const { if (BrainComponent == NULL || BrainComponent->IsRunning() == false) { return TEXT("/Engine/EngineResources/AICON-Red.AICON-Red"); } return TEXT("/Engine/EngineResources/AICON-Green.AICON-Green"); } /** Returns PathFollowingComponent subobject **/ UPathFollowingComponent* AAIController::GetPathFollowingComponent() const { return PathFollowingComponent; } /** Returns ActionsComp subobject **/ UPawnActionsComponent* AAIController::GetActionsComp() const { return ActionsComp; } UAIPerceptionComponent* AAIController::GetAIPerceptionComponent() { return PerceptionComponent; } const UAIPerceptionComponent* AAIController::GetAIPerceptionComponent() const { return PerceptionComponent; } void AAIController::OnGameplayTaskResourcesClaimed(FGameplayResourceSet NewlyClaimed, FGameplayResourceSet FreshlyReleased) { if (BrainComponent) { const uint8 LogicID = UGameplayTaskResource::GetResourceID<UAIResource_Logic>(); if (NewlyClaimed.HasID(LogicID)) { BrainComponent->LockResource(EAIRequestPriority::Logic); } else if (FreshlyReleased.HasID(LogicID)) { BrainComponent->ClearResourceLock(EAIRequestPriority::Logic); } } } //----------------------------------------------------------------------// // IGenericTeamAgentInterface //----------------------------------------------------------------------// void AAIController::SetGenericTeamId(const FGenericTeamId& NewTeamID) { if (TeamID != NewTeamID) { TeamID = NewTeamID; // @todo notify perception system that a controller changed team ID } }
29.730019
280
0.759499
armroyce
58848ecb914b9942e082aaaf3c94e461d8532f95
3,754
cpp
C++
Beautiful/WebDemo/downloadwidget.cpp
martinkro/tutorial-qt
8685434520c6ab61691722aa06ca075f8ddbeacf
[ "MIT" ]
2
2018-06-24T10:19:30.000Z
2018-12-13T14:31:49.000Z
Beautiful/WebDemo/downloadwidget.cpp
martinkro/tutorial-qt
8685434520c6ab61691722aa06ca075f8ddbeacf
[ "MIT" ]
null
null
null
Beautiful/WebDemo/downloadwidget.cpp
martinkro/tutorial-qt
8685434520c6ab61691722aa06ca075f8ddbeacf
[ "MIT" ]
null
null
null
#include "downloadwidget.h" #include <QFileInfo> #include <QUrl> #include <QWebEngineDownloadItem> DownloadWidget::DownloadWidget(QWebEngineDownloadItem *download, QWidget *parent) : QFrame(parent) , m_download(download) , m_timeAdded(QTime::currentTime()) { setupUi(this); m_dstName->setText(QFileInfo(m_download->path()).fileName()); m_srcUrl->setText(m_download->url().toDisplayString()); connect(m_cancelButton, &QPushButton::clicked, [this](bool) { if (m_download->state() == QWebEngineDownloadItem::DownloadInProgress) m_download->cancel(); else emit removeClicked(this); }); connect(m_download, &QWebEngineDownloadItem::downloadProgress, this, &DownloadWidget::updateWidget); connect(m_download, &QWebEngineDownloadItem::stateChanged, this, &DownloadWidget::updateWidget); updateWidget(); } inline QString DownloadWidget::withUnit(qreal bytes) { if (bytes < (1 << 10)) return tr("%L1 B").arg(bytes); else if (bytes < (1 << 20)) return tr("%L1 KiB").arg(bytes / (1 << 10), 0, 'f', 2); else if (bytes < (1 << 30)) return tr("%L1 MiB").arg(bytes / (1 << 20), 0, 'f', 2); else return tr("%L1 GiB").arg(bytes / (1 << 30), 0, 'f', 2); } void DownloadWidget::updateWidget() { qreal totalBytes = m_download->totalBytes(); qreal receivedBytes = m_download->receivedBytes(); qreal bytesPerSecond = receivedBytes / m_timeAdded.elapsed() * 1000; auto state = m_download->state(); switch (state) { case QWebEngineDownloadItem::DownloadRequested: Q_UNREACHABLE(); break; case QWebEngineDownloadItem::DownloadInProgress: if (totalBytes >= 0) { m_progressBar->setValue(qRound(100 * receivedBytes / totalBytes)); m_progressBar->setDisabled(false); m_progressBar->setFormat( tr("%p% - %1 of %2 downloaded - %3/s") .arg(withUnit(receivedBytes)) .arg(withUnit(totalBytes)) .arg(withUnit(bytesPerSecond))); } else { m_progressBar->setValue(0); m_progressBar->setDisabled(false); m_progressBar->setFormat( tr("unknown size - %1 downloaded - %2/s") .arg(withUnit(receivedBytes)) .arg(withUnit(bytesPerSecond))); } break; case QWebEngineDownloadItem::DownloadCompleted: m_progressBar->setValue(100); m_progressBar->setDisabled(true); m_progressBar->setFormat( tr("completed - %1 downloaded - %2/s") .arg(withUnit(receivedBytes)) .arg(withUnit(bytesPerSecond))); break; case QWebEngineDownloadItem::DownloadCancelled: m_progressBar->setValue(0); m_progressBar->setDisabled(true); m_progressBar->setFormat( tr("cancelled - %1 downloaded - %2/s") .arg(withUnit(receivedBytes)) .arg(withUnit(bytesPerSecond))); break; case QWebEngineDownloadItem::DownloadInterrupted: m_progressBar->setValue(0); m_progressBar->setDisabled(true); m_progressBar->setFormat( tr("interrupted: %1") .arg("")); break; } if (state == QWebEngineDownloadItem::DownloadInProgress) { static QIcon cancelIcon(QStringLiteral(":process-stop.png")); m_cancelButton->setIcon(cancelIcon); m_cancelButton->setToolTip(tr("Stop downloading")); } else { static QIcon removeIcon(QStringLiteral(":edit-clear.png")); m_cancelButton->setIcon(removeIcon); m_cancelButton->setToolTip(tr("Remove from list")); } }
34.759259
81
0.611881
martinkro
5884b95b75c3932c2fe703eaa5af5e083815b1ff
6,973
cpp
C++
services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/vitural_communicator_aggregator.cpp
openharmony-gitee-mirror/distributeddatamgr_datamgr
3f17e1a6a6e0f83f3a346e87073b39dd949b0c9e
[ "Apache-2.0" ]
null
null
null
services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/vitural_communicator_aggregator.cpp
openharmony-gitee-mirror/distributeddatamgr_datamgr
3f17e1a6a6e0f83f3a346e87073b39dd949b0c9e
[ "Apache-2.0" ]
null
null
null
services/distributeddataservice/libs/distributeddb/test/unittest/common/syncer/vitural_communicator_aggregator.cpp
openharmony-gitee-mirror/distributeddatamgr_datamgr
3f17e1a6a6e0f83f3a346e87073b39dd949b0c9e
[ "Apache-2.0" ]
1
2021-09-13T12:07:54.000Z
2021-09-13T12:07:54.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * 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 "vitural_communicator.h" #include <cstdint> #include <thread> #include "db_errno.h" #include "vitural_communicator_aggregator.h" #include "log_print.h" namespace DistributedDB { int VirtualCommunicatorAggregator::Initialize(IAdapter *inAdapter) { return E_OK; } void VirtualCommunicatorAggregator::Finalize() { } // If not success, return nullptr and set outErrorNo ICommunicator *VirtualCommunicatorAggregator::AllocCommunicator(uint64_t commLabel, int &outErrorNo) { if (isEnable_) { return AllocCommunicator(remoteDeviceId_, outErrorNo); } return nullptr; } ICommunicator *VirtualCommunicatorAggregator::AllocCommunicator(const LabelType &commLabel, int &outErrorNo) { if (isEnable_) { return AllocCommunicator(remoteDeviceId_, outErrorNo); } return nullptr; } void VirtualCommunicatorAggregator::ReleaseCommunicator(ICommunicator *inCommunicator) { // Called in main thread only VirtualCommunicator *communicator = static_cast<VirtualCommunicator *>(inCommunicator); OfflineDevice(communicator->GetDeviceId()); { std::lock_guard<std::mutex> lock(communicatorsLock_); communicators_.erase(communicator->GetDeviceId()); } RefObject::KillAndDecObjRef(communicator); communicator = nullptr; } int VirtualCommunicatorAggregator::RegCommunicatorLackCallback(const CommunicatorLackCallback &onCommLack, const Finalizer &inOper) { onCommLack_ = onCommLack; return E_OK; } int VirtualCommunicatorAggregator::RegOnConnectCallback(const OnConnectCallback &onConnect, const Finalizer &inOper) { onConnect_ = onConnect; RunOnConnectCallback("deviceId", true); return E_OK; } void VirtualCommunicatorAggregator::RunCommunicatorLackCallback(const LabelType &commLabel) { if (onCommLack_) { onCommLack_(commLabel); } } void VirtualCommunicatorAggregator::RunOnConnectCallback(const std::string &target, bool isConnect) { if (onConnect_) { onConnect_(target, isConnect); } } void VirtualCommunicatorAggregator::OnlineDevice(const std::string &deviceId) const { if (!isEnable_) { return; } // Called in main thread only for (const auto &iter : communicators_) { VirtualCommunicator *communicatorTmp = static_cast<VirtualCommunicator *>(iter.second); if (iter.first != deviceId) { communicatorTmp->CallbackOnConnect(deviceId, true); } } } void VirtualCommunicatorAggregator::OfflineDevice(const std::string &deviceId) const { if (!isEnable_) { return; } // Called in main thread only for (const auto &iter : communicators_) { VirtualCommunicator *communicatorTmp = static_cast<VirtualCommunicator *>(iter.second); if (iter.first != deviceId) { communicatorTmp->CallbackOnConnect(deviceId, false); } } } ICommunicator *VirtualCommunicatorAggregator::AllocCommunicator(const std::string &deviceId, int &outErrorNo) { // Called in main thread only VirtualCommunicator *communicator = new (std::nothrow) VirtualCommunicator(deviceId, this); if (communicator == nullptr) { outErrorNo = -E_OUT_OF_MEMORY; } { std::lock_guard<std::mutex> lock(communicatorsLock_); communicators_.insert(std::pair<std::string, ICommunicator *>(deviceId, communicator)); } OnlineDevice(deviceId); return communicator; } ICommunicator *VirtualCommunicatorAggregator::GetCommunicator(const std::string &deviceId) const { std::lock_guard<std::mutex> lock(communicatorsLock_); auto iter = communicators_.find(deviceId); if (iter != communicators_.end()) { VirtualCommunicator *communicator = static_cast<VirtualCommunicator *>(iter->second); return communicator; } return nullptr; } void VirtualCommunicatorAggregator::DispatchMessage(const std::string &srcTarget, const std::string &dstTarget, const Message *inMsg, const OnSendEnd &onEnd) { if (VirtualCommunicatorAggregator::GetBlockValue()) { std::unique_lock<std::mutex> lock(blockLock_); conditionVar_.wait(lock); } if (!isEnable_) { LOGD("[VirtualCommunicatorAggregator] DispatchMessage, VirtualCommunicatorAggregator is disabled"); delete inMsg; inMsg = nullptr; return CallSendEnd(-E_PERIPHERAL_INTERFACE_FAIL, onEnd); } std::lock_guard<std::mutex> lock(communicatorsLock_); auto iter = communicators_.find(dstTarget); if (iter != communicators_.end()) { LOGE("[VirtualCommunicatorAggregator] DispatchMessage, find dstTarget %s", dstTarget.c_str()); VirtualCommunicator *communicator = static_cast<VirtualCommunicator *>(iter->second); if (!communicator->IsEnabled()) { LOGE("[VirtualCommunicatorAggregator] DispatchMessage, find dstTarget %s disabled", dstTarget.c_str()); delete inMsg; inMsg = nullptr; return CallSendEnd(-E_PERIPHERAL_INTERFACE_FAIL, onEnd); } Message *msg = const_cast<Message *>(inMsg); msg->SetTarget(srcTarget); RefObject::IncObjRef(communicator); std::thread thread([communicator, srcTarget, msg]() { communicator->CallbackOnMessage(srcTarget, msg); RefObject::DecObjRef(communicator); }); thread.detach(); CallSendEnd(OK, onEnd); } else { LOGE("[VirtualCommunicatorAggregator] DispatchMessage, can't find dstTarget %s", dstTarget.c_str()); delete inMsg; inMsg = nullptr; CallSendEnd(-E_NOT_FOUND, onEnd); } } void VirtualCommunicatorAggregator::SetBlockValue(bool value) { std::unique_lock<std::mutex> lock(blockLock_); isBlock_ = value; if (!value) { conditionVar_.notify_all(); } } bool VirtualCommunicatorAggregator::GetBlockValue() const { return isBlock_; } void VirtualCommunicatorAggregator::Disable() { isEnable_ = false; } void VirtualCommunicatorAggregator::Enable() { LOGD("[VirtualCommunicatorAggregator] enable"); isEnable_ = true; } void VirtualCommunicatorAggregator::CallSendEnd(int errCode, const OnSendEnd &onEnd) { if (onEnd) { (void)RuntimeContext::GetInstance()->ScheduleTask([errCode, onEnd]() { onEnd(errCode); }); } } } // namespace DistributedDB
30.991111
116
0.703714
openharmony-gitee-mirror
58855a1d969826f5a467b796deb3b50623140186
15,638
cpp
C++
src/proxy_server/proxy_server.cpp
PetrPPetrov/gkm-world
7c24d1646e04b439733a7eb603c9a00526b39f4c
[ "BSD-2-Clause" ]
2
2021-06-04T09:27:52.000Z
2021-06-08T05:23:21.000Z
src/proxy_server/proxy_server.cpp
PetrPPetrov/gkm-world
7c24d1646e04b439733a7eb603c9a00526b39f4c
[ "BSD-2-Clause" ]
null
null
null
src/proxy_server/proxy_server.cpp
PetrPPetrov/gkm-world
7c24d1646e04b439733a7eb603c9a00526b39f4c
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2018-2020 Petr Petrovich Petrov. All rights reserved. // License: https://github.com/PetrPPetrov/gkm-world/blob/master/LICENSE #include <iostream> #include <fstream> #include <memory> #include <boost/uuid/uuid_io.hpp> #include <boost/uuid/random_generator.hpp> #include "gkm_world/protocol.h" #include "gkm_world/logger.h" #include "gkm_world/configuration_reader.h" #include "proxy_server.h" ProxyServer::ProxyServer(const std::string& cfg_file_name_) : cfg_file_name(cfg_file_name_), signals(io_service, SIGINT, SIGTERM) { setApplicationType(Packet::EApplicationType::ProxyServer); std::ifstream config_file(cfg_file_name); ConfigurationReader config_reader; config_reader.addParameter("proxy_server_port_number", port_number); config_reader.addParameter("balancer_server_ip", balancer_server_ip); config_reader.addParameter("balancer_server_port_number", balancer_server_port_number); config_reader.addParameter("log_min_severity", minimum_level); config_reader.addParameter("log_to_screen", log_to_screen); config_reader.addParameter("log_to_file", log_to_file); config_reader.addParameter("registered_users_file_name", registered_users_file_name); config_reader.read(config_file); balancer_server_end_point = boost::asio::ip::udp::endpoint(IpAddress::from_string(balancer_server_ip), balancer_server_port_number); proxy_server_end_point = boost::asio::ip::udp::endpoint(IpAddress(), port_number); socket = boost::asio::ip::udp::socket(io_service, proxy_server_end_point); } ProxyServer::~ProxyServer() { saveRegisteredUsers(registered_users_file_name); } bool ProxyServer::start() { Logger::setLoggingToScreen(log_to_screen); Logger::setLoggingToFile(log_to_file, "proxy_server_" + std::to_string(port_number) + ".log"); Logger::setMinimumLevel(minimum_level); Logger::registerThisThread(); LOG_INFO << "Proxy Server is starting..."; try { dumpParameters(); startImpl(); } catch (boost::system::system_error& error) { LOG_FATAL << "boost::system::system_error: " << error.what(); return false; } catch (const std::exception& exception) { LOG_FATAL << "std::exception: " << exception.what(); return false; } catch (...) { LOG_FATAL << "Unknown error"; return false; } return true; } void ProxyServer::dumpParameters() { LOG_INFO << "configuration_file_name " << cfg_file_name; LOG_INFO << "balancer_server_ip " << balancer_server_ip; LOG_INFO << "balancer_server_port_number " << balancer_server_port_number; LOG_INFO << "proxy_server_ip " << proxy_server_end_point.address(); LOG_INFO << "proxy_server_port_number " << proxy_server_end_point.port(); LOG_INFO << "log_min_severity " << getText(minimum_level); LOG_INFO << "log_to_screen " << log_to_screen; LOG_INFO << "log_to_file " << log_to_file; LOG_INFO << "registered_users_file_name " << registered_users_file_name; } void ProxyServer::startImpl() { using namespace boost::placeholders; loadRegisteredUsers(registered_users_file_name); doReceive(); signals.async_wait(boost::bind(&ProxyServer::onQuit, this, _1, _2)); setReceiveHandler(Packet::EType::Login, boost::bind(&ProxyServer::onLogin, this, _1)); setReceiveHandler(Packet::EType::Logout, boost::bind(&ProxyServer::onLogout, this, _1)); setReceiveHandler(Packet::EType::LogoutInternalAnswer, boost::bind(&ProxyServer::onLogoutInternalAnswer, this, _1)); setReceiveHandler(Packet::EType::InitializePosition, boost::bind(&ProxyServer::onInitializePosition, this, _1)); setReceiveHandler(Packet::EType::InitializePositionInternalAnswer, boost::bind(&ProxyServer::onInitializePositionInternalAnswer, this, _1)); setReceiveHandler(Packet::EType::UnitAction, boost::bind(&ProxyServer::onUnitAction, this, _1)); setReceiveHandler(Packet::EType::UnitActionInternalAnswer, boost::bind(&ProxyServer::onUnitActionInternalAnswer, this, _1)); setReceiveHandler(Packet::EType::RegisterProxyAnswer, boost::bind(&ProxyServer::onRegisterProxyAnswer, this, _1)); auto register_proxy = createPacket<Packet::RegisterProxy>(); guaranteedSendTo(register_proxy, balancer_server_end_point, boost::bind(&Transport::logError, this, _1, _2)); io_service.run(); } void ProxyServer::onQuit(const boost::system::error_code& error, int sig_number) { if (!error) { saveRegisteredUsers(registered_users_file_name); } else { LOG_ERROR << "users were not saved in the file"; } onQuitSignal(error, sig_number); } bool ProxyServer::onLogin(size_t received_bytes) { LOG_DEBUG << "onLogin"; const auto packet = getReceiveBufferAs<Packet::Login>(); std::string login = packet->login.str(); std::string password = packet->password.str(); std::string full_name = packet->full_name.str(); LOG_DEBUG << "end_point: " << remote_end_point; LOG_DEBUG << "password: " << login; LOG_DEBUG << "login: " << password; LOG_DEBUG << "full_name: " << full_name; auto fit_login_it = login_to_user_info.find(login); UserInfo::Ptr cur_user; if (fit_login_it != login_to_user_info.end()) { LOG_DEBUG << "existing user"; cur_user = fit_login_it->second; if (password != cur_user->password) { LOG_DEBUG << "authorization failure"; auto answer = createPacket<Packet::LoginAnswer>(packet->packet_number); answer->success = false; standardSend(answer); return true; } else { LOG_DEBUG << "authorization OK"; } } else { LOG_DEBUG << "new user"; UserInfo::Ptr new_user = std::make_shared<UserInfo>(); new_user->login = login; new_user->password = password; new_user->full_name = full_name; login_to_user_info.emplace(login, new_user); cur_user = new_user; } if (!cur_user->online) { LOG_DEBUG << "user is logging"; IndexType new_token; UserOnlineInfo* allocated_user_online_info = token_to_unit_info.allocate(new_token); online_user_count++; LOG_DEBUG << "generated new token " << new_token; cur_user->unit_token = new_token; cur_user->online = true; UserOnlineInfo* user_online_info = new(allocated_user_online_info) UserOnlineInfo(cur_user.get()); user_online_info->user_end_point = remote_end_point; } else { #ifdef _DEBUG LOG_DEBUG << "user is already online"; #endif } auto answer = createPacket<Packet::LoginAnswer>(packet->packet_number); answer->success = true; answer->unit_token = cur_user->unit_token; standardSend(answer); return true; } bool ProxyServer::onLogout(size_t received_bytes) { LOG_DEBUG << "onLogout"; const auto packet = getReceiveBufferAs<Packet::Logout>(); LOG_DEBUG << "end point: " << remote_end_point; IndexType unit_token = packet->unit_token; UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token); if (!user_online_info) { LOG_ERROR << "user does not exist"; return true; } if (user_online_info->user_end_point != remote_end_point) { LOG_ERROR << "user sent incorrect token " << unit_token << " ip: " << user_online_info->user_end_point << " and it should be ip: " << remote_end_point; return true; } auto request = createPacket<Packet::LogoutInternal>(); request->unit_token = user_online_info->user_info->unit_token; request->client_packet_number = packet->packet_number; standardSendTo(request, user_online_info->node_server_end_point); return true; } bool ProxyServer::onLogoutInternalAnswer(size_t received_bytes) { LOG_DEBUG << "onLogoutInternalAnswer"; if (!validateInternalServer(remote_end_point)) { LOG_WARNING << "internal server token validation error"; return true; } const auto packet = getReceiveBufferAs<Packet::LogoutInternalAnswer>(); IndexType unit_token = packet->unit_token; UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token); if (!user_online_info) { LOG_ERROR << "user does not exist"; return true; } user_online_info->user_info->online = false; user_online_info->user_info->unit_token = 0; user_online_info->in_game = false; user_online_info->user_info = nullptr; boost::asio::ip::udp::endpoint user_end_point = user_online_info->user_end_point; token_to_unit_info.deallocate(unit_token); online_user_count--; auto answer = createPacket<Packet::LogoutAnswer>(packet->client_packet_number); answer->success = true; standardSendTo(answer, user_end_point); return true; } bool ProxyServer::onInitializePosition(size_t received_bytes) { LOG_DEBUG << "onInitializePosition"; const auto packet = getReceiveBufferAs<Packet::InitializePosition>(); IndexType unit_token = packet->unit_location.unit_token; UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token); if (!user_online_info) { LOG_ERROR << "user does not exist"; return true; } if (user_online_info->user_end_point != remote_end_point) { LOG_ERROR << "unit sent incorrect token " << unit_token << " ip: " << user_online_info->user_end_point << " and it should be ip: " << remote_end_point; return true; } if (!user_online_info->in_game) { auto request = createPacket<Packet::InitializePositionInternal>(); request->client_packet_number = packet->packet_number; request->proxy_packet_number = request->packet_number; request->unit_location = packet->unit_location; request->proxy_server_address = socket.local_endpoint().address().TO_V().to_bytes(); request->proxy_server_port_number = port_number; standardSendTo(request, balancer_server_end_point); return true; } auto answer = createPacket<Packet::InitializePositionAnswer>(packet->packet_number); answer->success = true; answer->corrected_location = packet->unit_location; standardSend(answer); return true; } bool ProxyServer::onInitializePositionInternalAnswer(size_t received_bytes) { LOG_DEBUG << "onInitializePositionInternalAnswer"; if (!validateInternalServer(remote_end_point)) { LOG_WARNING << "internal server token validation error"; return true; } const auto packet = getReceiveBufferAs<Packet::InitializePositionInternalAnswer>(); IndexType unit_token = packet->corrected_location.unit_token; UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token); if (!user_online_info) { LOG_ERROR << "user does not exist"; return true; } if (!user_online_info->user_info->online) { LOG_ERROR << "user is not online or is already in game"; return true; } if (user_online_info->in_game) { LOG_ERROR << "user is already in game"; return true; } user_online_info->in_game = true; user_online_info->node_server_end_point = boost::asio::ip::udp::endpoint(IpAddress(packet->node_server_address), packet->node_server_port_number); if (user_online_info->node_server_end_point.address().is_loopback()) { user_online_info->node_server_end_point = boost::asio::ip::udp::endpoint(remote_end_point.address().TO_V(), packet->node_server_port_number); } auto answer = createPacket<Packet::InitializePositionAnswer>(packet->client_packet_number); answer->success = packet->success; answer->corrected_location = packet->corrected_location; standardSendTo(answer, user_online_info->user_end_point); return true; } bool ProxyServer::onUnitAction(size_t received_bytes) { LOG_DEBUG << "onUnitAction"; const auto packet = getReceiveBufferAs<Packet::UnitAction>(); IndexType unit_token = packet->unit_token; UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token); if (!user_online_info) { LOG_ERROR << "user does not exist"; return true; } if (user_online_info->user_end_point != remote_end_point) { LOG_ERROR << "user sent incorrect token " << unit_token << " ip: " << user_online_info->user_end_point << " and it should be ip: " << remote_end_point; return true; } if (!user_online_info->in_game) { LOG_ERROR << "user is not in game"; return true; } auto request = createPacket<Packet::UnitActionInternal>(); request->unit_token = user_online_info->user_info->unit_token; request->keyboard_state = packet->keyboard_state; request->client_packet_number = packet->packet_number; standardSendTo(request, user_online_info->node_server_end_point); return true; } bool ProxyServer::onUnitActionInternalAnswer(size_t received_bytes) { LOG_DEBUG << "onUserActionInternalAnswer"; if (!validateInternalServer(remote_end_point)) { LOG_WARNING << "fake internal server detected"; return true; } const auto packet = getReceiveBufferAs<Packet::UnitActionInternalAnswer>(); IndexType unit_token = packet->unit_location.unit_token; UserOnlineInfo* user_online_info = token_to_unit_info.find(unit_token); if (!user_online_info) { LOG_ERROR << "user does not exist"; return true; } if (!user_online_info->in_game) { LOG_ERROR << "user is not in game"; return true; } auto answer = createPacket<Packet::UnitActionAnswer>(packet->client_packet_number); answer->unit_location = packet->unit_location; answer->other_unit_count = packet->other_unit_count; if (answer->other_unit_count >= Packet::MAX_UNIT_COUNT_IN_PACKET) { answer->other_unit_count = Packet::MAX_UNIT_COUNT_IN_PACKET; } for (std::uint16_t i = 0; i < answer->other_unit_count; ++i) { answer->other_unit[i] = packet->other_unit[i]; } standardSendTo(answer, user_online_info->user_end_point); return true; } bool ProxyServer::onRegisterProxyAnswer(size_t received_bytes) { LOG_DEBUG << "onRegisterProxyAnswer"; if (!validateInternalServer(remote_end_point)) { LOG_WARNING << "fake internal server detected"; return true; } const auto packet = getReceiveBufferAs<Packet::RegisterProxyAnswer>(); proxy_token = packet->proxy_token; setApplicationToken(proxy_token); LOG_DEBUG << "proxy_token " << proxy_token; return true; } bool ProxyServer::validateInternalServer(const boost::asio::ip::udp::endpoint& end_point) const { // TODO: return true; } void ProxyServer::loadRegisteredUsers(const std::string& file_name) { LOG_DEBUG << "loading users from " << file_name << "..."; std::ifstream registered_users(file_name); while (!registered_users.bad() && !registered_users.eof()) { UserInfo::Ptr new_user = std::make_shared<UserInfo>(); registered_users >> *new_user; if (new_user->login.empty() || new_user->password.empty() || new_user->full_name.empty()) { break; } login_to_user_info.insert_or_assign(new_user->login, new_user); } LOG_DEBUG << "users are loaded!"; } void ProxyServer::saveRegisteredUsers(const std::string& file_name) const { LOG_DEBUG << "saving users to " << file_name << "..."; std::ofstream registered_users(file_name); for (auto cur_user : login_to_user_info) { registered_users << *cur_user.second.get(); } LOG_DEBUG << "users are saved!"; }
36.283063
159
0.700793
PetrPPetrov
5886178920a02fd588e4b2042d0693d1347b319c
2,160
hpp
C++
include/GameEngine/Graphics/Shader.hpp
iRohith/GameEngine
61d8ea417e5a9d03075d9cfcdc86f0a1a40f676f
[ "Apache-2.0" ]
null
null
null
include/GameEngine/Graphics/Shader.hpp
iRohith/GameEngine
61d8ea417e5a9d03075d9cfcdc86f0a1a40f676f
[ "Apache-2.0" ]
null
null
null
include/GameEngine/Graphics/Shader.hpp
iRohith/GameEngine
61d8ea417e5a9d03075d9cfcdc86f0a1a40f676f
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../Core/Core.hpp" #include "../Util/Array.hpp" #include <string_view> // TODO: ShaderLibrary (just copy from Hazel :| ) namespace GameEngine { template<typename T> using Ref = std::shared_ptr<T>; class ShaderUnit; class GEAPI Shader { public: static Ref<Shader> Create(const char* name, const char* vertFilePath, const char* fragFilePath, bool addToLibrary = true); static Ref<Shader> CreateFromUnits(const char* name, const ArrayConstView<Ref<ShaderUnit>>& shaderUnitsArray, bool addToLibrary = true, bool releaseShaderAfterUse = true); static Ref<Shader> Get(const char* name); inline const int GetID() const { return id; } inline const char* GetName() const { return name; } virtual void Use() const = 0; virtual void Unuse() const = 0; virtual ~Shader() = default; virtual void SetInt(const char* name, int value) = 0; virtual void SetIntArray(const char* name, const Array<int>&) = 0; virtual void SetFloat(const char* name, float value) = 0; virtual void SetFloat2(const char* name, const M::VecF<2>& value) = 0; virtual void SetFloat3(const char* name, const M::VecF<3>& value) = 0; virtual void SetFloat4(const char* name, const M::VecF<4>& value) = 0; virtual void SetMat4(const char* name, const M::MatrixF<4,4>& value) = 0; protected: Shader() = default; int id; const char* name; }; class GEAPI ShaderUnit { public: enum ShaderType { NONE, VERTEX, FRAGMENT/* TODO: , GEOMETRY, COMPUTE, TESSELLATION*/ }; static Ref<ShaderUnit> Create(const char* path, ShaderType t = ShaderType::NONE); static Ref<ShaderUnit> CreateFromCode(const std::string_view& str, ShaderType t = ShaderType::NONE); virtual void Attach(const Shader&) const = 0; virtual void Release() = 0; virtual ShaderType GetShaderType() const = 0; inline const int& GetID() const { return id; } virtual ~ShaderUnit() = default; protected: ShaderUnit() = default; int id; }; using ShaderType = ShaderUnit::ShaderType; }
37.894737
179
0.651852
iRohith
588758cc138652138d995edae399772c76791108
9,195
cpp
C++
piquassoboost/sampling/source/kernels/calc_vH_times_A_AVX.cpp
Budapest-Quantum-Computing-Group/piquassoboost
fd384be8f59cfd20d62654cf86c89f69d3cf8b8c
[ "Apache-2.0" ]
4
2021-11-29T13:28:19.000Z
2021-12-21T22:57:09.000Z
piquassoboost/sampling/source/kernels/calc_vH_times_A_AVX.cpp
Budapest-Quantum-Computing-Group/piquassoboost
fd384be8f59cfd20d62654cf86c89f69d3cf8b8c
[ "Apache-2.0" ]
11
2021-09-24T18:02:26.000Z
2022-01-27T18:51:47.000Z
piquassoboost/sampling/source/kernels/calc_vH_times_A_AVX.cpp
Budapest-Quantum-Computing-Group/piquassoboost
fd384be8f59cfd20d62654cf86c89f69d3cf8b8c
[ "Apache-2.0" ]
1
2021-11-13T10:06:52.000Z
2021-11-13T10:06:52.000Z
/** * Copyright 2021 Budapest Quantum Computing Group * * 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 "calc_vH_times_A_AVX.h" namespace pic { /** @brief AVX kernel to apply householder transformation on a matrix A' = (1 - 2*v o v) A for one specific reflection vector v. @param A matrix on which the householder transformation is applied. @param v A matrix instance of the reflection vector @param vH_times_A preallocated array to hold the data of vH_times_A. The result is returned via this reference. */ void calc_vH_times_A_AVX(matrix &A, matrix &v, matrix &vH_times_A) { // calculate the vector-matrix product (v^+) * A size_t sizeH = v.size(); // pointers to two successive rows of matrix A double* data = (double*)A.get_data(); double* data2 = data + 2*A.stride; // factor 2 is needed becouse of one complex16 consists of two doubles double* v_data = (double*)v.get_data(); double* vH_times_A_data = (double*)vH_times_A.get_data(); __m256d neg = _mm256_setr_pd(-1.0, 1.0, -1.0, 1.0); for (size_t row_idx = 0; row_idx < sizeH-1; row_idx=row_idx+2) { // extract two successive components v_i,v_{i+1} of vector v __m256d v_vec = _mm256_loadu_pd(v_data+2*row_idx); // create vector v_{i+1}, v_{i+1} __m128d* v_element = (__m128d*)&v_vec[2]; __m256d v_vec2 = _mm256_broadcast_pd( v_element ); // create vector v_i, v_i v_element = (__m128d*)&v_vec[0]; __m256d v_vec1 = _mm256_broadcast_pd( v_element ); for (size_t kdx = 0; kdx < 2*(A.cols-1); kdx = kdx + 4) { __m256d A_vec = _mm256_loadu_pd(data+kdx); __m256d A_vec2 = _mm256_loadu_pd(data2+kdx); // calculate the multiplications A_vec*conj(v_vec1) // 1 Multiply elements of A_vec and v_vec1 __m256d vec3 = _mm256_mul_pd(A_vec, v_vec1); // 2 Switch the real and imaginary elements of v_vec1 __m256d v_vec_permuted = _mm256_permute_pd(v_vec1, 0x5); // 3 Negate the imaginary elements of cx_vec v_vec_permuted = _mm256_mul_pd(v_vec_permuted, neg); // 4 Multiply elements of A_vec and the modified v_vec __m256d vec4 = _mm256_mul_pd(A_vec, v_vec_permuted); // 5 Horizontally subtract the elements in vec3 and vec4 A_vec = _mm256_hadd_pd(vec3, vec4); // calculate the multiplications A_vec2*conj(c_vec2) // 1 Multiply elements of AZ_vec and cx_vec vec3 = _mm256_mul_pd(A_vec2, v_vec2); // 2 Switch the real and imaginary elements of v_vec1 v_vec_permuted = _mm256_permute_pd(v_vec2, 0x5); // 3 Negate the imaginary elements of cx_vec v_vec_permuted = _mm256_mul_pd(v_vec_permuted, neg); // 4 Multiply elements of A_vec and the modified v_vec vec4 = _mm256_mul_pd(A_vec2, v_vec_permuted); // 5 Horizontally subtract the elements in vec3 and vec4 A_vec2 = _mm256_hadd_pd(vec3, vec4); // add A_vec and A_vec2 A_vec = _mm256_add_pd(A_vec, A_vec2); // add the result to _tmp __m256d _tmp = _mm256_loadu_pd(vH_times_A_data+kdx); _tmp = _mm256_add_pd(_tmp, A_vec); _mm256_storeu_pd(vH_times_A_data+kdx, _tmp); } if (A.cols % 2 == 1) { size_t kdx = 2*(A.cols-1); __m256d A_vec; A_vec = _mm256_insertf128_pd(A_vec, _mm_load_pd(data+kdx), 0); A_vec = _mm256_insertf128_pd(A_vec, _mm_load_pd(data2+kdx), 1); // calculate the multiplications A_vec*conj(v_vec) // 1 Multiply elements of A_vec and v_vec __m256d vec3 = _mm256_mul_pd(A_vec, v_vec); // 2 Switch the real and imaginary elements of v_vec1 __m256d v_vec_permuted = _mm256_permute_pd(v_vec, 0x5); // 3 Negate the imaginary elements of cx_vec v_vec_permuted = _mm256_mul_pd(v_vec_permuted, neg); // 4 Multiply elements of A_vec and the modified v_vec __m256d vec4 = _mm256_mul_pd(A_vec, v_vec_permuted); // 5 Horizontally subtract the elements in vec3 and vec4 A_vec = _mm256_hadd_pd(vec3, vec4); // sum elements of A_vec __m128d _tmp2 = _mm_add_pd(_mm256_castpd256_pd128(A_vec), _mm256_extractf128_pd(A_vec, 1)); // add the result to vH_times_A __m128d _tmp = _mm_loadu_pd(vH_times_A_data+kdx); _tmp = _mm_add_pd(_tmp, _tmp2); _mm_storeu_pd(vH_times_A_data+kdx, _tmp); } // move data pointers to the next row pair data = data + 4*A.stride; data2 = data2 + 4*A.stride; } if (sizeH % 2 == 1) { size_t row_idx = sizeH-1; // extract the last component of vector v __m128d v_vec = _mm_loadu_pd(v_data+2*row_idx); // create vector v_i, v_i __m128d* v_element = (__m128d*)&v_vec[0]; __m256d v_vec1 = _mm256_broadcast_pd( v_element ); for (size_t kdx = 0; kdx < 2*(A.cols-1); kdx = kdx + 4) { __m256d A_vec = _mm256_loadu_pd(data+kdx); // calculate the multiplications A_vec*conj(v_vec1) // 1 Multiply elements of A_vec and v_vec1 __m256d vec3 = _mm256_mul_pd(A_vec, v_vec1); // 2 Switch the real and imaginary elements of v_vec1 __m256d v_vec_permuted = _mm256_permute_pd(v_vec1, 0x5); // 3 Negate the imaginary elements of cx_vec v_vec_permuted = _mm256_mul_pd(v_vec_permuted, neg); // 4 Multiply elements of A_vec and the modified v_vec __m256d vec4 = _mm256_mul_pd(A_vec, v_vec_permuted); // 5 Horizontally subtract the elements in vec3 and vec4 A_vec = _mm256_hadd_pd(vec3, vec4); // add the result to _tmp __m256d _tmp = _mm256_loadu_pd(vH_times_A_data+kdx); _tmp = _mm256_add_pd(_tmp, A_vec); _mm256_storeu_pd(vH_times_A_data+kdx, _tmp); } if (A.cols % 2 == 1) { size_t kdx = 2*(A.cols-1); __m128d neg = _mm_setr_pd(-1.0, 1.0); __m128d A_vec = _mm_loadu_pd(data+kdx); // 1 Multiply elements of A_vec and v_vec1 __m128d vec3 = _mm_mul_pd(A_vec, v_vec); // 2 Switch the real and imaginary elements of v_vec1 __m128d v_vec_permuted = _mm_permute_pd(v_vec, 0x5); // 3 Negate the imaginary elements of cx_vec v_vec_permuted = _mm_mul_pd(v_vec_permuted, neg); // 4 Multiply elements of A_vec and the modified v_vec __m128d vec4 = _mm_mul_pd(A_vec, v_vec_permuted); // 5 Horizontally subtract the elements in vec3 and vec4 A_vec = _mm_hadd_pd(vec3, vec4); __m128d _tmp = _mm_loadu_pd(vH_times_A_data+kdx); _tmp = _mm_add_pd(_tmp, A_vec); _mm_storeu_pd(vH_times_A_data+kdx, _tmp); } } /* // The above code with non-AVX instructions // calculate the vector-matrix product (v^+) * A for (size_t row_idx = 0; row_idx < sizeH-1; row_idx=row_idx+2) { size_t offset_A_data = row_idx * A.stride; Complex16* data_A = A.get_data() + offset_A_data; Complex16* data_A2 = data_A + A.stride; for (size_t j = 0; j < A.cols-1; j = j + 2) { vH_times_A[j] = vH_times_A[j] + mult_a_bconj(data_A[j], v[row_idx]); vH_times_A[j+1] = vH_times_A[j+1] + mult_a_bconj(data_A[j+1], v[row_idx]); vH_times_A[j] = vH_times_A[j] + mult_a_bconj(data_A2[j], v[row_idx+1]); vH_times_A[j+1] = vH_times_A[j+1] + mult_a_bconj(data_A2[j+1], v[row_idx+1]); } if (A.cols % 2 == 1) { size_t j = A.cols-1; vH_times_A[j] = vH_times_A[j] + mult_a_bconj(data_A[j], v[row_idx]); vH_times_A[j] = vH_times_A[j] + mult_a_bconj(data_A2[j], v[row_idx+1]); } } if (sizeH % 2 == 1) { size_t row_idx = sizeH-1; size_t offset_A_data = row_idx * A.stride; Complex16* data_A = A.get_data() + offset_A_data; for (size_t j = 0; j < A.cols-1; j = j + 2) { vH_times_A[j] = vH_times_A[j] + mult_a_bconj(data_A[j], v[row_idx]); vH_times_A[j+1] = vH_times_A[j+1] + mult_a_bconj(data_A[j+1], v[row_idx]); } if (A.cols % 2 == 1) { size_t j = A.cols-1; vH_times_A[j] = vH_times_A[j] + mult_a_bconj(data_A[j], v[row_idx]); } } */ return; } } // PIC
32.15035
124
0.613051
Budapest-Quantum-Computing-Group
588a1b7f7b93a3adbf6d81cc599f3e6653c7a145
16,847
cpp
C++
Source/Game.cpp
AdriaSeSa/Minigame
ca2a0f2d47bba25341962b5229eb304159e91749
[ "MIT" ]
2
2021-03-16T00:49:11.000Z
2021-04-03T20:39:39.000Z
Source/Game.cpp
AdriaSeSa/Minigame
ca2a0f2d47bba25341962b5229eb304159e91749
[ "MIT" ]
null
null
null
Source/Game.cpp
AdriaSeSa/Minigame
ca2a0f2d47bba25341962b5229eb304159e91749
[ "MIT" ]
null
null
null
#include "Game.h" //Game::Game() {} //Game::~Game() {} Menu menu; bool Game::Init(Display Disp) { srand((unsigned)time(NULL)); canvas = Disp; bool result = canvas.createDisplay(SCREEN_WIDTH, SCREEN_HEIGHT); menu.initSurfaces(canvas.getRenderer()); player = new Player(400, 300, 32, 32, 2, canvas.getRenderer()); // Init enemyBornPoint for (int i = 0, k = 0; i < 2; i++) { int offsetY = OFFSET_SCREEN_HEIGHT; int offsetX = OFFSET_SCREEN_WIDTH; for (int j = 0; j < 3; j++, k += 2) { if (i == 0) { enemyPoints[k].x = (j * 32) + 224 + offsetX; enemyPoints[k].y = (i * 32) + offsetY; cout << "x: " << enemyPoints[k].x << "\ty: " << enemyPoints[k].y << endl; enemyPoints[k + 1].x = (i * 32) + offsetX; enemyPoints[k + 1].y = (j * 32) + offsetY + 228; cout << "x: " << enemyPoints[k+1].x << "\ty: " << enemyPoints[k+1].y << endl; } else { enemyPoints[k].x = (j * 32) + 224 + offsetX; enemyPoints[k].y = (i * 32) + offsetY + 480; enemyPoints[k + 1].x = (i * 32) + offsetX + 480; enemyPoints[k + 1].y = (j * 32) + offsetY + 228; } } } // Posicion de arboles, 1 significa que existe un arbol int treePos[17][17] { {1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1}, }; // Init arboles for (int i = 0, k = 0; i < 17; i++) { for (int j = 0; j < 17; j++) { if (treePos[i][j] == 1) { ent[k] = new Box(j * 32 + OFFSET_SCREEN_WIDTH, i * 32 + OFFSET_SCREEN_HEIGHT, 32, 32, 0, canvas.getRenderer()); k++; //cout << i*32 << endl; } } } //ent[12] = new Box(512, 0, 32, 32, 0, canvas.getRenderer()); //cout << ent[12]->getH() << endl; // Test zombie /* ent[96] = new Enemy(0, 200, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds()); ent[97] = new Enemy(0, 232, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds()); ent[98] = new Enemy(700, 250, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds()); ent[99] = new Enemy(700, 290, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds()); */ CreateEnemy(); currentScreen = MENU; //dp.draw(canvas.draw()); //Initialize keys array for (int i = 0; i < MAX_KEYBOARD_KEYS; ++i) keys[i] = KEY_IDLE; // Initialize Sprites IMG_Init; // Init map sprite BackTex = SDL_CreateTextureFromSurface(canvas.getRenderer(), IMG_Load("Assets/myAssets/Sprites/Map.png")); // Init Time TestTime = SDL_GetPerformanceCounter(); // Init Music Mix_Init(MIX_INIT_MP3); if (Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 1024) == -1) { printf("Mix_OpenAudio: %s\n", Mix_GetError()); } music = Mix_LoadMUS("Assets/myAssets/Sounds/BGM.mp3"); fx_shoot = Mix_LoadWAV("Assets/myAssets/Sounds/shoot.mp3"); fx_lose = Mix_LoadWAV("Assets/myAssets/Sounds/lose.mp3"); fx_win = Mix_LoadWAV("Assets/myAssets/Sounds/win.wav"); string temp; for (int i = 0; i < 5; i++) { temp = "Assets/myAssets/Sounds/zombiegrunt"+ to_string(i) +".mp3"; fx_death[i] = Mix_LoadWAV(temp.c_str()); } // -1 para que la musica suene para siempre Mix_PlayMusic(music, -1); Mix_Volume(-1, 25); Mix_VolumeMusic(20); return result; } bool Game::Tick() { //cerr << "Ticks -> " << SDL_GetTicks() << " \n"; // Tiempo que ha pasado durante ejecuto double currentTime = SDL_GetPerformanceCounter(); //cout << (currentTime -TestTime) / SDL_GetPerformanceFrequency() << endl; switch (currentScreen) { case Game::MENU: if (keys[SDL_SCANCODE_RETURN] == KEY_DOWN) currentScreen = GAMEPLAY; break; case Game::GAMEPLAY: //if (keys[SDL_SCANCODE_L] == KEY_DOWN) { Mix_PlayChannel(-1, fx_lose, 0); currentScreen = GAME_OVER; } //Esto cambiará cuando se pueda perder //--------------Debug------------ if (keys[SDL_SCANCODE_F10] == KEY_DOWN) { debug = !debug; } //----------Entities------------- endTime = SDL_GetPerformanceCounter(); timeOffset = SDL_GetPerformanceFrequency(); // Cada 1.5s ejecuta una vez para recalcular la posicion del jugador if (((endTime - enemySpawunTime) / timeOffset) >= spawnTime) { cout << "Spawn Time ->"<< spawnTime <<endl; enemySpawunTime = SDL_GetPerformanceCounter(); CreateEnemy(); if (tenScores == 4 && spawnTime >= spawnTimeLimit) { //spawnTime *= (1 - (((float)score / 100))); spawnTime -= 0.10; tenScores = 0; } tenScores++; } //----------Shoot---------------- for (int i = 0; i < 20; i++) { // Modificar posicion de bala if (shot[i].alive == false) continue; if (shot[i].direction == LEFT) //shoot left { shot[i].rec.x -= shot[i].speed; } else if (shot[i].direction == RIGHT) { //shoot right shot[i].rec.x += shot[i].speed; } else if (shot[i].direction == UP) { //shoot up shot[i].rec.y += shot[i].speed; } else if (shot[i].direction == DOWN) { //shoot down shot[i].rec.y -= shot[i].speed; } } //----------Player--------------- //bool bx, by, ex, ey; player->setBX(true); player->setBY(true); player->setYmove(0); player->setXmove(0); // Limitar rango de movimiento if (keys[SDL_SCANCODE_UP] == KEY_REPEAT && player->getY() > OFFSET_SCREEN_HEIGHT) { player->setYmove(-1); }; if (keys[SDL_SCANCODE_DOWN] == KEY_REPEAT && player->getY() < SCREEN_HEIGHT - OFFSET_SCREEN_HEIGHT - 32) { player->setYmove(1); } if (keys[SDL_SCANCODE_LEFT] == KEY_REPEAT && player->getX() > OFFSET_SCREEN_WIDTH) { player->setXmove(-1); } if (keys[SDL_SCANCODE_RIGHT] == KEY_REPEAT && player->getX() < SCREEN_WIDTH - OFFSET_SCREEN_WIDTH - 32) { player->setXmove(1); } for (int i = 0; i < MAX_ENTITIES; i++) { if (ent[i] == NULL) break; if (player->checkCollisions(ent[i]->getX(), ent[i]->getY(), false)) { player->setBX(false); } if (player->checkCollisions(ent[i]->getX(), ent[i]->getY(), true)) { player->setBY(false); } if (player->checkCollisions(ent[i]->getX(), ent[i]->getY(), false) && player->checkCollisions(ent[i]->getX(), ent[i]->getY(), true)) {//Player death //cout << fx_lose; Mix_PlayChannel(-1, fx_lose, 0); currentScreen = GAME_OVER; spawnTime = 1.3f; for (int j = 0; j < MAX_ENTITIES; j++) {//Entities if (ent[j] != NULL && ent[j]->getID() == 1) { ent[j]->setAlive(false); } } for (int j = 0; j < 20; j++) {//Bullet shot[j].alive = false; shot[j].rec.x = 840; shot[j].rec.y = 600; } } for (int j = 0; j < 20; j++) { if (SDL_HasIntersection(&shot[j].rec, ent[i]->getCollsionBounds())) { shot[j].alive = false; shot[j].rec.x = 554; shot[j].rec.y = 554; ent[i]->setAlive(false); if (ent[i]->getID() == 1) { score++; //cout << fx_death[rand() % 5]; Mix_PlayChannel(-1, fx_death[rand() % 5], 0); } } } //Entities collision ent[i]->setBX(true); ent[i]->setBY(true); for (int j = 0; j < MAX_ENTITIES; j++) { if (ent[j] == NULL) break; if (ent[j] == ent[i]) { continue; } //if (ent[i]->getID() == 2) { if (ent[i]->checkCollisions(ent[j]->getX(), ent[j]->getY(), false)) { ent[i]->setBX(false); } if (ent[i]->checkCollisions(ent[j]->getX(), ent[j]->getY(), true)) { ent[i]->setBY(false); } //} } } if(player->getBX()) player->moveX(); if(player->getBY()) player->moveY(); //Player Update player->tick(); //Entities update for (int i = 0; i < MAX_ENTITIES; i++) { if (ent[i] == NULL) break; ent[i]->tick(); } break; case Game::GAME_OVER: Mix_PauseMusic(); if (keys[SDL_SCANCODE_R] == KEY_DOWN) { Mix_PlayMusic(music, -1); currentScreen = GAMEPLAY; player->setX(SCREEN_WIDTH / 2); player->setY(SCREEN_HEIGHT / 2); score = 0; } else if (keys[SDL_SCANCODE_E] == KEY_DOWN) { Mix_PlayMusic(music, -1); currentScreen = MENU; score = 0; } break; } if (!Input()) return true; return false; } void Game::Draw() { SDL_RenderClear(canvas.getRenderer()); switch (currentScreen) { case MENU: SDL_SetRenderDrawColor(canvas.getRenderer(), 0, 0, 0, 0); SDL_RenderClear(canvas.getRenderer()); menu.menuHUD(canvas.getRenderer()); //MENU TEXT //////////////////////////////////////////////////////////////////////////////////////// menu.showText(canvas.getRenderer(), 230, 272, "Start Game with <Enter>", canvas.getFonts(50), canvas.getColors(0)); menu.showText(canvas.getRenderer(), 250, 340, "Exit Game with <Esc>", canvas.getFonts(50), canvas.getColors(0)); menu.showText(canvas.getRenderer(), 215, 400, "Zhida", canvas.getFonts(50), canvas.getColors(1)); menu.showText(canvas.getRenderer(), 215, 440, "Chen", canvas.getFonts(50), canvas.getColors(1)); menu.showText(canvas.getRenderer(), 310, 400, "Robert", canvas.getFonts(50), canvas.getColors(0)); menu.showText(canvas.getRenderer(), 310, 440, "Recorda", canvas.getFonts(50), canvas.getColors(0)); menu.showText(canvas.getRenderer(), 430, 400, "Pol", canvas.getFonts(50), canvas.getColors(1)); menu.showText(canvas.getRenderer(), 430, 440, "Rius", canvas.getFonts(50), canvas.getColors(1)); menu.showText(canvas.getRenderer(), 500, 400, "Adria", canvas.getFonts(50), canvas.getColors(0)); menu.showText(canvas.getRenderer(), 500, 440, "Sellares", canvas.getFonts(50), canvas.getColors(0)); menu.showText(canvas.getRenderer(), 585, 580, "v1.0 87b3badc6c411651e56bfd19c770d53e", canvas.getFonts(20), canvas.getColors(2)); //-------------------------------------------------------------------------------------------------------------------// break; case GAMEPLAY: //Rectangle Draw Test SDL_SetRenderDrawColor(canvas.getRenderer(), 0, 0, 0, 0); SDL_RenderClear(canvas.getRenderer()); SDL_Rect mapRect; mapRect.x = 148; mapRect.y = 28; mapRect.w = 544; mapRect.h = 544; //MAP SDL_RenderCopy(canvas.getRenderer(), BackTex, NULL, &mapRect); //--------Entities------- player->draw(canvas.getRenderer()); for (int i = 0; i < MAX_ENTITIES; i++) { if (ent[i] == NULL) break; ent[i]->draw(canvas.getRenderer()); } //ent[68]->draw(canvas.getRenderer()); //cout <<"x: "<< ent[68]->getCollsionBounds()->x << "\t y: "<<ent[68]->getCollsionBounds()->y << endl; //------------- for (int i = 0; i < 20; i++) //-------------SHOT---------- for (int i = 0; i < 20; i++) { if (shot[i].alive && shot[i].rec.x > OFFSET_SCREEN_WIDTH && shot[i].alive && shot[i].rec.x < SCREEN_WIDTH - OFFSET_SCREEN_WIDTH && shot[i].rec.y < SCREEN_HEIGHT - OFFSET_SCREEN_HEIGHT && shot[i].rec.y > OFFSET_SCREEN_HEIGHT) { SDL_RenderCopy(canvas.getRenderer(), shot[i].tex, NULL, &shot[i].rec); } } //----------HUD-------------- menu.gameplayHUD(canvas.getRenderer()); scoreS = to_string(score); //Converts Score to String menu.showText(canvas.getRenderer(), 75, 40, scoreS.c_str(), canvas.getFonts(35), canvas.getColors(2)); // ---------DEBUG------------- if (debug == true) { if (keys[SDL_SCANCODE_UP] == KEY_REPEAT) { menu.showText(canvas.getRenderer(), 0, -4, "UP!", canvas.getFonts(20), canvas.getColors(1)); } if (keys[SDL_SCANCODE_DOWN] == KEY_REPEAT) { menu.showText(canvas.getRenderer(), 0, -4, "DOWN!", canvas.getFonts(20), canvas.getColors(1)); } if (keys[SDL_SCANCODE_LEFT] == KEY_REPEAT) { menu.showText(canvas.getRenderer(), 0, -4, "LEFT!", canvas.getFonts(20), canvas.getColors(1)); } if (keys[SDL_SCANCODE_RIGHT] == KEY_REPEAT) { menu.showText(canvas.getRenderer(), 0, -4, "RIGHT!", canvas.getFonts(20), canvas.getColors(1)); } menu.showText(canvas.getRenderer(), 785, -4, "60 FPS", canvas.getFonts(20), canvas.getColors(1)); //DEBUG FPS // Posicion de spawn zombie SDL_SetRenderDrawColor(canvas.getRenderer(), 255, 255, 255, -255); SDL_Rect r; r.w = 32; r.h = 32; for (int i = 0; i < 12; i++) { r.x = enemyPoints[i].x; r.y = enemyPoints[i].y; SDL_RenderDrawRect(canvas.getRenderer(), &r); } } //----------------------------- break; case GAME_OVER: SDL_SetRenderDrawColor(canvas.getRenderer(), 0, 0, 0, 255); SDL_RenderClear(canvas.getRenderer()); scoreS = to_string(score); //Converts Score to String menu.showText(canvas.getRenderer(), 320, 100, scoreS.c_str(), canvas.getFonts(80), canvas.getColors(1)); menu.gameOverHUD(canvas.getRenderer(), canvas.getColors(2), canvas.getColors(1), canvas.getFonts(80), canvas.getFonts(50)); break; } SDL_RenderPresent(canvas.getRenderer()); SDL_Delay(10); } bool Game::Input() { SDL_Event event; for (int i = 0; i < MAX_MOUSE_BUTTONS; ++i) { if (mouse_buttons[i] == KEY_DOWN) mouse_buttons[i] = KEY_REPEAT; if (mouse_buttons[i] == KEY_UP) mouse_buttons[i] = KEY_IDLE; } while (SDL_PollEvent(&event) != 0) { switch (event.type) { case SDL_QUIT: window_events[WE_QUIT] = true; break; case SDL_WINDOWEVENT: { switch (event.window.event) { //case SDL_WINDOWEVENT_LEAVE: case SDL_WINDOWEVENT_HIDDEN: case SDL_WINDOWEVENT_MINIMIZED: case SDL_WINDOWEVENT_FOCUS_LOST: window_events[WE_HIDE] = true; break; //case SDL_WINDOWEVENT_ENTER: case SDL_WINDOWEVENT_SHOWN: case SDL_WINDOWEVENT_FOCUS_GAINED: case SDL_WINDOWEVENT_MAXIMIZED: case SDL_WINDOWEVENT_RESTORED: window_events[WE_SHOW] = true; break; case SDL_WINDOWEVENT_CLOSE: window_events[WE_QUIT] = true; break; default: break; } } break; //Comprobar estado del boton case SDL_MOUSEBUTTONDOWN: mouse_buttons[event.button.button - 1] = KEY_DOWN; break; case SDL_MOUSEBUTTONUP: mouse_buttons[event.button.button - 1] = KEY_UP; break; case SDL_MOUSEMOTION: { mouse_x = event.motion.x; mouse_y = event.motion.y; } break; default: break; } } const Uint8* Keys = SDL_GetKeyboardState(NULL); // Consider previous keys states for KEY_DOWN and KEY_UP for (int i = 0; i < MAX_KEYBOARD_KEYS; ++i) { // Valor 1 = tecla esta pulsada , valor 0 no lo esta. if (Keys[i] == 1) { if (keys[i] == KEY_IDLE) keys[i] = KEY_DOWN; else keys[i] = KEY_REPEAT; } else { if (keys[i] == KEY_REPEAT || keys[i] == KEY_DOWN) keys[i] = KEY_UP; else keys[i] = KEY_IDLE; } } // Init Shoot if (keys[SDL_SCANCODE_SPACE] == KEY_DOWN && currentScreen == GAMEPLAY) { int x, y, w, h; // Inicializar textura de shot if (shot[shotCount].tex == NULL) { shot[shotCount].tex = SDL_CreateTextureFromSurface(canvas.getRenderer(), IMG_Load("Assets/myAssets/Sprites/shoot.png")); shot[shotCount].rec.w = 8; shot[shotCount].rec.h = 8; cout << shotCount << endl; } // Inicializar restos de valor //shot[shotCount].rec.x = player->getX() + player->getW(); //shot[shotCount].rec.y = player->getY() + (player->getH()/2); if (player->getXmove() == -1 || player->getLastMove() == LEFT) { //shoot left shot[shotCount].rec.x = player->getX(); shot[shotCount].rec.y = player->getY() + (player->getH() / 2); shot[shotCount].direction = LEFT; } else if (player->getXmove() == 1 || player->getLastMove() == RIGHT) { //shoot right shot[shotCount].rec.x = player->getX() + player->getW(); shot[shotCount].rec.y = player->getY() + (player->getH() / 2); shot[shotCount].direction = RIGHT; } else if (player->getYmove() == 1 || player->getLastMove() == UP) { //shoot up shot[shotCount].rec.x = player->getX() + (player->getW() / 2); shot[shotCount].rec.y = player->getY() + player->getH(); shot[shotCount].direction = UP; } else if (player->getYmove() == -1 || player->getLastMove() == DOWN) { //shoot down shot[shotCount].rec.x = player->getX() + (player->getW() / 2); shot[shotCount].rec.y = player->getY(); shot[shotCount].direction = DOWN; } shot[shotCount].alive = true; // Repetir el bucle if (++shotCount >= 20) { shotCount = 0; } Mix_PlayChannel(-1, fx_shoot, 0); } // Salir del juego if (keys[SDL_SCANCODE_ESCAPE] == KEY_DOWN) { menu.freeMemory(); return false; } // Check QUIT window event to finish the game if (window_events[WE_QUIT] == true) { menu.freeMemory(); return false; } return true; } void Game::CreateEnemy() { int temp = rand() % 12; ent[zombieCount++] = new Enemy(enemyPoints[temp].x, enemyPoints[temp].y, 32, 32, 0.8f, canvas.getRenderer(), player->getCollsionBounds()); if (zombieCount == MAX_ENTITIES) { zombieCount = 96; } }
29.976868
144
0.606161
AdriaSeSa
588b75d6fbefa599c96a6c57f1a394102edcadca
1,357
hpp
C++
src/GDT/CollisionDetection.hpp
Stephen-Seo/GameDevTools
2895577ba28822225bd33c077131585aec2e44e3
[ "MIT" ]
null
null
null
src/GDT/CollisionDetection.hpp
Stephen-Seo/GameDevTools
2895577ba28822225bd33c077131585aec2e44e3
[ "MIT" ]
null
null
null
src/GDT/CollisionDetection.hpp
Stephen-Seo/GameDevTools
2895577ba28822225bd33c077131585aec2e44e3
[ "MIT" ]
null
null
null
#ifndef GDT_COLLISION_DETECTION_HPP #define GDT_COLLISION_DETECTION_HPP namespace GDT { /// Returns true if the point (x,y) is within a convex polygon. /** The shape of the polygon defined by arrayOfPairs must be convex and each point must be in clockwise or counterclockwise order. Otherwise, behavior is undefined. arrayOfPairs must be an array of at least size 3 of an array size 2. size must be the number of size-2-arrays within arrayOfPairs. Thus if arrayOfPairs is defined as float arrayOfPairs[4][2], then size must be 4. */ bool isWithinPolygon(float (*arrayOfPairs)[2], unsigned int size, float x, float y); /// Returns true if the point (x,y) is within a convex polygon. /** The shape of the polygon defined by arrayOfPairs must be convex and each point must be in clockwise or counterclockwise order. Otherwise, behavior is undefined. arrayOfPairs must be an array of at least size 6 and even. arraySize must be the size of arrayOfPairs. Thus if arrayOfPairs is defined as float arrayOfPairs[8], then arraySize must be 8. If the size of arrayOfPairs is not even, then behavior is undefined. */ bool isWithinPolygon(float* arrayOfPairs, unsigned int arraySize, float x, float y); } #endif
38.771429
88
0.693441
Stephen-Seo
588c08e180c75555b2c610aaaed82a5d3ec6385d
1,530
cpp
C++
lab8/hanoi.cpp
brandonlee503/EECS-161-Labs
f92aee55dfb2e6a8577593d9c5d1cf4d086a06ef
[ "MIT" ]
null
null
null
lab8/hanoi.cpp
brandonlee503/EECS-161-Labs
f92aee55dfb2e6a8577593d9c5d1cf4d086a06ef
[ "MIT" ]
null
null
null
lab8/hanoi.cpp
brandonlee503/EECS-161-Labs
f92aee55dfb2e6a8577593d9c5d1cf4d086a06ef
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #define DISKS 4 //Number of disks to maipulate - Default 2 #define COLS 3 //There are 3 pegs with Tower of Hanoi - Default 3 //Function declarations void print_array(int b[][COLS]); void towers(int diskSize, int b[][COLS], int source, int dest, int spare); int main() { //Init our 2D Towers array int b[DISKS][COLS] = {0}; for(int i = 0; i < DISKS; i++) { b[i][0] = i + 1; } //Print the board and go! print_array(b); towers(DISKS, b, 0, 1, 2); } //Outputs the array passed via parameter void print_array(int b[][COLS]) { for(int row = 0; row < DISKS; row++) { for(int col = 0; col < COLS; col++) { cout << b[row][col] << " "; } cout << endl; } cout << "--------" << endl; } //Hanoi Magic w/ Recursion void towers(int diskSize, int b[][COLS], int source, int dest, int spare) { if(diskSize != 0) { //Move all disks smaller than this one over to the spare towers(diskSize - 1, b, source, spare, dest); //Move the remaining disk to the destination peg //cout << "Move disk " << diskSize << " from peg " << source << " to peg " << dest << endl; b[diskSize - 1][dest] = b[diskSize - 1][source]; b[diskSize - 1][source] = 0; //Output results of this step print_array(b); //Move the disks we just moved to the spare back over to the dest peg towers(diskSize - 1, b, spare, dest, source); } }
25.081967
94
0.562092
brandonlee503
588cb1fa86a46bad6b75172beb3c20ce1bfcdcda
42,314
cpp
C++
streams/block/ciphers/cast/cast.cpp
ph4r05/CryptoStreams
0c197842f01994bf22f56121d886a1beebd23e89
[ "MIT" ]
8
2018-03-27T17:02:21.000Z
2021-09-09T07:26:00.000Z
streams/block/ciphers/cast/cast.cpp
DalavanCloud/CryptoStreams
7ed6eb5898d75389eee7f5afb7595a304f17514c
[ "MIT" ]
47
2018-03-27T17:57:07.000Z
2020-03-06T08:35:52.000Z
streams/block/ciphers/cast/cast.cpp
DalavanCloud/CryptoStreams
7ed6eb5898d75389eee7f5afb7595a304f17514c
[ "MIT" ]
3
2019-02-09T23:44:07.000Z
2019-09-24T11:06:02.000Z
// // Created by Dusan Klinec on 26/03/2018. // #include "cast.h" namespace block { namespace cast { // https://github.com/openssl/openssl/blob/master/crypto/cast/cast_lcl.h /* * Copyright 1995-2017 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #ifdef OPENSSL_SYS_WIN32 # include <stdlib.h> #endif #undef cast_c2l #define cast_c2l(c,l) (l =((unsigned long)(*((c)++))) , \ l|=((unsigned long)(*((c)++)))<< 8L, \ l|=((unsigned long)(*((c)++)))<<16L, \ l|=((unsigned long)(*((c)++)))<<24L) /* NOTE - c is not incremented as per cast_c2l */ #undef cast_c2ln #define cast_c2ln(c,l1,l2,n) { \ c+=n; \ l1=l2=0; \ switch (n) { \ case 8: l2 =((unsigned long)(*(--(c))))<<24L; \ case 7: l2|=((unsigned long)(*(--(c))))<<16L; \ case 6: l2|=((unsigned long)(*(--(c))))<< 8L; \ case 5: l2|=((unsigned long)(*(--(c)))); \ case 4: l1 =((unsigned long)(*(--(c))))<<24L; \ case 3: l1|=((unsigned long)(*(--(c))))<<16L; \ case 2: l1|=((unsigned long)(*(--(c))))<< 8L; \ case 1: l1|=((unsigned long)(*(--(c)))); \ } \ } #undef cast_l2c #define cast_l2c(l,c) (*((c)++)=(unsigned char)(((l) )&0xff), \ *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ *((c)++)=(unsigned char)(((l)>>24L)&0xff)) /* NOTE - c is not incremented as per cast_l2c */ #undef cast_l2cn #define cast_l2cn(l1,l2,c,n) { \ c+=n; \ switch (n) { \ case 8: *(--(c))=(unsigned char)(((l2)>>24L)&0xff); \ case 7: *(--(c))=(unsigned char)(((l2)>>16L)&0xff); \ case 6: *(--(c))=(unsigned char)(((l2)>> 8L)&0xff); \ case 5: *(--(c))=(unsigned char)(((l2) )&0xff); \ case 4: *(--(c))=(unsigned char)(((l1)>>24L)&0xff); \ case 3: *(--(c))=(unsigned char)(((l1)>>16L)&0xff); \ case 2: *(--(c))=(unsigned char)(((l1)>> 8L)&0xff); \ case 1: *(--(c))=(unsigned char)(((l1) )&0xff); \ } \ } /* NOTE - c is not incremented as per cast_n2l */ #define cast_cast_n2ln(c,l1,l2,n) { \ c+=n; \ l1=l2=0; \ switch (n) { \ case 8: l2 =((unsigned long)(*(--(c)))) ; \ /* fall thru */ \ case 7: l2|=((unsigned long)(*(--(c))))<< 8; \ /* fall thru */ \ case 6: l2|=((unsigned long)(*(--(c))))<<16; \ /* fall thru */ \ case 5: l2|=((unsigned long)(*(--(c))))<<24; \ /* fall thru */ \ case 4: l1 =((unsigned long)(*(--(c)))) ; \ /* fall thru */ \ case 3: l1|=((unsigned long)(*(--(c))))<< 8; \ /* fall thru */ \ case 2: l1|=((unsigned long)(*(--(c))))<<16; \ /* fall thru */ \ case 1: l1|=((unsigned long)(*(--(c))))<<24; \ } \ } /* NOTE - c is not incremented as per cast_l2n */ #define cast_cast_l2nn(l1,l2,c,n) { \ c+=n; \ switch (n) { \ case 8: *(--(c))=(unsigned char)(((l2) )&0xff); \ /* fall thru */ \ case 7: *(--(c))=(unsigned char)(((l2)>> 8)&0xff); \ /* fall thru */ \ case 6: *(--(c))=(unsigned char)(((l2)>>16)&0xff); \ /* fall thru */ \ case 5: *(--(c))=(unsigned char)(((l2)>>24)&0xff); \ /* fall thru */ \ case 4: *(--(c))=(unsigned char)(((l1) )&0xff); \ /* fall thru */ \ case 3: *(--(c))=(unsigned char)(((l1)>> 8)&0xff); \ /* fall thru */ \ case 2: *(--(c))=(unsigned char)(((l1)>>16)&0xff); \ /* fall thru */ \ case 1: *(--(c))=(unsigned char)(((l1)>>24)&0xff); \ } \ } #undef cast_n2l #define cast_n2l(c,l) (l =((unsigned long)(*((c)++)))<<24L, \ l|=((unsigned long)(*((c)++)))<<16L, \ l|=((unsigned long)(*((c)++)))<< 8L, \ l|=((unsigned long)(*((c)++)))) #undef cast_l2n #define cast_l2n(l,c) (*((c)++)=(unsigned char)(((l)>>24L)&0xff), \ *((c)++)=(unsigned char)(((l)>>16L)&0xff), \ *((c)++)=(unsigned char)(((l)>> 8L)&0xff), \ *((c)++)=(unsigned char)(((l) )&0xff)) #if defined(OPENSSL_SYS_WIN32) && defined(_MSC_VER) # define ROTL(a,n) (_lrotl(a,n)) #else # define ROTL(a,n) ((((a)<<(n))&0xffffffffL)|((a)>>((32-(n))&31))) #endif #define C_M 0x3fc #define C_0 22L #define C_1 14L #define C_2 6L #define C_3 2L /* left shift */ /* The rotate has an extra 16 added to it to help the x86 asm */ #if defined(CAST_PTR) # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ int i; \ t=(key[n*2] OP1 R)&0xffffffffL; \ i=key[n*2+1]; \ t=ROTL(t,i); \ L^= (((((*(CAST_LONG *)((unsigned char *) \ CAST_S_table0+((t>>C_2)&C_M)) OP2 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table1+((t<<C_3)&C_M)))&0xffffffffL) OP3 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table2+((t>>C_0)&C_M)))&0xffffffffL) OP1 \ *(CAST_LONG *)((unsigned char *) \ CAST_S_table3+((t>>C_1)&C_M)))&0xffffffffL; \ } #elif defined(CAST_PTR2) # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ int i; \ CAST_LONG u,v,w; \ w=(key[n*2] OP1 R)&0xffffffffL; \ i=key[n*2+1]; \ w=ROTL(w,i); \ u=w>>C_2; \ v=w<<C_3; \ u&=C_M; \ v&=C_M; \ t= *(CAST_LONG *)((unsigned char *)CAST_S_table0+u); \ u=w>>C_0; \ t=(t OP2 *(CAST_LONG *)((unsigned char *)CAST_S_table1+v))&0xffffffffL;\ v=w>>C_1; \ u&=C_M; \ v&=C_M; \ t=(t OP3 *(CAST_LONG *)((unsigned char *)CAST_S_table2+u)&0xffffffffL);\ t=(t OP1 *(CAST_LONG *)((unsigned char *)CAST_S_table3+v)&0xffffffffL);\ L^=(t&0xffffffff); \ } #else # define E_CAST(n,key,L,R,OP1,OP2,OP3) \ { \ CAST_LONG a,b,c,d; \ t=(key[n*2] OP1 R)&0xffffffff; \ t=ROTL(t,(key[n*2+1])); \ a=CAST_S_table0[(t>> 8)&0xff]; \ b=CAST_S_table1[(t )&0xff]; \ c=CAST_S_table2[(t>>24)&0xff]; \ d=CAST_S_table3[(t>>16)&0xff]; \ L^=(((((a OP2 b)&0xffffffffL) OP3 c)&0xffffffffL) OP1 d)&0xffffffffL; \ } #endif //extern const CAST_LONG CAST_S_table0[256]; //extern const CAST_LONG CAST_S_table1[256]; //extern const CAST_LONG CAST_S_table2[256]; //extern const CAST_LONG CAST_S_table3[256]; //extern const CAST_LONG CAST_S_table4[256]; //extern const CAST_LONG CAST_S_table5[256]; //extern const CAST_LONG CAST_S_table6[256]; //extern const CAST_LONG CAST_S_table7[256]; // https://github.com/openssl/openssl/blob/master/crypto/cast/cast_s.h /* * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the OpenSSL license (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ const CAST_LONG CAST_S_table0[256] = { 0x30fb40d4, 0x9fa0ff0b, 0x6beccd2f, 0x3f258c7a, 0x1e213f2f, 0x9c004dd3, 0x6003e540, 0xcf9fc949, 0xbfd4af27, 0x88bbbdb5, 0xe2034090, 0x98d09675, 0x6e63a0e0, 0x15c361d2, 0xc2e7661d, 0x22d4ff8e, 0x28683b6f, 0xc07fd059, 0xff2379c8, 0x775f50e2, 0x43c340d3, 0xdf2f8656, 0x887ca41a, 0xa2d2bd2d, 0xa1c9e0d6, 0x346c4819, 0x61b76d87, 0x22540f2f, 0x2abe32e1, 0xaa54166b, 0x22568e3a, 0xa2d341d0, 0x66db40c8, 0xa784392f, 0x004dff2f, 0x2db9d2de, 0x97943fac, 0x4a97c1d8, 0x527644b7, 0xb5f437a7, 0xb82cbaef, 0xd751d159, 0x6ff7f0ed, 0x5a097a1f, 0x827b68d0, 0x90ecf52e, 0x22b0c054, 0xbc8e5935, 0x4b6d2f7f, 0x50bb64a2, 0xd2664910, 0xbee5812d, 0xb7332290, 0xe93b159f, 0xb48ee411, 0x4bff345d, 0xfd45c240, 0xad31973f, 0xc4f6d02e, 0x55fc8165, 0xd5b1caad, 0xa1ac2dae, 0xa2d4b76d, 0xc19b0c50, 0x882240f2, 0x0c6e4f38, 0xa4e4bfd7, 0x4f5ba272, 0x564c1d2f, 0xc59c5319, 0xb949e354, 0xb04669fe, 0xb1b6ab8a, 0xc71358dd, 0x6385c545, 0x110f935d, 0x57538ad5, 0x6a390493, 0xe63d37e0, 0x2a54f6b3, 0x3a787d5f, 0x6276a0b5, 0x19a6fcdf, 0x7a42206a, 0x29f9d4d5, 0xf61b1891, 0xbb72275e, 0xaa508167, 0x38901091, 0xc6b505eb, 0x84c7cb8c, 0x2ad75a0f, 0x874a1427, 0xa2d1936b, 0x2ad286af, 0xaa56d291, 0xd7894360, 0x425c750d, 0x93b39e26, 0x187184c9, 0x6c00b32d, 0x73e2bb14, 0xa0bebc3c, 0x54623779, 0x64459eab, 0x3f328b82, 0x7718cf82, 0x59a2cea6, 0x04ee002e, 0x89fe78e6, 0x3fab0950, 0x325ff6c2, 0x81383f05, 0x6963c5c8, 0x76cb5ad6, 0xd49974c9, 0xca180dcf, 0x380782d5, 0xc7fa5cf6, 0x8ac31511, 0x35e79e13, 0x47da91d0, 0xf40f9086, 0xa7e2419e, 0x31366241, 0x051ef495, 0xaa573b04, 0x4a805d8d, 0x548300d0, 0x00322a3c, 0xbf64cddf, 0xba57a68e, 0x75c6372b, 0x50afd341, 0xa7c13275, 0x915a0bf5, 0x6b54bfab, 0x2b0b1426, 0xab4cc9d7, 0x449ccd82, 0xf7fbf265, 0xab85c5f3, 0x1b55db94, 0xaad4e324, 0xcfa4bd3f, 0x2deaa3e2, 0x9e204d02, 0xc8bd25ac, 0xeadf55b3, 0xd5bd9e98, 0xe31231b2, 0x2ad5ad6c, 0x954329de, 0xadbe4528, 0xd8710f69, 0xaa51c90f, 0xaa786bf6, 0x22513f1e, 0xaa51a79b, 0x2ad344cc, 0x7b5a41f0, 0xd37cfbad, 0x1b069505, 0x41ece491, 0xb4c332e6, 0x032268d4, 0xc9600acc, 0xce387e6d, 0xbf6bb16c, 0x6a70fb78, 0x0d03d9c9, 0xd4df39de, 0xe01063da, 0x4736f464, 0x5ad328d8, 0xb347cc96, 0x75bb0fc3, 0x98511bfb, 0x4ffbcc35, 0xb58bcf6a, 0xe11f0abc, 0xbfc5fe4a, 0xa70aec10, 0xac39570a, 0x3f04442f, 0x6188b153, 0xe0397a2e, 0x5727cb79, 0x9ceb418f, 0x1cacd68d, 0x2ad37c96, 0x0175cb9d, 0xc69dff09, 0xc75b65f0, 0xd9db40d8, 0xec0e7779, 0x4744ead4, 0xb11c3274, 0xdd24cb9e, 0x7e1c54bd, 0xf01144f9, 0xd2240eb1, 0x9675b3fd, 0xa3ac3755, 0xd47c27af, 0x51c85f4d, 0x56907596, 0xa5bb15e6, 0x580304f0, 0xca042cf1, 0x011a37ea, 0x8dbfaadb, 0x35ba3e4a, 0x3526ffa0, 0xc37b4d09, 0xbc306ed9, 0x98a52666, 0x5648f725, 0xff5e569d, 0x0ced63d0, 0x7c63b2cf, 0x700b45e1, 0xd5ea50f1, 0x85a92872, 0xaf1fbda7, 0xd4234870, 0xa7870bf3, 0x2d3b4d79, 0x42e04198, 0x0cd0ede7, 0x26470db8, 0xf881814c, 0x474d6ad7, 0x7c0c5e5c, 0xd1231959, 0x381b7298, 0xf5d2f4db, 0xab838653, 0x6e2f1e23, 0x83719c9e, 0xbd91e046, 0x9a56456e, 0xdc39200c, 0x20c8c571, 0x962bda1c, 0xe1e696ff, 0xb141ab08, 0x7cca89b9, 0x1a69e783, 0x02cc4843, 0xa2f7c579, 0x429ef47d, 0x427b169c, 0x5ac9f049, 0xdd8f0f00, 0x5c8165bf, }; const CAST_LONG CAST_S_table1[256] = { 0x1f201094, 0xef0ba75b, 0x69e3cf7e, 0x393f4380, 0xfe61cf7a, 0xeec5207a, 0x55889c94, 0x72fc0651, 0xada7ef79, 0x4e1d7235, 0xd55a63ce, 0xde0436ba, 0x99c430ef, 0x5f0c0794, 0x18dcdb7d, 0xa1d6eff3, 0xa0b52f7b, 0x59e83605, 0xee15b094, 0xe9ffd909, 0xdc440086, 0xef944459, 0xba83ccb3, 0xe0c3cdfb, 0xd1da4181, 0x3b092ab1, 0xf997f1c1, 0xa5e6cf7b, 0x01420ddb, 0xe4e7ef5b, 0x25a1ff41, 0xe180f806, 0x1fc41080, 0x179bee7a, 0xd37ac6a9, 0xfe5830a4, 0x98de8b7f, 0x77e83f4e, 0x79929269, 0x24fa9f7b, 0xe113c85b, 0xacc40083, 0xd7503525, 0xf7ea615f, 0x62143154, 0x0d554b63, 0x5d681121, 0xc866c359, 0x3d63cf73, 0xcee234c0, 0xd4d87e87, 0x5c672b21, 0x071f6181, 0x39f7627f, 0x361e3084, 0xe4eb573b, 0x602f64a4, 0xd63acd9c, 0x1bbc4635, 0x9e81032d, 0x2701f50c, 0x99847ab4, 0xa0e3df79, 0xba6cf38c, 0x10843094, 0x2537a95e, 0xf46f6ffe, 0xa1ff3b1f, 0x208cfb6a, 0x8f458c74, 0xd9e0a227, 0x4ec73a34, 0xfc884f69, 0x3e4de8df, 0xef0e0088, 0x3559648d, 0x8a45388c, 0x1d804366, 0x721d9bfd, 0xa58684bb, 0xe8256333, 0x844e8212, 0x128d8098, 0xfed33fb4, 0xce280ae1, 0x27e19ba5, 0xd5a6c252, 0xe49754bd, 0xc5d655dd, 0xeb667064, 0x77840b4d, 0xa1b6a801, 0x84db26a9, 0xe0b56714, 0x21f043b7, 0xe5d05860, 0x54f03084, 0x066ff472, 0xa31aa153, 0xdadc4755, 0xb5625dbf, 0x68561be6, 0x83ca6b94, 0x2d6ed23b, 0xeccf01db, 0xa6d3d0ba, 0xb6803d5c, 0xaf77a709, 0x33b4a34c, 0x397bc8d6, 0x5ee22b95, 0x5f0e5304, 0x81ed6f61, 0x20e74364, 0xb45e1378, 0xde18639b, 0x881ca122, 0xb96726d1, 0x8049a7e8, 0x22b7da7b, 0x5e552d25, 0x5272d237, 0x79d2951c, 0xc60d894c, 0x488cb402, 0x1ba4fe5b, 0xa4b09f6b, 0x1ca815cf, 0xa20c3005, 0x8871df63, 0xb9de2fcb, 0x0cc6c9e9, 0x0beeff53, 0xe3214517, 0xb4542835, 0x9f63293c, 0xee41e729, 0x6e1d2d7c, 0x50045286, 0x1e6685f3, 0xf33401c6, 0x30a22c95, 0x31a70850, 0x60930f13, 0x73f98417, 0xa1269859, 0xec645c44, 0x52c877a9, 0xcdff33a6, 0xa02b1741, 0x7cbad9a2, 0x2180036f, 0x50d99c08, 0xcb3f4861, 0xc26bd765, 0x64a3f6ab, 0x80342676, 0x25a75e7b, 0xe4e6d1fc, 0x20c710e6, 0xcdf0b680, 0x17844d3b, 0x31eef84d, 0x7e0824e4, 0x2ccb49eb, 0x846a3bae, 0x8ff77888, 0xee5d60f6, 0x7af75673, 0x2fdd5cdb, 0xa11631c1, 0x30f66f43, 0xb3faec54, 0x157fd7fa, 0xef8579cc, 0xd152de58, 0xdb2ffd5e, 0x8f32ce19, 0x306af97a, 0x02f03ef8, 0x99319ad5, 0xc242fa0f, 0xa7e3ebb0, 0xc68e4906, 0xb8da230c, 0x80823028, 0xdcdef3c8, 0xd35fb171, 0x088a1bc8, 0xbec0c560, 0x61a3c9e8, 0xbca8f54d, 0xc72feffa, 0x22822e99, 0x82c570b4, 0xd8d94e89, 0x8b1c34bc, 0x301e16e6, 0x273be979, 0xb0ffeaa6, 0x61d9b8c6, 0x00b24869, 0xb7ffce3f, 0x08dc283b, 0x43daf65a, 0xf7e19798, 0x7619b72f, 0x8f1c9ba4, 0xdc8637a0, 0x16a7d3b1, 0x9fc393b7, 0xa7136eeb, 0xc6bcc63e, 0x1a513742, 0xef6828bc, 0x520365d6, 0x2d6a77ab, 0x3527ed4b, 0x821fd216, 0x095c6e2e, 0xdb92f2fb, 0x5eea29cb, 0x145892f5, 0x91584f7f, 0x5483697b, 0x2667a8cc, 0x85196048, 0x8c4bacea, 0x833860d4, 0x0d23e0f9, 0x6c387e8a, 0x0ae6d249, 0xb284600c, 0xd835731d, 0xdcb1c647, 0xac4c56ea, 0x3ebd81b3, 0x230eabb0, 0x6438bc87, 0xf0b5b1fa, 0x8f5ea2b3, 0xfc184642, 0x0a036b7a, 0x4fb089bd, 0x649da589, 0xa345415e, 0x5c038323, 0x3e5d3bb9, 0x43d79572, 0x7e6dd07c, 0x06dfdf1e, 0x6c6cc4ef, 0x7160a539, 0x73bfbe70, 0x83877605, 0x4523ecf1, }; const CAST_LONG CAST_S_table2[256] = { 0x8defc240, 0x25fa5d9f, 0xeb903dbf, 0xe810c907, 0x47607fff, 0x369fe44b, 0x8c1fc644, 0xaececa90, 0xbeb1f9bf, 0xeefbcaea, 0xe8cf1950, 0x51df07ae, 0x920e8806, 0xf0ad0548, 0xe13c8d83, 0x927010d5, 0x11107d9f, 0x07647db9, 0xb2e3e4d4, 0x3d4f285e, 0xb9afa820, 0xfade82e0, 0xa067268b, 0x8272792e, 0x553fb2c0, 0x489ae22b, 0xd4ef9794, 0x125e3fbc, 0x21fffcee, 0x825b1bfd, 0x9255c5ed, 0x1257a240, 0x4e1a8302, 0xbae07fff, 0x528246e7, 0x8e57140e, 0x3373f7bf, 0x8c9f8188, 0xa6fc4ee8, 0xc982b5a5, 0xa8c01db7, 0x579fc264, 0x67094f31, 0xf2bd3f5f, 0x40fff7c1, 0x1fb78dfc, 0x8e6bd2c1, 0x437be59b, 0x99b03dbf, 0xb5dbc64b, 0x638dc0e6, 0x55819d99, 0xa197c81c, 0x4a012d6e, 0xc5884a28, 0xccc36f71, 0xb843c213, 0x6c0743f1, 0x8309893c, 0x0feddd5f, 0x2f7fe850, 0xd7c07f7e, 0x02507fbf, 0x5afb9a04, 0xa747d2d0, 0x1651192e, 0xaf70bf3e, 0x58c31380, 0x5f98302e, 0x727cc3c4, 0x0a0fb402, 0x0f7fef82, 0x8c96fdad, 0x5d2c2aae, 0x8ee99a49, 0x50da88b8, 0x8427f4a0, 0x1eac5790, 0x796fb449, 0x8252dc15, 0xefbd7d9b, 0xa672597d, 0xada840d8, 0x45f54504, 0xfa5d7403, 0xe83ec305, 0x4f91751a, 0x925669c2, 0x23efe941, 0xa903f12e, 0x60270df2, 0x0276e4b6, 0x94fd6574, 0x927985b2, 0x8276dbcb, 0x02778176, 0xf8af918d, 0x4e48f79e, 0x8f616ddf, 0xe29d840e, 0x842f7d83, 0x340ce5c8, 0x96bbb682, 0x93b4b148, 0xef303cab, 0x984faf28, 0x779faf9b, 0x92dc560d, 0x224d1e20, 0x8437aa88, 0x7d29dc96, 0x2756d3dc, 0x8b907cee, 0xb51fd240, 0xe7c07ce3, 0xe566b4a1, 0xc3e9615e, 0x3cf8209d, 0x6094d1e3, 0xcd9ca341, 0x5c76460e, 0x00ea983b, 0xd4d67881, 0xfd47572c, 0xf76cedd9, 0xbda8229c, 0x127dadaa, 0x438a074e, 0x1f97c090, 0x081bdb8a, 0x93a07ebe, 0xb938ca15, 0x97b03cff, 0x3dc2c0f8, 0x8d1ab2ec, 0x64380e51, 0x68cc7bfb, 0xd90f2788, 0x12490181, 0x5de5ffd4, 0xdd7ef86a, 0x76a2e214, 0xb9a40368, 0x925d958f, 0x4b39fffa, 0xba39aee9, 0xa4ffd30b, 0xfaf7933b, 0x6d498623, 0x193cbcfa, 0x27627545, 0x825cf47a, 0x61bd8ba0, 0xd11e42d1, 0xcead04f4, 0x127ea392, 0x10428db7, 0x8272a972, 0x9270c4a8, 0x127de50b, 0x285ba1c8, 0x3c62f44f, 0x35c0eaa5, 0xe805d231, 0x428929fb, 0xb4fcdf82, 0x4fb66a53, 0x0e7dc15b, 0x1f081fab, 0x108618ae, 0xfcfd086d, 0xf9ff2889, 0x694bcc11, 0x236a5cae, 0x12deca4d, 0x2c3f8cc5, 0xd2d02dfe, 0xf8ef5896, 0xe4cf52da, 0x95155b67, 0x494a488c, 0xb9b6a80c, 0x5c8f82bc, 0x89d36b45, 0x3a609437, 0xec00c9a9, 0x44715253, 0x0a874b49, 0xd773bc40, 0x7c34671c, 0x02717ef6, 0x4feb5536, 0xa2d02fff, 0xd2bf60c4, 0xd43f03c0, 0x50b4ef6d, 0x07478cd1, 0x006e1888, 0xa2e53f55, 0xb9e6d4bc, 0xa2048016, 0x97573833, 0xd7207d67, 0xde0f8f3d, 0x72f87b33, 0xabcc4f33, 0x7688c55d, 0x7b00a6b0, 0x947b0001, 0x570075d2, 0xf9bb88f8, 0x8942019e, 0x4264a5ff, 0x856302e0, 0x72dbd92b, 0xee971b69, 0x6ea22fde, 0x5f08ae2b, 0xaf7a616d, 0xe5c98767, 0xcf1febd2, 0x61efc8c2, 0xf1ac2571, 0xcc8239c2, 0x67214cb8, 0xb1e583d1, 0xb7dc3e62, 0x7f10bdce, 0xf90a5c38, 0x0ff0443d, 0x606e6dc6, 0x60543a49, 0x5727c148, 0x2be98a1d, 0x8ab41738, 0x20e1be24, 0xaf96da0f, 0x68458425, 0x99833be5, 0x600d457d, 0x282f9350, 0x8334b362, 0xd91d1120, 0x2b6d8da0, 0x642b1e31, 0x9c305a00, 0x52bce688, 0x1b03588a, 0xf7baefd5, 0x4142ed9c, 0xa4315c11, 0x83323ec5, 0xdfef4636, 0xa133c501, 0xe9d3531c, 0xee353783, }; const CAST_LONG CAST_S_table3[256] = { 0x9db30420, 0x1fb6e9de, 0xa7be7bef, 0xd273a298, 0x4a4f7bdb, 0x64ad8c57, 0x85510443, 0xfa020ed1, 0x7e287aff, 0xe60fb663, 0x095f35a1, 0x79ebf120, 0xfd059d43, 0x6497b7b1, 0xf3641f63, 0x241e4adf, 0x28147f5f, 0x4fa2b8cd, 0xc9430040, 0x0cc32220, 0xfdd30b30, 0xc0a5374f, 0x1d2d00d9, 0x24147b15, 0xee4d111a, 0x0fca5167, 0x71ff904c, 0x2d195ffe, 0x1a05645f, 0x0c13fefe, 0x081b08ca, 0x05170121, 0x80530100, 0xe83e5efe, 0xac9af4f8, 0x7fe72701, 0xd2b8ee5f, 0x06df4261, 0xbb9e9b8a, 0x7293ea25, 0xce84ffdf, 0xf5718801, 0x3dd64b04, 0xa26f263b, 0x7ed48400, 0x547eebe6, 0x446d4ca0, 0x6cf3d6f5, 0x2649abdf, 0xaea0c7f5, 0x36338cc1, 0x503f7e93, 0xd3772061, 0x11b638e1, 0x72500e03, 0xf80eb2bb, 0xabe0502e, 0xec8d77de, 0x57971e81, 0xe14f6746, 0xc9335400, 0x6920318f, 0x081dbb99, 0xffc304a5, 0x4d351805, 0x7f3d5ce3, 0xa6c866c6, 0x5d5bcca9, 0xdaec6fea, 0x9f926f91, 0x9f46222f, 0x3991467d, 0xa5bf6d8e, 0x1143c44f, 0x43958302, 0xd0214eeb, 0x022083b8, 0x3fb6180c, 0x18f8931e, 0x281658e6, 0x26486e3e, 0x8bd78a70, 0x7477e4c1, 0xb506e07c, 0xf32d0a25, 0x79098b02, 0xe4eabb81, 0x28123b23, 0x69dead38, 0x1574ca16, 0xdf871b62, 0x211c40b7, 0xa51a9ef9, 0x0014377b, 0x041e8ac8, 0x09114003, 0xbd59e4d2, 0xe3d156d5, 0x4fe876d5, 0x2f91a340, 0x557be8de, 0x00eae4a7, 0x0ce5c2ec, 0x4db4bba6, 0xe756bdff, 0xdd3369ac, 0xec17b035, 0x06572327, 0x99afc8b0, 0x56c8c391, 0x6b65811c, 0x5e146119, 0x6e85cb75, 0xbe07c002, 0xc2325577, 0x893ff4ec, 0x5bbfc92d, 0xd0ec3b25, 0xb7801ab7, 0x8d6d3b24, 0x20c763ef, 0xc366a5fc, 0x9c382880, 0x0ace3205, 0xaac9548a, 0xeca1d7c7, 0x041afa32, 0x1d16625a, 0x6701902c, 0x9b757a54, 0x31d477f7, 0x9126b031, 0x36cc6fdb, 0xc70b8b46, 0xd9e66a48, 0x56e55a79, 0x026a4ceb, 0x52437eff, 0x2f8f76b4, 0x0df980a5, 0x8674cde3, 0xedda04eb, 0x17a9be04, 0x2c18f4df, 0xb7747f9d, 0xab2af7b4, 0xefc34d20, 0x2e096b7c, 0x1741a254, 0xe5b6a035, 0x213d42f6, 0x2c1c7c26, 0x61c2f50f, 0x6552daf9, 0xd2c231f8, 0x25130f69, 0xd8167fa2, 0x0418f2c8, 0x001a96a6, 0x0d1526ab, 0x63315c21, 0x5e0a72ec, 0x49bafefd, 0x187908d9, 0x8d0dbd86, 0x311170a7, 0x3e9b640c, 0xcc3e10d7, 0xd5cad3b6, 0x0caec388, 0xf73001e1, 0x6c728aff, 0x71eae2a1, 0x1f9af36e, 0xcfcbd12f, 0xc1de8417, 0xac07be6b, 0xcb44a1d8, 0x8b9b0f56, 0x013988c3, 0xb1c52fca, 0xb4be31cd, 0xd8782806, 0x12a3a4e2, 0x6f7de532, 0x58fd7eb6, 0xd01ee900, 0x24adffc2, 0xf4990fc5, 0x9711aac5, 0x001d7b95, 0x82e5e7d2, 0x109873f6, 0x00613096, 0xc32d9521, 0xada121ff, 0x29908415, 0x7fbb977f, 0xaf9eb3db, 0x29c9ed2a, 0x5ce2a465, 0xa730f32c, 0xd0aa3fe8, 0x8a5cc091, 0xd49e2ce7, 0x0ce454a9, 0xd60acd86, 0x015f1919, 0x77079103, 0xdea03af6, 0x78a8565e, 0xdee356df, 0x21f05cbe, 0x8b75e387, 0xb3c50651, 0xb8a5c3ef, 0xd8eeb6d2, 0xe523be77, 0xc2154529, 0x2f69efdf, 0xafe67afb, 0xf470c4b2, 0xf3e0eb5b, 0xd6cc9876, 0x39e4460c, 0x1fda8538, 0x1987832f, 0xca007367, 0xa99144f8, 0x296b299e, 0x492fc295, 0x9266beab, 0xb5676e69, 0x9bd3ddda, 0xdf7e052f, 0xdb25701c, 0x1b5e51ee, 0xf65324e6, 0x6afce36c, 0x0316cc04, 0x8644213e, 0xb7dc59d0, 0x7965291f, 0xccd6fd43, 0x41823979, 0x932bcdf6, 0xb657c34d, 0x4edfd282, 0x7ae5290c, 0x3cb9536b, 0x851e20fe, 0x9833557e, 0x13ecf0b0, 0xd3ffb372, 0x3f85c5c1, 0x0aef7ed2, }; const CAST_LONG CAST_S_table4[256] = { 0x7ec90c04, 0x2c6e74b9, 0x9b0e66df, 0xa6337911, 0xb86a7fff, 0x1dd358f5, 0x44dd9d44, 0x1731167f, 0x08fbf1fa, 0xe7f511cc, 0xd2051b00, 0x735aba00, 0x2ab722d8, 0x386381cb, 0xacf6243a, 0x69befd7a, 0xe6a2e77f, 0xf0c720cd, 0xc4494816, 0xccf5c180, 0x38851640, 0x15b0a848, 0xe68b18cb, 0x4caadeff, 0x5f480a01, 0x0412b2aa, 0x259814fc, 0x41d0efe2, 0x4e40b48d, 0x248eb6fb, 0x8dba1cfe, 0x41a99b02, 0x1a550a04, 0xba8f65cb, 0x7251f4e7, 0x95a51725, 0xc106ecd7, 0x97a5980a, 0xc539b9aa, 0x4d79fe6a, 0xf2f3f763, 0x68af8040, 0xed0c9e56, 0x11b4958b, 0xe1eb5a88, 0x8709e6b0, 0xd7e07156, 0x4e29fea7, 0x6366e52d, 0x02d1c000, 0xc4ac8e05, 0x9377f571, 0x0c05372a, 0x578535f2, 0x2261be02, 0xd642a0c9, 0xdf13a280, 0x74b55bd2, 0x682199c0, 0xd421e5ec, 0x53fb3ce8, 0xc8adedb3, 0x28a87fc9, 0x3d959981, 0x5c1ff900, 0xfe38d399, 0x0c4eff0b, 0x062407ea, 0xaa2f4fb1, 0x4fb96976, 0x90c79505, 0xb0a8a774, 0xef55a1ff, 0xe59ca2c2, 0xa6b62d27, 0xe66a4263, 0xdf65001f, 0x0ec50966, 0xdfdd55bc, 0x29de0655, 0x911e739a, 0x17af8975, 0x32c7911c, 0x89f89468, 0x0d01e980, 0x524755f4, 0x03b63cc9, 0x0cc844b2, 0xbcf3f0aa, 0x87ac36e9, 0xe53a7426, 0x01b3d82b, 0x1a9e7449, 0x64ee2d7e, 0xcddbb1da, 0x01c94910, 0xb868bf80, 0x0d26f3fd, 0x9342ede7, 0x04a5c284, 0x636737b6, 0x50f5b616, 0xf24766e3, 0x8eca36c1, 0x136e05db, 0xfef18391, 0xfb887a37, 0xd6e7f7d4, 0xc7fb7dc9, 0x3063fcdf, 0xb6f589de, 0xec2941da, 0x26e46695, 0xb7566419, 0xf654efc5, 0xd08d58b7, 0x48925401, 0xc1bacb7f, 0xe5ff550f, 0xb6083049, 0x5bb5d0e8, 0x87d72e5a, 0xab6a6ee1, 0x223a66ce, 0xc62bf3cd, 0x9e0885f9, 0x68cb3e47, 0x086c010f, 0xa21de820, 0xd18b69de, 0xf3f65777, 0xfa02c3f6, 0x407edac3, 0xcbb3d550, 0x1793084d, 0xb0d70eba, 0x0ab378d5, 0xd951fb0c, 0xded7da56, 0x4124bbe4, 0x94ca0b56, 0x0f5755d1, 0xe0e1e56e, 0x6184b5be, 0x580a249f, 0x94f74bc0, 0xe327888e, 0x9f7b5561, 0xc3dc0280, 0x05687715, 0x646c6bd7, 0x44904db3, 0x66b4f0a3, 0xc0f1648a, 0x697ed5af, 0x49e92ff6, 0x309e374f, 0x2cb6356a, 0x85808573, 0x4991f840, 0x76f0ae02, 0x083be84d, 0x28421c9a, 0x44489406, 0x736e4cb8, 0xc1092910, 0x8bc95fc6, 0x7d869cf4, 0x134f616f, 0x2e77118d, 0xb31b2be1, 0xaa90b472, 0x3ca5d717, 0x7d161bba, 0x9cad9010, 0xaf462ba2, 0x9fe459d2, 0x45d34559, 0xd9f2da13, 0xdbc65487, 0xf3e4f94e, 0x176d486f, 0x097c13ea, 0x631da5c7, 0x445f7382, 0x175683f4, 0xcdc66a97, 0x70be0288, 0xb3cdcf72, 0x6e5dd2f3, 0x20936079, 0x459b80a5, 0xbe60e2db, 0xa9c23101, 0xeba5315c, 0x224e42f2, 0x1c5c1572, 0xf6721b2c, 0x1ad2fff3, 0x8c25404e, 0x324ed72f, 0x4067b7fd, 0x0523138e, 0x5ca3bc78, 0xdc0fd66e, 0x75922283, 0x784d6b17, 0x58ebb16e, 0x44094f85, 0x3f481d87, 0xfcfeae7b, 0x77b5ff76, 0x8c2302bf, 0xaaf47556, 0x5f46b02a, 0x2b092801, 0x3d38f5f7, 0x0ca81f36, 0x52af4a8a, 0x66d5e7c0, 0xdf3b0874, 0x95055110, 0x1b5ad7a8, 0xf61ed5ad, 0x6cf6e479, 0x20758184, 0xd0cefa65, 0x88f7be58, 0x4a046826, 0x0ff6f8f3, 0xa09c7f70, 0x5346aba0, 0x5ce96c28, 0xe176eda3, 0x6bac307f, 0x376829d2, 0x85360fa9, 0x17e3fe2a, 0x24b79767, 0xf5a96b20, 0xd6cd2595, 0x68ff1ebf, 0x7555442c, 0xf19f06be, 0xf9e0659a, 0xeeb9491d, 0x34010718, 0xbb30cab8, 0xe822fe15, 0x88570983, 0x750e6249, 0xda627e55, 0x5e76ffa8, 0xb1534546, 0x6d47de08, 0xefe9e7d4, }; const CAST_LONG CAST_S_table5[256] = { 0xf6fa8f9d, 0x2cac6ce1, 0x4ca34867, 0xe2337f7c, 0x95db08e7, 0x016843b4, 0xeced5cbc, 0x325553ac, 0xbf9f0960, 0xdfa1e2ed, 0x83f0579d, 0x63ed86b9, 0x1ab6a6b8, 0xde5ebe39, 0xf38ff732, 0x8989b138, 0x33f14961, 0xc01937bd, 0xf506c6da, 0xe4625e7e, 0xa308ea99, 0x4e23e33c, 0x79cbd7cc, 0x48a14367, 0xa3149619, 0xfec94bd5, 0xa114174a, 0xeaa01866, 0xa084db2d, 0x09a8486f, 0xa888614a, 0x2900af98, 0x01665991, 0xe1992863, 0xc8f30c60, 0x2e78ef3c, 0xd0d51932, 0xcf0fec14, 0xf7ca07d2, 0xd0a82072, 0xfd41197e, 0x9305a6b0, 0xe86be3da, 0x74bed3cd, 0x372da53c, 0x4c7f4448, 0xdab5d440, 0x6dba0ec3, 0x083919a7, 0x9fbaeed9, 0x49dbcfb0, 0x4e670c53, 0x5c3d9c01, 0x64bdb941, 0x2c0e636a, 0xba7dd9cd, 0xea6f7388, 0xe70bc762, 0x35f29adb, 0x5c4cdd8d, 0xf0d48d8c, 0xb88153e2, 0x08a19866, 0x1ae2eac8, 0x284caf89, 0xaa928223, 0x9334be53, 0x3b3a21bf, 0x16434be3, 0x9aea3906, 0xefe8c36e, 0xf890cdd9, 0x80226dae, 0xc340a4a3, 0xdf7e9c09, 0xa694a807, 0x5b7c5ecc, 0x221db3a6, 0x9a69a02f, 0x68818a54, 0xceb2296f, 0x53c0843a, 0xfe893655, 0x25bfe68a, 0xb4628abc, 0xcf222ebf, 0x25ac6f48, 0xa9a99387, 0x53bddb65, 0xe76ffbe7, 0xe967fd78, 0x0ba93563, 0x8e342bc1, 0xe8a11be9, 0x4980740d, 0xc8087dfc, 0x8de4bf99, 0xa11101a0, 0x7fd37975, 0xda5a26c0, 0xe81f994f, 0x9528cd89, 0xfd339fed, 0xb87834bf, 0x5f04456d, 0x22258698, 0xc9c4c83b, 0x2dc156be, 0x4f628daa, 0x57f55ec5, 0xe2220abe, 0xd2916ebf, 0x4ec75b95, 0x24f2c3c0, 0x42d15d99, 0xcd0d7fa0, 0x7b6e27ff, 0xa8dc8af0, 0x7345c106, 0xf41e232f, 0x35162386, 0xe6ea8926, 0x3333b094, 0x157ec6f2, 0x372b74af, 0x692573e4, 0xe9a9d848, 0xf3160289, 0x3a62ef1d, 0xa787e238, 0xf3a5f676, 0x74364853, 0x20951063, 0x4576698d, 0xb6fad407, 0x592af950, 0x36f73523, 0x4cfb6e87, 0x7da4cec0, 0x6c152daa, 0xcb0396a8, 0xc50dfe5d, 0xfcd707ab, 0x0921c42f, 0x89dff0bb, 0x5fe2be78, 0x448f4f33, 0x754613c9, 0x2b05d08d, 0x48b9d585, 0xdc049441, 0xc8098f9b, 0x7dede786, 0xc39a3373, 0x42410005, 0x6a091751, 0x0ef3c8a6, 0x890072d6, 0x28207682, 0xa9a9f7be, 0xbf32679d, 0xd45b5b75, 0xb353fd00, 0xcbb0e358, 0x830f220a, 0x1f8fb214, 0xd372cf08, 0xcc3c4a13, 0x8cf63166, 0x061c87be, 0x88c98f88, 0x6062e397, 0x47cf8e7a, 0xb6c85283, 0x3cc2acfb, 0x3fc06976, 0x4e8f0252, 0x64d8314d, 0xda3870e3, 0x1e665459, 0xc10908f0, 0x513021a5, 0x6c5b68b7, 0x822f8aa0, 0x3007cd3e, 0x74719eef, 0xdc872681, 0x073340d4, 0x7e432fd9, 0x0c5ec241, 0x8809286c, 0xf592d891, 0x08a930f6, 0x957ef305, 0xb7fbffbd, 0xc266e96f, 0x6fe4ac98, 0xb173ecc0, 0xbc60b42a, 0x953498da, 0xfba1ae12, 0x2d4bd736, 0x0f25faab, 0xa4f3fceb, 0xe2969123, 0x257f0c3d, 0x9348af49, 0x361400bc, 0xe8816f4a, 0x3814f200, 0xa3f94043, 0x9c7a54c2, 0xbc704f57, 0xda41e7f9, 0xc25ad33a, 0x54f4a084, 0xb17f5505, 0x59357cbe, 0xedbd15c8, 0x7f97c5ab, 0xba5ac7b5, 0xb6f6deaf, 0x3a479c3a, 0x5302da25, 0x653d7e6a, 0x54268d49, 0x51a477ea, 0x5017d55b, 0xd7d25d88, 0x44136c76, 0x0404a8c8, 0xb8e5a121, 0xb81a928a, 0x60ed5869, 0x97c55b96, 0xeaec991b, 0x29935913, 0x01fdb7f1, 0x088e8dfa, 0x9ab6f6f5, 0x3b4cbf9f, 0x4a5de3ab, 0xe6051d35, 0xa0e1d855, 0xd36b4cf1, 0xf544edeb, 0xb0e93524, 0xbebb8fbd, 0xa2d762cf, 0x49c92f54, 0x38b5f331, 0x7128a454, 0x48392905, 0xa65b1db8, 0x851c97bd, 0xd675cf2f, }; const CAST_LONG CAST_S_table6[256] = { 0x85e04019, 0x332bf567, 0x662dbfff, 0xcfc65693, 0x2a8d7f6f, 0xab9bc912, 0xde6008a1, 0x2028da1f, 0x0227bce7, 0x4d642916, 0x18fac300, 0x50f18b82, 0x2cb2cb11, 0xb232e75c, 0x4b3695f2, 0xb28707de, 0xa05fbcf6, 0xcd4181e9, 0xe150210c, 0xe24ef1bd, 0xb168c381, 0xfde4e789, 0x5c79b0d8, 0x1e8bfd43, 0x4d495001, 0x38be4341, 0x913cee1d, 0x92a79c3f, 0x089766be, 0xbaeeadf4, 0x1286becf, 0xb6eacb19, 0x2660c200, 0x7565bde4, 0x64241f7a, 0x8248dca9, 0xc3b3ad66, 0x28136086, 0x0bd8dfa8, 0x356d1cf2, 0x107789be, 0xb3b2e9ce, 0x0502aa8f, 0x0bc0351e, 0x166bf52a, 0xeb12ff82, 0xe3486911, 0xd34d7516, 0x4e7b3aff, 0x5f43671b, 0x9cf6e037, 0x4981ac83, 0x334266ce, 0x8c9341b7, 0xd0d854c0, 0xcb3a6c88, 0x47bc2829, 0x4725ba37, 0xa66ad22b, 0x7ad61f1e, 0x0c5cbafa, 0x4437f107, 0xb6e79962, 0x42d2d816, 0x0a961288, 0xe1a5c06e, 0x13749e67, 0x72fc081a, 0xb1d139f7, 0xf9583745, 0xcf19df58, 0xbec3f756, 0xc06eba30, 0x07211b24, 0x45c28829, 0xc95e317f, 0xbc8ec511, 0x38bc46e9, 0xc6e6fa14, 0xbae8584a, 0xad4ebc46, 0x468f508b, 0x7829435f, 0xf124183b, 0x821dba9f, 0xaff60ff4, 0xea2c4e6d, 0x16e39264, 0x92544a8b, 0x009b4fc3, 0xaba68ced, 0x9ac96f78, 0x06a5b79a, 0xb2856e6e, 0x1aec3ca9, 0xbe838688, 0x0e0804e9, 0x55f1be56, 0xe7e5363b, 0xb3a1f25d, 0xf7debb85, 0x61fe033c, 0x16746233, 0x3c034c28, 0xda6d0c74, 0x79aac56c, 0x3ce4e1ad, 0x51f0c802, 0x98f8f35a, 0x1626a49f, 0xeed82b29, 0x1d382fe3, 0x0c4fb99a, 0xbb325778, 0x3ec6d97b, 0x6e77a6a9, 0xcb658b5c, 0xd45230c7, 0x2bd1408b, 0x60c03eb7, 0xb9068d78, 0xa33754f4, 0xf430c87d, 0xc8a71302, 0xb96d8c32, 0xebd4e7be, 0xbe8b9d2d, 0x7979fb06, 0xe7225308, 0x8b75cf77, 0x11ef8da4, 0xe083c858, 0x8d6b786f, 0x5a6317a6, 0xfa5cf7a0, 0x5dda0033, 0xf28ebfb0, 0xf5b9c310, 0xa0eac280, 0x08b9767a, 0xa3d9d2b0, 0x79d34217, 0x021a718d, 0x9ac6336a, 0x2711fd60, 0x438050e3, 0x069908a8, 0x3d7fedc4, 0x826d2bef, 0x4eeb8476, 0x488dcf25, 0x36c9d566, 0x28e74e41, 0xc2610aca, 0x3d49a9cf, 0xbae3b9df, 0xb65f8de6, 0x92aeaf64, 0x3ac7d5e6, 0x9ea80509, 0xf22b017d, 0xa4173f70, 0xdd1e16c3, 0x15e0d7f9, 0x50b1b887, 0x2b9f4fd5, 0x625aba82, 0x6a017962, 0x2ec01b9c, 0x15488aa9, 0xd716e740, 0x40055a2c, 0x93d29a22, 0xe32dbf9a, 0x058745b9, 0x3453dc1e, 0xd699296e, 0x496cff6f, 0x1c9f4986, 0xdfe2ed07, 0xb87242d1, 0x19de7eae, 0x053e561a, 0x15ad6f8c, 0x66626c1c, 0x7154c24c, 0xea082b2a, 0x93eb2939, 0x17dcb0f0, 0x58d4f2ae, 0x9ea294fb, 0x52cf564c, 0x9883fe66, 0x2ec40581, 0x763953c3, 0x01d6692e, 0xd3a0c108, 0xa1e7160e, 0xe4f2dfa6, 0x693ed285, 0x74904698, 0x4c2b0edd, 0x4f757656, 0x5d393378, 0xa132234f, 0x3d321c5d, 0xc3f5e194, 0x4b269301, 0xc79f022f, 0x3c997e7e, 0x5e4f9504, 0x3ffafbbd, 0x76f7ad0e, 0x296693f4, 0x3d1fce6f, 0xc61e45be, 0xd3b5ab34, 0xf72bf9b7, 0x1b0434c0, 0x4e72b567, 0x5592a33d, 0xb5229301, 0xcfd2a87f, 0x60aeb767, 0x1814386b, 0x30bcc33d, 0x38a0c07d, 0xfd1606f2, 0xc363519b, 0x589dd390, 0x5479f8e6, 0x1cb8d647, 0x97fd61a9, 0xea7759f4, 0x2d57539d, 0x569a58cf, 0xe84e63ad, 0x462e1b78, 0x6580f87e, 0xf3817914, 0x91da55f4, 0x40a230f3, 0xd1988f35, 0xb6e318d2, 0x3ffa50bc, 0x3d40f021, 0xc3c0bdae, 0x4958c24c, 0x518f36b2, 0x84b1d370, 0x0fedce83, 0x878ddada, 0xf2a279c7, 0x94e01be8, 0x90716f4b, 0x954b8aa3, }; const CAST_LONG CAST_S_table7[256] = { 0xe216300d, 0xbbddfffc, 0xa7ebdabd, 0x35648095, 0x7789f8b7, 0xe6c1121b, 0x0e241600, 0x052ce8b5, 0x11a9cfb0, 0xe5952f11, 0xece7990a, 0x9386d174, 0x2a42931c, 0x76e38111, 0xb12def3a, 0x37ddddfc, 0xde9adeb1, 0x0a0cc32c, 0xbe197029, 0x84a00940, 0xbb243a0f, 0xb4d137cf, 0xb44e79f0, 0x049eedfd, 0x0b15a15d, 0x480d3168, 0x8bbbde5a, 0x669ded42, 0xc7ece831, 0x3f8f95e7, 0x72df191b, 0x7580330d, 0x94074251, 0x5c7dcdfa, 0xabbe6d63, 0xaa402164, 0xb301d40a, 0x02e7d1ca, 0x53571dae, 0x7a3182a2, 0x12a8ddec, 0xfdaa335d, 0x176f43e8, 0x71fb46d4, 0x38129022, 0xce949ad4, 0xb84769ad, 0x965bd862, 0x82f3d055, 0x66fb9767, 0x15b80b4e, 0x1d5b47a0, 0x4cfde06f, 0xc28ec4b8, 0x57e8726e, 0x647a78fc, 0x99865d44, 0x608bd593, 0x6c200e03, 0x39dc5ff6, 0x5d0b00a3, 0xae63aff2, 0x7e8bd632, 0x70108c0c, 0xbbd35049, 0x2998df04, 0x980cf42a, 0x9b6df491, 0x9e7edd53, 0x06918548, 0x58cb7e07, 0x3b74ef2e, 0x522fffb1, 0xd24708cc, 0x1c7e27cd, 0xa4eb215b, 0x3cf1d2e2, 0x19b47a38, 0x424f7618, 0x35856039, 0x9d17dee7, 0x27eb35e6, 0xc9aff67b, 0x36baf5b8, 0x09c467cd, 0xc18910b1, 0xe11dbf7b, 0x06cd1af8, 0x7170c608, 0x2d5e3354, 0xd4de495a, 0x64c6d006, 0xbcc0c62c, 0x3dd00db3, 0x708f8f34, 0x77d51b42, 0x264f620f, 0x24b8d2bf, 0x15c1b79e, 0x46a52564, 0xf8d7e54e, 0x3e378160, 0x7895cda5, 0x859c15a5, 0xe6459788, 0xc37bc75f, 0xdb07ba0c, 0x0676a3ab, 0x7f229b1e, 0x31842e7b, 0x24259fd7, 0xf8bef472, 0x835ffcb8, 0x6df4c1f2, 0x96f5b195, 0xfd0af0fc, 0xb0fe134c, 0xe2506d3d, 0x4f9b12ea, 0xf215f225, 0xa223736f, 0x9fb4c428, 0x25d04979, 0x34c713f8, 0xc4618187, 0xea7a6e98, 0x7cd16efc, 0x1436876c, 0xf1544107, 0xbedeee14, 0x56e9af27, 0xa04aa441, 0x3cf7c899, 0x92ecbae6, 0xdd67016d, 0x151682eb, 0xa842eedf, 0xfdba60b4, 0xf1907b75, 0x20e3030f, 0x24d8c29e, 0xe139673b, 0xefa63fb8, 0x71873054, 0xb6f2cf3b, 0x9f326442, 0xcb15a4cc, 0xb01a4504, 0xf1e47d8d, 0x844a1be5, 0xbae7dfdc, 0x42cbda70, 0xcd7dae0a, 0x57e85b7a, 0xd53f5af6, 0x20cf4d8c, 0xcea4d428, 0x79d130a4, 0x3486ebfb, 0x33d3cddc, 0x77853b53, 0x37effcb5, 0xc5068778, 0xe580b3e6, 0x4e68b8f4, 0xc5c8b37e, 0x0d809ea2, 0x398feb7c, 0x132a4f94, 0x43b7950e, 0x2fee7d1c, 0x223613bd, 0xdd06caa2, 0x37df932b, 0xc4248289, 0xacf3ebc3, 0x5715f6b7, 0xef3478dd, 0xf267616f, 0xc148cbe4, 0x9052815e, 0x5e410fab, 0xb48a2465, 0x2eda7fa4, 0xe87b40e4, 0xe98ea084, 0x5889e9e1, 0xefd390fc, 0xdd07d35b, 0xdb485694, 0x38d7e5b2, 0x57720101, 0x730edebc, 0x5b643113, 0x94917e4f, 0x503c2fba, 0x646f1282, 0x7523d24a, 0xe0779695, 0xf9c17a8f, 0x7a5b2121, 0xd187b896, 0x29263a4d, 0xba510cdf, 0x81f47c9f, 0xad1163ed, 0xea7b5965, 0x1a00726e, 0x11403092, 0x00da6d77, 0x4a0cdd61, 0xad1f4603, 0x605bdfb0, 0x9eedc364, 0x22ebe6a8, 0xcee7d28a, 0xa0e736a0, 0x5564a6b9, 0x10853209, 0xc7eb8f37, 0x2de705ca, 0x8951570f, 0xdf09822b, 0xbd691a6c, 0xaa12e4f2, 0x87451c0f, 0xe0f6a27a, 0x3ada4819, 0x4cf1764f, 0x0d771c2b, 0x67cdb156, 0x350d8384, 0x5938fa0f, 0x42399ef3, 0x36997b07, 0x0e84093d, 0x4aa93e61, 0x8360d87b, 0x1fa98b0c, 0x1149382c, 0xe97625a5, 0x0614d1b7, 0x0e25244b, 0x0c768347, 0x589e8d82, 0x0d2059d1, 0xa466bb1e, 0xf8da0a82, 0x04f19130, 0xba6e4ec0, 0x99265164, 0x1ee7230d, 0x50b2ad80, 0xeaee6801, 0x8db2a283, 0xea8bf59e, }; // https://github.com/openssl/openssl/blob/master/crypto/cast/c_skey.c #define CAST_exp(l,A,a,n) \ A[n/4]=l; \ a[n+3]=(l )&0xff; \ a[n+2]=(l>> 8)&0xff; \ a[n+1]=(l>>16)&0xff; \ a[n+0]=(l>>24)&0xff; #define S4 CAST_S_table4 #define S5 CAST_S_table5 #define S6 CAST_S_table6 #define S7 CAST_S_table7 void CAST_set_key(CAST_KEY *key, int len, const unsigned char *data) { CAST_LONG x[16]; CAST_LONG z[16]; CAST_LONG k[32]; CAST_LONG X[4], Z[4]; CAST_LONG l, *K; int i; for (i = 0; i < 16; i++) x[i] = 0; if (len > 16) len = 16; for (i = 0; i < len; i++) x[i] = data[i]; if (len <= 10) key->short_key = 1; else key->short_key = 0; K = &k[0]; X[0] = ((x[0] << 24) | (x[1] << 16) | (x[2] << 8) | x[3]) & 0xffffffffL; X[1] = ((x[4] << 24) | (x[5] << 16) | (x[6] << 8) | x[7]) & 0xffffffffL; X[2] = ((x[8] << 24) | (x[9] << 16) | (x[10] << 8) | x[11]) & 0xffffffffL; X[3] = ((x[12] << 24) | (x[13] << 16) | (x[14] << 8) | x[15]) & 0xffffffffL; for (;;) { l = X[0] ^ S4[x[13]] ^ S5[x[15]] ^ S6[x[12]] ^ S7[x[14]] ^ S6[x[8]]; CAST_exp(l, Z, z, 0); l = X[2] ^ S4[z[0]] ^ S5[z[2]] ^ S6[z[1]] ^ S7[z[3]] ^ S7[x[10]]; CAST_exp(l, Z, z, 4); l = X[3] ^ S4[z[7]] ^ S5[z[6]] ^ S6[z[5]] ^ S7[z[4]] ^ S4[x[9]]; CAST_exp(l, Z, z, 8); l = X[1] ^ S4[z[10]] ^ S5[z[9]] ^ S6[z[11]] ^ S7[z[8]] ^ S5[x[11]]; CAST_exp(l, Z, z, 12); K[0] = S4[z[8]] ^ S5[z[9]] ^ S6[z[7]] ^ S7[z[6]] ^ S4[z[2]]; K[1] = S4[z[10]] ^ S5[z[11]] ^ S6[z[5]] ^ S7[z[4]] ^ S5[z[6]]; K[2] = S4[z[12]] ^ S5[z[13]] ^ S6[z[3]] ^ S7[z[2]] ^ S6[z[9]]; K[3] = S4[z[14]] ^ S5[z[15]] ^ S6[z[1]] ^ S7[z[0]] ^ S7[z[12]]; l = Z[2] ^ S4[z[5]] ^ S5[z[7]] ^ S6[z[4]] ^ S7[z[6]] ^ S6[z[0]]; CAST_exp(l, X, x, 0); l = Z[0] ^ S4[x[0]] ^ S5[x[2]] ^ S6[x[1]] ^ S7[x[3]] ^ S7[z[2]]; CAST_exp(l, X, x, 4); l = Z[1] ^ S4[x[7]] ^ S5[x[6]] ^ S6[x[5]] ^ S7[x[4]] ^ S4[z[1]]; CAST_exp(l, X, x, 8); l = Z[3] ^ S4[x[10]] ^ S5[x[9]] ^ S6[x[11]] ^ S7[x[8]] ^ S5[z[3]]; CAST_exp(l, X, x, 12); K[4] = S4[x[3]] ^ S5[x[2]] ^ S6[x[12]] ^ S7[x[13]] ^ S4[x[8]]; K[5] = S4[x[1]] ^ S5[x[0]] ^ S6[x[14]] ^ S7[x[15]] ^ S5[x[13]]; K[6] = S4[x[7]] ^ S5[x[6]] ^ S6[x[8]] ^ S7[x[9]] ^ S6[x[3]]; K[7] = S4[x[5]] ^ S5[x[4]] ^ S6[x[10]] ^ S7[x[11]] ^ S7[x[7]]; l = X[0] ^ S4[x[13]] ^ S5[x[15]] ^ S6[x[12]] ^ S7[x[14]] ^ S6[x[8]]; CAST_exp(l, Z, z, 0); l = X[2] ^ S4[z[0]] ^ S5[z[2]] ^ S6[z[1]] ^ S7[z[3]] ^ S7[x[10]]; CAST_exp(l, Z, z, 4); l = X[3] ^ S4[z[7]] ^ S5[z[6]] ^ S6[z[5]] ^ S7[z[4]] ^ S4[x[9]]; CAST_exp(l, Z, z, 8); l = X[1] ^ S4[z[10]] ^ S5[z[9]] ^ S6[z[11]] ^ S7[z[8]] ^ S5[x[11]]; CAST_exp(l, Z, z, 12); K[8] = S4[z[3]] ^ S5[z[2]] ^ S6[z[12]] ^ S7[z[13]] ^ S4[z[9]]; K[9] = S4[z[1]] ^ S5[z[0]] ^ S6[z[14]] ^ S7[z[15]] ^ S5[z[12]]; K[10] = S4[z[7]] ^ S5[z[6]] ^ S6[z[8]] ^ S7[z[9]] ^ S6[z[2]]; K[11] = S4[z[5]] ^ S5[z[4]] ^ S6[z[10]] ^ S7[z[11]] ^ S7[z[6]]; l = Z[2] ^ S4[z[5]] ^ S5[z[7]] ^ S6[z[4]] ^ S7[z[6]] ^ S6[z[0]]; CAST_exp(l, X, x, 0); l = Z[0] ^ S4[x[0]] ^ S5[x[2]] ^ S6[x[1]] ^ S7[x[3]] ^ S7[z[2]]; CAST_exp(l, X, x, 4); l = Z[1] ^ S4[x[7]] ^ S5[x[6]] ^ S6[x[5]] ^ S7[x[4]] ^ S4[z[1]]; CAST_exp(l, X, x, 8); l = Z[3] ^ S4[x[10]] ^ S5[x[9]] ^ S6[x[11]] ^ S7[x[8]] ^ S5[z[3]]; CAST_exp(l, X, x, 12); K[12] = S4[x[8]] ^ S5[x[9]] ^ S6[x[7]] ^ S7[x[6]] ^ S4[x[3]]; K[13] = S4[x[10]] ^ S5[x[11]] ^ S6[x[5]] ^ S7[x[4]] ^ S5[x[7]]; K[14] = S4[x[12]] ^ S5[x[13]] ^ S6[x[3]] ^ S7[x[2]] ^ S6[x[8]]; K[15] = S4[x[14]] ^ S5[x[15]] ^ S6[x[1]] ^ S7[x[0]] ^ S7[x[13]]; if (K != k) break; K += 16; } for (i = 0; i < 16; i++) { key->data[i * 2] = k[i]; key->data[i * 2 + 1] = ((k[i + 16]) + 16) & 0x1f; } } // https://github.com/openssl/openssl/blob/master/crypto/cast/c_enc.c void CAST_encrypt(CAST_LONG *data, const CAST_KEY *key, int nr) { CAST_LONG l, r, t; const CAST_LONG *k; k = &(key->data[0]); l = data[0]; r = data[1]; E_CAST(0, k, l, r, +, ^, -); if (nr == 1) goto finish_enc; E_CAST(1, k, r, l, ^, -, +); if (nr == 2) goto finish_enc; E_CAST(2, k, l, r, -, +, ^); if (nr == 3) goto finish_enc; E_CAST(3, k, r, l, +, ^, -); if (nr == 4) goto finish_enc; E_CAST(4, k, l, r, ^, -, +); if (nr == 5) goto finish_enc; E_CAST(5, k, r, l, -, +, ^); if (nr == 6) goto finish_enc; E_CAST(6, k, l, r, +, ^, -); if (nr == 7) goto finish_enc; E_CAST(7, k, r, l, ^, -, +); if (nr == 8) goto finish_enc; E_CAST(8, k, l, r, -, +, ^); if (nr == 9) goto finish_enc; E_CAST(9, k, r, l, +, ^, -); if (nr == 10) goto finish_enc; E_CAST(10, k, l, r, ^, -, +); if (nr == 11) goto finish_enc; E_CAST(11, k, r, l, -, +, ^); if (nr == 12) goto finish_enc; if (!key->short_key) { E_CAST(12, k, l, r, +, ^, -); if (nr == 13) goto finish_enc; E_CAST(13, k, r, l, ^, -, +); if (nr == 14) goto finish_enc; E_CAST(14, k, l, r, -, +, ^); if (nr == 15) goto finish_enc; E_CAST(15, k, r, l, +, ^, -); } finish_enc: data[1] = l & 0xffffffffL; data[0] = r & 0xffffffffL; } void CAST_decrypt(CAST_LONG *data, const CAST_KEY *key, int nr) { CAST_LONG l, r, t; const CAST_LONG *k; k = &(key->data[0]); l = data[0]; r = data[1]; if (!key->short_key) { E_CAST(15, k, l, r, +, ^, -); if (nr == 1) goto finish_dec; E_CAST(14, k, r, l, -, +, ^); if (nr == 2) goto finish_dec; E_CAST(13, k, l, r, ^, -, +); if (nr == 3) goto finish_dec; E_CAST(12, k, r, l, +, ^, -); if (nr == 4) goto finish_dec; } E_CAST(11, k, l, r, -, +, ^); if (nr == 5) goto finish_dec; E_CAST(10, k, r, l, ^, -, +); if (nr == 6) goto finish_dec; E_CAST(9, k, l, r, +, ^, -); if (nr == 7) goto finish_dec; E_CAST(8, k, r, l, -, +, ^); if (nr == 8) goto finish_dec; E_CAST(7, k, l, r, ^, -, +); if (nr == 9) goto finish_dec; E_CAST(6, k, r, l, +, ^, -); if (nr == 10) goto finish_dec; E_CAST(5, k, l, r, -, +, ^); if (nr == 11) goto finish_dec; E_CAST(4, k, r, l, ^, -, +); if (nr == 12) goto finish_dec; E_CAST(3, k, l, r, +, ^, -); if (nr == 13) goto finish_dec; E_CAST(2, k, r, l, -, +, ^); if (nr == 14) goto finish_dec; E_CAST(1, k, l, r, ^, -, +); if (nr == 15) goto finish_dec; E_CAST(0, k, r, l, +, ^, -); finish_dec: data[1] = l & 0xffffffffL; data[0] = r & 0xffffffffL; } // https://github.com/openssl/openssl/blob/master/crypto/cast/c_ecb.c void CAST_ecb_encrypt(const unsigned char *in, unsigned char *out, const CAST_KEY *ks, int enc, int nr) { CAST_LONG l, d[2]; cast_n2l(in, l); d[0] = l; cast_n2l(in, l); d[1] = l; if (enc) CAST_encrypt(d, ks, nr); else CAST_decrypt(d, ks, nr); l = d[0]; cast_l2n(l, out); l = d[1]; cast_l2n(l, out); l = d[0] = d[1] = 0; } }}
45.014894
78
0.647776
ph4r05
588fed9981cff1a9b92be3f195b532e55571a118
1,964
hpp
C++
SDK/PUBG_CharacterCapture_Gamepad_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
7
2019-03-06T11:04:52.000Z
2019-07-10T20:00:51.000Z
SDK/PUBG_CharacterCapture_Gamepad_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
null
null
null
SDK/PUBG_CharacterCapture_Gamepad_parameters.hpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
10
2019-03-06T11:53:46.000Z
2021-02-18T14:01:11.000Z
#pragma once // PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_CharacterCapture_Gamepad_classes.hpp" namespace SDK { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.PrepassCharacterCapture struct UCharacterCapture_Gamepad_C_PrepassCharacterCapture_Params { class UWidget** BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.FinalizeCharacterCapture struct UCharacterCapture_Gamepad_C_FinalizeCharacterCapture_Params { }; // Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.SaveCharacterStudio struct UCharacterCapture_Gamepad_C_SaveCharacterStudio_Params { class AActor** Actor; // (Parm, ZeroConstructor, IsPlainOldData) }; // Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.InitCharacterCapture struct UCharacterCapture_Gamepad_C_InitCharacterCapture_Params { }; // Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.Construct struct UCharacterCapture_Gamepad_C_Construct_Params { }; // Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.Destruct struct UCharacterCapture_Gamepad_C_Destruct_Params { }; // Function CharacterCapture_Gamepad.CharacterCapture_Gamepad_C.ExecuteUbergraph_CharacterCapture_Gamepad struct UCharacterCapture_Gamepad_C_ExecuteUbergraph_CharacterCapture_Gamepad_Params { int* EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData) }; } #ifdef _MSC_VER #pragma pack(pop) #endif
32.733333
152
0.674134
realrespecter
5892bc7540710686cf938dafd30aa91ccb05abe4
7,783
inl
C++
include/hfsm2/detail/control.inl
hfsm/HFSM2
61ecd4d36508dcc348049ee72d51f6cfca095311
[ "MIT" ]
2
2021-01-26T02:50:53.000Z
2021-07-14T02:07:52.000Z
include/hfsm2/detail/control.inl
hfsm/HFSM2
61ecd4d36508dcc348049ee72d51f6cfca095311
[ "MIT" ]
1
2021-01-26T02:51:46.000Z
2021-01-26T06:06:31.000Z
include/hfsm2/detail/control.inl
hfsm/HFSM2
61ecd4d36508dcc348049ee72d51f6cfca095311
[ "MIT" ]
null
null
null
namespace hfsm2 { namespace detail { //////////////////////////////////////////////////////////////////////////////// template <typename TA> ControlT<TA>::Origin::Origin(ControlT& control_, const StateID id) : control{control_} , prevId(control._originId) { control.setOrigin(id); } //------------------------------------------------------------------------------ template <typename TA> ControlT<TA>::Origin::~Origin() { control.resetOrigin(prevId); } //////////////////////////////////////////////////////////////////////////////// template <typename TA> ControlT<TA>::Region::Region(ControlT& control_, const RegionID id, const StateID index, const LongIndex size) : control{control_} , prevId(control._regionId) , prevIndex(control._regionIndex) , prevSize(control._regionSize) { control.setRegion(id, index, size); } //------------------------------------------------------------------------------ template <typename TA> ControlT<TA>::Region::~Region() { control.resetRegion(prevId, prevIndex, prevSize); control._status.clear(); } //////////////////////////////////////////////////////////////////////////////// template <typename TA> void ControlT<TA>::setOrigin(const StateID id) { // TODO: see if this still can be used //HFSM_ASSERT(_regionId != INVALID_STATE_ID && _regionSize != INVALID_LONG_INDEX); //HFSM_ASSERT(_regionId < StateList::SIZE && _regionId + _regionSize <= StateList::SIZE); HFSM_ASSERT(id != INVALID_STATE_ID); _originId = id; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TA> void ControlT<TA>::resetOrigin(const StateID id) { // TODO: see if this still can be used //HFSM_ASSERT(_regionId != INVALID_STATE_ID && _regionSize != INVALID_LONG_INDEX); //HFSM_ASSERT(_regionId < StateList::SIZE && _regionId + _regionSize <= StateList::SIZE); HFSM_ASSERT(_originId != INVALID_STATE_ID); _originId = id; } //------------------------------------------------------------------------------ template <typename TA> void ControlT<TA>::setRegion(const RegionID id, const StateID index, const LongIndex size) { HFSM_ASSERT(index != INVALID_STATE_ID && size != INVALID_LONG_INDEX); if (_regionId == INVALID_REGION_ID) { HFSM_ASSERT(_regionIndex == INVALID_STATE_ID); HFSM_ASSERT(_regionSize == INVALID_LONG_INDEX); HFSM_ASSERT(index < StateList::SIZE && index + size <= StateList::SIZE); } else { HFSM_ASSERT(_regionIndex != INVALID_STATE_ID); HFSM_ASSERT(_regionSize != INVALID_LONG_INDEX); HFSM_ASSERT(_regionIndex <= index && index + size <= _regionIndex + _regionSize); } HFSM_ASSERT(_originId == INVALID_STATE_ID); _regionId = id; _regionIndex = index; _regionSize = size; } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TA> void ControlT<TA>::resetRegion(const RegionID id, const StateID index, const LongIndex size) { HFSM_ASSERT(_regionId != INVALID_REGION_ID); HFSM_ASSERT(_regionIndex != INVALID_STATE_ID); HFSM_ASSERT(_regionSize != INVALID_LONG_INDEX); if (index == INVALID_STATE_ID) HFSM_ASSERT(size == INVALID_LONG_INDEX); else HFSM_ASSERT(size != INVALID_LONG_INDEX); _regionId = id; _regionIndex = index; _regionSize = size; } //////////////////////////////////////////////////////////////////////////////// template <typename TA> FullControlT<TA>::Lock::Lock(FullControlT& control_) : control(!control_._locked ? &control_ : nullptr) { if (control) control->_locked = true; } //------------------------------------------------------------------------------ template <typename TA> FullControlT<TA>::Lock::~Lock() { if (control) control->_locked = false; } //////////////////////////////////////////////////////////////////////////////// template <typename TA> template <typename TState> Status FullControlT<TA>::updatePlan(TState& headState, const Status subStatus) { using State = TState; static constexpr StateID STATE_ID = State::STATE_ID; HFSM_ASSERT(subStatus); if (subStatus.failure) { headState.wrapPlanFailed(*this); return buildPlanStatus<State>(subStatus.outerTransition); } else if (subStatus.success) { if (Plan p = plan(_regionId)) { for (auto it = p.begin(); it; ++it) { if (isActive(it->origin) && _planData.tasksSuccesses[it->origin]) { Origin origin{*this, STATE_ID}; changeTo(it->destination); it.remove(); } else break; } return {false, false, subStatus.outerTransition}; } else { headState.wrapPlanSucceeded(*this); return buildPlanStatus<State>(subStatus.outerTransition); } } else return {false, false, subStatus.outerTransition}; } //------------------------------------------------------------------------------ template <typename TA> template <typename TState> Status FullControlT<TA>::buildPlanStatus(const bool outerTransition) { using State = TState; static constexpr StateID STATE_ID = State::STATE_ID; if (_status.failure) { _planData.tasksFailures[STATE_ID] = true; HFSM_LOG_PLAN_STATUS(_regionId, StatusEvent::FAILED); return {false, true, outerTransition}; } else if (_status.success) { _planData.tasksSuccesses[STATE_ID] = true; HFSM_LOG_PLAN_STATUS(_regionId, StatusEvent::SUCCEEDED); return {true, false, outerTransition}; } else return {false, false, outerTransition}; } //------------------------------------------------------------------------------ template <typename TA> void FullControlT<TA>::changeTo(const StateID stateId) { if (!_locked) { const Request request{Request::Type::RESTART, stateId}; _requests << request; if (_regionIndex + _regionSize <= stateId || stateId < _regionIndex) _status.outerTransition = true; #if defined HFSM_ENABLE_LOG_INTERFACE || defined HFSM_VERBOSE_DEBUG_LOG if (_logger) _logger->recordTransition(_originId, Transition::RESTART, stateId); #endif } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TA> void FullControlT<TA>::resume(const StateID stateId) { if (!_locked) { const Request request{Request::Type::RESUME, stateId}; _requests << request; if (_regionIndex + _regionSize <= stateId || stateId < _regionIndex) _status.outerTransition = true; #if defined HFSM_ENABLE_LOG_INTERFACE || defined HFSM_VERBOSE_DEBUG_LOG if (_logger) _logger->recordTransition(_originId, Transition::RESUME, stateId); #endif } } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TA> void FullControlT<TA>::schedule(const StateID stateId) { const Request transition{Request::Type::SCHEDULE, stateId}; _requests << transition; #if defined HFSM_ENABLE_LOG_INTERFACE || defined HFSM_VERBOSE_DEBUG_LOG if (_logger) _logger->recordTransition(_originId, Transition::SCHEDULE, stateId); #endif } //------------------------------------------------------------------------------ template <typename TA> void FullControlT<TA>::succeed() { _status.success = true; _planData.tasksSuccesses[_originId] = true; HFSM_LOG_TASK_STATUS(_regionId, _originId, StatusEvent::SUCCEEDED); } // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - template <typename TA> void FullControlT<TA>::fail() { _status.failure = true; _planData.tasksFailures [_originId] = true; HFSM_LOG_TASK_STATUS(_regionId, _originId, StatusEvent::FAILED); } //////////////////////////////////////////////////////////////////////////////// template <typename TA> void GuardControlT<TA>::cancelPendingChanges() { _cancelled = true; HFSM_LOG_CANCELLED_PENDING(_originId); } //////////////////////////////////////////////////////////////////////////////// } }
26.293919
90
0.583837
hfsm
58932de0acb7da802efbb453dc6e33b33665e5c7
446
cpp
C++
uva/10696 - f91.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
1
2021-11-22T02:26:43.000Z
2021-11-22T02:26:43.000Z
uva/10696 - f91.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
uva/10696 - f91.cpp
priojeetpriyom/competitive-programming
0024328972d4e14c04c0fd5d6dd3cdf131d84f9d
[ "MIT" ]
null
null
null
#include <cstdio> #include <iostream> using namespace std; int recursion(int f91) { if (f91>100) return f91-10; else return recursion(recursion((f91+11))); //else return recursion((f91+11)); } int main() { while(1) { int f91; scanf("%d",&f91); if (f91 == 0) break; else { printf("f91(%d) = %d\n",f91,recursion(f91)); } } return 0; }
17.84
56
0.484305
priojeetpriyom
58949d2c49e2184652171d477ca57d6392c0195d
970
cpp
C++
sample-code/CandC++/Class9and10_C++_OOAdv/src/implem/EmployeeExec.cpp
willrashley/course-adv-proglang
d91c7077cd35f4de4a6eff51c2febc6e9a8642e0
[ "MIT" ]
13
2022-01-13T13:46:00.000Z
2022-03-01T18:54:52.000Z
sample-code/CandC++/Class9and10_C++_OOAdv/src/implem/EmployeeExec.cpp
willrashley/course-adv-proglang
d91c7077cd35f4de4a6eff51c2febc6e9a8642e0
[ "MIT" ]
null
null
null
sample-code/CandC++/Class9and10_C++_OOAdv/src/implem/EmployeeExec.cpp
willrashley/course-adv-proglang
d91c7077cd35f4de4a6eff51c2febc6e9a8642e0
[ "MIT" ]
6
2022-02-01T13:51:47.000Z
2022-03-22T13:35:56.000Z
/* * EmployeeExec.cpp * * Created on: Feb 8, 2022 * Author: biplavs */ #include <iostream> using namespace std; #include <EmployeeExec.h> EmployeeExec::EmployeeExec() { // TODO Auto-generated constructor stub } // EmployeeExec with name, current salary and raise percentage EmployeeExec::EmployeeExec(string n, float c, float r) { name = n; current_salary = c; raise_in_percent = r; } EmployeeExec::~EmployeeExec() { // TODO Auto-generated destructor stub } // Show different with and without virtual qualifier void EmployeeExec::myprint () { cout<< "EmployeeExec: myprint derived class" <<endl; } void EmployeeExec::myshow() { cout<< "EmployeeExec: myshow derived class" <<endl; } void EmployeeExec::printSalary() { cout << "Salary of exec '" << name << "'is - " << endl; cout << "\t last - " << last_salary << endl; cout << "\t increment % - " << (raise_in_percent * 100) << endl; cout << "\t current - " << current_salary << endl; }
21.555556
65
0.668041
willrashley
589aaa6574fc575fbb734930ed87d51ef4205acd
703
hpp
C++
luanics/logging/Sink.hpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
luanics/logging/Sink.hpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
luanics/logging/Sink.hpp
luanics/cpp-illustrated
6049de2119a53d656a63b65d9441e680355ef196
[ "MIT" ]
null
null
null
#pragma once #include <memory> namespace luanics { namespace logging { class Record; /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// /// /// @class Sink /// /// @brief Back-end of logging framework. /// /// Consumes logging::Record handed off from Source. /// /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// class Sink { public: virtual void consume(std::unique_ptr<Record> record) = 0; virtual ~Sink() {} }; // class Sink } // namespace logging } // namespace luanics
23.433333
79
0.364154
luanics
589ada6488ccf3a4cad068d69d7bfcc61f91ab96
18,306
cpp
C++
Libraries/C++/CommonHelpers/v1.0/CommonHelpers/UnitTests/ThreadPool_UnitTest.cpp
davidbrownell/Common_cpp_Helpers
9e68c95873b5a4eff3a32b991d2c18dff176d6c9
[ "BSL-1.0" ]
null
null
null
Libraries/C++/CommonHelpers/v1.0/CommonHelpers/UnitTests/ThreadPool_UnitTest.cpp
davidbrownell/Common_cpp_Helpers
9e68c95873b5a4eff3a32b991d2c18dff176d6c9
[ "BSL-1.0" ]
null
null
null
Libraries/C++/CommonHelpers/v1.0/CommonHelpers/UnitTests/ThreadPool_UnitTest.cpp
davidbrownell/Common_cpp_Helpers
9e68c95873b5a4eff3a32b991d2c18dff176d6c9
[ "BSL-1.0" ]
null
null
null
///////////////////////////////////////////////////////////////////////// /// /// \file ThreadPool_UnitTest.cpp /// \brief Unit test for ThreadPool.h /// /// \author David Brownell <db@DavidBrownell.com> /// \date 2020-05-30 22:47:11 /// /// \note /// /// \bug /// ///////////////////////////////////////////////////////////////////////// /// /// \attention /// Copyright David Brownell 2020-21 /// 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. /// ///////////////////////////////////////////////////////////////////////// #define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file #define CATCH_CONFIG_ENABLE_BENCHMARKING #define CATCH_CONFIG_CONSOLE_WIDTH 200 #include "../ThreadPool.h" #include <catch.hpp> #include <optional> static unsigned long const ITERATIONS = 1; template <typename ThreadPoolT> void WorkTestImpl(size_t numItems, std::optional<std::uint64_t> expected=std::nullopt) { std::atomic_uint64_t total(0); { auto const work( [&total](size_t ctr) { total += ctr; } ); ThreadPoolT pool; for(size_t ctr = 0; ctr < numItems; ++ctr) { pool.enqueue( [&work, ctr](void) { work(ctr); } ); } } if(expected) { CHECK(total == *expected); } } TEST_CASE("Simple Work") { WorkTestImpl<CommonHelpers::SimpleThreadPool>(100, 4950); } TEST_CASE("Complex Work") { WorkTestImpl<CommonHelpers::ComplexThreadPool>(100, 4950); } #if (!defined DEBUG) TEST_CASE("Simple Work Benchmark", "[Benchmark]") { BENCHMARK("100") { WorkTestImpl<CommonHelpers::SimpleThreadPool>(100); }; BENCHMARK("1000") { WorkTestImpl<CommonHelpers::SimpleThreadPool>(1000); }; BENCHMARK("5000") { WorkTestImpl<CommonHelpers::SimpleThreadPool>(5000); }; BENCHMARK("10000") { WorkTestImpl<CommonHelpers::SimpleThreadPool>(10000); }; } TEST_CASE("Complex Work Benchmark", "[Benchmark]") { BENCHMARK("100") { WorkTestImpl<CommonHelpers::ComplexThreadPool>(100); }; BENCHMARK("1000") { WorkTestImpl<CommonHelpers::ComplexThreadPool>(1000); }; BENCHMARK("5000") { WorkTestImpl<CommonHelpers::ComplexThreadPool>(5000); }; BENCHMARK("10000") { WorkTestImpl<CommonHelpers::ComplexThreadPool>(10000); }; } #endif template <typename ThreadPoolT> void TaskTestImpl(size_t numItems) { std::vector<CommonHelpers::ThreadPoolFuture<size_t>> futures; futures.reserve(numItems); { auto const task( [](size_t ctr) { return ctr; } ); ThreadPoolT pool; while(futures.size() < numItems) { futures.emplace_back( pool.enqueue( [&task, ctr=futures.size()](void) -> size_t { return task(ctr); } ) ); } } // Tasks size_t expectedValue(0); for(auto & future : futures) { CHECK(future.get() == expectedValue); ++expectedValue; } } TEST_CASE("Simple Task") { TaskTestImpl<CommonHelpers::SimpleThreadPool>(100); } TEST_CASE("Complex Task") { TaskTestImpl<CommonHelpers::ComplexThreadPool>(100); } #if (!defined DEBUG) TEST_CASE("Simple Task Benchmark", "[Benchmark]") { BENCHMARK("100") { TaskTestImpl<CommonHelpers::SimpleThreadPool>(100); }; BENCHMARK("1000") { TaskTestImpl<CommonHelpers::SimpleThreadPool>(1000); }; BENCHMARK("5000") { TaskTestImpl<CommonHelpers::SimpleThreadPool>(5000); }; BENCHMARK("10000") { TaskTestImpl<CommonHelpers::SimpleThreadPool>(10000); }; } TEST_CASE("Complex Task Benchmark", "[Benchmark]") { BENCHMARK("100") { TaskTestImpl<CommonHelpers::ComplexThreadPool>(100); }; BENCHMARK("1000") { TaskTestImpl<CommonHelpers::ComplexThreadPool>(1000); }; BENCHMARK("5000") { TaskTestImpl<CommonHelpers::ComplexThreadPool>(5000); }; BENCHMARK("10000") { TaskTestImpl<CommonHelpers::ComplexThreadPool>(10000); }; } #endif TEST_CASE("Shutdown flag") { SECTION("Is Active") { std::optional<bool> isActive; { CommonHelpers::SimpleThreadPool pool(1); std::mutex m; std::condition_variable cv; pool.enqueue( [&m, &cv, &isActive](bool isActiveParam) { { std::unique_lock<std::decay_t<decltype(m)>> lock(m); UNUSED(lock); isActive = isActiveParam; } cv.notify_one(); } ); std::unique_lock<decltype(m)> lock(m); cv.wait( lock, [&isActive](void) { return static_cast<bool>(isActive); } ); } CHECK((isActive && *isActive)); } // I'm not quite sure how to test this; I know that the following code // does not work. #if 0 SECTION("Is Not Active") { std::condition_variable cv; std::optional<bool> isActive; { CommonHelpers::SimpleThreadPool pool(1); pool.enqueue( [](void) { using namespace std::chrono_literals; std::this_thread::sleep_for(0.5s); } ); // The pool should be stopping by the time this is executed // due to the sleep above. pool.enqueue( [&cv, &isActive](bool isActiveParam) { isActive = isActiveParam; cv.notify_one(); } ); } std::mutex m; std::unique_lock<decltype(m)> lock(m); cv.wait(lock); CHECK((isActive && isActive == false)); } #endif } TEST_CASE("Default Exception") { bool value(false); std::cerr << "The following exception description is expected...\n\n\n"; { CommonHelpers::SimpleThreadPool pool(1); pool.enqueue( [](void) { throw std::runtime_error("This is an exception handled by the default processor; it will not kill the thread"); } ); pool.enqueue( [&value](void) { value = true; } ); } std::cerr << "\n...no more exception descriptions are expected.\n\n"; CHECK(value); } TEST_CASE("Custom Exception Handler") { bool value(false); std::optional<size_t> exceptionThreadIndex; std::optional<std::string> exceptionDesc; { CommonHelpers::SimpleThreadPool pool( 1, [&exceptionThreadIndex, &exceptionDesc](size_t threadIndex) { exceptionThreadIndex = threadIndex; try { throw; } catch(std::exception const &ex) { exceptionDesc = ex.what(); } } ); pool.enqueue( [](void) { throw std::logic_error("My custom exception"); } ); pool.enqueue( [&value](void) { value = true; } ); } CHECK((exceptionThreadIndex && *exceptionThreadIndex == 0)); CHECK((exceptionDesc && *exceptionDesc == "My custom exception")); } template <typename PoolT> void ReentrantTasksTest(size_t numThreads) { int value(0); { PoolT pool(numThreads); pool.enqueue( [&value, &pool](void) { value = pool.enqueue( [](void) { return 10; } ).get(); } ); } CHECK(value == 10); } TEST_CASE("Reentrant Tasks") { SECTION("SimpleThreadPool") { ReentrantTasksTest<CommonHelpers::SimpleThreadPool>(1); ReentrantTasksTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { ReentrantTasksTest<CommonHelpers::ComplexThreadPool>(1); ReentrantTasksTest<CommonHelpers::ComplexThreadPool>(5); } } template <typename PoolT> void ParallelWorkSingleItemSingleArgTest(size_t numThreads) { PoolT pool(numThreads); int value(0); pool.parallel(10, [&value](int v) { value = v; }); CHECK(value == 10); } TEST_CASE("parallel work - single item - single arg") { SECTION("SimpleThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkSingleItemSingleArgTest<CommonHelpers::SimpleThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkSingleItemSingleArgTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkSingleItemSingleArgTest<CommonHelpers::ComplexThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkSingleItemSingleArgTest<CommonHelpers::ComplexThreadPool>(5); } } template <typename PoolT> void ParallelWorkSingleItemMultiArgTest(size_t numThreads) { PoolT pool(numThreads); int value(0); pool.parallel(10, [&value](bool, int v) { value = v; }); CHECK(value == 10); } TEST_CASE("parallel work - single item - multi arg") { SECTION("SimpleThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkSingleItemMultiArgTest<CommonHelpers::SimpleThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkSingleItemMultiArgTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkSingleItemMultiArgTest<CommonHelpers::ComplexThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkSingleItemMultiArgTest<CommonHelpers::ComplexThreadPool>(5); } } template <typename PoolT> void ParallelTaskSingleItemSingleArgTest(size_t numThreads) { PoolT pool(numThreads); CHECK(pool.parallel(10, [](int v) { return v; }) == 10); } TEST_CASE("parallel task - single item - single arg") { SECTION("SimpleThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskSingleItemSingleArgTest<CommonHelpers::SimpleThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskSingleItemSingleArgTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskSingleItemSingleArgTest<CommonHelpers::ComplexThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskSingleItemSingleArgTest<CommonHelpers::ComplexThreadPool>(5); } } template <typename PoolT> void ParallelTaskSingleItemMultiArgTest(size_t numThreads) { PoolT pool(numThreads); CHECK(pool.parallel(10, [](bool, int v) { return v; }) == 10); } TEST_CASE("parallel task - single item - multi arg") { SECTION("SimpleThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskSingleItemMultiArgTest<CommonHelpers::SimpleThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskSingleItemMultiArgTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskSingleItemMultiArgTest<CommonHelpers::ComplexThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskSingleItemMultiArgTest<CommonHelpers::ComplexThreadPool>(5); } } template <typename PoolT> void ParallelWorkVectorSingleArgTest(size_t numThreads) { PoolT pool(numThreads); std::vector<int> v; v.resize(3); std::vector<int> const expected{10, 20, 30}; pool.parallel( std::vector<int>{10, 20, 30}, [&v](int value) { size_t index( [&value](void) -> size_t { if(value == 10) return 0; if(value == 20) return 1; if(value == 30) return 2; return 3; }() ); v[index] = value; } ); CHECK(v == expected); } TEST_CASE("parallel work - vector - single arg") { SECTION("SimpleThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkVectorSingleArgTest<CommonHelpers::SimpleThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkVectorSingleArgTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkVectorSingleArgTest<CommonHelpers::ComplexThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkVectorSingleArgTest<CommonHelpers::ComplexThreadPool>(5); } } template <typename PoolT> void ParallelWorkVectorMultiArgTest(size_t numThreads) { PoolT pool(numThreads); std::vector<int> v; v.resize(3); std::vector<int> const expected{10, 20, 30}; pool.parallel( std::vector<int>{10, 20, 30}, [&v](bool, int value) { size_t index( [&value](void) -> size_t { if(value == 10) return 0; if(value == 20) return 1; if(value == 30) return 2; return 3; }() ); v[index] = value; } ); CHECK(v == expected); } TEST_CASE("parallel work - vector - multi arg") { SECTION("SimpleThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkVectorMultiArgTest<CommonHelpers::SimpleThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkVectorMultiArgTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkVectorMultiArgTest<CommonHelpers::ComplexThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelWorkVectorMultiArgTest<CommonHelpers::ComplexThreadPool>(5); } } template <typename PoolT> void ParallelTaskVectorSingleArgTest(size_t numThreads) { PoolT pool(numThreads); CHECK( pool.parallel( std::vector<int>{10, 20, 30}, [](int value) { return value; } ) == std::vector<int>{10, 20, 30} ); } TEST_CASE("parallel task - vector - single arg") { SECTION("SimpleThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskVectorSingleArgTest<CommonHelpers::SimpleThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskVectorSingleArgTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskVectorSingleArgTest<CommonHelpers::ComplexThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskVectorSingleArgTest<CommonHelpers::ComplexThreadPool>(5); } } template <typename PoolT> void ParallelTaskVectorMultiArgTest(size_t numThreads) { PoolT pool(numThreads); CHECK( pool.parallel( std::vector<int>{10, 20, 30}, [](bool, int value) { return value; } ) == std::vector<int>{10, 20, 30} ); } TEST_CASE("parallel task - vector - multi arg") { SECTION("SimpleThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskVectorMultiArgTest<CommonHelpers::SimpleThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskVectorMultiArgTest<CommonHelpers::SimpleThreadPool>(5); } SECTION("ComplexThreadPool") { for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskVectorMultiArgTest<CommonHelpers::ComplexThreadPool>(1); for(unsigned long ctr = 0; ctr < ITERATIONS; ctr++) ParallelTaskVectorMultiArgTest<CommonHelpers::ComplexThreadPool>(5); } }
32.4
128
0.532612
davidbrownell
589cad045e88539f85139d7bfc000dbfec36cfa7
2,049
cpp
C++
tests/engine/FilterGroup/tst_FilterGroupTest.cpp
tomvodi/QTail
2e7acf31664969e6890edede6b60e02b20f33eb2
[ "MIT" ]
1
2017-04-29T12:17:59.000Z
2017-04-29T12:17:59.000Z
tests/engine/FilterGroup/tst_FilterGroupTest.cpp
tomvodi/QTail
2e7acf31664969e6890edede6b60e02b20f33eb2
[ "MIT" ]
25
2016-06-11T17:35:42.000Z
2017-07-19T04:19:08.000Z
tests/engine/FilterGroup/tst_FilterGroupTest.cpp
tomvodi/QTail
2e7acf31664969e6890edede6b60e02b20f33eb2
[ "MIT" ]
null
null
null
/** * @author Thomas Baumann <teebaum@ymail.com> * * @section LICENSE * See LICENSE for more informations. * */ #include <QString> #include <QtTest> #include <QCoreApplication> #include <include/FilterGroup.h> class FilterGroupTest : public QObject { Q_OBJECT public: FilterGroupTest(); private Q_SLOTS: void initTestCase(); void cleanupTestCase(); void testStringConstructor(); void testSetGetName(); void testSetGetFilterRules(); void testAppendFilterRule(); void testToAndFromJson(); }; FilterGroupTest::FilterGroupTest() { } void FilterGroupTest::initTestCase() { } void FilterGroupTest::cleanupTestCase() { } void FilterGroupTest::testStringConstructor() { QString testGroupName("Testgroup"); FilterGroup group(testGroupName); QVERIFY2(group.name() == testGroupName, "Failed setting groupname through constructor"); } void FilterGroupTest::testSetGetName() { QString testGroupName("Testgroup"); FilterGroup group; group.setName(testGroupName); QVERIFY2(group.name() == testGroupName, "Failed setting/getting groupname"); } void FilterGroupTest::testSetGetFilterRules() { FilterRule rule1("Rule 1"); FilterRule rule2("Rule 2"); QList<FilterRule> ruleList; ruleList << rule1 << rule2; FilterGroup group; group.setFilterRules(ruleList); QVERIFY2(group.filterRules() == ruleList, "Failed set/get rules"); } void FilterGroupTest::testAppendFilterRule() { FilterRule rule("Rule 1"); FilterGroup group; group.addFilterRule(rule); QVERIFY2(group.filterRules().contains(rule), "Failed add rule"); } void FilterGroupTest::testToAndFromJson() { FilterRule rule("Rule 1"); FilterGroup group; group.setName("Test group"); group.addFilterRule(rule); QJsonObject groupJson = group.toJson(); QVERIFY2(! groupJson.isEmpty(), "Empty json returned"); FilterGroup group2; group2.fromJson(groupJson); QVERIFY2(group == group2, "Failed convert to and from json"); } QTEST_MAIN(FilterGroupTest) #include "tst_FilterGroupTest.moc"
20.287129
91
0.724744
tomvodi
589d5cdc662c53a95fb4d11936b5347906dc7248
412
cpp
C++
HDU/20/hdu2072.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
1
2017-08-19T16:02:15.000Z
2017-08-19T16:02:15.000Z
HDU/20/hdu2072.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
null
null
null
HDU/20/hdu2072.cpp
bilibiliShen/CodeBank
49a69b2b2c3603bf105140a9d924946ed3193457
[ "MIT" ]
1
2018-01-05T23:37:23.000Z
2018-01-05T23:37:23.000Z
//利用STL #include<set> 和 #include<sstream> 问题就简单多了 #include <iostream> #include <sstream> #include<string> #include<set> using namespace std; int main() { set <string> ans; stringstream temp; string s; while( getline(cin,s) && s!="#") { stringstream temp(s); ans.clear(); while(temp>>s) ans.insert(s); cout<<ans.size()<<endl; } return 0; }
19.619048
51
0.563107
bilibiliShen
58a02e53d9c457ea10ac2c87de94d6fa4b75b174
905
cc
C++
mycode/cpp/thread/oo_threadpool/main.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
2
2020-12-09T09:55:51.000Z
2021-01-08T11:38:22.000Z
mycode/cpp/thread/oo_threadpool/main.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
null
null
null
mycode/cpp/thread/oo_threadpool/main.cc
stdbilly/CS_Note
a8a87e135a525d53c283a4c70fb942c9ca59a758
[ "MIT" ]
null
null
null
#include "Threadpool.h" #include "Task.h" #include <unistd.h> #include <stdlib.h> #include <time.h> #include <iostream> #include <memory> using std::unique_ptr; using std::cout; using std::endl; using namespace wd; class MyTask : public Task { public: void process() override { ::srand(::clock()); //::srand(::time(nullptr)); int num = rand() % 100; cout << "sub thread " << pthread_self() << " num = " << num << endl; //sleep(1); } }; int main() { Threadpool threadpool(4, 10); threadpool.start(); unique_ptr<Task> task(new MyTask()); //Task* task = new MyTask(); int cnt = 20; while(cnt--) { threadpool.addTask(task.get()); cout << "main thread :cnt = " << cnt << endl; } threadpool.stop(); //这里要显式的stop,虽然析构函数也会调用stop(),但是析构函数是在mian()之后执行的, //此时task对象已经被销毁了,子线程无法正常执行,core dump return 0; }
22.073171
76
0.583425
stdbilly
58a08ac37d6c4e75a17b064bbddea071e696b1d3
3,334
cpp
C++
core/test/matrix/identity.cpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
core/test/matrix/identity.cpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
core/test/matrix/identity.cpp
flipflapflop/ginkgo
876234e142a0f5bb2a85bb1dd2cc488c3c5d6206
[ "BSD-3-Clause" ]
null
null
null
/*******************************<GINKGO LICENSE>****************************** Copyright (c) 2017-2019, the Ginkgo authors 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 its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************<GINKGO LICENSE>*******************************/ #include <ginkgo/core/matrix/identity.hpp> #include <gtest/gtest.h> #include <core/test/utils/assertions.hpp> #include <ginkgo/core/matrix/dense.hpp> namespace { class Identity : public ::testing::Test { protected: using Id = gko::matrix::Identity<>; using Vec = gko::matrix::Dense<>; Identity() : exec(gko::ReferenceExecutor::create()) {} std::shared_ptr<const gko::Executor> exec; }; TEST_F(Identity, CanBeEmpty) { auto empty = Id::create(exec); ASSERT_EQ(empty->get_size(), gko::dim<2>(0, 0)); } TEST_F(Identity, CanBeConstructedWithSize) { auto identity = Id::create(exec, 5); ASSERT_EQ(identity->get_size(), gko::dim<2>(5, 5)); } TEST_F(Identity, AppliesToVector) { auto identity = Id::create(exec, 3); auto x = Vec::create(exec, gko::dim<2>{3, 1}); auto b = gko::initialize<Vec>({2.0, 1.0, 5.0}, exec); identity->apply(b.get(), x.get()); GKO_ASSERT_MTX_NEAR(x, l({2.0, 1.0, 5.0}), 0.0); } TEST_F(Identity, AppliesToMultipleVectors) { auto identity = Id::create(exec, 3); auto x = Vec::create(exec, gko::dim<2>{3, 2}, 3); auto b = gko::initialize<Vec>(3, {{2.0, 3.0}, {1.0, 2.0}, {5.0, -1.0}}, exec); identity->apply(b.get(), x.get()); GKO_ASSERT_MTX_NEAR(x, l({{2.0, 3.0}, {1.0, 2.0}, {5.0, -1.0}}), 0.0); } TEST(IdentityFactory, CanGenerateIdentityMatrix) { auto exec = gko::ReferenceExecutor::create(); auto id_factory = gko::matrix::IdentityFactory<>::create(exec); auto mtx = gko::matrix::Dense<>::create(exec, gko::dim<2>{5, 5}); auto id = id_factory->generate(std::move(mtx)); ASSERT_EQ(id->get_size(), gko::dim<2>(5, 5)); } } // namespace
30.587156
78
0.685363
flipflapflop
58a1b176e88d49662c6fe422e4baf4be7a172899
5,945
cpp
C++
qtacrylicmainwindow.cpp
kollya/framelesshelper
921ce2b474e4a0dcba340ced68a6933f60199f95
[ "MIT" ]
null
null
null
qtacrylicmainwindow.cpp
kollya/framelesshelper
921ce2b474e4a0dcba340ced68a6933f60199f95
[ "MIT" ]
null
null
null
qtacrylicmainwindow.cpp
kollya/framelesshelper
921ce2b474e4a0dcba340ced68a6933f60199f95
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (C) 2021 by wangwenx190 (Yuhang Zhao) * * 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 "qtacrylicmainwindow.h" #include "utilities.h" #include "framelesswindowsmanager.h" #include <QtCore/qdebug.h> #include <QtGui/qevent.h> #include <QtGui/qpainter.h> QtAcrylicMainWindow::QtAcrylicMainWindow(QWidget *parent, Qt::WindowFlags flags) : QMainWindow(parent, flags) {} QtAcrylicMainWindow::~QtAcrylicMainWindow() = default; QColor QtAcrylicMainWindow::tintColor() const { const QColor color = m_acrylicHelper.getTintColor(); if (color.isValid() && (color != Qt::transparent)) { return color; } else { return palette().color(backgroundRole()); } } void QtAcrylicMainWindow::setTintColor(const QColor &value) { if (!value.isValid()) { qWarning() << "Tint color not valid."; return; } if (m_acrylicHelper.getTintColor() != value) { m_acrylicHelper.setTintColor(value); QPalette pal = palette(); pal.setColor(backgroundRole(), m_acrylicHelper.getTintColor()); setPalette(pal); //m_acrylicHelper.updateAcrylicBrush(tintColor()); update(); Q_EMIT tintColorChanged(); } } qreal QtAcrylicMainWindow::tintOpacity() const { return m_acrylicHelper.getTintOpacity(); } void QtAcrylicMainWindow::setTintOpacity(const qreal value) { if (m_acrylicHelper.getTintOpacity() != value) { m_acrylicHelper.setTintOpacity(value); m_acrylicHelper.updateAcrylicBrush(tintColor()); update(); Q_EMIT tintOpacityChanged(); } } qreal QtAcrylicMainWindow::noiseOpacity() const { return m_acrylicHelper.getNoiseOpacity(); } void QtAcrylicMainWindow::setNoiseOpacity(const qreal value) { if (m_acrylicHelper.getNoiseOpacity() != value) { m_acrylicHelper.setNoiseOpacity(value); m_acrylicHelper.updateAcrylicBrush(tintColor()); update(); Q_EMIT noiseOpacityChanged(); } } bool QtAcrylicMainWindow::frameVisible() const { return m_frameVisible; } void QtAcrylicMainWindow::setFrameVisible(const bool value) { if (m_frameVisible != value) { m_frameVisible = value; update(); Q_EMIT frameVisibleChanged(); } } QColor QtAcrylicMainWindow::frameColor() const { return m_acrylicHelper.getFrameColor(); } void QtAcrylicMainWindow::setFrameColor(const QColor &value) { if (m_acrylicHelper.getFrameColor() != value) { m_acrylicHelper.setFrameColor(value); update(); Q_EMIT frameColorChanged(); } } qreal QtAcrylicMainWindow::frameThickness() const { return m_acrylicHelper.getFrameThickness(); } void QtAcrylicMainWindow::setFrameThickness(const qreal value) { if (m_acrylicHelper.getFrameThickness() != value) { m_acrylicHelper.setFrameThickness(value); update(); Q_EMIT frameThicknessChanged(); } } bool QtAcrylicMainWindow::acrylicEnabled() const { return m_acrylicEnabled; } void QtAcrylicMainWindow::setAcrylicEnabled(const bool value) { if (m_acrylicEnabled != value) { m_acrylicEnabled = value; if (m_inited) { Utilities::setBlurEffectEnabled(windowHandle(), m_acrylicEnabled); } setAutoFillBackground(!m_acrylicEnabled); setAttribute(Qt::WA_NoSystemBackground, m_acrylicEnabled); setAttribute(Qt::WA_OpaquePaintEvent, m_acrylicEnabled); setBackgroundRole(m_acrylicEnabled ? QPalette::Base : QPalette::Window); update(); Q_EMIT acrylicEnabledChanged(); } } void QtAcrylicMainWindow::showEvent(QShowEvent *event) { QMainWindow::showEvent(event); updateContentMargin(); if (!m_inited) { FramelessWindowsManager::addWindow(windowHandle()); m_acrylicHelper.install(windowHandle()); m_acrylicHelper.updateAcrylicBrush(tintColor()); connect(&m_acrylicHelper, &QtAcrylicEffectHelper::needsRepaint, this, qOverload<>(&QtAcrylicMainWindow::update)); m_inited = true; } } void QtAcrylicMainWindow::updateContentMargin() { const qreal m = isMaximized() ? 0.0 : 1.0 / devicePixelRatioF(); setContentsMargins(m, m, m, m); } void QtAcrylicMainWindow::paintEvent(QPaintEvent *event) { QPainter painter(this); const QRect rect = {0, 0, width(), height()}; if (acrylicEnabled()) { m_acrylicHelper.paintWindowBackground(&painter, rect); } if (frameVisible()) { m_acrylicHelper.paintWindowFrame(&painter, rect); } QMainWindow::paintEvent(event); } void QtAcrylicMainWindow::changeEvent(QEvent *event) { if( event->type()==QEvent::WindowStateChange ) { updateContentMargin(); Q_EMIT windowStateChanged(); } QMainWindow::changeEvent(event); } void QtAcrylicMainWindow::displaySystemMenu() { #ifdef WIN32 Utilities::displaySystemMenu(windowHandle()); #endif }
29.430693
121
0.704458
kollya
58a9f25c0802a949b51582de3a1b3777c8af4c0e
466
cpp
C++
Functions/perimeter.cpp
pepm99/School-C-
2d4b23d16a3b2fd0e589686db7d02cf6a647e447
[ "MIT" ]
null
null
null
Functions/perimeter.cpp
pepm99/School-C-
2d4b23d16a3b2fd0e589686db7d02cf6a647e447
[ "MIT" ]
null
null
null
Functions/perimeter.cpp
pepm99/School-C-
2d4b23d16a3b2fd0e589686db7d02cf6a647e447
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; double perimeter (double a, double b) { double p = 2*a+2*b; return p; } double lice(double a, double b) { double s = a*b; return s; } int main() { double a,b,a1,b1; cout<<"a="; cin>>a; cout<<"b="; cin>>b; cout<<"a1="; cin>>a1; cout<<"a1="; cin>>a1; cout<<"P="<<perimeter(a,b)-perimeter(a1,b1); cout<<'\n'; cout<<"S="<<lice(a,b)-lice(a1,b1); return 0; }
14.5625
45
0.51073
pepm99
58aa9e5187ab209f628b83120cb10779917599b5
1,472
cpp
C++
Parciales/examen_2/P7_PlanetsKingdoms.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
Parciales/examen_2/P7_PlanetsKingdoms.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
Parciales/examen_2/P7_PlanetsKingdoms.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // https://cses.fi/problemset/task/1683 typedef int long long ll; typedef vector<ll> vl; typedef vector<vector<ll>> vll; typedef map<ll, bool> mpb; typedef vector<bool> vb; void DFS(vll &adj, mpb &visited, vl &a, ll x) { visited[x] = true; for (ll i : adj[x]){ if (!visited[i]) DFS(adj, visited, a, i); } a.push_back(x); } void Fx(vl &b, vll &reinos, ll x, ll y) { b[x] = y; for (ll i : reinos[x]){ if (b[i] == -1) Fx(b, reinos, i, y); } } void solve(ll n, mpb &visited, vl &a, vl &b, vl &c, vll &adj, vll &reinos) { for (ll i = 0; i < n; ++i){ if (!visited[i]) DFS(adj, visited, a, i); } reverse(begin(a), end(a)); for (ll i : a){ if (b[i] == -1){ Fx(b, reinos, i, i); c.push_back(i); } } } int main(int argc, char const *argv[]) { ll n, m, x, y; cin >> n >> m; vll adj, reinos; vl a, b = vl(n, -1), c; mpb visited; adj.resize(n), reinos.resize(n); while (m--){ cin >> x >> y; --x, --y; adj[x].push_back(y); reinos[y].push_back(x); } solve(n, visited, a, b, c, adj, reinos); int ID[200000]{}; int sol = 0; for (size_t i = 0; i < n; ++i){ if (!ID[b[i]]) ID[b[i]] = ++sol; } cout << sol << '\n'; for (size_t i = 0; i < n; ++i){ cout << ID[b[i]] << " \n"[i == n - 1]; } return 0; }
18.871795
69
0.463995
luismoroco
58ac9941c5a1a39438fe02513d50b423713874f9
3,807
cpp
C++
src/systemc/tests/systemc/misc/stars/star127536/test.cpp
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
765
2015-01-14T16:17:04.000Z
2022-03-28T07:46:28.000Z
src/systemc/tests/systemc/misc/stars/star127536/test.cpp
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
148
2018-07-20T00:58:36.000Z
2021-11-16T01:52:33.000Z
src/systemc/tests/systemc/misc/stars/star127536/test.cpp
hyu-iot/gem5
aeccc8bd8e9a86f96fc7a6f40d978f8494337fc5
[ "BSD-3-Clause" ]
807
2015-01-06T09:55:38.000Z
2022-03-30T10:23:36.000Z
/***************************************************************************** Licensed to Accellera Systems Initiative Inc. (Accellera) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. Accellera licenses this file to you 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. *****************************************************************************/ /***************************************************************************** test.cpp -- Original Author: Martin Janssen, Synopsys, Inc., 2002-02-15 *****************************************************************************/ /***************************************************************************** MODIFICATION LOG - modifiers, enter your name, affiliation, date and changes you are making here. Name, Affiliation, Date: Description of Modification: *****************************************************************************/ /* Hello, sorry for asking again about the sc_start/sc_cycle problem but... The following program causes trouble (SystemC V2.0b2): */ #include "systemc.h" SC_MODULE(createpulse) { public: sc_in_clk i_clk; private: int trigger1,trigger2; void pulse() { while(true) { wait(); cout << sc_time_stamp() << ": trigger1 : " <<trigger1++ << endl; wait(1,SC_NS); cout << sc_time_stamp() << ": trigger2 : " <<trigger2++ << endl; } } public: SC_CTOR(createpulse) { SC_THREAD(pulse); sensitive << i_clk.pos(); trigger1 = 0; trigger2 = 0; } }; // createpulse dut("testpulse"); int sc_main(int argc, char *argv[]) { int i; sc_trace_file *tf; sc_signal<bool> clk1; sc_set_time_resolution(1,SC_NS); sc_set_default_time_unit(1,SC_NS); // sc_clock dummy( "dummy", 2, SC_NS ); createpulse dut("testpulse"); dut.i_clk(clk1); // see other posting tf=sc_create_vcd_trace_file("vcdtrace"); sc_trace(tf,clk1,"clock"); // sc_initialize(); // comment out for sc_start version for(i=0;i<10;i++) { clk1=0; // sc_cycle(5,SC_NS); // change to sc_start sc_start( 5, SC_NS ); clk1=1; // sc_cycle(5,SC_NS); // change to sc_start sc_start( 5, SC_NS ); } cout << "finishing at " << sc_time_stamp() << endl; sc_close_vcd_trace_file(tf); return(EXIT_SUCCESS); } /* With this programm, the clk1 is generated as can be seen in the trace file. But the pulse procedure gets stuck in the second wait function. With SystemC V1.x, this worked with replacing sc_cycle with sc_start (and removing the sc_initialize), however calling sc_start multiple was an undocumented feature and it doesnt work in V2.0b2 (no clk is generated). I know that this problem can be solved by creating an own clock generation module using wait()s and just a single sc_start in sc_main, but IMHO sometimes it is desirable to do it the way shown above. So is this possible with SystemC V2.0 ? Regards, Sven Heithecker -- Sven Heithecker IDA, Hans-Sommer-Str. 66 Technical University of Braunschweig 38106 Braunschweig Tel. +49-(0)531-391-3751(voice)/4587(fax) Germany http://www.ida.ing.tu-bs.de/~svenh heithecker@ida.ing.tu-bs.de */
29.284615
79
0.605989
hyu-iot
58ad2d4dc1277ae1c5d9ab3850780c9bf8bbe509
497
cpp
C++
Project.cpp
SanteriHetekivi/CompositeModelAssignment
6856fef2e105ce889ab09b7e7eefdc476452a771
[ "Apache-2.0" ]
null
null
null
Project.cpp
SanteriHetekivi/CompositeModelAssignment
6856fef2e105ce889ab09b7e7eefdc476452a771
[ "Apache-2.0" ]
null
null
null
Project.cpp
SanteriHetekivi/CompositeModelAssignment
6856fef2e105ce889ab09b7e7eefdc476452a771
[ "Apache-2.0" ]
null
null
null
#include "Project.h" Project::Project(int id, std::string name) : Base(id, name) { this->_type = "Project"; this->_childen_json_name = "employees"; } Project::Project(nlohmann::json base) : Base(base) { this->_type = "Project"; this->_childen_json_name = "employees"; this->addChildren(base); } void Project::addEmployee(Employee employee) { this->addChild(employee); } void Project::callAddChild(nlohmann::json child) { this->addEmployee(Employee(child)); } Project::~Project() { }
16.032258
59
0.700201
SanteriHetekivi
58ad638394e98a88fb6bb66d9e7b9d0ce81bb78a
6,994
cpp
C++
breeze/cryptography/brz/sha512.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
1
2021-04-03T22:35:52.000Z
2021-04-03T22:35:52.000Z
breeze/cryptography/brz/sha512.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
null
null
null
breeze/cryptography/brz/sha512.cpp
gennaroprota/breeze
f1dfd7154222ae358f5ece936c2897a3ae110003
[ "BSD-3-Clause" ]
1
2021-10-01T04:26:48.000Z
2021-10-01T04:26:48.000Z
// =========================================================================== // Copyright 2006-2007 Gennaro Prota // // Licensed under the 3-Clause BSD License. // (See accompanying file 3_CLAUSE_BSD_LICENSE.txt or // <https://opensource.org/licenses/BSD-3-Clause>.) // ___________________________________________________________________________ #include "breeze/cryptography/sha512.hpp" #include "breeze/cryptography/private/sha_common.tpp" #include "breeze/iteration/begin_end.hpp" #include <algorithm> #include <functional> namespace breeze_ns { namespace { typedef sha512_engine::word_type word_type ; using sha_common_private::ror ; word_type const k[] = { // These words represent the first sixty-four bits of the // fractional parts of the cube roots of the first eighty prime // numbers. // ----------------------------------------------------------------------- 0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL, 0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL, 0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL, 0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL, 0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL, 0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL, 0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL, 0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL, 0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL, 0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL, 0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL, 0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL, 0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL, 0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL, 0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL, 0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL, 0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL } ; word_type big_sigma0( word_type x ) { return ror< 28 >( x ) ^ ror< 34 >( x ) ^ ror< 39 >( x ) ; } word_type big_sigma1( word_type x ) { return ror< 14 >( x ) ^ ror< 18 >( x ) ^ ror< 41 >( x ) ; } word_type sigma0( word_type x ) { return ror< 1 >( x ) ^ ror< 8 >( x ) ^ ( x >> 7 ) ; } word_type sigma1( word_type x ) { return ror< 19 >( x ) ^ ror< 61 >( x ) ^ ( x >> 6 ) ; } } void sha512_engine::init_state( state_type & state ) { // These words are obtained by taking the first sixty-four bits // of the fractional parts of the square roots of the first // eight prime numbers. // ----------------------------------------------------------------------- state[ 0 ] = 0x6a09e667f3bcc908ULL ; state[ 1 ] = 0xbb67ae8584caa73bULL ; state[ 2 ] = 0x3c6ef372fe94f82bULL ; state[ 3 ] = 0xa54ff53a5f1d36f1ULL ; state[ 4 ] = 0x510e527fade682d1ULL ; state[ 5 ] = 0x9b05688c2b3e6c1fULL ; state[ 6 ] = 0x1f83d9abfb41bd6bULL ; state[ 7 ] = 0x5be0cd19137e2179ULL ; } void sha512_engine::process_block( block_type const & block, state_type & state ) { using sha_common_private::ch ; using sha_common_private::maj ; // Create an 80-word "schedule" from the message block. // ----------------------------------------------------------------------- int const count = 80 ; word_type sched[ count ] ; std::copy( breeze::cbegin( block ), breeze::cend( block ), breeze::begin( sched ) ) ; for ( int i = 16 ; i < count ; ++ i ) { sched[ i ] = sigma1( sched[ i - 2 ] ) + sched[ i - 7 ] + sigma0( sched[ i - 15 ] ) + sched[ i - 16 ] ; } word_type working[ 8 ] ; std::copy( breeze::cbegin( state ), breeze::cend( state ), breeze::begin( working ) ) ; // 0 1 2 3 4 5 6 7 // a b c d e f g h // ----------------------------------------------------------------------- { word_type t[ 2 ] ; for ( int i = 0 ; i < count ; ++ i ) { t[ 0 ] = working[ 7 ] + big_sigma1( working[ 4 ] ) + ch( working[ 4 ], working[ 5 ], working[ 6 ] ) + k[ i ] + sched[ i ] ; t[ 1 ] = big_sigma0( working[ 0 ] ) + maj( working[ 0 ], working[ 1 ], working[ 2 ] ) ; working[ 7 ] = working[ 6 ] ; working[ 6 ] = working[ 5 ] ; working[ 5 ] = working[ 4 ] ; working[ 4 ] = working[ 3 ] + t[ 0 ] ; working[ 3 ] = working[ 2 ] ; working[ 2 ] = working[ 1 ] ; working[ 1 ] = working[ 0 ] ; working[ 0 ] = t[ 0 ] + t[ 1 ] ; } } std::transform( breeze::cbegin( state ), breeze::cend( state ), breeze::cbegin( working ), breeze::begin( state ), std::plus< word_type >() ) ; } void sha512_224_engine::init_state( state_type & state ) { state[ 0 ] = 0x8c3d37c819544da2ULL ; state[ 1 ] = 0x73e1996689dcd4d6ULL ; state[ 2 ] = 0x1dfab7ae32ff9c82ULL ; state[ 3 ] = 0x679dd514582f9fcfULL ; state[ 4 ] = 0x0f6d2b697bd44da8ULL ; state[ 5 ] = 0x77e36f7304c48942ULL ; state[ 6 ] = 0x3f9d85a86a1d36c8ULL ; state[ 7 ] = 0x1112e6ad91d692a1ULL ; } void sha512_224_engine::process_block( block_type const & block, state_type & state ) { sha512_engine::process_block( block, state ) ; } void sha512_256_engine::init_state( state_type & state ) { state[ 0 ] = 0x22312194fc2bf72cULL ; state[ 1 ] = 0x9f555fa3c84c64c2ULL ; state[ 2 ] = 0x2393b86b6f53b151ULL ; state[ 3 ] = 0x963877195940eabdULL ; state[ 4 ] = 0x96283ee2a88effe3ULL ; state[ 5 ] = 0xbe5e1e2553863992ULL ; state[ 6 ] = 0x2b0199fc2c85b8aaULL ; state[ 7 ] = 0x0eb72ddc81c52ca2ULL ; } void sha512_256_engine::process_block( block_type const & block, state_type & state ) { sha512_engine::process_block( block, state ) ; } }
34.623762
80
0.615671
gennaroprota
58ad8e01cff2451b726585464523a59170982242
1,769
hpp
C++
Trunk/Backstage/WebServer/src/mutex.hpp
tinoryj/StreamingMediaSystem_Demo
9252cd01cb615a1c55f7613466be1c30a9038b21
[ "MIT" ]
1
2018-06-18T14:53:36.000Z
2018-06-18T14:53:36.000Z
Trunk/Backstage/WebServer/src/mutex.hpp
tinoryj/StreamingMediaSystem_Demo
9252cd01cb615a1c55f7613466be1c30a9038b21
[ "MIT" ]
1
2018-01-13T16:13:42.000Z
2018-03-23T07:12:29.000Z
src/mutex.hpp
tinoryj/SimpleHTTPServer_epoll_threadPoll
1409acddf9427234a4e322c7134528b40ff9f0a9
[ "MIT" ]
null
null
null
#ifndef _MUTEX_HPP_ #define _MUTEX_HPP_ //参照muduo库的mutex写出的一个简易的Mutex类 #include <bits/stdc++.h> #include <assert.h> #include <pthread.h> class MutexLock{ public: MutexLock(): holder_(0){ pthread_mutex_init(&mutex_, NULL); // 初始化 } ~MutexLock(){ assert(holder_ == 0); pthread_mutex_destroy(&mutex_); // 销毁锁 } const bool isLockedByThisThread(){ // 测试锁是否被当前线程持有 return holder_ == pthread_self(); } const void assertLocked() { assert(isLockedByThisThread()); } void lock(){ pthread_mutex_lock(&mutex_); assignHolder(); // 指定拥有者 } void unlock(){ unassignHolder(); // 丢弃拥有者 pthread_mutex_unlock(&mutex_); } pthread_mutex_t* getPthreadMutex(){ return &mutex_; } private: friend class Condition; class UnassignGuard{ public: UnassignGuard(MutexLock& owner) : owner_(owner){ owner_.unassignHolder(); } ~UnassignGuard(){ owner_.assignHolder(); } private: MutexLock& owner_; }; void unassignHolder(){ holder_ = 0; } void assignHolder(){ holder_ = pthread_self(); } pthread_mutex_t mutex_; pthread_t holder_; }; class MutexLockGuard{ public: MutexLockGuard(MutexLock& mutex) : mutex_(mutex){ mutex_.lock(); } ~MutexLockGuard(){ mutex_.unlock(); } private: MutexLock& mutex_; }; class Condition{ private: MutexLock& mutex_; pthread_cond_t pcond_; public: Condition(MutexLock& mutex) : mutex_(mutex){ pthread_cond_init(&pcond_, NULL); } ~Condition(){ pthread_cond_destroy(&pcond_); // 销毁条件变量 } void wait(){ MutexLock::UnassignGuard ug(mutex_); pthread_cond_wait(&pcond_, mutex_.getPthreadMutex()); // 等待Mutex } void notify(){ pthread_cond_signal(&pcond_); // 唤醒一个线程 } void notifyAll(){ pthread_cond_broadcast(&pcond_); // 唤醒多个线程 } }; #endif
13.503817
66
0.686829
tinoryj
58b04981df50d849c1d72a66645283e7e092ddd4
1,600
cpp
C++
TAO/tests/Bug_2560_Regression/Stock_Factory_i.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/Bug_2560_Regression/Stock_Factory_i.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/Bug_2560_Regression/Stock_Factory_i.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// // $Id: Stock_Factory_i.cpp 92387 2010-10-28 07:46:18Z johnnyw $ // #include "Stock_Factory_i.h" #include <iostream> Quoter_Stock_Factory_i::Quoter_Stock_Factory_i () { PortableServer::Servant_var<Quoter_Stock_i> servant1 = new Quoter_Stock_i ("RHAT", "RedHat, Inc.", 210); PortableServer::Servant_var<Quoter_Stock_i> servant2 = new Quoter_Stock_i ("MSFT", "Microsoft, Inc.", 91); PortableServer::POA_var poa1 = servant1->_default_POA (); CORBA::String_var str = servant1->symbol (); PortableServer::ObjectId_var oid1 = PortableServer::string_to_ObjectId (str.in ()); poa1->activate_object_with_id (oid1.in(), servant1.in ()); CORBA::Object_var obj = poa1->id_to_reference (oid1.in ()); ref1_ = Quoter::Stock::_narrow (obj.in ()); PortableServer::POA_var poa2 = servant2->_default_POA (); str = servant2->symbol (); PortableServer::ObjectId_var oid2 = PortableServer::string_to_ObjectId (str.in ()); poa2->activate_object_with_id (oid2.in(), servant2.in ()); obj = poa2->id_to_reference (oid2.in ()); ref2_ = Quoter::Stock::_narrow (obj.in ()); } Quoter::Stock_ptr Quoter_Stock_Factory_i::get_stock (const char *symbol) { try { if (ACE_OS::strcmp (symbol, "RHAT") == 0) { return Quoter::Stock::_duplicate(ref1_.in ()); } else if (ACE_OS::strcmp (symbol, "MSFT") == 0) { return Quoter::Stock::_duplicate(ref2_.in ()); } } catch (CORBA::Exception & e) { std::cerr << "CORBA exception raised: " << e << std::endl; } std::cerr << "Invalid_Stock_Symbol: " << symbol << std::endl ; throw Quoter::Invalid_Stock_Symbol (); }
34.782609
85
0.680625
cflowe
58b2d00d44df941d3746fdb53502e0945d50ce72
25,145
cpp
C++
indra/llprimitive/llmaterialtable.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
null
null
null
indra/llprimitive/llmaterialtable.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
null
null
null
indra/llprimitive/llmaterialtable.cpp
SaladDais/LSO2-VM-Performance
d7ec9ad9daa9a2c9e48c5f06cd768606e3e50638
[ "ISC" ]
null
null
null
/** * @file llmaterialtable.cpp * @brief Table of material names and IDs for viewer * * $LicenseInfo:firstyear=2001&license=viewerlgpl$ * Second Life Viewer Source Code * Copyright (C) 2010, Linden Research, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; * version 2.1 of the License only. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA * $/LicenseInfo$ */ #include "linden_common.h" #include "llmaterialtable.h" #include "indra_constants.h" #include "llstl.h" #include "material_codes.h" #include "sound_ids.h" LLMaterialTable LLMaterialTable::basic(1); /* Old Havok 1 constants // these are the approximately correct friction values for various materials // however Havok1's friction dynamics are not very correct, so the effective // friction coefficients that result from these numbers are approximately // 25-50% too low, more incorrect for the lower values. F32 const LLMaterialTable::FRICTION_MIN = 0.2f; F32 const LLMaterialTable::FRICTION_GLASS = 0.2f; // borosilicate glass F32 const LLMaterialTable::FRICTION_LIGHT = 0.2f; // F32 const LLMaterialTable::FRICTION_METAL = 0.3f; // steel F32 const LLMaterialTable::FRICTION_PLASTIC = 0.4f; // HDPE F32 const LLMaterialTable::FRICTION_WOOD = 0.6f; // southern pine F32 const LLMaterialTable::FRICTION_FLESH = 0.60f; // saltwater F32 const LLMaterialTable::FRICTION_LAND = 0.78f; // dirt F32 const LLMaterialTable::FRICTION_STONE = 0.8f; // concrete F32 const LLMaterialTable::FRICTION_RUBBER = 0.9f; // F32 const LLMaterialTable::FRICTION_MAX = 0.95f; // */ // #if LL_CURRENT_HAVOK_VERSION == LL_HAVOK_VERSION_460 // Havok4 has more correct friction dynamics, however here we have to use // the "incorrect" equivalents for the legacy Havok1 behavior F32 const LLMaterialTable::FRICTION_MIN = 0.15f; F32 const LLMaterialTable::FRICTION_GLASS = 0.13f; // borosilicate glass F32 const LLMaterialTable::FRICTION_LIGHT = 0.14f; // F32 const LLMaterialTable::FRICTION_METAL = 0.22f; // steel F32 const LLMaterialTable::FRICTION_PLASTIC = 0.3f; // HDPE F32 const LLMaterialTable::FRICTION_WOOD = 0.44f; // southern pine F32 const LLMaterialTable::FRICTION_FLESH = 0.46f; // saltwater F32 const LLMaterialTable::FRICTION_LAND = 0.58f; // dirt F32 const LLMaterialTable::FRICTION_STONE = 0.6f; // concrete F32 const LLMaterialTable::FRICTION_RUBBER = 0.67f; // F32 const LLMaterialTable::FRICTION_MAX = 0.71f; // // #endif F32 const LLMaterialTable::RESTITUTION_MIN = 0.02f; F32 const LLMaterialTable::RESTITUTION_LAND = LLMaterialTable::RESTITUTION_MIN; F32 const LLMaterialTable::RESTITUTION_FLESH = 0.2f; // saltwater F32 const LLMaterialTable::RESTITUTION_STONE = 0.4f; // concrete F32 const LLMaterialTable::RESTITUTION_METAL = 0.4f; // steel F32 const LLMaterialTable::RESTITUTION_WOOD = 0.5f; // southern pine F32 const LLMaterialTable::RESTITUTION_GLASS = 0.7f; // borosilicate glass F32 const LLMaterialTable::RESTITUTION_PLASTIC = 0.7f; // HDPE F32 const LLMaterialTable::RESTITUTION_LIGHT = 0.7f; // F32 const LLMaterialTable::RESTITUTION_RUBBER = 0.9f; // F32 const LLMaterialTable::RESTITUTION_MAX = 0.95f; F32 const LLMaterialTable::DEFAULT_FRICTION = 0.5f; F32 const LLMaterialTable::DEFAULT_RESTITUTION = 0.4f; LLMaterialTable::LLMaterialTable() : mCollisionSoundMatrix(NULL), mSlidingSoundMatrix(NULL), mRollingSoundMatrix(NULL) { } LLMaterialTable::LLMaterialTable(U8 isBasic) { initBasicTable(); } LLMaterialTable::~LLMaterialTable() { if (mCollisionSoundMatrix) { delete [] mCollisionSoundMatrix; mCollisionSoundMatrix = NULL; } if (mSlidingSoundMatrix) { delete [] mSlidingSoundMatrix; mSlidingSoundMatrix = NULL; } if (mRollingSoundMatrix) { delete [] mRollingSoundMatrix; mRollingSoundMatrix = NULL; } for_each(mMaterialInfoList.begin(), mMaterialInfoList.end(), DeletePointer()); mMaterialInfoList.clear(); } void LLMaterialTable::initTableTransNames(std::map<std::string, std::string> namemap) { for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; std::string name = infop->mName; infop->mName = namemap[name]; } } void LLMaterialTable::initBasicTable() { // *TODO: Translate add(LL_MCODE_STONE,std::string("Stone"), LL_DEFAULT_STONE_UUID); add(LL_MCODE_METAL,std::string("Metal"), LL_DEFAULT_METAL_UUID); add(LL_MCODE_GLASS,std::string("Glass"), LL_DEFAULT_GLASS_UUID); add(LL_MCODE_WOOD,std::string("Wood"), LL_DEFAULT_WOOD_UUID); add(LL_MCODE_FLESH,std::string("Flesh"), LL_DEFAULT_FLESH_UUID); add(LL_MCODE_PLASTIC,std::string("Plastic"), LL_DEFAULT_PLASTIC_UUID); add(LL_MCODE_RUBBER,std::string("Rubber"), LL_DEFAULT_RUBBER_UUID); add(LL_MCODE_LIGHT,std::string("Light"), LL_DEFAULT_LIGHT_UUID); // specify densities for these materials. . . // these were taken from http://www.mcelwee.net/html/densities_of_various_materials.html addDensity(LL_MCODE_STONE,30.f); addDensity(LL_MCODE_METAL,50.f); addDensity(LL_MCODE_GLASS,20.f); addDensity(LL_MCODE_WOOD,10.f); addDensity(LL_MCODE_FLESH,10.f); addDensity(LL_MCODE_PLASTIC,5.f); addDensity(LL_MCODE_RUBBER,0.5f); // addDensity(LL_MCODE_LIGHT,20.f); // // add damage and energy values addDamageAndEnergy(LL_MCODE_STONE, 1.f, 1.f, 1.f); // concrete addDamageAndEnergy(LL_MCODE_METAL, 1.f, 1.f, 1.f); // steel addDamageAndEnergy(LL_MCODE_GLASS, 1.f, 1.f, 1.f); // borosilicate glass addDamageAndEnergy(LL_MCODE_WOOD, 1.f, 1.f, 1.f); // southern pine addDamageAndEnergy(LL_MCODE_FLESH, 1.f, 1.f, 1.f); // saltwater addDamageAndEnergy(LL_MCODE_PLASTIC, 1.f, 1.f, 1.f); // HDPE addDamageAndEnergy(LL_MCODE_RUBBER, 1.f, 1.f, 1.f); // addDamageAndEnergy(LL_MCODE_LIGHT, 1.f, 1.f, 1.f); // addFriction(LL_MCODE_STONE,0.8f); // concrete addFriction(LL_MCODE_METAL,0.3f); // steel addFriction(LL_MCODE_GLASS,0.2f); // borosilicate glass addFriction(LL_MCODE_WOOD,0.6f); // southern pine addFriction(LL_MCODE_FLESH,0.9f); // saltwater addFriction(LL_MCODE_PLASTIC,0.4f); // HDPE addFriction(LL_MCODE_RUBBER,0.9f); // addFriction(LL_MCODE_LIGHT,0.2f); // addRestitution(LL_MCODE_STONE,0.4f); // concrete addRestitution(LL_MCODE_METAL,0.4f); // steel addRestitution(LL_MCODE_GLASS,0.7f); // borosilicate glass addRestitution(LL_MCODE_WOOD,0.5f); // southern pine addRestitution(LL_MCODE_FLESH,0.3f); // saltwater addRestitution(LL_MCODE_PLASTIC,0.7f); // HDPE addRestitution(LL_MCODE_RUBBER,0.9f); // addRestitution(LL_MCODE_LIGHT,0.7f); // addShatterSound(LL_MCODE_STONE,LLUUID("ea296329-0f09-4993-af1b-e6784bab1dc9")); addShatterSound(LL_MCODE_METAL,LLUUID("d1375446-1c4d-470b-9135-30132433b678")); addShatterSound(LL_MCODE_GLASS,LLUUID("85cda060-b393-48e6-81c8-2cfdfb275351")); addShatterSound(LL_MCODE_WOOD,LLUUID("6f00669f-15e0-4793-a63e-c03f62fee43a")); addShatterSound(LL_MCODE_FLESH,LLUUID("2d8c6f51-149e-4e23-8413-93a379b42b67")); addShatterSound(LL_MCODE_PLASTIC,LLUUID("d55c7f3c-e1c3-4ddc-9eff-9ef805d9190e")); addShatterSound(LL_MCODE_RUBBER,LLUUID("212b6d1e-8d9c-4986-b3aa-f3c6df8d987d")); addShatterSound(LL_MCODE_LIGHT,LLUUID("d55c7f3c-e1c3-4ddc-9eff-9ef805d9190e")); // CollisionSounds mCollisionSoundMatrix = new LLUUID[LL_MCODE_END*LL_MCODE_END]; if (mCollisionSoundMatrix) { addCollisionSound(LL_MCODE_STONE, LL_MCODE_STONE, SND_STONE_STONE); addCollisionSound(LL_MCODE_STONE, LL_MCODE_METAL, SND_STONE_METAL); addCollisionSound(LL_MCODE_STONE, LL_MCODE_GLASS, SND_STONE_GLASS); addCollisionSound(LL_MCODE_STONE, LL_MCODE_WOOD, SND_STONE_WOOD); addCollisionSound(LL_MCODE_STONE, LL_MCODE_FLESH, SND_STONE_FLESH); addCollisionSound(LL_MCODE_STONE, LL_MCODE_PLASTIC, SND_STONE_PLASTIC); addCollisionSound(LL_MCODE_STONE, LL_MCODE_RUBBER, SND_STONE_RUBBER); addCollisionSound(LL_MCODE_STONE, LL_MCODE_LIGHT, SND_STONE_PLASTIC); addCollisionSound(LL_MCODE_METAL, LL_MCODE_METAL, SND_METAL_METAL); addCollisionSound(LL_MCODE_METAL, LL_MCODE_GLASS, SND_METAL_GLASS); addCollisionSound(LL_MCODE_METAL, LL_MCODE_WOOD, SND_METAL_WOOD); addCollisionSound(LL_MCODE_METAL, LL_MCODE_FLESH, SND_METAL_FLESH); addCollisionSound(LL_MCODE_METAL, LL_MCODE_PLASTIC, SND_METAL_PLASTIC); addCollisionSound(LL_MCODE_METAL, LL_MCODE_LIGHT, SND_METAL_PLASTIC); addCollisionSound(LL_MCODE_METAL, LL_MCODE_RUBBER, SND_METAL_RUBBER); addCollisionSound(LL_MCODE_GLASS, LL_MCODE_GLASS, SND_GLASS_GLASS); addCollisionSound(LL_MCODE_GLASS, LL_MCODE_WOOD, SND_GLASS_WOOD); addCollisionSound(LL_MCODE_GLASS, LL_MCODE_FLESH, SND_GLASS_FLESH); addCollisionSound(LL_MCODE_GLASS, LL_MCODE_PLASTIC, SND_GLASS_PLASTIC); addCollisionSound(LL_MCODE_GLASS, LL_MCODE_RUBBER, SND_GLASS_RUBBER); addCollisionSound(LL_MCODE_GLASS, LL_MCODE_LIGHT, SND_GLASS_PLASTIC); addCollisionSound(LL_MCODE_WOOD, LL_MCODE_WOOD, SND_WOOD_WOOD); addCollisionSound(LL_MCODE_WOOD, LL_MCODE_FLESH, SND_WOOD_FLESH); addCollisionSound(LL_MCODE_WOOD, LL_MCODE_PLASTIC, SND_WOOD_PLASTIC); addCollisionSound(LL_MCODE_WOOD, LL_MCODE_RUBBER, SND_WOOD_RUBBER); addCollisionSound(LL_MCODE_WOOD, LL_MCODE_LIGHT, SND_WOOD_PLASTIC); addCollisionSound(LL_MCODE_FLESH, LL_MCODE_FLESH, SND_FLESH_FLESH); addCollisionSound(LL_MCODE_FLESH, LL_MCODE_PLASTIC, SND_FLESH_PLASTIC); addCollisionSound(LL_MCODE_FLESH, LL_MCODE_RUBBER, SND_FLESH_RUBBER); addCollisionSound(LL_MCODE_FLESH, LL_MCODE_LIGHT, SND_FLESH_PLASTIC); addCollisionSound(LL_MCODE_RUBBER, LL_MCODE_RUBBER, SND_RUBBER_RUBBER); addCollisionSound(LL_MCODE_RUBBER, LL_MCODE_PLASTIC, SND_RUBBER_PLASTIC); addCollisionSound(LL_MCODE_RUBBER, LL_MCODE_LIGHT, SND_RUBBER_PLASTIC); addCollisionSound(LL_MCODE_PLASTIC, LL_MCODE_PLASTIC, SND_PLASTIC_PLASTIC); addCollisionSound(LL_MCODE_PLASTIC, LL_MCODE_LIGHT, SND_PLASTIC_PLASTIC); addCollisionSound(LL_MCODE_LIGHT, LL_MCODE_LIGHT, SND_PLASTIC_PLASTIC); } // Sliding Sounds mSlidingSoundMatrix = new LLUUID[LL_MCODE_END*LL_MCODE_END]; if (mSlidingSoundMatrix) { addSlidingSound(LL_MCODE_STONE, LL_MCODE_STONE, SND_SLIDE_STONE_STONE); addSlidingSound(LL_MCODE_STONE, LL_MCODE_METAL, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_STONE, LL_MCODE_GLASS, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_STONE, LL_MCODE_WOOD, SND_SLIDE_STONE_WOOD); addSlidingSound(LL_MCODE_STONE, LL_MCODE_FLESH, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_STONE, LL_MCODE_PLASTIC, SND_SLIDE_STONE_PLASTIC); addSlidingSound(LL_MCODE_STONE, LL_MCODE_RUBBER, SND_SLIDE_STONE_RUBBER); addSlidingSound(LL_MCODE_STONE, LL_MCODE_LIGHT, SND_SLIDE_STONE_PLASTIC); addSlidingSound(LL_MCODE_METAL, LL_MCODE_METAL, SND_SLIDE_METAL_METAL); addSlidingSound(LL_MCODE_METAL, LL_MCODE_GLASS, SND_SLIDE_METAL_GLASS); addSlidingSound(LL_MCODE_METAL, LL_MCODE_WOOD, SND_SLIDE_METAL_WOOD); addSlidingSound(LL_MCODE_METAL, LL_MCODE_FLESH, SND_SLIDE_METAL_FLESH); addSlidingSound(LL_MCODE_METAL, LL_MCODE_PLASTIC, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_METAL, LL_MCODE_RUBBER, SND_SLIDE_METAL_RUBBER); addSlidingSound(LL_MCODE_METAL, LL_MCODE_LIGHT, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_GLASS, LL_MCODE_GLASS, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_GLASS, LL_MCODE_WOOD, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_GLASS, LL_MCODE_FLESH, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_GLASS, LL_MCODE_PLASTIC, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_GLASS, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_GLASS, LL_MCODE_LIGHT, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_WOOD, LL_MCODE_WOOD, SND_SLIDE_WOOD_WOOD); addSlidingSound(LL_MCODE_WOOD, LL_MCODE_FLESH, SND_SLIDE_WOOD_FLESH); addSlidingSound(LL_MCODE_WOOD, LL_MCODE_PLASTIC, SND_SLIDE_WOOD_PLASTIC); addSlidingSound(LL_MCODE_WOOD, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_WOOD, LL_MCODE_LIGHT, SND_SLIDE_WOOD_PLASTIC); addSlidingSound(LL_MCODE_FLESH, LL_MCODE_FLESH, SND_SLIDE_FLESH_FLESH); addSlidingSound(LL_MCODE_FLESH, LL_MCODE_PLASTIC, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_FLESH, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_FLESH, LL_MCODE_LIGHT, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_RUBBER, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_RUBBER, LL_MCODE_PLASTIC, SND_SLIDE_RUBBER_PLASTIC); addSlidingSound(LL_MCODE_RUBBER, LL_MCODE_LIGHT, SND_SLIDE_RUBBER_PLASTIC); addSlidingSound(LL_MCODE_PLASTIC, LL_MCODE_PLASTIC, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_PLASTIC, LL_MCODE_LIGHT, SND_SLIDE_STONE_STONE_01); addSlidingSound(LL_MCODE_LIGHT, LL_MCODE_LIGHT, SND_SLIDE_STONE_STONE_01); } // Rolling Sounds mRollingSoundMatrix = new LLUUID[LL_MCODE_END*LL_MCODE_END]; if (mRollingSoundMatrix) { addRollingSound(LL_MCODE_STONE, LL_MCODE_STONE, SND_ROLL_STONE_STONE); addRollingSound(LL_MCODE_STONE, LL_MCODE_METAL, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_STONE, LL_MCODE_GLASS, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_STONE, LL_MCODE_WOOD, SND_ROLL_STONE_WOOD); addRollingSound(LL_MCODE_STONE, LL_MCODE_FLESH, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_STONE, LL_MCODE_PLASTIC, SND_ROLL_STONE_PLASTIC); addRollingSound(LL_MCODE_STONE, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_STONE, LL_MCODE_LIGHT, SND_ROLL_STONE_PLASTIC); addRollingSound(LL_MCODE_METAL, LL_MCODE_METAL, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_METAL, LL_MCODE_GLASS, SND_ROLL_METAL_GLASS); addRollingSound(LL_MCODE_METAL, LL_MCODE_WOOD, SND_ROLL_METAL_WOOD); addRollingSound(LL_MCODE_METAL, LL_MCODE_FLESH, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_METAL, LL_MCODE_PLASTIC, SND_ROLL_METAL_WOOD); addRollingSound(LL_MCODE_METAL, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_METAL, LL_MCODE_LIGHT, SND_ROLL_METAL_WOOD); addRollingSound(LL_MCODE_GLASS, LL_MCODE_GLASS, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_GLASS, LL_MCODE_WOOD, SND_ROLL_GLASS_WOOD); addRollingSound(LL_MCODE_GLASS, LL_MCODE_FLESH, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_GLASS, LL_MCODE_PLASTIC, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_GLASS, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_GLASS, LL_MCODE_LIGHT, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_WOOD, LL_MCODE_WOOD, SND_ROLL_WOOD_WOOD); addRollingSound(LL_MCODE_WOOD, LL_MCODE_FLESH, SND_ROLL_WOOD_FLESH); addRollingSound(LL_MCODE_WOOD, LL_MCODE_PLASTIC, SND_ROLL_WOOD_PLASTIC); addRollingSound(LL_MCODE_WOOD, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_WOOD, LL_MCODE_LIGHT, SND_ROLL_WOOD_PLASTIC); addRollingSound(LL_MCODE_FLESH, LL_MCODE_FLESH, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_FLESH, LL_MCODE_PLASTIC, SND_ROLL_FLESH_PLASTIC); addRollingSound(LL_MCODE_FLESH, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_FLESH, LL_MCODE_LIGHT, SND_ROLL_FLESH_PLASTIC); addRollingSound(LL_MCODE_RUBBER, LL_MCODE_RUBBER, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_RUBBER, LL_MCODE_PLASTIC, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_RUBBER, LL_MCODE_LIGHT, SND_SLIDE_STONE_STONE_01); addRollingSound(LL_MCODE_PLASTIC, LL_MCODE_PLASTIC, SND_ROLL_PLASTIC_PLASTIC); addRollingSound(LL_MCODE_PLASTIC, LL_MCODE_LIGHT, SND_ROLL_PLASTIC_PLASTIC); addRollingSound(LL_MCODE_LIGHT, LL_MCODE_LIGHT, SND_ROLL_PLASTIC_PLASTIC); } } BOOL LLMaterialTable::add(U8 mcode, const std::string& name, const LLUUID &uuid) { LLMaterialInfo *infop; infop = new LLMaterialInfo(mcode,name,uuid); if (!infop) return FALSE; // Add at the end so the order in menus matches the order in this // file. JNC 11.30.01 mMaterialInfoList.push_back(infop); return TRUE; } BOOL LLMaterialTable::addCollisionSound(U8 mcode, U8 mcode2, const LLUUID &uuid) { if (mCollisionSoundMatrix && (mcode < LL_MCODE_END) && (mcode2 < LL_MCODE_END)) { mCollisionSoundMatrix[mcode * LL_MCODE_END + mcode2] = uuid; if (mcode != mcode2) { mCollisionSoundMatrix[mcode2 * LL_MCODE_END + mcode] = uuid; } } return TRUE; } BOOL LLMaterialTable::addSlidingSound(U8 mcode, U8 mcode2, const LLUUID &uuid) { if (mSlidingSoundMatrix && (mcode < LL_MCODE_END) && (mcode2 < LL_MCODE_END)) { mSlidingSoundMatrix[mcode * LL_MCODE_END + mcode2] = uuid; if (mcode != mcode2) { mSlidingSoundMatrix[mcode2 * LL_MCODE_END + mcode] = uuid; } } return TRUE; } BOOL LLMaterialTable::addRollingSound(U8 mcode, U8 mcode2, const LLUUID &uuid) { if (mRollingSoundMatrix && (mcode < LL_MCODE_END) && (mcode2 < LL_MCODE_END)) { mRollingSoundMatrix[mcode * LL_MCODE_END + mcode2] = uuid; if (mcode != mcode2) { mRollingSoundMatrix[mcode2 * LL_MCODE_END + mcode] = uuid; } } return TRUE; } BOOL LLMaterialTable::addShatterSound(U8 mcode, const LLUUID &uuid) { for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { infop->mShatterSoundID = uuid; return TRUE; } } return FALSE; } BOOL LLMaterialTable::addDensity(U8 mcode, const F32 &density) { for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { infop->mDensity = density; return TRUE; } } return FALSE; } BOOL LLMaterialTable::addRestitution(U8 mcode, const F32 &restitution) { for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { infop->mRestitution = restitution; return TRUE; } } return FALSE; } BOOL LLMaterialTable::addFriction(U8 mcode, const F32 &friction) { for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { infop->mFriction = friction; return TRUE; } } return FALSE; } BOOL LLMaterialTable::addDamageAndEnergy(U8 mcode, const F32 &hp_mod, const F32 &damage_mod, const F32 &ep_mod) { for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { infop->mHPModifier = hp_mod; infop->mDamageModifier = damage_mod; infop->mEPModifier = ep_mod; return TRUE; } } return FALSE; } LLUUID LLMaterialTable::getDefaultTextureID(const std::string& name) { for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (name == infop->mName) { return infop->mDefaultTextureID; } } return LLUUID::null; } LLUUID LLMaterialTable::getDefaultTextureID(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mDefaultTextureID; } } return LLUUID::null; } U8 LLMaterialTable::getMCode(const std::string& name) { for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (name == infop->mName) { return infop->mMCode; } } return 0; } std::string LLMaterialTable::getName(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mName; } } return std::string(); } LLUUID LLMaterialTable::getCollisionSoundUUID(U8 mcode, U8 mcode2) { mcode &= LL_MCODE_MASK; mcode2 &= LL_MCODE_MASK; //LL_INFOS() << "code 1: " << ((U32) mcode) << " code 2:" << ((U32) mcode2) << LL_ENDL; if (mCollisionSoundMatrix && (mcode < LL_MCODE_END) && (mcode2 < LL_MCODE_END)) { return(mCollisionSoundMatrix[mcode * LL_MCODE_END + mcode2]); } else { //LL_INFOS() << "Null Sound" << LL_ENDL; return(SND_NULL); } } bool LLMaterialTable::isCollisionSound(const LLUUID &uuid) { for (U8 i = 0; i < LL_MCODE_END; i++) { for (U8 j = 0; j < LL_MCODE_END; j++) { i &= LL_MCODE_MASK; j &= LL_MCODE_MASK; if (mCollisionSoundMatrix[i * LL_MCODE_END + j] == uuid) { return true; } } } return false; } LLUUID LLMaterialTable::getSlidingSoundUUID(U8 mcode, U8 mcode2) { mcode &= LL_MCODE_MASK; mcode2 &= LL_MCODE_MASK; if (mSlidingSoundMatrix && (mcode < LL_MCODE_END) && (mcode2 < LL_MCODE_END)) { return(mSlidingSoundMatrix[mcode * LL_MCODE_END + mcode2]); } else { return(SND_NULL); } } LLUUID LLMaterialTable::getRollingSoundUUID(U8 mcode, U8 mcode2) { mcode &= LL_MCODE_MASK; mcode2 &= LL_MCODE_MASK; if (mRollingSoundMatrix && (mcode < LL_MCODE_END) && (mcode2 < LL_MCODE_END)) { return(mRollingSoundMatrix[mcode * LL_MCODE_END + mcode2]); } else { return(SND_NULL); } } LLUUID LLMaterialTable::getGroundCollisionSoundUUID(U8 mcode) { // Create material appropriate sounds for collisions with the ground // For now, simply return a single sound for all materials return SND_STONE_DIRT_02; } LLUUID LLMaterialTable::getGroundSlidingSoundUUID(U8 mcode) { // Create material-specific sound for sliding on ground // For now, just return a single sound return SND_SLIDE_STONE_STONE_01; } LLUUID LLMaterialTable::getGroundRollingSoundUUID(U8 mcode) { // Create material-specific sound for rolling on ground // For now, just return a single sound return SND_SLIDE_STONE_STONE_01; } LLUUID LLMaterialTable::getCollisionParticleUUID(U8 mcode, U8 mcode2) { // Returns an appropriate UUID to use as sprite at collision betweeen objects // For now, just return a single image return IMG_SHOT; } LLUUID LLMaterialTable::getGroundCollisionParticleUUID(U8 mcode) { // Returns an appropriate // For now, just return a single sound return IMG_SMOKE_POOF; } F32 LLMaterialTable::getDensity(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mDensity; } } return 0.f; } F32 LLMaterialTable::getRestitution(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mRestitution; } } return LLMaterialTable::DEFAULT_RESTITUTION; } F32 LLMaterialTable::getFriction(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mFriction; } } return LLMaterialTable::DEFAULT_FRICTION; } F32 LLMaterialTable::getHPMod(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mHPModifier; } } return 1.f; } F32 LLMaterialTable::getDamageMod(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mDamageModifier; } } return 1.f; } F32 LLMaterialTable::getEPMod(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mEPModifier; } } return 1.f; } LLUUID LLMaterialTable::getShatterSoundUUID(U8 mcode) { mcode &= LL_MCODE_MASK; for (info_list_t::iterator iter = mMaterialInfoList.begin(); iter != mMaterialInfoList.end(); ++iter) { LLMaterialInfo *infop = *iter; if (mcode == infop->mMCode) { return infop->mShatterSoundID; } } return SND_NULL; }
33.260582
111
0.767668
SaladDais
58b4d7e5a0a91e8babfcc14df33b8639e3b1a651
11,988
hpp
C++
LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/RandomGenerators.hpp
wis1906/letsgo-ar-space-generation
02d888a44bb9eb112f308356ab42720529349338
[ "MIT" ]
null
null
null
LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/RandomGenerators.hpp
wis1906/letsgo-ar-space-generation
02d888a44bb9eb112f308356ab42720529349338
[ "MIT" ]
null
null
null
LetsGo/ThirdParty/ApproxMVBB/Includes/ApproxMVBB/RandomGenerators.hpp
wis1906/letsgo-ar-space-generation
02d888a44bb9eb112f308356ab42720529349338
[ "MIT" ]
null
null
null
// ======================================================================================== // ApproxMVBB // Copyright (C) 2014 by Gabriel Nützi <nuetzig (at) imes (d0t) mavt (d0t) ethz // (døt) ch> // // 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/. // ======================================================================================== #ifndef ApproxMVBB_RandomGenerator_hpp #define ApproxMVBB_RandomGenerator_hpp #include "ApproxMVBB/Common/StaticAssert.hpp" #include "ApproxMVBB/Config/Config.hpp" #include ApproxMVBB_TypeDefs_INCLUDE_FILE #include <cstdint> #include <ctime> #include <limits> #include <random> #include <type_traits> namespace ApproxMVBB { namespace RandomGenerators { /** This is a fixed-increment version of Java 8's SplittableRandom generator See http://dx.doi.org/10.1145/2714064.2660195 and http://docs.oracle.com/javase/8/docs/api/java/util/SplittableRandom.html It is a very fast generator passing BigCrush, and it can be useful if for some reason you absolutely want 64 bits of state; otherwise, we rather suggest to use a xorshift128+ (for moderately parallel computations) or xorshift1024* (for massively parallel computations) generator. */ class APPROXMVBB_EXPORT SplitMix64 { private: uint64_t x; //< The state can be seeded with any value. public: SplitMix64(const SplitMix64& gen) = default; SplitMix64(SplitMix64&& gen) = default; SplitMix64(uint64_t seed); void seed(uint64_t seed); uint64_t operator()(); // for standard random using result_type = uint64_t; static constexpr result_type min() { return std::numeric_limits<result_type>::min(); } static constexpr result_type max() { return std::numeric_limits<result_type>::max(); } }; /** This is the fastest generator passing BigCrush without systematic failures, but due to the relatively short period it is acceptable only for applications with a mild amount of parallelism; otherwise, use a xorshift1024* generator. The state must be seeded so that it is not everywhere zero. If you have a 64-bit seed, we suggest to seed a splitmix64 generator and use its output to fill s. */ class APPROXMVBB_EXPORT XorShift128Plus { private: uint64_t s[2]; public: XorShift128Plus(const XorShift128Plus& gen) = default; XorShift128Plus(XorShift128Plus&& gen) = default; XorShift128Plus(uint64_t seed); /** Take time() to seed this generator */ XorShift128Plus(); void seed(uint64_t seed); /** Generate random number */ uint64_t operator()(); /** This is the jump function for the generator. It is equivalent to 2^64 calls to next(); it can be used to generate 2^64 non-overlapping subsequences for parallel computations. */ void jump(); // for standard random using result_type = uint64_t; static constexpr result_type min() { return std::numeric_limits<result_type>::min(); } static constexpr result_type max() { return std::numeric_limits<result_type>::max(); } }; /* This is a fast, top-quality generator. If 1024 bits of state are too much, try a xorshift128+ generator. The state must be seeded so that it is not everywhere zero. If you have a 64-bit seed, we suggest to seed a splitmix64 generator and use its output to fill s. */ class APPROXMVBB_EXPORT XorShift1024Star { private: uint64_t s[16]; int p = 0; public: XorShift1024Star(const XorShift1024Star& gen) = default; XorShift1024Star(XorShift1024Star&& gen) = default; XorShift1024Star(uint64_t seed); /** Take time() to seed this generator */ XorShift1024Star(); void seed(uint64_t seed); /** Generate random number */ uint64_t operator()(); /** This is the jump function for the generator. It is equivalent to 2^512 calls to next(); it can be used to generate 2^512 non-overlapping subsequences for parallel computations. */ void jump(); // for standard random using result_type = uint64_t; static constexpr result_type min() { return std::numeric_limits<result_type>::min(); } static constexpr result_type max() { return std::numeric_limits<result_type>::max(); } }; /** A fast portable, non-truly uniform integer distribution */ template<typename T> class AlmostUniformUIntDistribution { public: ApproxMVBB_STATIC_ASSERT(std::is_unsigned<T>::value); AlmostUniformUIntDistribution(T min, T max) : m_min(min), m_max(max) { m_nRange = m_max - m_min; } template<typename G> T operator()(G& g) { return ((static_cast<double>(g() - G::min())) / (static_cast<double>(G::max() - G::min()))) * m_nRange + m_min; } private: T m_min, m_max, m_nRange; }; /** A fast portable, non-truly uniform real distribution */ template<typename T> class AlmostUniformRealDistribution { public: ApproxMVBB_STATIC_ASSERT(std::is_floating_point<T>::value); AlmostUniformRealDistribution(T min, T max) : m_min(min), m_max(max) { m_nRange = m_max - m_min; } template<typename G> T operator()(G& g) { return ((static_cast<T>(g() - G::min())) / (static_cast<T>(G::max() - G::min()))) * m_nRange + m_min; } private: T m_min, m_max, m_nRange; }; /** Default random generator definitions */ static const uint64_t defaultSeed = 314159; using DefaultRandomGen = XorShift128Plus; /** Define the Uniform distributions for the library and for the tests */ #ifdef ApproxMVBB_BUILD_TESTS template<typename T> using DefaultUniformUIntDistribution = AlmostUniformUIntDistribution<T>; template<typename T> using DefaultUniformRealDistribution = AlmostUniformRealDistribution<T>; #else template<typename T> using DefaultUniformUIntDistribution = std::uniform_int_distribution<T>; template<typename T> using DefaultUniformRealDistribution = std::uniform_real_distribution<T>; #endif } // namespace RandomGenerators } // namespace ApproxMVBB namespace ApproxMVBB { namespace RandomGenerators { inline SplitMix64::SplitMix64(uint64_t sd) : x(sd) { } inline void SplitMix64::seed(uint64_t sd) { x = sd; } inline uint64_t SplitMix64::operator()() { uint64_t z = (x += uint64_t(0x9E3779B97F4A7C15)); z = (z ^ (z >> 30)) * uint64_t(0xBF58476D1CE4E5B9); z = (z ^ (z >> 27)) * uint64_t(0x94D049BB133111EB); return z ^ (z >> 31); } inline XorShift128Plus::XorShift128Plus(uint64_t sd) { seed(sd); } /** Take time() to seed this generator */ inline XorShift128Plus::XorShift128Plus() { seed(static_cast<uint64_t>(time(nullptr))); } inline void XorShift128Plus::seed(uint64_t sd) { s[0] = SplitMix64{sd}(); s[1] = s[0]; } /** Generate random number */ inline uint64_t XorShift128Plus::operator()() { uint64_t s1 = s[0]; const uint64_t s0 = s[1]; s[0] = s0; s1 ^= s1 << 23; // a s[1] = s1 ^ s0 ^ (s1 >> 18) ^ (s0 >> 5); // b, c return s[1] + s0; } inline void XorShift128Plus::jump() { static const uint64_t JUMP[] = {0x8a5cd789635d2dff, 0x121fd2155c472f96}; uint64_t s0 = 0; uint64_t s1 = 0; for(unsigned int i = 0; i < sizeof(JUMP) / sizeof(*JUMP); i++) for(int b = 0; b < 64; b++) { if(JUMP[i] & uint64_t(1) << b) { s0 ^= s[0]; s1 ^= s[1]; } this->operator()(); } s[0] = s0; s[1] = s1; } inline XorShift1024Star::XorShift1024Star(uint64_t sd) { seed(sd); } /** Take time() to seed this generator */ inline XorShift1024Star::XorShift1024Star() { seed(static_cast<uint64_t>(time(nullptr))); } inline void XorShift1024Star::seed(uint64_t sd) { uint64_t ss = SplitMix64{sd}(); for(auto& v : s) { v = ss; } } /** Generate random number */ inline uint64_t XorShift1024Star::operator()() { const uint64_t s0 = s[p]; uint64_t s1 = s[p = (p + 1) & 15]; s1 ^= s1 << 31; // a s[p] = s1 ^ s0 ^ (s1 >> 11) ^ (s0 >> 30); // b,c return s[p] * uint64_t(1181783497276652981); } /** This is the jump function for the generator. It is equivalent to 2^512 calls to next(); it can be used to generate 2^512 non-overlapping subsequences for parallel computations. */ inline void XorShift1024Star::jump() { static const uint64_t JUMP[] = {0x84242f96eca9c41d, 0xa3c65b8776f96855, 0x5b34a39f070b5837, 0x4489affce4f31a1e, 0x2ffeeb0a48316f40, 0xdc2d9891fe68c022, 0x3659132bb12fea70, 0xaac17d8efa43cab8, 0xc4cb815590989b13, 0x5ee975283d71c93b, 0x691548c86c1bd540, 0x7910c41d10a1e6a5, 0x0b5fc64563b3e2a8, 0x047f7684e9fc949d, 0xb99181f2d8f685ca, 0x284600e3f30e38c3}; uint64_t t[16] = {0}; for(unsigned int i = 0; i < sizeof(JUMP) / sizeof(*JUMP); i++) for(int b = 0; b < 64; b++) { if(JUMP[i] & uint64_t(1) << b) for(int j = 0; j < 16; j++) t[j] ^= s[(j + p) & 15]; this->operator()(); } for(int j = 0; j < 16; j++) s[(j + p) & 15] = t[j]; } } // namespace RandomGenerators } // namespace ApproxMVBB #endif
34.34957
127
0.505172
wis1906
58b4ecd312d9528373d8831c3492fba4facfd7cd
5,538
cpp
C++
valeur_ajouter/QRCode_Generator/QRCode/test_main.cpp
SuperBatata/Sportify-QT-C---project
8c0a9630cc6577721cb0f9fe0afd1eb082b4d4ba
[ "MIT" ]
null
null
null
valeur_ajouter/QRCode_Generator/QRCode/test_main.cpp
SuperBatata/Sportify-QT-C---project
8c0a9630cc6577721cb0f9fe0afd1eb082b4d4ba
[ "MIT" ]
null
null
null
valeur_ajouter/QRCode_Generator/QRCode/test_main.cpp
SuperBatata/Sportify-QT-C---project
8c0a9630cc6577721cb0f9fe0afd1eb082b4d4ba
[ "MIT" ]
null
null
null
/* * QR Code Generator * Copyright (C) 2014 Stefano BARILETTI <hackaroth@gmail.com> * * 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 <string.h> #include <iostream> #include <fstream> #include <streambuf> #include <stdlib.h> #include "QRController.h" using namespace std; typedef struct _params { bool Verbose; int Version; int Width; int Height; string Data; string of; eCorrectionLevel ECL; _params(void) { Verbose = false; Version = 0; Width = 300; Height = 300; Data = "QR CODE"; of = "./out.bmp"; ECL = eclLow; } }params; string load_from_file(char* file_name) { string data = ""; ifstream f(file_name); f.seekg(0, std::ios::end); data.reserve((unsigned int)f.tellg()); f.seekg(0, std::ios::beg); data.assign((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>()); f.close(); return data; } void parse_parameters(int argc, char* argv[], params &p) { for (int i = 1; i < argc; i++) { if (strcmp (argv[i],"-w") == 0) { i++; if (atoi(argv[i]) > 0) p.Width = atoi(argv[i]); } else if (strcmp (argv[i],"-h") == 0) { i++; if (atoi(argv[i]) > 0) p.Height = atoi(argv[i]); } else if (strcmp (argv[i],"-ecl") == 0) { i++; if (strcmp (argv[i],"L") == 0) p.ECL = eclLow; else if (strcmp (argv[i],"M") == 0) p.ECL = eclMedium; else if (strcmp (argv[i],"Q") == 0) p.ECL = eclQuality; else if (strcmp (argv[i],"H") == 0) p.ECL = eclHigh; } else if (strcmp (argv[i],"-v") == 0) { i++; if (atoi(argv[i]) >= 0 && atoi(argv[i]) <= 40) p.Version = atoi(argv[i]); } else if (strcmp (argv[i],"-if") == 0) { i++; string data = load_from_file(argv[i]); if (data.length() > 0) p.Data = data; } else if (strcmp (argv[i],"-d") == 0) p.Data = argv[++i]; else if (strcmp (argv[i],"-of") == 0) p.of = argv[++i]; else if (strcmp (argv[i],"--V") == 0) p.Verbose = true; } } void show_license(void) { printf("QR CODE Version 1.0\n" "Copyright (C) 2014 Stefano BARILETTI <hackaroth@gmail.com>\n\n" "This program is free software: you can redistribute it and/or modify it\n" "under the terms of the GNU General Public License as published by the\n" "Free Software Foundation, either version 3 of the License, or\n" "(at your option) any later version.\n\n" "This program is distributed in the hope that it will be useful, but\n" "WITHOUT ANY WARRANTY; without even the implied warranty of\n" "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n" "See the GNU General Public License for more details.\n\n"); } void show_help(void) { printf("USAGE:\n" "QRCODE -v, -w, -h, -ecl, -if, -d, -of, --V, --help\n\n" "-v\tQR Code Version: From 0 to 40\n\tSet 0 for auto version selection.\n\n" "-w\tImage width\n\tSet the width of the output image\n\n" "-h\tImage height\n\tSet the height of the output image\n\n" "-ecl\tError correction level: L, M, Q, H\n\tSet the error correction level of the qr code.\n\tDefault value is L\n\n" "-if\tInput File\n\tCreate a Qr Code reading data from a file\n\n" "-d\tData\n\tSpecifies the data that must be encoded.\n\tIf the -if option is specified, this option take precedence \n\n" "-of\tOutput File\n\tSpecifies the output file name and path\n\n" "--V\tVerbose\n\tShow the Qr Code settings\n\n" "--help\tHelp\n\tShow this help\n\n"); } int test_main(int argc, char* argv[]) { show_license(); params p; if (argc > 1 && strcmp (argv[1],"--help") == 0) { show_help(); } else { parse_parameters(argc, argv, p); if (p.Verbose) { cout << "*** SETTINGS ***" << endl; cout << "Ver:\t" << p.Version << endl; cout << "Width:\t" << p.Width << endl; cout << "Height:\t" << p.Height << endl; cout << "ECL:\t" << p.ECL << endl; cout << "Output:\t" << p.of << endl; cout << endl; cout << p.Data << endl; } QRController* controller = new QRController(p.Data, p.ECL, p.Width, p.Height, p.Version); controller->SaveToFile(p.of); delete controller; } return 0; }
28.994764
133
0.5381
SuperBatata
58b66778648a001230b3bbc5e2bad52dfae5f1d7
540
hpp
C++
Kreator/implementation/Platform/OpenGL/OpenGLRendererContext.hpp
ashish1009/Kreator
68ff5073faef22ade314772a5127dd1cc98060b7
[ "Apache-2.0" ]
null
null
null
Kreator/implementation/Platform/OpenGL/OpenGLRendererContext.hpp
ashish1009/Kreator
68ff5073faef22ade314772a5127dd1cc98060b7
[ "Apache-2.0" ]
null
null
null
Kreator/implementation/Platform/OpenGL/OpenGLRendererContext.hpp
ashish1009/Kreator
68ff5073faef22ade314772a5127dd1cc98060b7
[ "Apache-2.0" ]
null
null
null
// // OpenGLRendererContext.hpp // Kreator // // Created by iKan on 09/04/22. // #pragma once #include <Renderer/Graphics/Context.hpp> namespace Kreator { /// Implementation of Renderer Graphics context for Open GL API class OpenGLRendererContext : public RendererContext { public: OpenGLRendererContext(GLFWwindow* window); virtual ~OpenGLRendererContext(); void Init() override; void SwapBuffers() override; private: GLFWwindow* m_Window; }; }
19.285714
67
0.637037
ashish1009
58b7850f102ffd92d424a925293aa874646a22b7
30,804
cpp
C++
src/history/test/HistoryTests.cpp
viichain/vii-core
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/history/test/HistoryTests.cpp
viichain/vii-core
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
src/history/test/HistoryTests.cpp
viichain/vii-core
2e5b794fb71e1385a2b5bc96920b5a69d4d8560f
[ "Apache-2.0", "BSD-2-Clause", "MIT", "ECL-2.0", "BSL-1.0", "BSD-3-Clause" ]
null
null
null
#include "bucket/BucketManager.h" #include "catchup/test/CatchupWorkTests.h" #include "history/FileTransferInfo.h" #include "history/HistoryArchiveManager.h" #include "history/HistoryManager.h" #include "history/test/HistoryTestsUtils.h" #include "historywork/GetHistoryArchiveStateWork.h" #include "historywork/GunzipFileWork.h" #include "historywork/GzipFileWork.h" #include "historywork/PutHistoryArchiveStateWork.h" #include "ledger/LedgerManager.h" #include "main/ExternalQueue.h" #include "main/PersistentState.h" #include "process/ProcessManager.h" #include "test/TestAccount.h" #include "test/TestUtils.h" #include "test/TxTests.h" #include "test/test.h" #include "util/Fs.h" #include "util/Logging.h" #include "work/WorkScheduler.h" #include "historywork/DownloadBucketsWork.h" #include <lib/catch.hpp> #include <lib/util/format.h> using namespace viichain; using namespace historytestutils; TEST_CASE("next checkpoint ledger", "[history]") { CatchupSimulation catchupSimulation{}; HistoryManager& hm = catchupSimulation.getApp().getHistoryManager(); REQUIRE(hm.nextCheckpointLedger(0) == 64); REQUIRE(hm.nextCheckpointLedger(1) == 64); REQUIRE(hm.nextCheckpointLedger(32) == 64); REQUIRE(hm.nextCheckpointLedger(62) == 64); REQUIRE(hm.nextCheckpointLedger(63) == 64); REQUIRE(hm.nextCheckpointLedger(64) == 64); REQUIRE(hm.nextCheckpointLedger(65) == 128); REQUIRE(hm.nextCheckpointLedger(66) == 128); REQUIRE(hm.nextCheckpointLedger(126) == 128); REQUIRE(hm.nextCheckpointLedger(127) == 128); REQUIRE(hm.nextCheckpointLedger(128) == 128); REQUIRE(hm.nextCheckpointLedger(129) == 192); REQUIRE(hm.nextCheckpointLedger(130) == 192); } TEST_CASE("HistoryManager compress", "[history]") { CatchupSimulation catchupSimulation{}; std::string s = "hello there"; HistoryManager& hm = catchupSimulation.getApp().getHistoryManager(); std::string fname = hm.localFilename("compressme"); { std::ofstream out(fname, std::ofstream::binary); out.write(s.data(), s.size()); } std::string compressed = fname + ".gz"; auto& wm = catchupSimulation.getApp().getWorkScheduler(); auto g = wm.executeWork<GzipFileWork>(fname); REQUIRE(g->getState() == BasicWork::State::WORK_SUCCESS); REQUIRE(!fs::exists(fname)); REQUIRE(fs::exists(compressed)); auto u = wm.executeWork<GunzipFileWork>(compressed); REQUIRE(u->getState() == BasicWork::State::WORK_SUCCESS); REQUIRE(fs::exists(fname)); REQUIRE(!fs::exists(compressed)); } TEST_CASE("HistoryArchiveState get_put", "[history]") { CatchupSimulation catchupSimulation{}; HistoryArchiveState has; has.currentLedger = 0x1234; auto archive = catchupSimulation.getApp().getHistoryArchiveManager().getHistoryArchive( "test"); REQUIRE(archive); has.resolveAllFutures(); auto& wm = catchupSimulation.getApp().getWorkScheduler(); auto put = wm.executeWork<PutHistoryArchiveStateWork>(has, archive); REQUIRE(put->getState() == BasicWork::State::WORK_SUCCESS); HistoryArchiveState has2; auto get = wm.executeWork<GetHistoryArchiveStateWork>(has2, 0, archive); REQUIRE(get->getState() == BasicWork::State::WORK_SUCCESS); REQUIRE(has2.currentLedger == 0x1234); } TEST_CASE("History bucket verification", "[history][bucketverification][batching]") { Config cfg(getTestConfig()); VirtualClock clock; auto cg = std::make_shared<TmpDirHistoryConfigurator>(); cg->configure(cfg, true); Application::pointer app = createTestApplication(clock, cfg); REQUIRE(app->getHistoryArchiveManager().initializeHistoryArchive("test")); auto bucketGenerator = TestBucketGenerator{ *app, app->getHistoryArchiveManager().getHistoryArchive("test")}; std::vector<std::string> hashes; auto& wm = app->getWorkScheduler(); std::map<std::string, std::shared_ptr<Bucket>> mBuckets; auto tmpDir = std::make_unique<TmpDir>(app->getTmpDirManager().tmpDir("bucket-test")); SECTION("successful download and verify") { hashes.push_back(bucketGenerator.generateBucket( TestBucketState::CONTENTS_AND_HASH_OK)); hashes.push_back(bucketGenerator.generateBucket( TestBucketState::CONTENTS_AND_HASH_OK)); auto verify = wm.executeWork<DownloadBucketsWork>(mBuckets, hashes, *tmpDir); REQUIRE(verify->getState() == BasicWork::State::WORK_SUCCESS); } SECTION("download fails file not found") { hashes.push_back( bucketGenerator.generateBucket(TestBucketState::FILE_NOT_UPLOADED)); auto verify = wm.executeWork<DownloadBucketsWork>(mBuckets, hashes, *tmpDir); REQUIRE(verify->getState() == BasicWork::State::WORK_FAILURE); } SECTION("download succeeds but unzip fails") { hashes.push_back(bucketGenerator.generateBucket( TestBucketState::CORRUPTED_ZIPPED_FILE)); auto verify = wm.executeWork<DownloadBucketsWork>(mBuckets, hashes, *tmpDir); REQUIRE(verify->getState() == BasicWork::State::WORK_FAILURE); } SECTION("verify fails hash mismatch") { hashes.push_back( bucketGenerator.generateBucket(TestBucketState::HASH_MISMATCH)); auto verify = wm.executeWork<DownloadBucketsWork>(mBuckets, hashes, *tmpDir); REQUIRE(verify->getState() == BasicWork::State::WORK_FAILURE); } SECTION("no hashes to verify") { auto verify = wm.executeWork<DownloadBucketsWork>( mBuckets, std::vector<std::string>(), *tmpDir); REQUIRE(verify->getState() == BasicWork::State::WORK_SUCCESS); } } TEST_CASE("Ledger chain verification", "[ledgerheaderverification]") { Config cfg(getTestConfig(0)); VirtualClock clock; auto cg = std::make_shared<TmpDirHistoryConfigurator>(); cg->configure(cfg, true); Application::pointer app = createTestApplication(clock, cfg); REQUIRE(app->getHistoryArchiveManager().initializeHistoryArchive("test")); auto tmpDir = app->getTmpDirManager().tmpDir("tmp-chain-test"); auto& wm = app->getWorkScheduler(); LedgerHeaderHistoryEntry firstVerified{}; LedgerHeaderHistoryEntry verifiedAhead{}; uint32_t initLedger = 127; LedgerRange ledgerRange{ initLedger, initLedger + app->getHistoryManager().getCheckpointFrequency() * 10}; CheckpointRange checkpointRange{ledgerRange, app->getHistoryManager()}; auto ledgerChainGenerator = TestLedgerChainGenerator{ *app, app->getHistoryArchiveManager().getHistoryArchive("test"), checkpointRange, tmpDir}; auto checkExpectedBehavior = [&](Work::State expectedState, LedgerHeaderHistoryEntry lcl, LedgerHeaderHistoryEntry last) { auto lclPair = LedgerNumHashPair(lcl.header.ledgerSeq, make_optional<Hash>(lcl.hash)); auto ledgerRangeEnd = LedgerNumHashPair(last.header.ledgerSeq, make_optional<Hash>(last.hash)); auto w = wm.executeWork<VerifyLedgerChainWork>(tmpDir, ledgerRange, lclPair, ledgerRangeEnd); REQUIRE(expectedState == w->getState()); }; LedgerHeaderHistoryEntry lcl, last; LOG(DEBUG) << "fully valid"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_OK); checkExpectedBehavior(BasicWork::State::WORK_SUCCESS, lcl, last); } LOG(DEBUG) << "invalid link due to bad hash"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_ERR_BAD_HASH); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "invalid ledger version"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_ERR_BAD_LEDGER_VERSION); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "overshot"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_ERR_OVERSHOT); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "undershot"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_ERR_UNDERSHOT); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "missing entries"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_ERR_MISSING_ENTRIES); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "chain does not agree with LCL"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_OK); lcl.hash = HashUtils::random(); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "chain does not agree with LCL on checkpoint boundary"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_OK); lcl.header.ledgerSeq += app->getHistoryManager().getCheckpointFrequency() - 1; lcl.hash = HashUtils::random(); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "chain does not agree with LCL outside of range"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_OK); lcl.header.ledgerSeq -= 1; lcl.hash = HashUtils::random(); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "chain does not agree with trusted hash"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_OK); last.hash = HashUtils::random(); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } LOG(DEBUG) << "missing file"; { std::tie(lcl, last) = ledgerChainGenerator.makeLedgerChainFiles( HistoryManager::VERIFY_STATUS_OK); FileTransferInfo ft(tmpDir, HISTORY_FILE_TYPE_LEDGER, last.header.ledgerSeq); std::remove(ft.localPath_nogz().c_str()); checkExpectedBehavior(BasicWork::State::WORK_FAILURE, lcl, last); } } TEST_CASE("History publish", "[history]") { CatchupSimulation catchupSimulation{}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(1); catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger); } static std::string resumeModeName(uint32_t count) { switch (count) { case 0: return "CATCHUP_MINIMAL"; case std::numeric_limits<uint32_t>::max(): return "CATCHUP_COMPLETE"; default: return "CATCHUP_RECENT"; } } static std::string dbModeName(Config::TestDbMode mode) { switch (mode) { case Config::TESTDB_IN_MEMORY_SQLITE: return "TESTDB_IN_MEMORY_SQLITE"; case Config::TESTDB_ON_DISK_SQLITE: return "TESTDB_ON_DISK_SQLITE"; #ifdef USE_POSTGRES case Config::TESTDB_POSTGRESQL: return "TESTDB_POSTGRESQL"; #endif default: abort(); } } TEST_CASE("History catchup", "[history][catchup]") { CatchupSimulation catchupSimulation{VirtualClock::REAL_TIME}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3); auto app = catchupSimulation.createCatchupApplication( std::numeric_limits<uint32_t>::max(), Config::TESTDB_ON_DISK_SQLITE, "app"); auto offlineNonCheckpointDestinationLedger = checkpointLedger - app->getHistoryManager().getCheckpointFrequency() / 2; SECTION("when not enough publishes has been performed") { catchupSimulation.ensureLedgerAvailable(checkpointLedger); SECTION("online") { REQUIRE(!catchupSimulation.catchupOnline(app, checkpointLedger)); } SECTION("offline") { REQUIRE(!catchupSimulation.catchupOffline(app, checkpointLedger)); } SECTION("offline, in the middle of checkpoint") { REQUIRE(!catchupSimulation.catchupOffline( app, offlineNonCheckpointDestinationLedger)); } } SECTION("when enough publishes has been performed, but no trigger ledger " "was externalized") { catchupSimulation.ensureLedgerAvailable(checkpointLedger + 1); catchupSimulation.ensurePublishesComplete(); SECTION("online") { REQUIRE(!catchupSimulation.catchupOnline(app, checkpointLedger)); } SECTION("offline") { REQUIRE(catchupSimulation.catchupOffline(app, checkpointLedger)); } SECTION("offline, in the middle of checkpoint") { REQUIRE(catchupSimulation.catchupOffline( app, offlineNonCheckpointDestinationLedger)); } } SECTION("when enough publishes has been performed, but no closing ledger " "was externalized") { catchupSimulation.ensureLedgerAvailable(checkpointLedger + 2); catchupSimulation.ensurePublishesComplete(); REQUIRE(!catchupSimulation.catchupOnline(app, checkpointLedger)); } SECTION("when enough publishes has been performed, 3 ledgers are buffered " "and no closing ledger was externalized") { catchupSimulation.ensureLedgerAvailable(checkpointLedger + 5); catchupSimulation.ensurePublishesComplete(); REQUIRE(!catchupSimulation.catchupOnline(app, checkpointLedger, 3)); } SECTION("when enough publishes has been performed, 3 ledgers are buffered " "and closing ledger was externalized") { catchupSimulation.ensureLedgerAvailable(checkpointLedger + 6); catchupSimulation.ensurePublishesComplete(); REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 3)); } } TEST_CASE("History catchup with different modes", "[history][catchup]") { CatchupSimulation catchupSimulation{}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); std::vector<Application::pointer> apps; std::vector<uint32_t> counts = {0, std::numeric_limits<uint32_t>::max(), 60}; std::vector<Config::TestDbMode> dbModes = {Config::TESTDB_IN_MEMORY_SQLITE, Config::TESTDB_ON_DISK_SQLITE}; #ifdef USE_POSTGRES if (!force_sqlite) dbModes.push_back(Config::TESTDB_POSTGRESQL); #endif for (auto dbMode : dbModes) { for (auto count : counts) { auto a = catchupSimulation.createCatchupApplication( count, dbMode, std::string("full, ") + resumeModeName(count) + ", " + dbModeName(dbMode)); REQUIRE(catchupSimulation.catchupOnline(a, checkpointLedger, 5)); apps.push_back(a); } } } TEST_CASE("History prefix catchup", "[history][catchup][prefixcatchup]") { CatchupSimulation catchupSimulation{}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); auto a = catchupSimulation.createCatchupApplication( std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE, std::string("Catchup to prefix of published history")); REQUIRE(catchupSimulation.catchupOnline(a, 10, 5)); uint32_t freq = a->getHistoryManager().getCheckpointFrequency(); REQUIRE(a->getLedgerManager().getLastClosedLedgerNum() == freq + 7); auto b = catchupSimulation.createCatchupApplication( std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE, std::string("Catchup to second prefix of published history")); REQUIRE(catchupSimulation.catchupOnline(b, freq + 10, 5)); REQUIRE(b->getLedgerManager().getLastClosedLedgerNum() == 2 * freq + 7); } TEST_CASE("Catchup non-initentry buckets to initentry-supporting works", "[history][historyinitentry]") { uint32_t newProto = Bucket::FIRST_PROTOCOL_SUPPORTING_INITENTRY_AND_METAENTRY; uint32_t oldProto = newProto - 1; auto configurator = std::make_shared<RealGenesisTmpDirHistoryConfigurator>(); CatchupSimulation catchupSimulation{VirtualClock::VIRTUAL_TIME, configurator}; catchupSimulation.generateRandomLedger(oldProto); auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger); std::vector<Application::pointer> apps; std::vector<uint32_t> counts = {0, std::numeric_limits<uint32_t>::max(), 60}; for (auto count : counts) { auto a = catchupSimulation.createCatchupApplication( count, Config::TESTDB_IN_MEMORY_SQLITE, std::string("full, ") + resumeModeName(count) + ", " + dbModeName(Config::TESTDB_IN_MEMORY_SQLITE)); REQUIRE(catchupSimulation.catchupOnline(a, checkpointLedger - 2)); auto mc = a->getBucketManager().readMergeCounters(); REQUIRE(mc.mPostInitEntryProtocolMerges == 0); REQUIRE(mc.mNewInitEntries == 0); REQUIRE(mc.mOldInitEntries == 0); for (auto i = 0; i < 3; ++i) { auto root = TestAccount{*a, txtest::getRoot(a->getNetworkID())}; auto stranger = TestAccount{ *a, txtest::getAccount(fmt::format("stranger{}", i))}; auto& lm = a->getLedgerManager(); TxSetFramePtr txSet = std::make_shared<TxSetFrame>( lm.getLastClosedLedgerHeader().hash); uint32_t ledgerSeq = lm.getLastClosedLedgerNum() + 1; uint64_t minBalance = lm.getLastMinBalance(5); uint64_t big = minBalance + ledgerSeq; uint64_t closeTime = 60 * 5 * ledgerSeq; txSet->add(root.tx({txtest::createAccount(stranger, big)})); txSet->getContentsHash(); auto upgrades = xdr::xvector<UpgradeType, 6>{}; if (i == 0) { auto ledgerUpgrade = LedgerUpgrade{LEDGER_UPGRADE_VERSION}; ledgerUpgrade.newLedgerVersion() = newProto; auto v = xdr::xdr_to_opaque(ledgerUpgrade); upgrades.push_back(UpgradeType{v.begin(), v.end()}); } CLOG(DEBUG, "History") << "Closing synthetic ledger " << ledgerSeq << " with " << txSet->size(lm.getLastClosedLedgerHeader().header) << " txs (txhash:" << hexAbbrev(txSet->getContentsHash()) << ")"; VIIValue sv(txSet->getContentsHash(), closeTime, upgrades, VII_VALUE_BASIC); lm.closeLedger(LedgerCloseData(ledgerSeq, txSet, sv)); } mc = a->getBucketManager().readMergeCounters(); REQUIRE(mc.mPostInitEntryProtocolMerges != 0); REQUIRE(mc.mNewInitEntries != 0); REQUIRE(mc.mOldInitEntries != 0); apps.push_back(a); } } TEST_CASE("Publish catchup alternation with stall", "[history][catchup][catchupalternation]") { CatchupSimulation catchupSimulation{}; auto& lm = catchupSimulation.getApp().getLedgerManager(); auto checkpoint = 3; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(checkpoint); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); auto completeApp = catchupSimulation.createCatchupApplication( std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE, std::string("completeApp")); auto minimalApp = catchupSimulation.createCatchupApplication( 0, Config::TESTDB_IN_MEMORY_SQLITE, std::string("minimalApp")); REQUIRE(catchupSimulation.catchupOnline(completeApp, checkpointLedger, 5)); REQUIRE(catchupSimulation.catchupOnline(minimalApp, checkpointLedger, 5)); for (int i = 1; i < 4; ++i) { checkpoint += i; checkpointLedger = catchupSimulation.getLastCheckpointLedger(checkpoint); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); REQUIRE( catchupSimulation.catchupOnline(completeApp, checkpointLedger, 5)); REQUIRE( catchupSimulation.catchupOnline(minimalApp, checkpointLedger, 5)); } catchupSimulation.generateRandomLedger(); catchupSimulation.generateRandomLedger(); catchupSimulation.generateRandomLedger(); auto targetLedger = lm.getLastClosedLedgerNum(); REQUIRE(!catchupSimulation.catchupOnline(completeApp, targetLedger, 5)); REQUIRE(!catchupSimulation.catchupOnline(minimalApp, targetLedger, 5)); catchupSimulation.ensureOnlineCatchupPossible(targetLedger, 5); REQUIRE(catchupSimulation.catchupOnline(completeApp, targetLedger, 5)); REQUIRE(catchupSimulation.catchupOnline(minimalApp, targetLedger, 5)); } TEST_CASE("Repair missing buckets via history", "[history][historybucketrepair]") { CatchupSimulation catchupSimulation{}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(1); catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger); HistoryArchiveState has(checkpointLedger + 1, catchupSimulation.getBucketListAtLastPublish()); has.resolveAllFutures(); auto state = has.toString(); auto cfg = getTestConfig(1); cfg.BUCKET_DIR_PATH += "2"; VirtualClock clock; auto app = createTestApplication( clock, catchupSimulation.getHistoryConfigurator().configure(cfg, false)); app->getPersistentState().setState(PersistentState::kHistoryArchiveState, state); app->start(); catchupSimulation.crankUntil( app, [&]() { return app->getWorkScheduler().allChildrenDone(); }, std::chrono::seconds(30)); auto hash1 = catchupSimulation.getBucketListAtLastPublish().getHash(); auto hash2 = app->getBucketManager().getBucketList().getHash(); REQUIRE(hash1 == hash2); } TEST_CASE("Repair missing buckets fails", "[history][historybucketrepair]") { CatchupSimulation catchupSimulation{}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(1); catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger); HistoryArchiveState has(checkpointLedger + 1, catchupSimulation.getBucketListAtLastPublish()); has.resolveAllFutures(); auto state = has.toString(); auto dir = catchupSimulation.getHistoryConfigurator().getArchiveDirName(); REQUIRE(!dir.empty()); fs::deltree(dir + "/bucket"); auto cfg = getTestConfig(1); VirtualClock clock; cfg.BUCKET_DIR_PATH += "2"; auto app = createTestApplication( clock, catchupSimulation.getHistoryConfigurator().configure(cfg, false)); app->getPersistentState().setState(PersistentState::kHistoryArchiveState, state); REQUIRE_THROWS_AS(app->start(), std::runtime_error); } TEST_CASE("Publish catchup via s3", "[!hide][s3]") { CatchupSimulation catchupSimulation{ VirtualClock::VIRTUAL_TIME, std::make_shared<S3HistoryConfigurator>()}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3); catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger); auto app = catchupSimulation.createCatchupApplication( std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE, "s3"); REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5)); } TEST_CASE("persist publish queue", "[history]") { Config cfg(getTestConfig(0, Config::TESTDB_ON_DISK_SQLITE)); cfg.MAX_CONCURRENT_SUBPROCESSES = 0; cfg.ARTIFICIALLY_ACCELERATE_TIME_FOR_TESTING = true; TmpDirHistoryConfigurator tcfg; cfg = tcfg.configure(cfg, true); { VirtualClock clock; Application::pointer app0 = createTestApplication(clock, cfg); app0->start(); auto& hm0 = app0->getHistoryManager(); while (hm0.getPublishQueueCount() < 5) { clock.crank(true); } REQUIRE(hm0.getPublishSuccessCount() == 0); REQUIRE(hm0.getMinLedgerQueuedToPublish() == 7); while (clock.cancelAllEvents() || app0->getProcessManager().getNumRunningProcesses() > 0) { clock.crank(true); } LOG(INFO) << app0->isStopping(); ExternalQueue ps(*app0); ps.deleteOldEntries(50000); } cfg.MAX_CONCURRENT_SUBPROCESSES = 32; { VirtualClock clock; Application::pointer app1 = Application::create(clock, cfg, 0); app1->getHistoryArchiveManager().initializeHistoryArchive("test"); for (size_t i = 0; i < 100; ++i) clock.crank(false); app1->start(); auto& hm1 = app1->getHistoryManager(); while (hm1.getPublishSuccessCount() < 5) { clock.crank(true); ExternalQueue ps(*app1); ps.deleteOldEntries(50000); } auto minLedger = hm1.getMinLedgerQueuedToPublish(); LOG(INFO) << "minLedger " << minLedger; bool okQueue = minLedger == 0 || minLedger >= 35; REQUIRE(okQueue); clock.cancelAllEvents(); while (clock.cancelAllEvents() || app1->getProcessManager().getNumRunningProcesses() > 0) { clock.crank(true); } LOG(INFO) << app1->isStopping(); } } TEST_CASE("catchup with a gap", "[history][catchup][catchupstall]") { CatchupSimulation catchupSimulation{}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(1); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); auto app = catchupSimulation.createCatchupApplication( std::numeric_limits<uint32_t>::max(), Config::TESTDB_IN_MEMORY_SQLITE, "app2"); REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5)); checkpointLedger = catchupSimulation.getLastCheckpointLedger(2); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); auto init = app->getLedgerManager().getLastClosedLedgerNum() + 2; REQUIRE(init == 73); LOG(INFO) << "Starting catchup (with gap) from " << init; REQUIRE(!catchupSimulation.catchupOnline(app, init, 5, init + 10)); REQUIRE(app->getLedgerManager().getLastClosedLedgerNum() == 82); checkpointLedger = catchupSimulation.getLastCheckpointLedger(3); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); CHECK(catchupSimulation.catchupOnline(app, checkpointLedger, 5)); } TEST_CASE("Catchup recent", "[history][catchup][catchuprecent][!hide]") { CatchupSimulation catchupSimulation{}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(3); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); auto dbMode = Config::TESTDB_IN_MEMORY_SQLITE; std::vector<Application::pointer> apps; std::vector<uint32_t> recents = {0, 1, 2, 31, 32, 33, 62, 63, 64, 65, 66, 126, 127, 128, 129, 130, 190, 191, 192, 193, 194, 1000}; for (auto r : recents) { auto name = std::string("catchup-recent-") + std::to_string(r); auto app = catchupSimulation.createCatchupApplication(r, dbMode, name); REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5)); apps.push_back(app); } checkpointLedger = catchupSimulation.getLastCheckpointLedger(5); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); for (auto const& app : apps) { REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5)); } checkpointLedger = catchupSimulation.getLastCheckpointLedger(30); catchupSimulation.ensureOnlineCatchupPossible(checkpointLedger, 5); for (auto const& app : apps) { REQUIRE(catchupSimulation.catchupOnline(app, checkpointLedger, 5)); } } TEST_CASE("Catchup manual", "[history][catchup][catchupmanual]") { CatchupSimulation catchupSimulation{}; auto checkpointLedger = catchupSimulation.getLastCheckpointLedger(6); catchupSimulation.ensureOfflineCatchupPossible(checkpointLedger); auto dbMode = Config::TESTDB_IN_MEMORY_SQLITE; for (auto i = 0; i < viichain::gCatchupRangeCases.size(); i += 10) { auto test = viichain::gCatchupRangeCases[i]; auto configuration = test.second; auto name = fmt::format("lcl = {}, to ledger = {}, count = {}", test.first, configuration.toLedger(), configuration.count()); LOG(INFO) << "Catchup configuration: " << name; auto app = catchupSimulation.createCatchupApplication( configuration.count(), dbMode, name); REQUIRE( catchupSimulation.catchupOffline(app, configuration.toLedger())); } } TEST_CASE("initialize existing history store fails", "[history]") { Config cfg(getTestConfig(0, Config::TESTDB_ON_DISK_SQLITE)); TmpDirHistoryConfigurator tcfg; cfg = tcfg.configure(cfg, true); { VirtualClock clock; Application::pointer app = createTestApplication(clock, cfg); REQUIRE( app->getHistoryArchiveManager().initializeHistoryArchive("test")); } { VirtualClock clock; Application::pointer app = createTestApplication(clock, cfg); REQUIRE( !app->getHistoryArchiveManager().initializeHistoryArchive("test")); } }
37.889299
86
0.657674
viichain
58b78abae22bb807c6b62e0f412e727385b3c970
1,932
cpp
C++
tests/track/pointer.cpp
lexxmark/ref_ptr
526e1c9a96a83de8d7290ca6fc72616681135079
[ "Apache-2.0" ]
3
2017-04-04T16:45:22.000Z
2019-09-01T14:26:16.000Z
tests/track/pointer.cpp
lexxmark/ref_ptr
526e1c9a96a83de8d7290ca6fc72616681135079
[ "Apache-2.0" ]
null
null
null
tests/track/pointer.cpp
lexxmark/ref_ptr
526e1c9a96a83de8d7290ca6fc72616681135079
[ "Apache-2.0" ]
2
2019-11-19T21:58:22.000Z
2021-09-08T00:32:18.000Z
#include <UnitTest++/UnitTest++.h> #define RSL_NULL_PTR_POLICY_DEFAULT(T) rsl::track::may_be_null<T> #define RSL_ON_DANGLE_POLICY_DEFAULT(T) rsl::track::null_on_dangle<T> #include <track/pointer.h> SUITE(track_ptr_tests) { using namespace rsl::track; TEST(basic_test) { trackable object; { auto p = make_ptr(&object); CHECK(p); CHECK_EQUAL(4*sizeof(void*), sizeof(p)); } } TEST(null_track_ptr_test) { { pointer<char> p; CHECK(!p); } { pointer<int> ptr = nullptr; CHECK(!ptr); } } TEST(null_make_track_ptr_test) { { auto ptr = make_ptr<int>(nullptr); CHECK(!ptr); } { trackable object; auto ptr = make_ptr<int>(nullptr, object); CHECK(!ptr); } { trackable* object = nullptr; auto ptr = make_ptr(object); CHECK(!ptr); } } TEST(check_track_ptr_after_delete_test) { auto object = std::make_unique<trackable>(); auto ptr = make_ptr(object.get()); CHECK(ptr); object.reset(); CHECK(!ptr); } TEST(three_track_ptrs_test) { trackable object; { auto ptr1 = make_ptr(&object); CHECK(ptr1); { auto ptr2 = make_ptr(&object); CHECK(ptr2); { auto ptr3 = make_ptr(&object); CHECK(ptr3); } CHECK(ptr2); } CHECK(ptr1); } } TEST(copy_objects_test) { trackable object1; auto ptr1 = make_ptr(&object1); { pointer<trackable> ptr2; { auto object2 = object1; ptr2 = make_ptr(&object2, object2); CHECK(ptr1); CHECK(ptr2); } CHECK(ptr1); CHECK(!ptr2); } CHECK(ptr1); } TEST(sub_object_test) { struct Object : public trackable { int i = 0; }; Object object; auto ptr1 = make_ptr(&object); auto ptr2 = make_ptr(&object.i, object); CHECK_EQUAL(0, ptr1->i); CHECK_EQUAL(0, *ptr2); ptr1->i = 1; CHECK_EQUAL(1, object.i); CHECK_EQUAL(1, *ptr2); *ptr2 = 2; CHECK_EQUAL(2, object.i); CHECK_EQUAL(2, ptr1->i); } }
14.41791
69
0.613872
lexxmark
58bd16a0451473f7dfc3da70c4f56941b51add8d
1,748
hpp
C++
src/driver_authenticator.hpp
simwijs/naoqi_driver
89b00459dc517f8564b1d7092eb36a3fc68a7096
[ "Apache-2.0" ]
null
null
null
src/driver_authenticator.hpp
simwijs/naoqi_driver
89b00459dc517f8564b1d7092eb36a3fc68a7096
[ "Apache-2.0" ]
null
null
null
src/driver_authenticator.hpp
simwijs/naoqi_driver
89b00459dc517f8564b1d7092eb36a3fc68a7096
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015 Aldebaran * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ #ifndef DRIVER_AUTHENTICATOR_HPP #define DRIVER_AUTHENTICATOR_HPP #include <qi/messaging/authprovider.hpp> namespace naoqi { class DriverAuthenticator : public qi::ClientAuthenticator { public: static const std::string user_key; static const std::string pass_key; DriverAuthenticator( const std::string& user, const std::string& pass) : _u(user), _p(pass) {} qi::CapabilityMap initialAuthData() { qi::CapabilityMap result; result[DriverAuthenticator::user_key] = qi::AnyValue::from(_u); result[DriverAuthenticator::pass_key] = qi::AnyValue::from(_p); return result; } qi::CapabilityMap _processAuth(const qi::CapabilityMap&) { return qi::CapabilityMap(); } private: std::string _u; std::string _p; }; const std::string DriverAuthenticator::user_key = "user"; const std::string DriverAuthenticator::pass_key = "token"; class DriverAuthenticatorFactory : public qi::ClientAuthenticatorFactory { public: std::string user; std::string pass; qi::ClientAuthenticatorPtr newAuthenticator() { return boost::make_shared<DriverAuthenticator>(user, pass); } }; } #endif // DRIVER_AUTHENTICATOR
27.3125
75
0.735126
simwijs
58bfd1e86ade32425829d201cf5f15563df29400
995
cpp
C++
TextDungeon/TextDungeon/Audio.cpp
Consalv0/TextDungeon
cabceee081745cc52801efc8b9c10268412578c8
[ "MIT" ]
null
null
null
TextDungeon/TextDungeon/Audio.cpp
Consalv0/TextDungeon
cabceee081745cc52801efc8b9c10268412578c8
[ "MIT" ]
null
null
null
TextDungeon/TextDungeon/Audio.cpp
Consalv0/TextDungeon
cabceee081745cc52801efc8b9c10268412578c8
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Audio.h" // Play the notes in a song. void Audio::Play(array<Note>^ tune) { System::Collections::IEnumerator^ myEnum = tune->GetEnumerator(); while (myEnum->MoveNext()) { Note n = *safe_cast<Note ^>(myEnum->Current); if (n.NoteTone == Tone::REST) Thread::Sleep((int)n.NoteDuration); else Console::Beep((int)n.NoteTone, (int)n.NoteDuration); } } void Audio::MainTheme() { // Declare the first few notes of the song, "Mary Had A Little Lamb". array<Note>^ Mary = { Note(Tone::C, Duration::QUARTER),Note(Tone::B, Duration::QUARTER),Note(Tone::GbelowC, Duration::QUARTER),Note(Tone::B, Duration::QUARTER),Note(Tone::C, Duration::QUARTER),Note(Tone::C, Duration::QUARTER),Note(Tone::C, Duration::HALF),Note(Tone::B, Duration::QUARTER),Note(Tone::B, Duration::QUARTER),Note(Tone::B, Duration::HALF),Note(Tone::C, Duration::QUARTER),Note(Tone::E, Duration::QUARTER),Note(Tone::E, Duration::HALF) }; // Play the song Play(Mary); }
45.227273
452
0.674372
Consalv0
58c2e888e4de6793a9dc0157cf9b5f4eb7b98680
1,933
hpp
C++
external/pss/include/rantala/tools/insertion_sort.hpp
kurpicz/dsss
ac50a22b1beec1d8613a6cd868798426352305c8
[ "BSD-2-Clause" ]
3
2018-10-24T22:15:17.000Z
2019-09-21T22:56:05.000Z
external/pss/include/rantala/tools/insertion_sort.hpp
kurpicz/dsss
ac50a22b1beec1d8613a6cd868798426352305c8
[ "BSD-2-Clause" ]
null
null
null
external/pss/include/rantala/tools/insertion_sort.hpp
kurpicz/dsss
ac50a22b1beec1d8613a6cd868798426352305c8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2007-2008 by Tommi Rantala <tt.rantala@gmail.com> * * 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 namespace rantala { static inline int cmp(const unsigned char* a, const unsigned char* b) { assert(a != 0); assert(b != 0); return strcmp(reinterpret_cast<const char*>(a), reinterpret_cast<const char*>(b)); } static inline void insertion_sort(unsigned char** strings, int n, size_t depth) { for (unsigned char** i = strings + 1; --n > 0; ++i) { unsigned char** j = i; unsigned char* tmp = *i; while (j > strings) { unsigned char* s = *(j-1)+depth; unsigned char* t = tmp+depth; while (*s == *t and not is_end(*s)) { ++s; ++t; } if (*s <= *t) break; *j = *(j-1); --j; } *j = tmp; } } static inline void insertion_sort(unsigned char** strings, size_t n) { insertion_sort(strings, n, 0); } } // namespace rantala
31.177419
79
0.694775
kurpicz
58c3fbf3ae0847cd1840a0026566255648e30af6
4,978
cpp
C++
src/design_editor/Settings.cpp
TheMrButcher/opengl_lessons
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
1
2016-10-25T21:15:16.000Z
2016-10-25T21:15:16.000Z
src/design_editor/Settings.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
375
2016-06-04T11:27:40.000Z
2019-04-14T17:11:09.000Z
src/design_editor/Settings.cpp
TheMrButcher/gamebase
76ac96c45773a54a85d49c6994770b0c3496303f
[ "MIT" ]
null
null
null
/** * Copyright (c) 2018 Slavnejshev Filipp * This file is licensed under the terms of the MIT license. */ #include "Settings.h" #include "Presentation.h" #include <gamebase/impl/app/Config.h> #include <gamebase/text/StringUtils.h> #include <json/reader.h> #include <json/writer.h> namespace gamebase { namespace editor { namespace settings { bool isInterfaceExtended = false; std::string workDir; std::string imagesDir; std::string soundsDir; std::string musicDir; std::string mainConf; std::string designedObjConf; bool isBackupEnabled; bool isComplexBoxMode; namespace { bool complexLayerMode; bool complexAnimationMode; } bool isComplexLayerMode() { return complexLayerMode; } void setComplexLayerMode(bool value) { complexLayerMode = value; if (complexLayerMode) { presentationForDesignView()->setPropertyBaseType( "ImmobileLayer", "list", ""); presentationForDesignView()->setPropertyBaseType( "GameView", "list", ""); } else { presentationForDesignView()->setPropertyBaseType( "ImmobileLayer", "list", "ObjectConstruct"); presentationForDesignView()->setPropertyBaseType( "GameView", "list", "Layer"); } } bool isComplexAnimationMode() { return complexAnimationMode; } void setComplexAnimationMode(bool value) { complexAnimationMode = value; if (complexAnimationMode) { presentationForDesignView()->setPropertyBaseType( "AnimatedObject", "animations", ""); presentationForDesignView()->setPropertyBaseType( "CompositeAnimation", "animations", ""); presentationForDesignView()->setPropertyBaseType( "ParallelAnimation", "animations", ""); presentationForDesignView()->setPropertyBaseType( "RepeatingAnimation", "animation", ""); presentationForDesignView()->setPropertyBaseType( "AnimatedCheckBoxSkin", "checkAnimation", ""); presentationForDesignView()->setPropertyBaseType( "AnimatedCheckBoxSkin", "uncheckAnimation", ""); presentationForDesignView()->setPropertyBaseType( "AnimatedObjectConstruct", "animations", ""); } else { presentationForDesignView()->setPropertyBaseType( "AnimatedObject", "animations", "BasicAnimation"); presentationForDesignView()->setPropertyBaseType( "CompositeAnimation", "animations", "BasicAnimation"); presentationForDesignView()->setPropertyBaseType( "ParallelAnimation", "animations", "BasicAnimation"); presentationForDesignView()->setPropertyBaseType( "RepeatingAnimation", "animation", "BasicAnimation"); presentationForDesignView()->setPropertyBaseType( "AnimatedCheckBoxSkin", "checkAnimation", "BasicAnimation"); presentationForDesignView()->setPropertyBaseType( "AnimatedCheckBoxSkin", "uncheckAnimation", "BasicAnimation"); presentationForDesignView()->setPropertyBaseType( "AnimatedObjectConstruct", "animations", "BasicAnimation"); } } void init() { isInterfaceExtended = impl::getValueFromConfig("interface", "basic") == "extended"; workDir = impl::getValueFromConfig("workingPath", "."); imagesDir = impl::getValueFromConfig("designedObjectImagesPath", impl::getValueFromConfig("imagesPath")); soundsDir = impl::getValueFromConfig("soundsPath", addSlash(imagesDir) + "..\\sounds\\"); musicDir = impl::getValueFromConfig("musicPath", addSlash(imagesDir) + "..\\music\\"); isBackupEnabled = impl::getValueFromConfig("isBackupEnabled", "true") == "true"; isComplexBoxMode = impl::getValueFromConfig("isComplexBoxMode", "false") == "true"; setComplexLayerMode(impl::getValueFromConfig("isComplexLayerMode", "false") == "true"); setComplexAnimationMode(impl::getValueFromConfig("isComplexAnimationMode", "false") == "true"); mainConf = impl::configAsString(); formDesignedObjConfig(); } void formMainConfig(int width, int height, impl::GraphicsMode::Enum mode) { Json::Value conf; Json::Reader r; r.parse(mainConf, conf); conf["version"] = "VER3"; conf["workingPath"] = workDir; conf["designedObjectImagesPath"] = imagesDir; conf["soundsPath"] = soundsDir; conf["musicPath"] = musicDir; conf["width"] = width; conf["height"] = height; conf["mode"] = mode == impl::GraphicsMode::Window ? std::string("window") : std::string("fullscreen"); conf["isBackupEnabled"] = isBackupEnabled; conf["isComplexBoxMode"] = isComplexBoxMode; conf["isComplexLayerMode"] = isComplexLayerMode(); conf["isComplexAnimationMode"] = isComplexAnimationMode(); Json::StyledWriter w; mainConf = w.write(conf); } void formDesignedObjConfig() { Json::Value conf; Json::Reader r; r.parse(mainConf, conf); conf["imagesPath"] = imagesDir; Json::FastWriter w; designedObjConf = w.write(conf); } } } }
34.331034
109
0.684813
TheMrButcher
58cd1f4e7274498d12e2a00f4fb69ba75193e758
1,886
cpp
C++
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_Asap_Regular_18_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_Asap_Regular_18_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
Tools/STM32FW/STM32Cube_FW_F7_V1.16.2/Projects/STM32F7508-DISCO/Demonstrations/TouchGFX/Gui/generated/fonts/src/Table_Asap_Regular_18_4bpp.cpp
ramkumarkoppu/NUCLEO-F767ZI-ESW
85e129d71ee8eccbd0b94b5e07e75b6b91679ee8
[ "MIT" ]
null
null
null
#include <touchgfx/Font.hpp> #ifndef NO_USING_NAMESPACE_TOUCHGFX using namespace touchgfx; #endif FONT_LOCATION_FLASH_PRAGMA KEEP extern const touchgfx::GlyphNode glyphs_Asap_Regular_18_4bpp[] FONT_LOCATION_FLASH_ATTRIBUTE = { { 0, 32, 0, 0, 0, 0, 4, 255, 0, 0}, { 0, 65, 11, 13, 13, 0, 11, 255, 0, 0}, { 72, 66, 10, 13, 13, 1, 11, 255, 0, 0}, { 137, 70, 8, 13, 13, 1, 9, 255, 0, 0}, { 189, 71, 10, 13, 13, 1, 12, 255, 0, 0}, { 254, 76, 8, 13, 13, 1, 9, 255, 0, 0}, { 306, 79, 12, 13, 13, 1, 13, 255, 0, 0}, { 384, 83, 9, 13, 13, 0, 9, 255, 0, 0}, { 443, 84, 10, 13, 13, 0, 10, 255, 0, 0}, { 508, 88, 11, 13, 13, 0, 11, 255, 0, 0}, { 580, 97, 9, 10, 10, 0, 10, 255, 0, 0}, { 625, 98, 9, 14, 14, 1, 10, 255, 0, 0}, { 688, 99, 9, 10, 10, 0, 9, 255, 0, 0}, { 733, 100, 9, 14, 14, 0, 10, 255, 0, 0}, { 796, 101, 9, 10, 10, 0, 10, 255, 0, 0}, { 841, 103, 10, 14, 10, 0, 10, 255, 0, 0}, { 911, 104, 8, 14, 14, 1, 10, 255, 0, 0}, { 967, 105, 3, 14, 14, 1, 5, 255, 0, 0}, { 988, 108, 5, 14, 14, 1, 5, 255, 0, 0}, { 1023, 109, 13, 10, 10, 1, 15, 255, 0, 0}, { 1088, 110, 8, 10, 10, 1, 10, 255, 0, 0}, { 1128, 111, 10, 10, 10, 0, 10, 255, 0, 0}, { 1178, 112, 9, 14, 10, 1, 10, 255, 0, 0}, { 1241, 114, 6, 10, 10, 1, 7, 255, 0, 0}, { 1271, 115, 7, 10, 10, 0, 7, 255, 0, 0}, { 1306, 116, 6, 13, 13, 0, 6, 255, 0, 0}, { 1345, 117, 8, 10, 10, 1, 10, 255, 0, 0}, { 1385, 118, 9, 10, 10, 0, 9, 255, 0, 0}, { 1430, 121, 9, 14, 10, 0, 9, 255, 0, 0} };
44.904762
99
0.389183
ramkumarkoppu
58d0b8f3df5159b07b13a689dcd84a7a3cd180ea
65,825
cc
C++
media/gpu/vaapi_video_decode_accelerator.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
media/gpu/vaapi_video_decode_accelerator.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/gpu/vaapi_video_decode_accelerator.cc
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.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 "media/gpu/vaapi_video_decode_accelerator.h" #include <string.h> #include <memory> #include "base/bind.h" #include "base/files/scoped_file.h" #include "base/logging.h" #include "base/macros.h" #include "base/metrics/histogram.h" #include "base/stl_util.h" #include "base/strings/string_util.h" #include "base/synchronization/waitable_event.h" #include "base/threading/thread_task_runner_handle.h" #include "base/trace_event/trace_event.h" #include "gpu/ipc/service/gpu_channel.h" #include "media/base/bind_to_current_loop.h" #include "media/gpu/accelerated_video_decoder.h" #include "media/gpu/h264_decoder.h" #include "media/gpu/vaapi_picture.h" #include "media/gpu/vp8_decoder.h" #include "media/gpu/vp9_decoder.h" #include "media/video/picture.h" #include "third_party/libva/va/va_dec_vp8.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_image.h" namespace media { namespace { // UMA errors that the VaapiVideoDecodeAccelerator class reports. enum VAVDADecoderFailure { VAAPI_ERROR = 0, VAVDA_DECODER_FAILURES_MAX, }; // Buffer format to use for output buffers backing PictureBuffers. This is the // format decoded frames in VASurfaces are converted into. const gfx::BufferFormat kAllocatePictureFormat = gfx::BufferFormat::BGRA_8888; const gfx::BufferFormat kImportPictureFormat = gfx::BufferFormat::YVU_420; } static void ReportToUMA(VAVDADecoderFailure failure) { UMA_HISTOGRAM_ENUMERATION("Media.VAVDA.DecoderFailure", failure, VAVDA_DECODER_FAILURES_MAX + 1); } #define RETURN_AND_NOTIFY_ON_FAILURE(result, log, error_code, ret) \ do { \ if (!(result)) { \ LOG(ERROR) << log; \ NotifyError(error_code); \ return ret; \ } \ } while (0) class VaapiVideoDecodeAccelerator::VaapiDecodeSurface : public base::RefCountedThreadSafe<VaapiDecodeSurface> { public: VaapiDecodeSurface(int32_t bitstream_id, const scoped_refptr<VASurface>& va_surface); int32_t bitstream_id() const { return bitstream_id_; } scoped_refptr<VASurface> va_surface() { return va_surface_; } private: friend class base::RefCountedThreadSafe<VaapiDecodeSurface>; ~VaapiDecodeSurface(); int32_t bitstream_id_; scoped_refptr<VASurface> va_surface_; }; VaapiVideoDecodeAccelerator::VaapiDecodeSurface::VaapiDecodeSurface( int32_t bitstream_id, const scoped_refptr<VASurface>& va_surface) : bitstream_id_(bitstream_id), va_surface_(va_surface) {} VaapiVideoDecodeAccelerator::VaapiDecodeSurface::~VaapiDecodeSurface() {} class VaapiH264Picture : public H264Picture { public: VaapiH264Picture( const scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface>& dec_surface); VaapiH264Picture* AsVaapiH264Picture() override { return this; } scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> dec_surface() { return dec_surface_; } private: ~VaapiH264Picture() override; scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> dec_surface_; DISALLOW_COPY_AND_ASSIGN(VaapiH264Picture); }; VaapiH264Picture::VaapiH264Picture( const scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface>& dec_surface) : dec_surface_(dec_surface) {} VaapiH264Picture::~VaapiH264Picture() {} class VaapiVideoDecodeAccelerator::VaapiH264Accelerator : public H264Decoder::H264Accelerator { public: VaapiH264Accelerator(VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper); ~VaapiH264Accelerator() override; // H264Decoder::H264Accelerator implementation. scoped_refptr<H264Picture> CreateH264Picture() override; bool SubmitFrameMetadata(const H264SPS* sps, const H264PPS* pps, const H264DPB& dpb, const H264Picture::Vector& ref_pic_listp0, const H264Picture::Vector& ref_pic_listb0, const H264Picture::Vector& ref_pic_listb1, const scoped_refptr<H264Picture>& pic) override; bool SubmitSlice(const H264PPS* pps, const H264SliceHeader* slice_hdr, const H264Picture::Vector& ref_pic_list0, const H264Picture::Vector& ref_pic_list1, const scoped_refptr<H264Picture>& pic, const uint8_t* data, size_t size) override; bool SubmitDecode(const scoped_refptr<H264Picture>& pic) override; bool OutputPicture(const scoped_refptr<H264Picture>& pic) override; void Reset() override; private: scoped_refptr<VaapiDecodeSurface> H264PictureToVaapiDecodeSurface( const scoped_refptr<H264Picture>& pic); void FillVAPicture(VAPictureH264* va_pic, scoped_refptr<H264Picture> pic); int FillVARefFramesFromDPB(const H264DPB& dpb, VAPictureH264* va_pics, int num_pics); VaapiWrapper* vaapi_wrapper_; VaapiVideoDecodeAccelerator* vaapi_dec_; DISALLOW_COPY_AND_ASSIGN(VaapiH264Accelerator); }; class VaapiVP8Picture : public VP8Picture { public: VaapiVP8Picture( const scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface>& dec_surface); VaapiVP8Picture* AsVaapiVP8Picture() override { return this; } scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> dec_surface() { return dec_surface_; } private: ~VaapiVP8Picture() override; scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> dec_surface_; DISALLOW_COPY_AND_ASSIGN(VaapiVP8Picture); }; VaapiVP8Picture::VaapiVP8Picture( const scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface>& dec_surface) : dec_surface_(dec_surface) {} VaapiVP8Picture::~VaapiVP8Picture() {} class VaapiVideoDecodeAccelerator::VaapiVP8Accelerator : public VP8Decoder::VP8Accelerator { public: VaapiVP8Accelerator(VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper); ~VaapiVP8Accelerator() override; // VP8Decoder::VP8Accelerator implementation. scoped_refptr<VP8Picture> CreateVP8Picture() override; bool SubmitDecode(const scoped_refptr<VP8Picture>& pic, const Vp8FrameHeader* frame_hdr, const scoped_refptr<VP8Picture>& last_frame, const scoped_refptr<VP8Picture>& golden_frame, const scoped_refptr<VP8Picture>& alt_frame) override; bool OutputPicture(const scoped_refptr<VP8Picture>& pic) override; private: scoped_refptr<VaapiDecodeSurface> VP8PictureToVaapiDecodeSurface( const scoped_refptr<VP8Picture>& pic); VaapiWrapper* vaapi_wrapper_; VaapiVideoDecodeAccelerator* vaapi_dec_; DISALLOW_COPY_AND_ASSIGN(VaapiVP8Accelerator); }; class VaapiVP9Picture : public VP9Picture { public: VaapiVP9Picture( const scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface>& dec_surface); VaapiVP9Picture* AsVaapiVP9Picture() override { return this; } scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> dec_surface() { return dec_surface_; } private: ~VaapiVP9Picture() override; scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> dec_surface_; DISALLOW_COPY_AND_ASSIGN(VaapiVP9Picture); }; VaapiVP9Picture::VaapiVP9Picture( const scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface>& dec_surface) : dec_surface_(dec_surface) {} VaapiVP9Picture::~VaapiVP9Picture() {} class VaapiVideoDecodeAccelerator::VaapiVP9Accelerator : public VP9Decoder::VP9Accelerator { public: VaapiVP9Accelerator(VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper); ~VaapiVP9Accelerator() override; // VP9Decoder::VP9Accelerator implementation. scoped_refptr<VP9Picture> CreateVP9Picture() override; bool SubmitDecode( const scoped_refptr<VP9Picture>& pic, const Vp9Segmentation& seg, const Vp9LoopFilter& lf, const std::vector<scoped_refptr<VP9Picture>>& ref_pictures) override; bool OutputPicture(const scoped_refptr<VP9Picture>& pic) override; private: scoped_refptr<VaapiDecodeSurface> VP9PictureToVaapiDecodeSurface( const scoped_refptr<VP9Picture>& pic); VaapiWrapper* vaapi_wrapper_; VaapiVideoDecodeAccelerator* vaapi_dec_; DISALLOW_COPY_AND_ASSIGN(VaapiVP9Accelerator); }; VaapiVideoDecodeAccelerator::InputBuffer::InputBuffer() : id(0) {} VaapiVideoDecodeAccelerator::InputBuffer::~InputBuffer() {} void VaapiVideoDecodeAccelerator::NotifyError(Error error) { if (!task_runner_->BelongsToCurrentThread()) { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); task_runner_->PostTask(FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::NotifyError, weak_this_, error)); return; } // Post Cleanup() as a task so we don't recursively acquire lock_. task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::Cleanup, weak_this_)); LOG(ERROR) << "Notifying of error " << error; if (client_) { client_->NotifyError(error); client_ptr_factory_.reset(); } } VaapiPicture* VaapiVideoDecodeAccelerator::PictureById( int32_t picture_buffer_id) { Pictures::iterator it = pictures_.find(picture_buffer_id); if (it == pictures_.end()) { LOG(WARNING) << "Picture id " << picture_buffer_id << " does not exist"; return NULL; } return it->second.get(); } VaapiVideoDecodeAccelerator::VaapiVideoDecodeAccelerator( const MakeGLContextCurrentCallback& make_context_current_cb, const BindGLImageCallback& bind_image_cb) : state_(kUninitialized), input_ready_(&lock_), surfaces_available_(&lock_), task_runner_(base::ThreadTaskRunnerHandle::Get()), decoder_thread_("VaapiDecoderThread"), num_frames_at_client_(0), num_stream_bufs_at_decoder_(0), finish_flush_pending_(false), awaiting_va_surfaces_recycle_(false), requested_num_pics_(0), output_format_(kAllocatePictureFormat), make_context_current_cb_(make_context_current_cb), bind_image_cb_(bind_image_cb), weak_this_factory_(this) { weak_this_ = weak_this_factory_.GetWeakPtr(); va_surface_release_cb_ = BindToCurrentLoop( base::Bind(&VaapiVideoDecodeAccelerator::RecycleVASurfaceID, weak_this_)); } VaapiVideoDecodeAccelerator::~VaapiVideoDecodeAccelerator() { DCHECK(task_runner_->BelongsToCurrentThread()); } bool VaapiVideoDecodeAccelerator::Initialize(const Config& config, Client* client) { DCHECK(task_runner_->BelongsToCurrentThread()); if (config.is_encrypted) { NOTREACHED() << "Encrypted streams are not supported for this VDA"; return false; } switch (config.output_mode) { case Config::OutputMode::ALLOCATE: output_format_ = kAllocatePictureFormat; break; case Config::OutputMode::IMPORT: output_format_ = kImportPictureFormat; break; default: NOTREACHED() << "Only ALLOCATE and IMPORT OutputModes are supported"; return false; } client_ptr_factory_.reset(new base::WeakPtrFactory<Client>(client)); client_ = client_ptr_factory_->GetWeakPtr(); VideoCodecProfile profile = config.profile; base::AutoLock auto_lock(lock_); DCHECK_EQ(state_, kUninitialized); DVLOG(2) << "Initializing VAVDA, profile: " << profile; #if defined(USE_X11) if (gl::GetGLImplementation() != gl::kGLImplementationDesktopGL) { DVLOG(1) << "HW video decode acceleration not available without " "DesktopGL (GLX)."; return false; } #elif defined(USE_OZONE) if (gl::GetGLImplementation() != gl::kGLImplementationEGLGLES2) { DVLOG(1) << "HW video decode acceleration not available without " << "EGLGLES2."; return false; } #endif // USE_X11 vaapi_wrapper_ = VaapiWrapper::CreateForVideoCodec( VaapiWrapper::kDecode, profile, base::Bind(&ReportToUMA, VAAPI_ERROR)); if (!vaapi_wrapper_.get()) { DVLOG(1) << "Failed initializing VAAPI for profile " << profile; return false; } if (profile >= H264PROFILE_MIN && profile <= H264PROFILE_MAX) { h264_accelerator_.reset( new VaapiH264Accelerator(this, vaapi_wrapper_.get())); decoder_.reset(new H264Decoder(h264_accelerator_.get())); } else if (profile >= VP8PROFILE_MIN && profile <= VP8PROFILE_MAX) { vp8_accelerator_.reset(new VaapiVP8Accelerator(this, vaapi_wrapper_.get())); decoder_.reset(new VP8Decoder(vp8_accelerator_.get())); } else if (profile >= VP9PROFILE_MIN && profile <= VP9PROFILE_MAX) { vp9_accelerator_.reset(new VaapiVP9Accelerator(this, vaapi_wrapper_.get())); decoder_.reset(new VP9Decoder(vp9_accelerator_.get())); } else { DLOG(ERROR) << "Unsupported profile " << profile; return false; } CHECK(decoder_thread_.Start()); decoder_thread_task_runner_ = decoder_thread_.task_runner(); state_ = kIdle; output_mode_ = config.output_mode; return true; } void VaapiVideoDecodeAccelerator::OutputPicture( const scoped_refptr<VASurface>& va_surface, int32_t input_id, VaapiPicture* picture) { DCHECK(task_runner_->BelongsToCurrentThread()); int32_t output_id = picture->picture_buffer_id(); TRACE_EVENT2("Video Decoder", "VAVDA::OutputSurface", "input_id", input_id, "output_id", output_id); DVLOG(3) << "Outputting VASurface " << va_surface->id() << " into pixmap bound to picture buffer id " << output_id; RETURN_AND_NOTIFY_ON_FAILURE(picture->DownloadFromSurface(va_surface), "Failed putting surface into pixmap", PLATFORM_FAILURE, ); // Notify the client a picture is ready to be displayed. ++num_frames_at_client_; TRACE_COUNTER1("Video Decoder", "Textures at client", num_frames_at_client_); DVLOG(4) << "Notifying output picture id " << output_id << " for input " << input_id << " is ready"; // TODO(posciak): Use visible size from decoder here instead // (crbug.com/402760). Passing (0, 0) results in the client using the // visible size extracted from the container instead. if (client_) client_->PictureReady( Picture(output_id, input_id, gfx::Rect(0, 0), picture->AllowOverlay())); } void VaapiVideoDecodeAccelerator::TryOutputSurface() { DCHECK(task_runner_->BelongsToCurrentThread()); // Handle Destroy() arriving while pictures are queued for output. if (!client_) return; if (pending_output_cbs_.empty() || output_buffers_.empty()) return; OutputCB output_cb = pending_output_cbs_.front(); pending_output_cbs_.pop(); VaapiPicture* picture = PictureById(output_buffers_.front()); DCHECK(picture); output_buffers_.pop(); output_cb.Run(picture); if (finish_flush_pending_ && pending_output_cbs_.empty()) FinishFlush(); } void VaapiVideoDecodeAccelerator::MapAndQueueNewInputBuffer( const BitstreamBuffer& bitstream_buffer) { DCHECK(task_runner_->BelongsToCurrentThread()); TRACE_EVENT1("Video Decoder", "MapAndQueueNewInputBuffer", "input_id", bitstream_buffer.id()); DVLOG(4) << "Mapping new input buffer id: " << bitstream_buffer.id() << " size: " << (int)bitstream_buffer.size(); std::unique_ptr<SharedMemoryRegion> shm( new SharedMemoryRegion(bitstream_buffer, true)); // Skip empty buffers. if (bitstream_buffer.size() == 0) { if (client_) client_->NotifyEndOfBitstreamBuffer(bitstream_buffer.id()); return; } RETURN_AND_NOTIFY_ON_FAILURE(shm->Map(), "Failed to map input buffer", UNREADABLE_INPUT, ); base::AutoLock auto_lock(lock_); // Set up a new input buffer and queue it for later. linked_ptr<InputBuffer> input_buffer(new InputBuffer()); input_buffer->shm.reset(shm.release()); input_buffer->id = bitstream_buffer.id(); ++num_stream_bufs_at_decoder_; TRACE_COUNTER1("Video Decoder", "Stream buffers at decoder", num_stream_bufs_at_decoder_); input_buffers_.push(input_buffer); input_ready_.Signal(); } bool VaapiVideoDecodeAccelerator::GetInputBuffer_Locked() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); lock_.AssertAcquired(); if (curr_input_buffer_.get()) return true; // Will only wait if it is expected that in current state new buffers will // be queued from the client via Decode(). The state can change during wait. while (input_buffers_.empty() && (state_ == kDecoding || state_ == kIdle)) { input_ready_.Wait(); } // We could have got woken up in a different state or never got to sleep // due to current state; check for that. switch (state_) { case kFlushing: // Here we are only interested in finishing up decoding buffers that are // already queued up. Otherwise will stop decoding. if (input_buffers_.empty()) return false; // else fallthrough case kDecoding: case kIdle: DCHECK(!input_buffers_.empty()); curr_input_buffer_ = input_buffers_.front(); input_buffers_.pop(); DVLOG(4) << "New current bitstream buffer, id: " << curr_input_buffer_->id << " size: " << curr_input_buffer_->shm->size(); decoder_->SetStream( static_cast<uint8_t*>(curr_input_buffer_->shm->memory()), curr_input_buffer_->shm->size()); return true; default: // We got woken up due to being destroyed/reset, ignore any already // queued inputs. return false; } } void VaapiVideoDecodeAccelerator::ReturnCurrInputBuffer_Locked() { lock_.AssertAcquired(); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DCHECK(curr_input_buffer_.get()); int32_t id = curr_input_buffer_->id; curr_input_buffer_.reset(); DVLOG(4) << "End of input buffer " << id; task_runner_->PostTask( FROM_HERE, base::Bind(&Client::NotifyEndOfBitstreamBuffer, client_, id)); --num_stream_bufs_at_decoder_; TRACE_COUNTER1("Video Decoder", "Stream buffers at decoder", num_stream_bufs_at_decoder_); } // TODO(posciak): refactor the whole class to remove sleeping in wait for // surfaces, and reschedule DecodeTask instead. bool VaapiVideoDecodeAccelerator::WaitForSurfaces_Locked() { lock_.AssertAcquired(); DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); while (available_va_surfaces_.empty() && (state_ == kDecoding || state_ == kFlushing || state_ == kIdle)) { surfaces_available_.Wait(); } if (state_ != kDecoding && state_ != kFlushing && state_ != kIdle) return false; return true; } void VaapiVideoDecodeAccelerator::DecodeTask() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); TRACE_EVENT0("Video Decoder", "VAVDA::DecodeTask"); base::AutoLock auto_lock(lock_); if (state_ != kDecoding) return; // Main decode task. DVLOG(4) << "Decode task"; // Try to decode what stream data is (still) in the decoder until we run out // of it. while (GetInputBuffer_Locked()) { DCHECK(curr_input_buffer_.get()); AcceleratedVideoDecoder::DecodeResult res; { // We are OK releasing the lock here, as decoder never calls our methods // directly and we will reacquire the lock before looking at state again. // This is the main decode function of the decoder and while keeping // the lock for its duration would be fine, it would defeat the purpose // of having a separate decoder thread. base::AutoUnlock auto_unlock(lock_); res = decoder_->Decode(); } switch (res) { case AcceleratedVideoDecoder::kAllocateNewSurfaces: DVLOG(1) << "Decoder requesting a new set of surfaces"; task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::InitiateSurfaceSetChange, weak_this_, decoder_->GetRequiredNumOfPictures(), decoder_->GetPicSize())); // We'll get rescheduled once ProvidePictureBuffers() finishes. return; case AcceleratedVideoDecoder::kRanOutOfStreamData: ReturnCurrInputBuffer_Locked(); break; case AcceleratedVideoDecoder::kRanOutOfSurfaces: // No more output buffers in the decoder, try getting more or go to // sleep waiting for them. if (!WaitForSurfaces_Locked()) return; break; case AcceleratedVideoDecoder::kDecodeError: RETURN_AND_NOTIFY_ON_FAILURE(false, "Error decoding stream", PLATFORM_FAILURE, ); return; } } } void VaapiVideoDecodeAccelerator::InitiateSurfaceSetChange(size_t num_pics, gfx::Size size) { DCHECK(task_runner_->BelongsToCurrentThread()); DCHECK(!awaiting_va_surfaces_recycle_); // At this point decoder has stopped running and has already posted onto our // loop any remaining output request callbacks, which executed before we got // here. Some of them might have been pended though, because we might not // have had enough TFPictures to output surfaces to. Initiate a wait cycle, // which will wait for client to return enough PictureBuffers to us, so that // we can finish all pending output callbacks, releasing associated surfaces. DVLOG(1) << "Initiating surface set change"; awaiting_va_surfaces_recycle_ = true; requested_num_pics_ = num_pics; requested_pic_size_ = size; TryFinishSurfaceSetChange(); } static VideoPixelFormat BufferFormatToVideoPixelFormat( gfx::BufferFormat format) { switch (format) { case gfx::BufferFormat::BGRA_8888: return PIXEL_FORMAT_ARGB; case gfx::BufferFormat::YVU_420: return PIXEL_FORMAT_YV12; default: LOG(FATAL) << "Add more cases as needed"; return PIXEL_FORMAT_UNKNOWN; } } void VaapiVideoDecodeAccelerator::TryFinishSurfaceSetChange() { DCHECK(task_runner_->BelongsToCurrentThread()); if (!awaiting_va_surfaces_recycle_) return; if (!pending_output_cbs_.empty() || pictures_.size() != available_va_surfaces_.size()) { // Either: // 1. Not all pending pending output callbacks have been executed yet. // Wait for the client to return enough pictures and retry later. // 2. The above happened and all surface release callbacks have been posted // as the result, but not all have executed yet. Post ourselves after them // to let them release surfaces. DVLOG(2) << "Awaiting pending output/surface release callbacks to finish"; task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::TryFinishSurfaceSetChange, weak_this_)); return; } // All surfaces released, destroy them and dismiss all PictureBuffers. awaiting_va_surfaces_recycle_ = false; available_va_surfaces_.clear(); vaapi_wrapper_->DestroySurfaces(); for (Pictures::iterator iter = pictures_.begin(); iter != pictures_.end(); ++iter) { DVLOG(2) << "Dismissing picture id: " << iter->first; if (client_) client_->DismissPictureBuffer(iter->first); } pictures_.clear(); // And ask for a new set as requested. DVLOG(1) << "Requesting " << requested_num_pics_ << " pictures of size: " << requested_pic_size_.ToString(); VideoPixelFormat format = BufferFormatToVideoPixelFormat(output_format_); task_runner_->PostTask( FROM_HERE, base::Bind(&Client::ProvidePictureBuffers, client_, requested_num_pics_, format, 1, requested_pic_size_, VaapiPicture::GetGLTextureTarget())); } void VaapiVideoDecodeAccelerator::Decode( const BitstreamBuffer& bitstream_buffer) { DCHECK(task_runner_->BelongsToCurrentThread()); TRACE_EVENT1("Video Decoder", "VAVDA::Decode", "Buffer id", bitstream_buffer.id()); if (bitstream_buffer.id() < 0) { if (base::SharedMemory::IsHandleValid(bitstream_buffer.handle())) base::SharedMemory::CloseHandle(bitstream_buffer.handle()); LOG(ERROR) << "Invalid bitstream_buffer, id: " << bitstream_buffer.id(); NotifyError(INVALID_ARGUMENT); return; } // We got a new input buffer from the client, map it and queue for later use. MapAndQueueNewInputBuffer(bitstream_buffer); base::AutoLock auto_lock(lock_); switch (state_) { case kIdle: state_ = kDecoding; decoder_thread_task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::DecodeTask, base::Unretained(this))); break; case kDecoding: // Decoder already running, fallthrough. case kResetting: // When resetting, allow accumulating bitstream buffers, so that // the client can queue after-seek-buffers while we are finishing with // the before-seek one. break; default: RETURN_AND_NOTIFY_ON_FAILURE( false, "Decode request from client in invalid state: " << state_, PLATFORM_FAILURE, ); break; } } void VaapiVideoDecodeAccelerator::RecycleVASurfaceID( VASurfaceID va_surface_id) { DCHECK(task_runner_->BelongsToCurrentThread()); base::AutoLock auto_lock(lock_); available_va_surfaces_.push_back(va_surface_id); surfaces_available_.Signal(); } void VaapiVideoDecodeAccelerator::AssignPictureBuffers( const std::vector<PictureBuffer>& buffers) { DCHECK(task_runner_->BelongsToCurrentThread()); base::AutoLock auto_lock(lock_); DCHECK(pictures_.empty()); while (!output_buffers_.empty()) output_buffers_.pop(); RETURN_AND_NOTIFY_ON_FAILURE( buffers.size() >= requested_num_pics_, "Got an invalid number of picture buffers. (Got " << buffers.size() << ", requested " << requested_num_pics_ << ")", INVALID_ARGUMENT, ); DCHECK(requested_pic_size_ == buffers[0].size()); std::vector<VASurfaceID> va_surface_ids; RETURN_AND_NOTIFY_ON_FAILURE( vaapi_wrapper_->CreateSurfaces(VA_RT_FORMAT_YUV420, requested_pic_size_, buffers.size(), &va_surface_ids), "Failed creating VA Surfaces", PLATFORM_FAILURE, ); DCHECK_EQ(va_surface_ids.size(), buffers.size()); for (size_t i = 0; i < buffers.size(); ++i) { uint32_t texture_id = buffers[i].texture_ids().size() > 0 ? buffers[i].texture_ids()[0] : 0; uint32_t internal_texture_id = buffers[i].internal_texture_ids().size() > 0 ? buffers[i].internal_texture_ids()[0] : 0; linked_ptr<VaapiPicture> picture(VaapiPicture::CreatePicture( vaapi_wrapper_, make_context_current_cb_, bind_image_cb_, buffers[i].id(), requested_pic_size_, texture_id, internal_texture_id)); RETURN_AND_NOTIFY_ON_FAILURE( picture.get(), "Failed creating a VaapiPicture", PLATFORM_FAILURE, ); bool inserted = pictures_.insert(std::make_pair(buffers[i].id(), picture)).second; DCHECK(inserted); if (output_mode_ == Config::OutputMode::ALLOCATE) { RETURN_AND_NOTIFY_ON_FAILURE( picture->Allocate(output_format_), "Failed to allocate memory for a VaapiPicture", PLATFORM_FAILURE, ); output_buffers_.push(buffers[i].id()); } available_va_surfaces_.push_back(va_surface_ids[i]); surfaces_available_.Signal(); } // The resolution changing may happen while resetting or flushing. In this // case we do not change state and post DecodeTask(). if (state_ != kResetting && state_ != kFlushing) { state_ = kDecoding; decoder_thread_task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::DecodeTask, base::Unretained(this))); } } #if defined(USE_OZONE) static void CloseGpuMemoryBufferHandle( const gfx::GpuMemoryBufferHandle& handle) { for (const auto& fd : handle.native_pixmap_handle.fds) { // Close the fd by wrapping it in a ScopedFD and letting // it fall out of scope. base::ScopedFD scoped_fd(fd.fd); } } void VaapiVideoDecodeAccelerator::ImportBufferForPicture( int32_t picture_buffer_id, const gfx::GpuMemoryBufferHandle& gpu_memory_buffer_handle) { DCHECK(task_runner_->BelongsToCurrentThread()); DVLOG(2) << "Importing picture id: " << picture_buffer_id; if (output_mode_ != Config::OutputMode::IMPORT) { CloseGpuMemoryBufferHandle(gpu_memory_buffer_handle); LOG(ERROR) << "Cannot import in non-import mode"; NotifyError(INVALID_ARGUMENT); return; } VaapiPicture* picture = PictureById(picture_buffer_id); if (!picture) { CloseGpuMemoryBufferHandle(gpu_memory_buffer_handle); // It's possible that we've already posted a DismissPictureBuffer for this // picture, but it has not yet executed when this ImportBufferForPicture // was posted to us by the client. In that case just ignore this (we've // already dismissed it and accounted for that). DVLOG(3) << "got picture id=" << picture_buffer_id << " not in use (anymore?)."; return; } if (!picture->ImportGpuMemoryBufferHandle(output_format_, gpu_memory_buffer_handle)) { // ImportGpuMemoryBufferHandle will close the handles even on failure, so // we don't need to do this ourselves. LOG(ERROR) << "Failed to import GpuMemoryBufferHandle"; NotifyError(PLATFORM_FAILURE); return; } ReusePictureBuffer(picture_buffer_id); } #endif void VaapiVideoDecodeAccelerator::ReusePictureBuffer( int32_t picture_buffer_id) { DCHECK(task_runner_->BelongsToCurrentThread()); TRACE_EVENT1("Video Decoder", "VAVDA::ReusePictureBuffer", "Picture id", picture_buffer_id); if (!PictureById(picture_buffer_id)) { // It's possible that we've already posted a DismissPictureBuffer for this // picture, but it has not yet executed when this ReusePictureBuffer // was posted to us by the client. In that case just ignore this (we've // already dismissed it and accounted for that). DVLOG(3) << "got picture id=" << picture_buffer_id << " not in use (anymore?)."; return; } --num_frames_at_client_; TRACE_COUNTER1("Video Decoder", "Textures at client", num_frames_at_client_); output_buffers_.push(picture_buffer_id); TryOutputSurface(); } void VaapiVideoDecodeAccelerator::FlushTask() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DVLOG(1) << "Flush task"; // First flush all the pictures that haven't been outputted, notifying the // client to output them. bool res = decoder_->Flush(); RETURN_AND_NOTIFY_ON_FAILURE(res, "Failed flushing the decoder.", PLATFORM_FAILURE, ); // Put the decoder in idle state, ready to resume. decoder_->Reset(); task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::FinishFlush, weak_this_)); } void VaapiVideoDecodeAccelerator::Flush() { DCHECK(task_runner_->BelongsToCurrentThread()); DVLOG(1) << "Got flush request"; base::AutoLock auto_lock(lock_); state_ = kFlushing; // Queue a flush task after all existing decoding tasks to clean up. decoder_thread_task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::FlushTask, base::Unretained(this))); input_ready_.Signal(); surfaces_available_.Signal(); } void VaapiVideoDecodeAccelerator::FinishFlush() { DCHECK(task_runner_->BelongsToCurrentThread()); finish_flush_pending_ = false; base::AutoLock auto_lock(lock_); if (state_ != kFlushing) { DCHECK_EQ(state_, kDestroying); return; // We could've gotten destroyed already. } // Still waiting for textures from client to finish outputting all pending // frames. Try again later. if (!pending_output_cbs_.empty()) { finish_flush_pending_ = true; return; } state_ = kIdle; task_runner_->PostTask(FROM_HERE, base::Bind(&Client::NotifyFlushDone, client_)); DVLOG(1) << "Flush finished"; } void VaapiVideoDecodeAccelerator::ResetTask() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); DVLOG(1) << "ResetTask"; // All the decoding tasks from before the reset request from client are done // by now, as this task was scheduled after them and client is expected not // to call Decode() after Reset() and before NotifyResetDone. decoder_->Reset(); base::AutoLock auto_lock(lock_); // Return current input buffer, if present. if (curr_input_buffer_.get()) ReturnCurrInputBuffer_Locked(); // And let client know that we are done with reset. task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::FinishReset, weak_this_)); } void VaapiVideoDecodeAccelerator::Reset() { DCHECK(task_runner_->BelongsToCurrentThread()); DVLOG(1) << "Got reset request"; // This will make any new decode tasks exit early. base::AutoLock auto_lock(lock_); state_ = kResetting; finish_flush_pending_ = false; // Drop all remaining input buffers, if present. while (!input_buffers_.empty()) { task_runner_->PostTask( FROM_HERE, base::Bind(&Client::NotifyEndOfBitstreamBuffer, client_, input_buffers_.front()->id)); input_buffers_.pop(); } decoder_thread_task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::ResetTask, base::Unretained(this))); input_ready_.Signal(); surfaces_available_.Signal(); } void VaapiVideoDecodeAccelerator::FinishReset() { DCHECK(task_runner_->BelongsToCurrentThread()); DVLOG(1) << "FinishReset"; base::AutoLock auto_lock(lock_); if (state_ != kResetting) { DCHECK(state_ == kDestroying || state_ == kUninitialized) << state_; return; // We could've gotten destroyed already. } // Drop pending outputs. while (!pending_output_cbs_.empty()) pending_output_cbs_.pop(); if (awaiting_va_surfaces_recycle_) { // Decoder requested a new surface set while we were waiting for it to // finish the last DecodeTask, running at the time of Reset(). // Let the surface set change finish first before resetting. task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::FinishReset, weak_this_)); return; } num_stream_bufs_at_decoder_ = 0; state_ = kIdle; task_runner_->PostTask(FROM_HERE, base::Bind(&Client::NotifyResetDone, client_)); // The client might have given us new buffers via Decode() while we were // resetting and might be waiting for our move, and not call Decode() anymore // until we return something. Post a DecodeTask() so that we won't // sleep forever waiting for Decode() in that case. Having two of them // in the pipe is harmless, the additional one will return as soon as it sees // that we are back in kDecoding state. if (!input_buffers_.empty()) { state_ = kDecoding; decoder_thread_task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::DecodeTask, base::Unretained(this))); } DVLOG(1) << "Reset finished"; } void VaapiVideoDecodeAccelerator::Cleanup() { DCHECK(task_runner_->BelongsToCurrentThread()); base::AutoLock auto_lock(lock_); if (state_ == kUninitialized || state_ == kDestroying) return; DVLOG(1) << "Destroying VAVDA"; state_ = kDestroying; client_ptr_factory_.reset(); weak_this_factory_.InvalidateWeakPtrs(); // Signal all potential waiters on the decoder_thread_, let them early-exit, // as we've just moved to the kDestroying state, and wait for all tasks // to finish. input_ready_.Signal(); surfaces_available_.Signal(); { base::AutoUnlock auto_unlock(lock_); decoder_thread_.Stop(); } state_ = kUninitialized; } void VaapiVideoDecodeAccelerator::Destroy() { DCHECK(task_runner_->BelongsToCurrentThread()); Cleanup(); delete this; } bool VaapiVideoDecodeAccelerator::TryToSetupDecodeOnSeparateThread( const base::WeakPtr<Client>& decode_client, const scoped_refptr<base::SingleThreadTaskRunner>& decode_task_runner) { return false; } bool VaapiVideoDecodeAccelerator::DecodeSurface( const scoped_refptr<VaapiDecodeSurface>& dec_surface) { if (!vaapi_wrapper_->ExecuteAndDestroyPendingBuffers( dec_surface->va_surface()->id())) { DVLOG(1) << "Failed decoding picture"; return false; } return true; } void VaapiVideoDecodeAccelerator::SurfaceReady( const scoped_refptr<VaapiDecodeSurface>& dec_surface) { if (!task_runner_->BelongsToCurrentThread()) { task_runner_->PostTask( FROM_HERE, base::Bind(&VaapiVideoDecodeAccelerator::SurfaceReady, weak_this_, dec_surface)); return; } DCHECK(!awaiting_va_surfaces_recycle_); { base::AutoLock auto_lock(lock_); // Drop any requests to output if we are resetting or being destroyed. if (state_ == kResetting || state_ == kDestroying) return; } pending_output_cbs_.push( base::Bind(&VaapiVideoDecodeAccelerator::OutputPicture, weak_this_, dec_surface->va_surface(), dec_surface->bitstream_id())); TryOutputSurface(); } scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> VaapiVideoDecodeAccelerator::CreateSurface() { DCHECK(decoder_thread_task_runner_->BelongsToCurrentThread()); base::AutoLock auto_lock(lock_); if (available_va_surfaces_.empty()) return nullptr; DCHECK(!awaiting_va_surfaces_recycle_); scoped_refptr<VASurface> va_surface(new VASurface( available_va_surfaces_.front(), requested_pic_size_, vaapi_wrapper_->va_surface_format(), va_surface_release_cb_)); available_va_surfaces_.pop_front(); scoped_refptr<VaapiDecodeSurface> dec_surface = new VaapiDecodeSurface(curr_input_buffer_->id, va_surface); return dec_surface; } VaapiVideoDecodeAccelerator::VaapiH264Accelerator::VaapiH264Accelerator( VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper) : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { DCHECK(vaapi_wrapper_); DCHECK(vaapi_dec_); } VaapiVideoDecodeAccelerator::VaapiH264Accelerator::~VaapiH264Accelerator() {} scoped_refptr<H264Picture> VaapiVideoDecodeAccelerator::VaapiH264Accelerator::CreateH264Picture() { scoped_refptr<VaapiDecodeSurface> va_surface = vaapi_dec_->CreateSurface(); if (!va_surface) return nullptr; return new VaapiH264Picture(va_surface); } // Fill |va_pic| with default/neutral values. static void InitVAPicture(VAPictureH264* va_pic) { memset(va_pic, 0, sizeof(*va_pic)); va_pic->picture_id = VA_INVALID_ID; va_pic->flags = VA_PICTURE_H264_INVALID; } bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitFrameMetadata( const H264SPS* sps, const H264PPS* pps, const H264DPB& dpb, const H264Picture::Vector& ref_pic_listp0, const H264Picture::Vector& ref_pic_listb0, const H264Picture::Vector& ref_pic_listb1, const scoped_refptr<H264Picture>& pic) { VAPictureParameterBufferH264 pic_param; memset(&pic_param, 0, sizeof(pic_param)); #define FROM_SPS_TO_PP(a) pic_param.a = sps->a #define FROM_SPS_TO_PP2(a, b) pic_param.b = sps->a FROM_SPS_TO_PP2(pic_width_in_mbs_minus1, picture_width_in_mbs_minus1); // This assumes non-interlaced video FROM_SPS_TO_PP2(pic_height_in_map_units_minus1, picture_height_in_mbs_minus1); FROM_SPS_TO_PP(bit_depth_luma_minus8); FROM_SPS_TO_PP(bit_depth_chroma_minus8); #undef FROM_SPS_TO_PP #undef FROM_SPS_TO_PP2 #define FROM_SPS_TO_PP_SF(a) pic_param.seq_fields.bits.a = sps->a #define FROM_SPS_TO_PP_SF2(a, b) pic_param.seq_fields.bits.b = sps->a FROM_SPS_TO_PP_SF(chroma_format_idc); FROM_SPS_TO_PP_SF2(separate_colour_plane_flag, residual_colour_transform_flag); FROM_SPS_TO_PP_SF(gaps_in_frame_num_value_allowed_flag); FROM_SPS_TO_PP_SF(frame_mbs_only_flag); FROM_SPS_TO_PP_SF(mb_adaptive_frame_field_flag); FROM_SPS_TO_PP_SF(direct_8x8_inference_flag); pic_param.seq_fields.bits.MinLumaBiPredSize8x8 = (sps->level_idc >= 31); FROM_SPS_TO_PP_SF(log2_max_frame_num_minus4); FROM_SPS_TO_PP_SF(pic_order_cnt_type); FROM_SPS_TO_PP_SF(log2_max_pic_order_cnt_lsb_minus4); FROM_SPS_TO_PP_SF(delta_pic_order_always_zero_flag); #undef FROM_SPS_TO_PP_SF #undef FROM_SPS_TO_PP_SF2 #define FROM_PPS_TO_PP(a) pic_param.a = pps->a FROM_PPS_TO_PP(num_slice_groups_minus1); pic_param.slice_group_map_type = 0; pic_param.slice_group_change_rate_minus1 = 0; FROM_PPS_TO_PP(pic_init_qp_minus26); FROM_PPS_TO_PP(pic_init_qs_minus26); FROM_PPS_TO_PP(chroma_qp_index_offset); FROM_PPS_TO_PP(second_chroma_qp_index_offset); #undef FROM_PPS_TO_PP #define FROM_PPS_TO_PP_PF(a) pic_param.pic_fields.bits.a = pps->a #define FROM_PPS_TO_PP_PF2(a, b) pic_param.pic_fields.bits.b = pps->a FROM_PPS_TO_PP_PF(entropy_coding_mode_flag); FROM_PPS_TO_PP_PF(weighted_pred_flag); FROM_PPS_TO_PP_PF(weighted_bipred_idc); FROM_PPS_TO_PP_PF(transform_8x8_mode_flag); pic_param.pic_fields.bits.field_pic_flag = 0; FROM_PPS_TO_PP_PF(constrained_intra_pred_flag); FROM_PPS_TO_PP_PF2(bottom_field_pic_order_in_frame_present_flag, pic_order_present_flag); FROM_PPS_TO_PP_PF(deblocking_filter_control_present_flag); FROM_PPS_TO_PP_PF(redundant_pic_cnt_present_flag); pic_param.pic_fields.bits.reference_pic_flag = pic->ref; #undef FROM_PPS_TO_PP_PF #undef FROM_PPS_TO_PP_PF2 pic_param.frame_num = pic->frame_num; InitVAPicture(&pic_param.CurrPic); FillVAPicture(&pic_param.CurrPic, pic); // Init reference pictures' array. for (int i = 0; i < 16; ++i) InitVAPicture(&pic_param.ReferenceFrames[i]); // And fill it with picture info from DPB. FillVARefFramesFromDPB(dpb, pic_param.ReferenceFrames, arraysize(pic_param.ReferenceFrames)); pic_param.num_ref_frames = sps->max_num_ref_frames; if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, sizeof(pic_param), &pic_param)) return false; VAIQMatrixBufferH264 iq_matrix_buf; memset(&iq_matrix_buf, 0, sizeof(iq_matrix_buf)); if (pps->pic_scaling_matrix_present_flag) { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][j] = pps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][j] = pps->scaling_list8x8[i][j]; } } else { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 16; ++j) iq_matrix_buf.ScalingList4x4[i][j] = sps->scaling_list4x4[i][j]; } for (int i = 0; i < 2; ++i) { for (int j = 0; j < 64; ++j) iq_matrix_buf.ScalingList8x8[i][j] = sps->scaling_list8x8[i][j]; } } return vaapi_wrapper_->SubmitBuffer(VAIQMatrixBufferType, sizeof(iq_matrix_buf), &iq_matrix_buf); } bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitSlice( const H264PPS* pps, const H264SliceHeader* slice_hdr, const H264Picture::Vector& ref_pic_list0, const H264Picture::Vector& ref_pic_list1, const scoped_refptr<H264Picture>& pic, const uint8_t* data, size_t size) { VASliceParameterBufferH264 slice_param; memset(&slice_param, 0, sizeof(slice_param)); slice_param.slice_data_size = slice_hdr->nalu_size; slice_param.slice_data_offset = 0; slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; slice_param.slice_data_bit_offset = slice_hdr->header_bit_size; #define SHDRToSP(a) slice_param.a = slice_hdr->a SHDRToSP(first_mb_in_slice); slice_param.slice_type = slice_hdr->slice_type % 5; SHDRToSP(direct_spatial_mv_pred_flag); // TODO posciak: make sure parser sets those even when override flags // in slice header is off. SHDRToSP(num_ref_idx_l0_active_minus1); SHDRToSP(num_ref_idx_l1_active_minus1); SHDRToSP(cabac_init_idc); SHDRToSP(slice_qp_delta); SHDRToSP(disable_deblocking_filter_idc); SHDRToSP(slice_alpha_c0_offset_div2); SHDRToSP(slice_beta_offset_div2); if (((slice_hdr->IsPSlice() || slice_hdr->IsSPSlice()) && pps->weighted_pred_flag) || (slice_hdr->IsBSlice() && pps->weighted_bipred_idc == 1)) { SHDRToSP(luma_log2_weight_denom); SHDRToSP(chroma_log2_weight_denom); SHDRToSP(luma_weight_l0_flag); SHDRToSP(luma_weight_l1_flag); SHDRToSP(chroma_weight_l0_flag); SHDRToSP(chroma_weight_l1_flag); for (int i = 0; i <= slice_param.num_ref_idx_l0_active_minus1; ++i) { slice_param.luma_weight_l0[i] = slice_hdr->pred_weight_table_l0.luma_weight[i]; slice_param.luma_offset_l0[i] = slice_hdr->pred_weight_table_l0.luma_offset[i]; for (int j = 0; j < 2; ++j) { slice_param.chroma_weight_l0[i][j] = slice_hdr->pred_weight_table_l0.chroma_weight[i][j]; slice_param.chroma_offset_l0[i][j] = slice_hdr->pred_weight_table_l0.chroma_offset[i][j]; } } if (slice_hdr->IsBSlice()) { for (int i = 0; i <= slice_param.num_ref_idx_l1_active_minus1; ++i) { slice_param.luma_weight_l1[i] = slice_hdr->pred_weight_table_l1.luma_weight[i]; slice_param.luma_offset_l1[i] = slice_hdr->pred_weight_table_l1.luma_offset[i]; for (int j = 0; j < 2; ++j) { slice_param.chroma_weight_l1[i][j] = slice_hdr->pred_weight_table_l1.chroma_weight[i][j]; slice_param.chroma_offset_l1[i][j] = slice_hdr->pred_weight_table_l1.chroma_offset[i][j]; } } } } static_assert( arraysize(slice_param.RefPicList0) == arraysize(slice_param.RefPicList1), "Invalid RefPicList sizes"); for (size_t i = 0; i < arraysize(slice_param.RefPicList0); ++i) { InitVAPicture(&slice_param.RefPicList0[i]); InitVAPicture(&slice_param.RefPicList1[i]); } for (size_t i = 0; i < ref_pic_list0.size() && i < arraysize(slice_param.RefPicList0); ++i) { if (ref_pic_list0[i]) FillVAPicture(&slice_param.RefPicList0[i], ref_pic_list0[i]); } for (size_t i = 0; i < ref_pic_list1.size() && i < arraysize(slice_param.RefPicList1); ++i) { if (ref_pic_list1[i]) FillVAPicture(&slice_param.RefPicList1[i], ref_pic_list1[i]); } if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType, sizeof(slice_param), &slice_param)) return false; // Can't help it, blame libva... void* non_const_ptr = const_cast<uint8_t*>(data); return vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, size, non_const_ptr); } bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::SubmitDecode( const scoped_refptr<H264Picture>& pic) { DVLOG(4) << "Decoding POC " << pic->pic_order_cnt; scoped_refptr<VaapiDecodeSurface> dec_surface = H264PictureToVaapiDecodeSurface(pic); return vaapi_dec_->DecodeSurface(dec_surface); } bool VaapiVideoDecodeAccelerator::VaapiH264Accelerator::OutputPicture( const scoped_refptr<H264Picture>& pic) { scoped_refptr<VaapiDecodeSurface> dec_surface = H264PictureToVaapiDecodeSurface(pic); vaapi_dec_->SurfaceReady(dec_surface); return true; } void VaapiVideoDecodeAccelerator::VaapiH264Accelerator::Reset() { vaapi_wrapper_->DestroyPendingBuffers(); } scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> VaapiVideoDecodeAccelerator::VaapiH264Accelerator:: H264PictureToVaapiDecodeSurface(const scoped_refptr<H264Picture>& pic) { VaapiH264Picture* vaapi_pic = pic->AsVaapiH264Picture(); CHECK(vaapi_pic); return vaapi_pic->dec_surface(); } void VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVAPicture( VAPictureH264* va_pic, scoped_refptr<H264Picture> pic) { VASurfaceID va_surface_id = VA_INVALID_SURFACE; if (!pic->nonexisting) { scoped_refptr<VaapiDecodeSurface> dec_surface = H264PictureToVaapiDecodeSurface(pic); va_surface_id = dec_surface->va_surface()->id(); } va_pic->picture_id = va_surface_id; va_pic->frame_idx = pic->frame_num; va_pic->flags = 0; switch (pic->field) { case H264Picture::FIELD_NONE: break; case H264Picture::FIELD_TOP: va_pic->flags |= VA_PICTURE_H264_TOP_FIELD; break; case H264Picture::FIELD_BOTTOM: va_pic->flags |= VA_PICTURE_H264_BOTTOM_FIELD; break; } if (pic->ref) { va_pic->flags |= pic->long_term ? VA_PICTURE_H264_LONG_TERM_REFERENCE : VA_PICTURE_H264_SHORT_TERM_REFERENCE; } va_pic->TopFieldOrderCnt = pic->top_field_order_cnt; va_pic->BottomFieldOrderCnt = pic->bottom_field_order_cnt; } int VaapiVideoDecodeAccelerator::VaapiH264Accelerator::FillVARefFramesFromDPB( const H264DPB& dpb, VAPictureH264* va_pics, int num_pics) { H264Picture::Vector::const_reverse_iterator rit; int i; // Return reference frames in reverse order of insertion. // Libva does not document this, but other implementations (e.g. mplayer) // do it this way as well. for (rit = dpb.rbegin(), i = 0; rit != dpb.rend() && i < num_pics; ++rit) { if ((*rit)->ref) FillVAPicture(&va_pics[i++], *rit); } return i; } VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::VaapiVP8Accelerator( VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper) : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { DCHECK(vaapi_wrapper_); DCHECK(vaapi_dec_); } VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::~VaapiVP8Accelerator() {} scoped_refptr<VP8Picture> VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::CreateVP8Picture() { scoped_refptr<VaapiDecodeSurface> va_surface = vaapi_dec_->CreateSurface(); if (!va_surface) return nullptr; return new VaapiVP8Picture(va_surface); } #define ARRAY_MEMCPY_CHECKED(to, from) \ do { \ static_assert(sizeof(to) == sizeof(from), \ #from " and " #to " arrays must be of same size"); \ memcpy(to, from, sizeof(to)); \ } while (0) bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::SubmitDecode( const scoped_refptr<VP8Picture>& pic, const Vp8FrameHeader* frame_hdr, const scoped_refptr<VP8Picture>& last_frame, const scoped_refptr<VP8Picture>& golden_frame, const scoped_refptr<VP8Picture>& alt_frame) { VAIQMatrixBufferVP8 iq_matrix_buf; memset(&iq_matrix_buf, 0, sizeof(VAIQMatrixBufferVP8)); const Vp8SegmentationHeader& sgmnt_hdr = frame_hdr->segmentation_hdr; const Vp8QuantizationHeader& quant_hdr = frame_hdr->quantization_hdr; static_assert(arraysize(iq_matrix_buf.quantization_index) == kMaxMBSegments, "incorrect quantization matrix size"); for (size_t i = 0; i < kMaxMBSegments; ++i) { int q = quant_hdr.y_ac_qi; if (sgmnt_hdr.segmentation_enabled) { if (sgmnt_hdr.segment_feature_mode == Vp8SegmentationHeader::FEATURE_MODE_ABSOLUTE) q = sgmnt_hdr.quantizer_update_value[i]; else q += sgmnt_hdr.quantizer_update_value[i]; } #define CLAMP_Q(q) std::min(std::max(q, 0), 127) static_assert(arraysize(iq_matrix_buf.quantization_index[i]) == 6, "incorrect quantization matrix size"); iq_matrix_buf.quantization_index[i][0] = CLAMP_Q(q); iq_matrix_buf.quantization_index[i][1] = CLAMP_Q(q + quant_hdr.y_dc_delta); iq_matrix_buf.quantization_index[i][2] = CLAMP_Q(q + quant_hdr.y2_dc_delta); iq_matrix_buf.quantization_index[i][3] = CLAMP_Q(q + quant_hdr.y2_ac_delta); iq_matrix_buf.quantization_index[i][4] = CLAMP_Q(q + quant_hdr.uv_dc_delta); iq_matrix_buf.quantization_index[i][5] = CLAMP_Q(q + quant_hdr.uv_ac_delta); #undef CLAMP_Q } if (!vaapi_wrapper_->SubmitBuffer( VAIQMatrixBufferType, sizeof(VAIQMatrixBufferVP8), &iq_matrix_buf)) return false; VAProbabilityDataBufferVP8 prob_buf; memset(&prob_buf, 0, sizeof(VAProbabilityDataBufferVP8)); const Vp8EntropyHeader& entr_hdr = frame_hdr->entropy_hdr; ARRAY_MEMCPY_CHECKED(prob_buf.dct_coeff_probs, entr_hdr.coeff_probs); if (!vaapi_wrapper_->SubmitBuffer(VAProbabilityBufferType, sizeof(VAProbabilityDataBufferVP8), &prob_buf)) return false; VAPictureParameterBufferVP8 pic_param; memset(&pic_param, 0, sizeof(VAPictureParameterBufferVP8)); pic_param.frame_width = frame_hdr->width; pic_param.frame_height = frame_hdr->height; if (last_frame) { scoped_refptr<VaapiDecodeSurface> last_frame_surface = VP8PictureToVaapiDecodeSurface(last_frame); pic_param.last_ref_frame = last_frame_surface->va_surface()->id(); } else { pic_param.last_ref_frame = VA_INVALID_SURFACE; } if (golden_frame) { scoped_refptr<VaapiDecodeSurface> golden_frame_surface = VP8PictureToVaapiDecodeSurface(golden_frame); pic_param.golden_ref_frame = golden_frame_surface->va_surface()->id(); } else { pic_param.golden_ref_frame = VA_INVALID_SURFACE; } if (alt_frame) { scoped_refptr<VaapiDecodeSurface> alt_frame_surface = VP8PictureToVaapiDecodeSurface(alt_frame); pic_param.alt_ref_frame = alt_frame_surface->va_surface()->id(); } else { pic_param.alt_ref_frame = VA_INVALID_SURFACE; } pic_param.out_of_loop_frame = VA_INVALID_SURFACE; const Vp8LoopFilterHeader& lf_hdr = frame_hdr->loopfilter_hdr; #define FHDR_TO_PP_PF(a, b) pic_param.pic_fields.bits.a = (b) FHDR_TO_PP_PF(key_frame, frame_hdr->IsKeyframe() ? 0 : 1); FHDR_TO_PP_PF(version, frame_hdr->version); FHDR_TO_PP_PF(segmentation_enabled, sgmnt_hdr.segmentation_enabled); FHDR_TO_PP_PF(update_mb_segmentation_map, sgmnt_hdr.update_mb_segmentation_map); FHDR_TO_PP_PF(update_segment_feature_data, sgmnt_hdr.update_segment_feature_data); FHDR_TO_PP_PF(filter_type, lf_hdr.type); FHDR_TO_PP_PF(sharpness_level, lf_hdr.sharpness_level); FHDR_TO_PP_PF(loop_filter_adj_enable, lf_hdr.loop_filter_adj_enable); FHDR_TO_PP_PF(mode_ref_lf_delta_update, lf_hdr.mode_ref_lf_delta_update); FHDR_TO_PP_PF(sign_bias_golden, frame_hdr->sign_bias_golden); FHDR_TO_PP_PF(sign_bias_alternate, frame_hdr->sign_bias_alternate); FHDR_TO_PP_PF(mb_no_coeff_skip, frame_hdr->mb_no_skip_coeff); FHDR_TO_PP_PF(loop_filter_disable, lf_hdr.level == 0); #undef FHDR_TO_PP_PF ARRAY_MEMCPY_CHECKED(pic_param.mb_segment_tree_probs, sgmnt_hdr.segment_prob); static_assert(arraysize(sgmnt_hdr.lf_update_value) == arraysize(pic_param.loop_filter_level), "loop filter level arrays mismatch"); for (size_t i = 0; i < arraysize(sgmnt_hdr.lf_update_value); ++i) { int lf_level = lf_hdr.level; if (sgmnt_hdr.segmentation_enabled) { if (sgmnt_hdr.segment_feature_mode == Vp8SegmentationHeader::FEATURE_MODE_ABSOLUTE) lf_level = sgmnt_hdr.lf_update_value[i]; else lf_level += sgmnt_hdr.lf_update_value[i]; } // Clamp to [0..63] range. lf_level = std::min(std::max(lf_level, 0), 63); pic_param.loop_filter_level[i] = lf_level; } static_assert( arraysize(lf_hdr.ref_frame_delta) == arraysize(pic_param.loop_filter_deltas_ref_frame) && arraysize(lf_hdr.mb_mode_delta) == arraysize(pic_param.loop_filter_deltas_mode) && arraysize(lf_hdr.ref_frame_delta) == arraysize(lf_hdr.mb_mode_delta), "loop filter deltas arrays size mismatch"); for (size_t i = 0; i < arraysize(lf_hdr.ref_frame_delta); ++i) { pic_param.loop_filter_deltas_ref_frame[i] = lf_hdr.ref_frame_delta[i]; pic_param.loop_filter_deltas_mode[i] = lf_hdr.mb_mode_delta[i]; } #define FHDR_TO_PP(a) pic_param.a = frame_hdr->a FHDR_TO_PP(prob_skip_false); FHDR_TO_PP(prob_intra); FHDR_TO_PP(prob_last); FHDR_TO_PP(prob_gf); #undef FHDR_TO_PP ARRAY_MEMCPY_CHECKED(pic_param.y_mode_probs, entr_hdr.y_mode_probs); ARRAY_MEMCPY_CHECKED(pic_param.uv_mode_probs, entr_hdr.uv_mode_probs); ARRAY_MEMCPY_CHECKED(pic_param.mv_probs, entr_hdr.mv_probs); pic_param.bool_coder_ctx.range = frame_hdr->bool_dec_range; pic_param.bool_coder_ctx.value = frame_hdr->bool_dec_value; pic_param.bool_coder_ctx.count = frame_hdr->bool_dec_count; if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, sizeof(pic_param), &pic_param)) return false; VASliceParameterBufferVP8 slice_param; memset(&slice_param, 0, sizeof(slice_param)); slice_param.slice_data_size = frame_hdr->frame_size; slice_param.slice_data_offset = frame_hdr->first_part_offset; slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; slice_param.macroblock_offset = frame_hdr->macroblock_bit_offset; // Number of DCT partitions plus control partition. slice_param.num_of_partitions = frame_hdr->num_of_dct_partitions + 1; // Per VAAPI, this size only includes the size of the macroblock data in // the first partition (in bytes), so we have to subtract the header size. slice_param.partition_size[0] = frame_hdr->first_part_size - ((frame_hdr->macroblock_bit_offset + 7) / 8); for (size_t i = 0; i < frame_hdr->num_of_dct_partitions; ++i) slice_param.partition_size[i + 1] = frame_hdr->dct_partition_sizes[i]; if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType, sizeof(VASliceParameterBufferVP8), &slice_param)) return false; void* non_const_ptr = const_cast<uint8_t*>(frame_hdr->data); if (!vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, frame_hdr->frame_size, non_const_ptr)) return false; scoped_refptr<VaapiDecodeSurface> dec_surface = VP8PictureToVaapiDecodeSurface(pic); return vaapi_dec_->DecodeSurface(dec_surface); } bool VaapiVideoDecodeAccelerator::VaapiVP8Accelerator::OutputPicture( const scoped_refptr<VP8Picture>& pic) { scoped_refptr<VaapiDecodeSurface> dec_surface = VP8PictureToVaapiDecodeSurface(pic); vaapi_dec_->SurfaceReady(dec_surface); return true; } scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> VaapiVideoDecodeAccelerator::VaapiVP8Accelerator:: VP8PictureToVaapiDecodeSurface(const scoped_refptr<VP8Picture>& pic) { VaapiVP8Picture* vaapi_pic = pic->AsVaapiVP8Picture(); CHECK(vaapi_pic); return vaapi_pic->dec_surface(); } VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::VaapiVP9Accelerator( VaapiVideoDecodeAccelerator* vaapi_dec, VaapiWrapper* vaapi_wrapper) : vaapi_wrapper_(vaapi_wrapper), vaapi_dec_(vaapi_dec) { DCHECK(vaapi_wrapper_); DCHECK(vaapi_dec_); } VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::~VaapiVP9Accelerator() {} scoped_refptr<VP9Picture> VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::CreateVP9Picture() { scoped_refptr<VaapiDecodeSurface> va_surface = vaapi_dec_->CreateSurface(); if (!va_surface) return nullptr; return new VaapiVP9Picture(va_surface); } bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::SubmitDecode( const scoped_refptr<VP9Picture>& pic, const Vp9Segmentation& seg, const Vp9LoopFilter& lf, const std::vector<scoped_refptr<VP9Picture>>& ref_pictures) { VADecPictureParameterBufferVP9 pic_param; memset(&pic_param, 0, sizeof(pic_param)); const Vp9FrameHeader* frame_hdr = pic->frame_hdr.get(); DCHECK(frame_hdr); if (frame_hdr->profile != 0) { DVLOG(1) << "Unsupported profile" << frame_hdr->profile; return false; } pic_param.frame_width = base::checked_cast<uint16_t>(frame_hdr->width); pic_param.frame_height = base::checked_cast<uint16_t>(frame_hdr->height); CHECK_EQ(ref_pictures.size(), arraysize(pic_param.reference_frames)); for (size_t i = 0; i < arraysize(pic_param.reference_frames); ++i) { VASurfaceID va_surface_id; if (ref_pictures[i]) { scoped_refptr<VaapiDecodeSurface> surface = VP9PictureToVaapiDecodeSurface(ref_pictures[i]); va_surface_id = surface->va_surface()->id(); } else { va_surface_id = VA_INVALID_SURFACE; } pic_param.reference_frames[i] = va_surface_id; } #define FHDR_TO_PP_PF1(a) pic_param.pic_fields.bits.a = frame_hdr->a #define FHDR_TO_PP_PF2(a, b) pic_param.pic_fields.bits.a = b FHDR_TO_PP_PF2(subsampling_x, frame_hdr->subsampling_x == 1); FHDR_TO_PP_PF2(subsampling_y, frame_hdr->subsampling_y == 1); FHDR_TO_PP_PF2(frame_type, frame_hdr->IsKeyframe() ? 0 : 1); FHDR_TO_PP_PF1(show_frame); FHDR_TO_PP_PF1(error_resilient_mode); FHDR_TO_PP_PF1(intra_only); FHDR_TO_PP_PF1(allow_high_precision_mv); FHDR_TO_PP_PF2(mcomp_filter_type, frame_hdr->interp_filter); FHDR_TO_PP_PF1(frame_parallel_decoding_mode); FHDR_TO_PP_PF2(reset_frame_context, frame_hdr->reset_context); FHDR_TO_PP_PF1(refresh_frame_context); FHDR_TO_PP_PF1(frame_context_idx); FHDR_TO_PP_PF2(segmentation_enabled, seg.enabled); FHDR_TO_PP_PF2(segmentation_temporal_update, seg.temporal_update); FHDR_TO_PP_PF2(segmentation_update_map, seg.update_map); FHDR_TO_PP_PF2(last_ref_frame, frame_hdr->frame_refs[0]); FHDR_TO_PP_PF2(last_ref_frame_sign_bias, frame_hdr->ref_sign_biases[0]); FHDR_TO_PP_PF2(golden_ref_frame, frame_hdr->frame_refs[1]); FHDR_TO_PP_PF2(golden_ref_frame_sign_bias, frame_hdr->ref_sign_biases[1]); FHDR_TO_PP_PF2(alt_ref_frame, frame_hdr->frame_refs[2]); FHDR_TO_PP_PF2(alt_ref_frame_sign_bias, frame_hdr->ref_sign_biases[2]); FHDR_TO_PP_PF2(lossless_flag, frame_hdr->quant_params.IsLossless()); #undef FHDR_TO_PP_PF2 #undef FHDR_TO_PP_PF1 pic_param.filter_level = lf.filter_level; pic_param.sharpness_level = lf.sharpness_level; pic_param.log2_tile_rows = frame_hdr->log2_tile_rows; pic_param.log2_tile_columns = frame_hdr->log2_tile_cols; pic_param.frame_header_length_in_bytes = frame_hdr->uncompressed_header_size; pic_param.first_partition_size = frame_hdr->first_partition_size; ARRAY_MEMCPY_CHECKED(pic_param.mb_segment_tree_probs, seg.tree_probs); ARRAY_MEMCPY_CHECKED(pic_param.segment_pred_probs, seg.pred_probs); pic_param.profile = frame_hdr->profile; if (!vaapi_wrapper_->SubmitBuffer(VAPictureParameterBufferType, sizeof(pic_param), &pic_param)) return false; VASliceParameterBufferVP9 slice_param; memset(&slice_param, 0, sizeof(slice_param)); slice_param.slice_data_size = frame_hdr->frame_size; slice_param.slice_data_offset = 0; slice_param.slice_data_flag = VA_SLICE_DATA_FLAG_ALL; static_assert(arraysize(Vp9Segmentation::feature_enabled) == arraysize(slice_param.seg_param), "seg_param array of incorrect size"); for (size_t i = 0; i < arraysize(slice_param.seg_param); ++i) { VASegmentParameterVP9& seg_param = slice_param.seg_param[i]; #define SEG_TO_SP_SF(a, b) seg_param.segment_flags.fields.a = b SEG_TO_SP_SF(segment_reference_enabled, seg.FeatureEnabled(i, Vp9Segmentation::SEG_LVL_REF_FRAME)); SEG_TO_SP_SF(segment_reference, seg.FeatureData(i, Vp9Segmentation::SEG_LVL_REF_FRAME)); SEG_TO_SP_SF(segment_reference_skipped, seg.FeatureEnabled(i, Vp9Segmentation::SEG_LVL_SKIP)); #undef SEG_TO_SP_SF ARRAY_MEMCPY_CHECKED(seg_param.filter_level, lf.lvl[i]); seg_param.luma_dc_quant_scale = seg.y_dequant[i][0]; seg_param.luma_ac_quant_scale = seg.y_dequant[i][1]; seg_param.chroma_dc_quant_scale = seg.uv_dequant[i][0]; seg_param.chroma_ac_quant_scale = seg.uv_dequant[i][1]; } if (!vaapi_wrapper_->SubmitBuffer(VASliceParameterBufferType, sizeof(slice_param), &slice_param)) return false; void* non_const_ptr = const_cast<uint8_t*>(frame_hdr->data); if (!vaapi_wrapper_->SubmitBuffer(VASliceDataBufferType, frame_hdr->frame_size, non_const_ptr)) return false; scoped_refptr<VaapiDecodeSurface> dec_surface = VP9PictureToVaapiDecodeSurface(pic); return vaapi_dec_->DecodeSurface(dec_surface); } bool VaapiVideoDecodeAccelerator::VaapiVP9Accelerator::OutputPicture( const scoped_refptr<VP9Picture>& pic) { scoped_refptr<VaapiDecodeSurface> dec_surface = VP9PictureToVaapiDecodeSurface(pic); vaapi_dec_->SurfaceReady(dec_surface); return true; } scoped_refptr<VaapiVideoDecodeAccelerator::VaapiDecodeSurface> VaapiVideoDecodeAccelerator::VaapiVP9Accelerator:: VP9PictureToVaapiDecodeSurface(const scoped_refptr<VP9Picture>& pic) { VaapiVP9Picture* vaapi_pic = pic->AsVaapiVP9Picture(); CHECK(vaapi_pic); return vaapi_pic->dec_surface(); } // static VideoDecodeAccelerator::SupportedProfiles VaapiVideoDecodeAccelerator::GetSupportedProfiles() { return VaapiWrapper::GetSupportedDecodeProfiles(); } } // namespace media
35.370768
80
0.714546
Wzzzx
58d884e94c43d12a08a34f33a92387ac0233dc97
899
cpp
C++
Ch09/date_941.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
Ch09/date_941.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
Ch09/date_941.cpp
rzotya0327/UDProg-Introduction
c64244ee541d4ad0c85645385ef4f0c2e1886621
[ "CC0-1.0" ]
null
null
null
#include "std_lib_facilities.h" struct Date { int y; int m; int d; }; Date today; Date tomorrow; void init_day(Date& date, int y, int m, int d) { if (y > 0) date.y = y; else error("Invalid year"); if (m <= 12 && m > 0) date.m = m; //ekkor valid, felveheti az értéket else error("Invalid month"); if (d > 0 && d <=31) date.d = d; else error("Invalid day"); } void add_day(Date& dd, int n) { dd.d += n; if (dd.d > 31); } ostream& operator<<(ostream& os, const Date& d) { return os << '(' << d.y << ',' << d.m << ',' << d.d << ')'; } int main() try { Date today; init_day(today, 1978, 6, 25); Date tomorrow = today; add_day(tomorrow, 1); cout << "Today: " << today << endl; cout << "Tomorrow: " << tomorrow << endl; //Date bad_day; //init_day(bad_day, 2004, 13, -5); return 0; } catch (exception& e) { cout << e.what() << endl; return 1; }
14.5
54
0.549499
rzotya0327
58da56970c2661321a3644370d00a59248fcd730
1,092
cpp
C++
Engine/Source/Editor/SandboxApp.cpp
douysu/Sudou
23286e22a96814863ee55c6e2b5cc67be18acba9
[ "Apache-2.0" ]
3
2022-01-07T01:09:06.000Z
2022-01-21T03:11:33.000Z
Engine/Source/Editor/SandboxApp.cpp
douysu/Sudou
23286e22a96814863ee55c6e2b5cc67be18acba9
[ "Apache-2.0" ]
null
null
null
Engine/Source/Editor/SandboxApp.cpp
douysu/Sudou
23286e22a96814863ee55c6e2b5cc67be18acba9
[ "Apache-2.0" ]
null
null
null
#include "Runtime/Core/Application.h" #include "Runtime/Core/EntryPoint.h" #include "Runtime/GUI/ImGuiLayer.h" #include "Runtime/Core/Input.h" #include "Runtime/Core/KeyCodes.h" #include "Runtime/Core/MouseButtonCodes.h" #include "imgui/imgui.h" class ExampleLayer : public Sudou::Layer { public: ExampleLayer() : Layer("Example") {} void OnUpdate() override { if (Sudou::Input::IsKeyPressed(SD_KEY_TAB)) { SD_TRACE("Tab key is pressed (poll)"); } } void OnEvent(Sudou::Event& event) override { if (event.GetEventType() == Sudou::EventType::KeyPressed) { Sudou::KeyPressedEvent& e = (Sudou::KeyPressedEvent&)event; if (e.GetKeyCode() == SD_KEY_TAB) SD_TRACE("Tab key is pressed (event)"); SD_TRACE("{0}", (char)e.GetKeyCode()); } } virtual void OnImGuiRender() override { ImGui::Begin("Test"); ImGui::Text("Hello Sudou!"); ImGui::End(); } }; class Sandbox : public Sudou::Application { public: Sandbox() { PushLayer(new ExampleLayer()); } ~Sandbox() { } }; Sudou::Application* Sudou::CreateApplication() { return new Sandbox(); }
18.508475
62
0.675824
douysu
58dc8c5933254d81e8ba484a0dbff92210c644f3
784
cpp
C++
data/dailyCodingProblem774.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
2
2020-09-04T20:56:23.000Z
2021-06-11T07:42:26.000Z
data/dailyCodingProblem774.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
data/dailyCodingProblem774.cpp
vidit1999/daily_coding_problem
b90319cb4ddce11149f54010ba36c4bd6fa0a787
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /* Using a read7() method that returns 7 characters from a file, implement readN(n) which reads n characters. For example, given a file with the content “Hello world”, three read7() returns “Hello w”, “orld” and then “”. */ int index; string read7(string& s){ string ans = ""; int count = 7; while(index < s.length() && count--){ ans.push_back(s[index++]); } return ans; } string readN(string s, int n){ string ans = ""; int count = 0; while(count < n){ string r = read7(s); if(r.empty()) break; for(int i=0; i<r.length() && count<n; i++, count++){ ans.push_back(r[i]); } } return ans; } // main function int main(){ index = 0; string s = "Hello world"; cout << readN(s, 17) << "\n"; return 0; }
15.68
61
0.609694
vidit1999
58dce6983f47c9a22164b0532804eef635d29945
2,790
cc
C++
RecoTracker/TkMSParametrization/src/MSLayersKeeperX0DetLayer.cc
malbouis/cmssw
16173a30d3f0c9ecc5419c474bb4d272c58b65c8
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoTracker/TkMSParametrization/src/MSLayersKeeperX0DetLayer.cc
gartung/cmssw
3072dde3ce94dcd1791d778988198a44cde02162
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoTracker/TkMSParametrization/src/MSLayersKeeperX0DetLayer.cc
gartung/cmssw
3072dde3ce94dcd1791d778988198a44cde02162
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "MSLayersKeeperX0DetLayer.h" #include "TrackingTools/DetLayers/interface/DetLayer.h" #include "TrackingTools/DetLayers/interface/BarrelDetLayer.h" #include "TrackingTools/DetLayers/interface/ForwardDetLayer.h" #include "DataFormats/GeometrySurface/interface/BoundSurface.h" #include "DataFormats/GeometrySurface/interface/MediumProperties.h" #include "Geometry/CommonDetUnit/interface/GeomDet.h" #include <vector> using namespace std; MSLayersKeeperX0DetLayer::MSLayersKeeperX0DetLayer() { // vector<MSLayer> allLayers = MSLayersKeeperX0DetLayerGeom().detLayers(); //MP vector<MSLayer> allLayers; theLayersData = MSLayersAtAngle(allLayers); vector<MSLayer>::iterator it; PixelRecoPointRZ zero(0., 0.); for (it = allLayers.begin(); it != allLayers.end(); it++) { PixelRecoPointRZ middle = it->face() == GeomDetEnumerators::barrel ? PixelRecoPointRZ(it->position(), it->range().mean()) : PixelRecoPointRZ(it->range().mean(), it->position()); float cotTheta = PixelRecoLineRZ(zero, middle).cotLine(); float x0 = getDataX0(*it).x0; DataX0 dataX0; if (it->face() == GeomDetEnumerators::barrel) { float sumX0D = theLayersData.sumX0D(zero, middle); dataX0 = DataX0(x0, sumX0D, cotTheta); } else { float hrange = (it->range().max() - it->range().min()) / 2.; float cot1 = it->position() / (it->range().mean() - hrange / 2); float cot2 = it->position() / (it->range().mean() + hrange / 2); PixelRecoLineRZ line1(zero, cot1); PixelRecoLineRZ line2(zero, cot2); float sum1 = theLayersData.sumX0D(zero, it->crossing(line1).first); float sum2 = theLayersData.sumX0D(zero, it->crossing(line2).first); float slope = (sum2 - sum1) / (1 / cot2 - 1 / cot1); float sumX0D = sum1 + slope * (1 / cotTheta - 1 / cot1); dataX0 = DataX0(x0, sumX0D, cotTheta); dataX0.setForwardSumX0DSlope(slope); } setDataX0(*it, dataX0); theLayersData.update(*it); } //cout << "MSLayersKeeperX0DetLayer LAYERS: "<<endl; //theLayersData.print(); } // vector<MSLayer> // MSLayersKeeperX0DetLayer::MSLayersKeeperX0DetLayerGeom::detLayers() const // { // vector<MSLayer> result; // vector<const DetLayer*>::const_iterator it; // for (it = theLayers.begin(); it != theLayers.end(); it++) { // // const DetUnit * du = (*it)->detUnits().front(); // const GeomDetUnit * du; // //MP how access the geomdetunit?? // const MediumProperties * mp = du->surface().mediumProperties(); // float x0 = (mp) ? mp->radLen() : 0.03; // cout << "MediumProperties: "<<mp<<" x0="<<x0<<endl; // MSLayer layer(*it, DataX0(x0,0,0)); // result.push_back( layer); // } // return result; // }
38.219178
89
0.647312
malbouis
58dce8362c760d85774b75d402d8c3dae2cf69fa
3,434
cpp
C++
main.cpp
aszecsei/kestrel_compiler
3b592c77042f534ee725d076701800d5ad19318c
[ "MIT" ]
null
null
null
main.cpp
aszecsei/kestrel_compiler
3b592c77042f534ee725d076701800d5ad19318c
[ "MIT" ]
null
null
null
main.cpp
aszecsei/kestrel_compiler
3b592c77042f534ee725d076701800d5ad19318c
[ "MIT" ]
null
null
null
/* main.c -- main program for a Kestrel compiler */ /* Author: Douglas W. Jones * Date 9/30/2016 -- code from lecture 17 with pro-forma comment changes */ #include "main.h" #include "environment.h" #include "lexical.h" #include "block.h" #include "program.h" const char* main_infile; const char* main_outfile; int main( int argc, char * argv[] ) { bool isinfile = false; /* has the input file been specified? */ bool isoutfile = false; /* has the output file been specified? */ int i; /* indexing the argument number in argv */ /* first, deal with the program name */ LogHandler::programName = DEFAULT_NAME; if ((argc > 0) /* Unix/Linux shells guarantee this */ && (argv[0] != NULL) /* Unix/Linux implies this */ && (argv[0][0] != '\0')) { /* but nonstarndard exec could do this */ LogHandler::programName = argv[0]; } /* assert: program name is now well defined */ /* set argument strings to indicate that they have not been set */ main_infile = NULL; /* this means read from stdin */ main_outfile = "a.s"; /* write to stdout */ /* then deal with the command line arguments */ i = 1; /* start with the argument after the program name */ while ((i < argc) && (argv[i] != NULL)) { /* for each arg */ const char * arg = argv[i]; /* this argument */ char ch = *arg; /* first char of this argument */ if ( ch == '\0' ) { /* ignore empty argument strings */ } else if ( ch != DASH ) { /* arg not starting with dash is the input file name */ if (isinfile) { /* too many input files given */ Log::Fatal(ER_EXTRAINFILE); } else main_infile = arg; isinfile = true; } else { /* command line -option */ arg++; /* strip skip over the leading dash */ ch = *arg; /* first char of argument */ if (ch == '\0') { /* - by itself */ /* ... meaning read stdin */ if (isinfile) { /* input files already given */ Log::Fatal(ER_EXTRAINFILE); } isinfile = true; } else if (ch == 'o') { /* -o outfile or -o=outfile or -ooutfile */ if (isoutfile) { /* too many files */ Log::Fatal(ER_EXTRAOUTFILE); } arg++; /* strip off the letter o */ ch = *arg; if (ch == '\0') { /* -o filename */ i = i + 1; if ((i > argc) && (argv[i] != NULL)) { Log::Fatal(ER_MISSINGFILE); } /* =BUG= what about -o - */ main_outfile = argv[i]; isoutfile = true; } else { /* -ofilename or -o=filename */ if (ch == '=') { arg++; /* strip off the = */ ch = *arg; } if (ch == '\0') { Log::Error(ER_MISSINGFILE); } /* =BUG= what about -o- and -o=- */ main_outfile = arg; isoutfile = true; } /* put code to parse other options here */ } else if (!strcmp( arg, "help" )) { /* -help */ LogHandler::ProgramHelp(); } else if (!strcmp( arg, "?" )) { /* -? means help */ LogHandler::ProgramHelp(); } else if (ch == 'v') { LogHandler::verbosity = Log::DEBUG; } else { Log::Fatal(ER_BADARG); } } i++; /* advance to the next argument */ } /* now, we have the textual file names */ if ((!isoutfile)) { /* compute main_outfile */ lex_open( strdup(main_infile) ); Program * p = Program::compile(std::string(main_infile), std::string(main_outfile)); lex_close(); } /* =BUG= must call initializers for major subsystems */ }
27.918699
96
0.562609
aszecsei
58de7d6710236d98603c6e13f4f7df58f67b2ad4
323
cpp
C++
PlatformIOBlink/src/main.cpp
Niapollab/Microprocessor-Architecture_5-semester
6f7303ce85d45720ee7c847cb9969fc7cc5a1737
[ "Apache-2.0" ]
1
2021-12-20T04:44:23.000Z
2021-12-20T04:44:23.000Z
PlatformIOBlink/src/main.cpp
Niapollab/Microprocessor-Architecture_5-semester
6f7303ce85d45720ee7c847cb9969fc7cc5a1737
[ "Apache-2.0" ]
null
null
null
PlatformIOBlink/src/main.cpp
Niapollab/Microprocessor-Architecture_5-semester
6f7303ce85d45720ee7c847cb9969fc7cc5a1737
[ "Apache-2.0" ]
null
null
null
#include <Arduino.h> #ifdef __PLATFORMIO_BUILD_DEBUG__ #include <avr_debugger.h> #endif #define BLINK_DELAY 2000 void setup() { #ifdef __PLATFORMIO_BUILD_DEBUG__ debug_init(); #endif pinMode(LED_BUILTIN, OUTPUT); } void loop() { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); delay(BLINK_DELAY); }
16.15
57
0.743034
Niapollab
58dee9dad1c5a50edebdcbad1dfeb8178d6a2e38
2,993
cpp
C++
traces/trace_maker.cpp
umn-cris/MQSim
0c103c0a0fb0aee8d8f30e5bbbfb9224c1d6cb8d
[ "MIT" ]
null
null
null
traces/trace_maker.cpp
umn-cris/MQSim
0c103c0a0fb0aee8d8f30e5bbbfb9224c1d6cb8d
[ "MIT" ]
null
null
null
traces/trace_maker.cpp
umn-cris/MQSim
0c103c0a0fb0aee8d8f30e5bbbfb9224c1d6cb8d
[ "MIT" ]
null
null
null
#include <string> #include <stdio.h> #include <iostream> #include <fstream> #include <time.h> using namespace std; const unsigned int sector_size_in_bytes = 512; const unsigned int zone_size_MB = 256; unsigned int smallest_zone_number = 2; unsigned int biggest_zone_number = 14; unsigned int total_size_of_accessed_file_in_GB = 1; unsigned int total_no_of_request = 10000; int main(int argc, char** argv) { cout << "This generates a sequential write requets." << endl; unsigned int request_size_in_KB = 8; cout << "please enter the request size in KB : "; scanf("%u", &request_size_in_KB); cout << "please enter the smallest zone number : "; scanf("%u", &smallest_zone_number); cout << "please enter the whole file size to be accessed in GB : "; scanf("%u", &total_size_of_accessed_file_in_GB); string outputfile = "sequential_write_" + to_string(request_size_in_KB)+ "KB_from_zone" \ + to_string(smallest_zone_number) + "_" + to_string(total_size_of_accessed_file_in_GB) + "GB"; cout << "output file name is " << outputfile << endl; srand(time(NULL)); ofstream writeFile; writeFile.open(outputfile); string trace_line = ""; //cout << "request size is " << request_size_in_KB << " KB" << endl; total_no_of_request = total_size_of_accessed_file_in_GB * 1024 * 1024 / request_size_in_KB; cout << "total number of requests is " << total_no_of_request << endl; unsigned long long int first_arrival_time = 4851300; unsigned long long int first_start_LBA = smallest_zone_number * 512 * 1024; //256 * 1024 * 1024 / 512; == 256 MB / 512 B // |---------512 byte-------||---------512 byte-------| // LBA : 1 2 string arrival_time; string start_LBA; string device_number; string request_size_in_sector; string type_of_request; unsigned long long int prev_arrival_time = first_arrival_time; unsigned long long int prev_start_LBA = first_start_LBA; for (int i = 0; i < total_no_of_request; i++) { arrival_time = to_string(prev_arrival_time); start_LBA = to_string(prev_start_LBA); device_number = "1"; request_size_in_sector = to_string(request_size_in_KB * 2); // 2 == 1024 / sector_size_in_bytes type_of_request = "0"; // 0 means that it's a write reqeust, read request is "1" trace_line = arrival_time + " " + device_number + " " + start_LBA + " " + request_size_in_sector + " " + type_of_request + "\n"; writeFile.write(trace_line.c_str(), trace_line.size()); trace_line.clear(); //sscanf(arrival_time.c_str(), "%llu", &prev_arrival_time); //sscanf(start_LBA.c_str(), "%llu", &prev_start_LBA); prev_arrival_time = prev_arrival_time + ((rand() % 15) * 1000); prev_start_LBA = prev_start_LBA + request_size_in_KB * 2; // 2 == 1024 / sector_size_in_bytes; } writeFile.close(); return 0; }
38.87013
136
0.657534
umn-cris
58df715b2c535d54e974256dfe0719118f781e16
3,936
hpp
C++
src/adcs/dev/ADS1015.hpp
Pathfinder-for-Pitch-Momentum-Bias/FlightSoftware
7256f52f7c5887af7fc8679b163629d1235fa1bb
[ "MIT" ]
6
2020-02-24T07:46:22.000Z
2021-09-26T22:57:05.000Z
src/adcs/dev/ADS1015.hpp
pathfinder-for-autonomous-navigation/FlightSoftware
a3c30b10e2a28d17a2de0180c996bcc5f9ada7c7
[ "MIT" ]
537
2019-05-29T04:31:30.000Z
2022-03-06T17:18:56.000Z
src/adcs/dev/ADS1015.hpp
Pathfinder-for-Pitch-Momentum-Bias/FlightSoftware
7256f52f7c5887af7fc8679b163629d1235fa1bb
[ "MIT" ]
5
2020-04-01T17:29:37.000Z
2022-02-25T22:26:14.000Z
// // src/adcs/dev/ADS1015.hpp // FlightSoftware // // Contributors: // Kyle Krol kpk63@cornell.edu // // Pathfinder for Autonomous Navigation // Space Systems Design Studio // Cornell Univeristy // // TODO : // Test version 2_0 with the differential reads as well #ifndef SRC_ADCS_DEV_ADS1015_HPP_ #define SRC_ADCS_DEV_ADS1015_HPP_ #include "I2CDevice.hpp" namespace adcs { namespace dev { /** @class ADS1015 * Single shot conversion driver for the ADS1015 using the alert/ready pin. */ class ADS1015 : public I2CDevice { public: /** @enum ADDR * Possible address values for the ADS1015. */ enum ADDR : unsigned char { GND = 0x48, VDD = 0x49, SSDA = 0x4A, SSCL = 0x4B }; /** @enum GAIN * Possible gain values for the ADS1015. */ enum GAIN : unsigned short { /** Offers a full range input of =/- 6.144 V. */ TWO_THIRDS = 0x0000, /** Offers a full range input of =/- 4.096 V. */ ONE = 0x0200, /** Offers a full range input of =/- 2.048 V and is the default. */ TWO = 0x0400, /** Offers a full range input of =/- 1.024 V. */ FOUR = 0x0500, /** Offers a full range input of =/- 0.512 V. */ EIGHT = 0x0800, /** Offers a full range input of =/- 0.256 V. */ SIXTEEN = 0x0A00 }; /** @enum SR * Possible sample rates for the ADS1015. */ enum SR : unsigned short { SPS_128 = 0x0000, SPS_250 = 0x0020, SPS_490 = 0x0040, SPS_920 = 0x0060, /** Default sample rate. */ SPS_1600 = 0x0080, SPS_2400 = 0x00A0, SPS_3300 = 0x00C0 }; /** @enum CHANNEL * Possible read channels both single ended and differential. */ enum CHANNEL : unsigned short { DIFFERENTIAL_0_1 = 0x0000, DIFFERENTIAL_0_3 = 0x1000, DIFFERENTIAL_1_3 = 0x2000, DIFFERENTIAL_2_3 = 0x3000, SINGLE_0 = 0x4000, SINGLE_1 = 0x5000, SINGLE_2 = 0x6000, SINGLE_3 = 0x7000, }; /** Establishes default settings and sets up the ADC on the given bus with the * specified settings. See the \c I2CDevice class documentation for more * details. */ void setup(i2c_t3 *wire, uint8_t addr, unsigned int alert_pin, unsigned long timeout = DEV_I2C_TIMEOUT); /** Configures the alert pin to signal when a conversion is complete. If this * is succesful, the device is enabled. * @return True if the reset is succesful and false otherwise. */ virtual bool reset() override; /** Sets the gain value of the ADS1015. */ inline void set_gain(GAIN gain) { this->gain = gain; } /** Returns the current gain of the ADS1015. * \returns current gain value. */ inline GAIN get_gain() const { return this->gain; } /** Sets the sample rate of the ADS1015. */ void set_sample_rate(SR sample_rate); /** Returns the current sample rate of the ADS1015. * \returns current sample rate value. */ inline SR get_sample_rate() const { return this->sample_rate; } /** Initializes a read on the specified ADC channel. * \param[in] channel Channel the read is being taken on. */ void start_read(CHANNEL channel); /** Completes an in progress read and stores the result in val. * \param[out] val Location where the result is stored. * \returns true if the read was successful and false otherwise. */ bool end_read(int16_t &val); /** Equivalent to calling start_read and end_read. * \param[in] channel Channel the read is being taken on. * \param[out] val Location where the result is stored. * \returns true if the read was succesful and false otherwise. */ bool read(CHANNEL channel, int16_t &val); private: /** ADC conversion complete alert pin. */ unsigned int alert_pin; /** Timestamp of the start of the most recent conversion. */ unsigned long timestamp; /** Sample timeout delay. */ unsigned int sample_delay; /** ADC samples per second. */ SR sample_rate; /** ADC gain value. */ GAIN gain; }; } // namespace dev } // namespace adcs #endif
32
106
0.667937
Pathfinder-for-Pitch-Momentum-Bias
58e0235318b844ba7b585f2fd9bc8dbb65a78e8f
13,528
cc
C++
code/render/physics/havok/havokscene.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
67
2015-03-30T19:56:16.000Z
2022-03-11T13:52:17.000Z
code/render/physics/havok/havokscene.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
5
2015-04-15T17:17:33.000Z
2016-02-11T00:40:17.000Z
code/render/physics/havok/havokscene.cc
gscept/nebula-trifid
e7c0a0acb05eedad9ed37a72c1bdf2d658511b42
[ "BSD-2-Clause" ]
34
2015-03-30T15:08:00.000Z
2021-09-23T05:55:10.000Z
//------------------------------------------------------------------------------ // havokscene.cc // (C) 2013-2014 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "physics/scene.h" #include "physics/filterset.h" #include "physics/physicsserver.h" #include "physics/physicsbody.h" #include "physics/visualdebuggerserver.h" #include "physics/character.h" #include "physics/model/templates.h" #include "havokcharacterrigidbody.h" #include "conversion.h" #include "havokutil.h" #include <Physics2012/Dynamics/World/hkpWorld.h> #include <Physics2012/Collide/Dispatch/hkpAgentRegisterUtil.h> #include <Physics2012/Dynamics/Entity/hkpRigidBody.h> #include <Physics2012/Collide/Query/CastUtil/hkpWorldRayCastInput.h> #include <Physics2012/Collide/Shape/hkpShapeBase.h> #include <Physics2012/Collide/Query/Collector/RayCollector/hkpClosestRayHitCollector.h> #include <Physics2012/Dynamics/Collide/Filter/Pair/hkpPairCollisionFilter.h> #include <Physics2012/Collide/Query/Collector/RayCollector/hkpAllRayHitCollector.h> #include <Physics2012/Collide/Shape/Convex/Sphere/hkpSphereShape.h> #include <Physics2012/Collide/Shape/Convex/Box/hkpBoxShape.h> #include <Physics2012/Collide/Agent/Query/hkpCdBodyPairCollector.h> #include <Physics2012/Collide/Agent/Collidable/hkpCollidable.h> #include <Physics2012/Collide/Query/Collector/BodyPairCollector/hkpAllCdBodyPairCollector.h> #include <Physics2012/Collide/Agent/hkpProcessCollisionInput.h> #include <Physics2012/Collide/Filter/Group/hkpGroupFilter.h> #include <Physics2012/Collide/Filter/Group/hkpGroupFilterSetup.h> using namespace Physics; using namespace Math; namespace Havok { __ImplementClass(Havok::HavokScene,'HKSC', Physics::BaseScene); //------------------------------------------------------------------------------ /** */ HavokScene::HavokScene(): initialized(false), lastFrame(-1) { this->world = 0; } //------------------------------------------------------------------------------ /** */ HavokScene::~HavokScene() { this->world = 0; this->filter = 0; } //------------------------------------------------------------------------------ /** */ void HavokScene::RenderDebug() { IndexT i; for (i = 0; i < this->objects.Size() ; i++) { this->objects[i]->RenderDebug(); } } //------------------------------------------------------------------------------ /** */ Util::Array<Ptr<Contact>> HavokScene::RayCheck(const Math::vector& pos, const Math::vector& dir, const FilterSet& excludeSet, BaseScene::RayTestType rayType) { n_assert(this->IsInitialized()); hkVector4 position = Neb2HkFloat4(pos); hkVector4 direction = Neb2HkFloat4(dir); hkVector4 targetPoint; targetPoint.setAdd(position, direction); hkpWorldRayCastInput rayCastInput; rayCastInput.m_enableShapeCollectionFilter = true; rayCastInput.m_filterInfo = (int)Math::n_log2(Physics::Picking) /*FIXME*/; rayCastInput.m_from = position; rayCastInput.m_to = targetPoint; hkArray<hkpWorldRayCastOutput> hits; if (Test_Closest == rayType) { hkpClosestRayHitCollector collector; this->world->castRay(rayCastInput, collector); if(collector.hasHit()) { hkpWorldRayCastOutput hit = collector.getHit(); hits.pushBack(hit); } } else { hkpAllRayHitCollector collector; this->world->castRay(rayCastInput, collector); hits = collector.getHits(); } Util::Array<Ptr<Contact>> contacts; IndexT i; for (i = 0; i < hits.getSize(); i++) { const hkpWorldRayCastOutput& hit = hits[i]; if (HK_NULL == hit.m_rootCollidable) { continue; } // get the nebula physicsobject from the entity void* owner = hit.m_rootCollidable->getOwner(); hkpWorldObject* entity = (hkpWorldObject*)owner; n_assert(0 != entity); hkUlong userData = entity->getUserData(); HavokUtil::CheckWorldObjectUserData(userData); Ptr<PhysicsObject> physObject = (PhysicsObject*)userData; if (excludeSet.CheckObject(physObject)) { continue; } Ptr<Contact> contact = Contact::Create(); contact->SetCollisionObject(physObject); contact->SetMaterial(physObject->GetMaterialType()); contact->SetType(Contact::RayCheck); contact->SetNormalVector(Hk2NebFloat4(hit.m_normal)); contact->SetPoint(pos + (dir * hit.m_hitFraction)); contacts.Append(contact); if (Test_Closest == rayType) { break; } } return contacts; } //------------------------------------------------------------------------------ /** */ Ptr<Contact> HavokScene::GetClosestContactUnderMouse(const Math::line& worldMouseRay, const FilterSet& excludeSet) { Util::Array<Ptr<Contact>> contacts = this->RayCheck(worldMouseRay.b, worldMouseRay.m, excludeSet, Test_Closest); if (contacts.IsEmpty()) { return 0; } return contacts[0]; } //------------------------------------------------------------------------------ /** */ Ptr<Contact> HavokScene::GetClosestContactAlongRay(const Math::vector& pos, const Math::vector& dir, const FilterSet& excludeSet) { Util::Array<Ptr<Contact>> contacts = this->RayCheck(pos, dir, excludeSet, Test_Closest); if (contacts.IsEmpty()) { return 0; } return contacts[0]; } //------------------------------------------------------------------------------ /** */ bool HavokScene::ApplyImpulseAlongRay(const Math::vector& pos, const Math::vector& dir, const FilterSet& excludeSet, float impulse) { Util::Array<Ptr<Contact>> contacts = this->RayCheck(pos, dir, excludeSet, Test_All); bool hitValidTarget = false; IndexT i; for (i = 0; i < contacts.Size(); i++) { const Ptr<Contact> contact = contacts[i]; const Ptr<PhysicsObject>& physObject = contact->GetCollisionObject(); hkRefPtr<hkpRigidBody> rigidBody = HK_NULL; if (physObject->IsA(PhysicsBody::RTTI)) { Ptr<HavokBody> havokBody = physObject.downcast<HavokBody>(); rigidBody = havokBody->GetRigidBody(); } if (HK_NULL != rigidBody) { hitValidTarget = true; vector impulseVector = float4::normalize(dir) * impulse; rigidBody->applyPointImpulse(Neb2HkFloat4(impulseVector), Neb2HkFloat4(contact->GetPoint())); } } return hitValidTarget; } //------------------------------------------------------------------------------ /** */ void HavokScene::OnActivate() { n_assert(!this->IsInitialized()); // set up default behaviour for world hkpWorldCinfo worldInfo; worldInfo.m_broadPhaseBorderBehaviour = #if _DEBUG //TODO: Revert when broadphase borders can be defined in the leveleditor hkpWorldCinfo::BROADPHASE_BORDER_DO_NOTHING; //hkpWorldCinfo::BROADPHASE_BORDER_ASSERT; #else hkpWorldCinfo::BROADPHASE_BORDER_DO_NOTHING; #endif worldInfo.m_fireCollisionCallbacks = true; //< this is needed for custom contact listeners this->world = n_new(hkpWorld(worldInfo)); // set default gravity this->SetGravity(Math::vector(0, -9.8f, 0)); // this is needed to detect collisions hkpAgentRegisterUtil::registerAllAgents(this->world->getCollisionDispatcher()); this->SetupCollisionFilter(); this->initialized = true; } //------------------------------------------------------------------------------ /** */ void HavokScene::OnDeactivate() { n_assert(this->IsInitialized()); } //------------------------------------------------------------------------------ /** */ void HavokScene::SetGravity(const Math::vector& v) { hkVector4 hkGravity = Neb2HkFloat4(v); this->world->setGravity(hkGravity); BaseScene::SetGravity(v); } //------------------------------------------------------------------------------ /** */ void HavokScene::Trigger() { // to have a consistent simulation const float& simulationFrameTime = HavokPhysicsServer::Instance()->GetSimulationFrameTime(); if (-1 == this->lastFrame) { // first frame, simulate one step this->lastFrame = PhysicsServer::Instance()->GetTime(); this->StepWorld(simulationFrameTime); this->sinceLastTrigger = 0; return; } // else default behaviour: this->sinceLastTrigger += this->simulationSpeed * (PhysicsServer::Instance()->GetTime() - this->lastFrame); this->lastFrame = PhysicsServer::Instance()->GetTime(); if (this->sinceLastTrigger > simulationFrameTime) { //for (; this->sinceLastTrigger > simulationFrameTime; this->sinceLastTrigger -= simulationFrameTime) //< may cause noticable minilags! { this->StepWorld(simulationFrameTime); this->sinceLastTrigger -= simulationFrameTime; this->time += simulationFrameTime; } } // important note: it is tempting to just step the world using sinceLastTrigger but it will make the simulation inconsistent and // will likely mess up the behaviour of the character - for example jump height might vary between different jumps } //------------------------------------------------------------------------------ /** */ void HavokScene::StepWorld(float time) { IndexT i; for (i = 0; i < this->objects.Size(); i++) { this->objects[i]->OnStepBefore(); } this->world->stepDeltaTime(time); if (HavokVisualDebuggerServer::HasInstance()) { // also perform a step for the visualdebugger HavokVisualDebuggerServer::Instance()->OnStep(); } HavokPhysicsServer::Instance()->HandleCollisions(); for (i = 0; i < this->objects.Size(); i++) { this->objects[i]->OnStepAfter(); } } //------------------------------------------------------------------------------ /** */ int HavokScene::GetObjectsInSphere(const Math::vector& pos, float radius, const Physics::FilterSet& excludeSet, Util::Array<Ptr<PhysicsObject>>& result) { hkRefPtr<hkpShape> sphere = n_new(hkpSphereShape(radius)); return this->GetObjectsInShape(sphere, matrix44::translation(pos), excludeSet, result); } //------------------------------------------------------------------------------ /** */ int HavokScene::GetObjectsInBox(const Math::vector& scale, const Math::matrix44& m, const Physics::FilterSet& excludeSet, Util::Array<Ptr<PhysicsObject>>& result) { hkRefPtr<hkpShape> box = n_new(hkpBoxShape(Neb2HkFloat4(scale))); return this->GetObjectsInShape(box, m, excludeSet, result); } //------------------------------------------------------------------------------ /** */ int HavokScene::GetObjectsInShape(hkRefPtr<hkpShape> shape, const Math::matrix44& m, const Physics::FilterSet& excludeSet, Util::Array<Ptr<PhysicsObject>>& result) { n_assert(result.IsEmpty()); hkpCollidable* collidable = n_new(hkpCollidable(shape, &NebMatrix442HkTransform(m))); hkpAllCdBodyPairCollector collector; const hkpProcessCollisionInput* input = this->world->getCollisionInput(); this->world->getPenetrations(collidable, *input, collector); const hkArray<hkpRootCdBodyPair>& hits = collector.getHits(); IndexT i; for (i = 0; i < hits.getSize(); i++) { void* owner = hits[i].m_rootCollidableB->getOwner(); hkpWorldObject* entity = (hkpWorldObject*)owner; n_assert(0 != entity); hkUlong userData = entity->getUserData(); HavokUtil::CheckWorldObjectUserData(userData); Ptr<PhysicsObject> physObject = (PhysicsObject*)userData; if (excludeSet.CheckObject(physObject) || InvalidIndex != result.FindIndex(physObject)) //< might be a shape of a compoundshape belonging to the same object { continue; } result.InsertSorted(physObject); } n_delete(collidable); return result.Size(); } //------------------------------------------------------------------------------ /** */ void HavokScene::SetupCollisionFilter() { n_assert(this->world); /// set up a group filter as the default hkRefPtr<hkpGroupFilter> groupFilter = n_new(hkpGroupFilter()); // initialize the group filter like hkpGroupFilterSetup::setupGroupFilter but with the default nebula collidecategories groupFilter->enableCollisionsUsingBitfield(Physics::All, Physics::All); groupFilter->enableCollisionsUsingBitfield(1<<Physics::None, 0xffffffff); groupFilter->enableCollisionsUsingBitfield(0xffffffff, 1<<Physics::None); //FIXME: Physics::CollideCategory is already shifted - its values should optimally be just 1, 2, 3... like in hkpGroupFilterSetup::setupGroupFilter. //FIXME: (ctd) The below workaround have also been made for the physicsobjects' SetCollideCategory-methods groupFilter->disableCollisionsBetween((int)n_log2(Physics::Kinematic), (int)n_log2(Physics::Kinematic)); groupFilter->disableCollisionsBetween((int)n_log2(Physics::Kinematic), (int)n_log2(Physics::Static)); this->world->setCollisionFilter(groupFilter); this->filter = groupFilter; } //------------------------------------------------------------------------------ /** */ void HavokScene::DisableCollisionBetweenCategories(int categoryA, int categoryB) { n_assert(HK_NULL != this->filter); hkpGroupFilter* groupFilter = dynamic_cast<hkpGroupFilter*>(this->filter.val()); groupFilter->disableCollisionsBetween(categoryA, categoryB); } //------------------------------------------------------------------------------ /** */ void HavokScene::EnableCollisionBetweenCategories(int categoryA, int categoryB) { n_assert(HK_NULL != this->filter); hkpGroupFilter* groupFilter = dynamic_cast<hkpGroupFilter*>(this->filter.val()); groupFilter->enableCollisionsBetween(categoryA, categoryB); } //------------------------------------------------------------------------------ /** */ bool HavokScene::IsCollisionEnabledBetweenCategories(int categoryA, int categoryB) { n_assert(HK_NULL != this->filter); hkpGroupFilter* groupFilter = dynamic_cast<hkpGroupFilter*>(this->filter.val()); return groupFilter->isCollisionEnabled(categoryA, categoryB); } }
28.540084
159
0.648137
gscept